title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Lexicographically largest subsequence such that every character occurs at least k times
07 Jul, 2022 Given a string S and an integer K. The task is to find lexicographically largest subsequence of S, say T, such that every character in T must occur at least K times.Examples: Input : S = "banana", K = 2. Output : nn Possible subsequence where each character exists at least 2 times are: From the above subsequences, "nn" is the lexicographically largest. The idea is to solve greedily the above problem. If we want to make the subsequence lexicographically largest, we must give priority to lexicographically larger characters. ‘z’ is the largest character, let suppose z occurs fz times in S. If fz >= K, append ‘z’z k times in the string T and keep removing characters from the left of S until all the z’s are removed. Apply the strategy with ‘y’, ‘w’, ....., ‘a’. In the end, you will find the answer.Let see an example. Suppose S = “zzwzawa” and K = 2. Start with the largest character ‘z’. Here fz = 3 >= K. So T will become “zzz” and we will remove letters from the left of S until all the z’s are removed. So now S will become “awa”. Next largest is ‘y’ but that occurs 0 times in k so we will skip it. We will skip ‘w’, ‘v’ etc also until we go to ‘a’ which occurs 2 times. Now T will become “zzzaa” and S will become a empty string. Our answer is “zzzaa”.Below is implementation of this approach: C++ Java Python3 C# Javascript // C++ program to find lexicographically largest// subsequence where every character appears at// least k times.#include <bits/stdc++.h>using namespace std; // Find lexicographically largest subsequence of// s[0..n-1] such that every character appears// at least k times. The result is filled in t[]void subsequence(char s[], char t[], int n, int k){ int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\0';} // Driver codeint main(){ char s[] = "banana"; int n = sizeof(s); int k = 2; char t[n]; subsequence(s, t, n - 1, k); cout << t << endl; return 0;} import java.util.Arrays; // Java program to find lexicographically largest// subsequence where every character appears at// least k times. class GFG { // Find lexicographically largest subsequence of// s[0..n-1] such that every character appears// at least k times. The result is filled in t[]static void subsequence(char s[], char t[], int n, int k){ int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\0';} // Driver code public static void main(String[] args) { char s[] = {'b','a','n','a','n','a'}; int n = s.length; int k = 2; char t[] = new char[n]; subsequence(s, t, n - 1, k); for(int i = 0;i<t.length;i++) if(t[i]!=0) System.out.print(t[i]); }} // This code is contributed by Jajput-Ji # Python3 program to find lexicographically largest# subsequence where every character appears at# least k times. # Find lexicographically largest subsequence of# s[0..n-1] such that every character appears# at least k times. The result is filled in t[]def subsequence(s, t, n, k): last = 0 cnt = 0 new_last = 0 size = 0 string = 'zyxwvutsrqponmlkjihgfedcba' # Starting from largest character 'z' to 'a' for ch in string: cnt = 0 for i in range(last, n): if s[i] == ch: cnt += 1 # If frequency is greater than k if cnt >= k: # From the last point we leave for i in range(last, n): # check if string contain ch if s[i] == ch: # If yes, append to output string t[size] = ch new_last = i size += 1 # Update the last point. last = new_last # Driver Codeif __name__ == "__main__": s = ['b', 'a', 'n', 'a', 'n', 'a'] n = len(s) k = 2 t = [''] * n subsequence(s, t, n - 1, k) t = ''.join(t) print(t) # This code is contributed by# sanjeev2552 // C# program to find lexicographically// largest subsequence where every// character appears at least k times.using System; class GFG{ // Find lexicographically largest subsequence// of s[0..n-1] such that every character// appears at least k times. The result is// filled in t[]static void subsequence(char []s, char []t, int n, int k){ int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character // 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of // the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\0';} // Driver codepublic static void Main(){ char []s = {'b','a','n','a','n','a'}; int n = s.Length; int k = 2; char []t = new char[n]; subsequence(s, t, n - 1, k); for(int i = 0; i < t.Length; i++) if(t[i] != 0) Console.Write(t[i]);}} // This code contributed by Rajput-Ji <script> // Javascript program to find// lexicographically largest// subsequence where every// character appears at// least k times. // Find lexicographically largest subsequence of// s[0..n-1] such that every character appears// at least k times. The result is filled in t[]function subsequence(s, t, n, k){ var last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (var ch = 'z'.charCodeAt(0); ch >= 'a'.charCodeAt(0); ch--) { cnt = 0; // Counting the frequency of the character for (var i = last; i < n; i++) { if (s[i].charCodeAt(0) == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (var i = last; i < n; i++) { // check if string contain ch if (s[i].charCodeAt(0) == ch) { // If yes, append to output string t[size++] = String.fromCharCode(ch); new_last = i; } } // Update the last point. last = new_last; } }} // Driver codevar s = "banana";var n = s.length;var k = 2;var t = Array(n);subsequence(s, t, n - 1, k);document.write( t.join('') ); </script> Output: nn Time Complexity: O(n) Auxiliary Space: O(n)This article is contributed by Aarti_Rathi and Anuj Chauhan (anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji sanjeev2552 rutvik_56 simmytarika5 lexicographic-ordering subsequence Greedy Strings Strings Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for array rotation Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Minimum Number of Platforms Required for a Railway/Bus Station Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 231, "s": 54, "text": "Given a string S and an integer K. The task is to find lexicographically largest subsequence of S, say T, such that every character in T must occur at least K times.Examples: " }, { "code": null, "e": 343, "s": 231, "text": "Input : S = \"banana\", K = 2.\nOutput : nn\nPossible subsequence where each character exists at least 2 times are:" }, { "code": null, "e": 411, "s": 343, "text": "From the above subsequences, \"nn\" is the lexicographically largest." }, { "code": null, "e": 1364, "s": 411, "text": "The idea is to solve greedily the above problem. If we want to make the subsequence lexicographically largest, we must give priority to lexicographically larger characters. ‘z’ is the largest character, let suppose z occurs fz times in S. If fz >= K, append ‘z’z k times in the string T and keep removing characters from the left of S until all the z’s are removed. Apply the strategy with ‘y’, ‘w’, ....., ‘a’. In the end, you will find the answer.Let see an example. Suppose S = “zzwzawa” and K = 2. Start with the largest character ‘z’. Here fz = 3 >= K. So T will become “zzz” and we will remove letters from the left of S until all the z’s are removed. So now S will become “awa”. Next largest is ‘y’ but that occurs 0 times in k so we will skip it. We will skip ‘w’, ‘v’ etc also until we go to ‘a’ which occurs 2 times. Now T will become “zzzaa” and S will become a empty string. Our answer is “zzzaa”.Below is implementation of this approach: " }, { "code": null, "e": 1368, "s": 1364, "text": "C++" }, { "code": null, "e": 1373, "s": 1368, "text": "Java" }, { "code": null, "e": 1381, "s": 1373, "text": "Python3" }, { "code": null, "e": 1384, "s": 1381, "text": "C#" }, { "code": null, "e": 1395, "s": 1384, "text": "Javascript" }, { "code": "// C++ program to find lexicographically largest// subsequence where every character appears at// least k times.#include <bits/stdc++.h>using namespace std; // Find lexicographically largest subsequence of// s[0..n-1] such that every character appears// at least k times. The result is filled in t[]void subsequence(char s[], char t[], int n, int k){ int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\\0';} // Driver codeint main(){ char s[] = \"banana\"; int n = sizeof(s); int k = 2; char t[n]; subsequence(s, t, n - 1, k); cout << t << endl; return 0;}", "e": 2706, "s": 1395, "text": null }, { "code": "import java.util.Arrays; // Java program to find lexicographically largest// subsequence where every character appears at// least k times. class GFG { // Find lexicographically largest subsequence of// s[0..n-1] such that every character appears// at least k times. The result is filled in t[]static void subsequence(char s[], char t[], int n, int k){ int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\\0';} // Driver code public static void main(String[] args) { char s[] = {'b','a','n','a','n','a'}; int n = s.length; int k = 2; char t[] = new char[n]; subsequence(s, t, n - 1, k); for(int i = 0;i<t.length;i++) if(t[i]!=0) System.out.print(t[i]); }} // This code is contributed by Jajput-Ji", "e": 4192, "s": 2706, "text": null }, { "code": "# Python3 program to find lexicographically largest# subsequence where every character appears at# least k times. # Find lexicographically largest subsequence of# s[0..n-1] such that every character appears# at least k times. The result is filled in t[]def subsequence(s, t, n, k): last = 0 cnt = 0 new_last = 0 size = 0 string = 'zyxwvutsrqponmlkjihgfedcba' # Starting from largest character 'z' to 'a' for ch in string: cnt = 0 for i in range(last, n): if s[i] == ch: cnt += 1 # If frequency is greater than k if cnt >= k: # From the last point we leave for i in range(last, n): # check if string contain ch if s[i] == ch: # If yes, append to output string t[size] = ch new_last = i size += 1 # Update the last point. last = new_last # Driver Codeif __name__ == \"__main__\": s = ['b', 'a', 'n', 'a', 'n', 'a'] n = len(s) k = 2 t = [''] * n subsequence(s, t, n - 1, k) t = ''.join(t) print(t) # This code is contributed by# sanjeev2552", "e": 5381, "s": 4192, "text": null }, { "code": "// C# program to find lexicographically// largest subsequence where every// character appears at least k times.using System; class GFG{ // Find lexicographically largest subsequence// of s[0..n-1] such that every character// appears at least k times. The result is// filled in t[]static void subsequence(char []s, char []t, int n, int k){ int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character // 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of // the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\\0';} // Driver codepublic static void Main(){ char []s = {'b','a','n','a','n','a'}; int n = s.Length; int k = 2; char []t = new char[n]; subsequence(s, t, n - 1, k); for(int i = 0; i < t.Length; i++) if(t[i] != 0) Console.Write(t[i]);}} // This code contributed by Rajput-Ji", "e": 6907, "s": 5381, "text": null }, { "code": "<script> // Javascript program to find// lexicographically largest// subsequence where every// character appears at// least k times. // Find lexicographically largest subsequence of// s[0..n-1] such that every character appears// at least k times. The result is filled in t[]function subsequence(s, t, n, k){ var last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (var ch = 'z'.charCodeAt(0); ch >= 'a'.charCodeAt(0); ch--) { cnt = 0; // Counting the frequency of the character for (var i = last; i < n; i++) { if (s[i].charCodeAt(0) == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (var i = last; i < n; i++) { // check if string contain ch if (s[i].charCodeAt(0) == ch) { // If yes, append to output string t[size++] = String.fromCharCode(ch); new_last = i; } } // Update the last point. last = new_last; } }} // Driver codevar s = \"banana\";var n = s.length;var k = 2;var t = Array(n);subsequence(s, t, n - 1, k);document.write( t.join('') ); </script>", "e": 8216, "s": 6907, "text": null }, { "code": null, "e": 8226, "s": 8216, "text": "Output: " }, { "code": null, "e": 8229, "s": 8226, "text": "nn" }, { "code": null, "e": 8251, "s": 8229, "text": "Time Complexity: O(n)" }, { "code": null, "e": 8720, "s": 8251, "text": "Auxiliary Space: O(n)This article is contributed by Aarti_Rathi and Anuj Chauhan (anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8730, "s": 8720, "text": "Rajput-Ji" }, { "code": null, "e": 8742, "s": 8730, "text": "sanjeev2552" }, { "code": null, "e": 8752, "s": 8742, "text": "rutvik_56" }, { "code": null, "e": 8765, "s": 8752, "text": "simmytarika5" }, { "code": null, "e": 8788, "s": 8765, "text": "lexicographic-ordering" }, { "code": null, "e": 8800, "s": 8788, "text": "subsequence" }, { "code": null, "e": 8807, "s": 8800, "text": "Greedy" }, { "code": null, "e": 8815, "s": 8807, "text": "Strings" }, { "code": null, "e": 8823, "s": 8815, "text": "Strings" }, { "code": null, "e": 8830, "s": 8823, "text": "Greedy" }, { "code": null, "e": 8928, "s": 8830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8955, "s": 8928, "text": "Program for array rotation" }, { "code": null, "e": 9015, "s": 8955, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9034, "s": 9015, "text": "Coin Change | DP-7" }, { "code": null, "e": 9115, "s": 9034, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 9178, "s": 9115, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 9224, "s": 9178, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 9249, "s": 9224, "text": "Reverse a string in Java" }, { "code": null, "e": 9309, "s": 9249, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9324, "s": 9309, "text": "C++ Data Types" } ]
Django ORM – Inserting, Updating & Deleting Data
11 Feb, 2020 Prerequisite: Django models Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). This article discusses all the useful operations we can perform using Django ORM. For demonstration purposes, we will use the following Django models. class Album(models.Model): title = models.CharField(max_length = 30) artist = models.CharField(max_length = 30) genre = models.CharField(max_length = 30) def __str__(self): return self.title class Song(models.Model): name = models.CharField(max_length = 100) album = models.ForeignKey(Album, on_delete = models.CASCADE) def __str__(self): return self.name We can access the Django ORM by running the following command inside our project directory. python manage.py shell This brings us to an interactive Python console. Assuming that our models exist in myProject/albums/models.py we can import our models using the following command: >>> from books.models import Song, Album To create an object of model Album and save it into the database, we need to write the following command: >>> a = Album(title = "Divide", artist = "Ed Sheeran", genre = "Pop") >>> a.save() To create an object of model Song and save it into the database, we need to write the following command: >>> s = Song(name = "Castle on the Hill", album = a) >>> s.save() Let us add 2 more Albums records for the sake of demonstration. >>> a = Album(title = "Abbey Road", artist = "The Beatles", genre = "Rock") >>> a.save() >>> a = Album(title = "Revolver", artist = "The Beatles", genre = "Rock") >>> a.save() To retrieve all the objects of a model, we write the following command: >>> Album.objects.all() <QuerySet [<Album: Divide>, <Album: Abbey Road>, <Album: Revolver>]> The output is a QuerySet, or a set of objects that match the query. Notice that the name printed is the output of the __str__() function. We can also filter queries using the functions filter(), exclude() and get(). The filter() function returns a QuerySet having objects that match the given lookup parameters. >>> Album.objects.filter(artist = "The Beatles") <QuerySet [<Album: Abbey Road>, <Album: Revolver>]> The exclude() function returns a QuerySet having objects other than those matching the given lookup parameters. >>> Album.objects.exclude(genre = "Rock") <QuerySet [<Album: Divide>]> The get() function returns a single object which matches the given lookup parameter. It gives an error when the query returns multiple objects. >>> Album.objects.get(pk = 3) <QuerySet [<Album: Revolver>]> We can modify an existing object as follows: >>> a = Album.objects.get(pk = 3) >>> a.genre = "Pop" >>> a.save() To delete a single object, we need to write the following commands: >>> a = Album.objects.get(pk = 2) >>> a.delete() >>> Album.objects.all() <QuerySet [<Album: Divide>, <Album: Revolver>]> To delete multiple objects, we can use filter() or exclude() functions as follows: >>> Album.objects.filter(genre = "Pop").delete() >>> Album.objects.all() <QuerySet []> NaveenArora Django-basics Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Feb, 2020" }, { "code": null, "e": 80, "s": 52, "text": "Prerequisite: Django models" }, { "code": null, "e": 327, "s": 80, "text": "Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). This article discusses all the useful operations we can perform using Django ORM." }, { "code": null, "e": 396, "s": 327, "text": "For demonstration purposes, we will use the following Django models." }, { "code": "class Album(models.Model): title = models.CharField(max_length = 30) artist = models.CharField(max_length = 30) genre = models.CharField(max_length = 30) def __str__(self): return self.title class Song(models.Model): name = models.CharField(max_length = 100) album = models.ForeignKey(Album, on_delete = models.CASCADE) def __str__(self): return self.name", "e": 792, "s": 396, "text": null }, { "code": null, "e": 884, "s": 792, "text": "We can access the Django ORM by running the following command inside our project directory." }, { "code": null, "e": 907, "s": 884, "text": "python manage.py shell" }, { "code": null, "e": 1071, "s": 907, "text": "This brings us to an interactive Python console. Assuming that our models exist in myProject/albums/models.py we can import our models using the following command:" }, { "code": null, "e": 1112, "s": 1071, "text": ">>> from books.models import Song, Album" }, { "code": null, "e": 1218, "s": 1112, "text": "To create an object of model Album and save it into the database, we need to write the following command:" }, { "code": null, "e": 1301, "s": 1218, "text": ">>> a = Album(title = \"Divide\", artist = \"Ed Sheeran\", genre = \"Pop\")\n>>> a.save()" }, { "code": null, "e": 1406, "s": 1301, "text": "To create an object of model Song and save it into the database, we need to write the following command:" }, { "code": null, "e": 1472, "s": 1406, "text": ">>> s = Song(name = \"Castle on the Hill\", album = a)\n>>> s.save()" }, { "code": null, "e": 1536, "s": 1472, "text": "Let us add 2 more Albums records for the sake of demonstration." }, { "code": null, "e": 1712, "s": 1536, "text": ">>> a = Album(title = \"Abbey Road\", artist = \"The Beatles\", genre = \"Rock\")\n>>> a.save()\n>>> a = Album(title = \"Revolver\", artist = \"The Beatles\", genre = \"Rock\")\n>>> a.save()" }, { "code": null, "e": 1784, "s": 1712, "text": "To retrieve all the objects of a model, we write the following command:" }, { "code": null, "e": 1877, "s": 1784, "text": ">>> Album.objects.all()\n<QuerySet [<Album: Divide>, <Album: Abbey Road>, <Album: Revolver>]>" }, { "code": null, "e": 2015, "s": 1877, "text": "The output is a QuerySet, or a set of objects that match the query. Notice that the name printed is the output of the __str__() function." }, { "code": null, "e": 2189, "s": 2015, "text": "We can also filter queries using the functions filter(), exclude() and get(). The filter() function returns a QuerySet having objects that match the given lookup parameters." }, { "code": null, "e": 2290, "s": 2189, "text": ">>> Album.objects.filter(artist = \"The Beatles\")\n<QuerySet [<Album: Abbey Road>, <Album: Revolver>]>" }, { "code": null, "e": 2402, "s": 2290, "text": "The exclude() function returns a QuerySet having objects other than those matching the given lookup parameters." }, { "code": null, "e": 2473, "s": 2402, "text": ">>> Album.objects.exclude(genre = \"Rock\")\n<QuerySet [<Album: Divide>]>" }, { "code": null, "e": 2617, "s": 2473, "text": "The get() function returns a single object which matches the given lookup parameter. It gives an error when the query returns multiple objects." }, { "code": null, "e": 2678, "s": 2617, "text": ">>> Album.objects.get(pk = 3)\n<QuerySet [<Album: Revolver>]>" }, { "code": null, "e": 2723, "s": 2678, "text": "We can modify an existing object as follows:" }, { "code": null, "e": 2790, "s": 2723, "text": ">>> a = Album.objects.get(pk = 3)\n>>> a.genre = \"Pop\"\n>>> a.save()" }, { "code": null, "e": 2858, "s": 2790, "text": "To delete a single object, we need to write the following commands:" }, { "code": null, "e": 2979, "s": 2858, "text": ">>> a = Album.objects.get(pk = 2)\n>>> a.delete()\n>>> Album.objects.all()\n<QuerySet [<Album: Divide>, <Album: Revolver>]>" }, { "code": null, "e": 3062, "s": 2979, "text": "To delete multiple objects, we can use filter() or exclude() functions as follows:" }, { "code": null, "e": 3149, "s": 3062, "text": ">>> Album.objects.filter(genre = \"Pop\").delete()\n>>> Album.objects.all()\n<QuerySet []>" }, { "code": null, "e": 3161, "s": 3149, "text": "NaveenArora" }, { "code": null, "e": 3175, "s": 3161, "text": "Django-basics" }, { "code": null, "e": 3189, "s": 3175, "text": "Python Django" }, { "code": null, "e": 3196, "s": 3189, "text": "Python" }, { "code": null, "e": 3294, "s": 3196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3322, "s": 3294, "text": "Read JSON file using Python" }, { "code": null, "e": 3372, "s": 3322, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3394, "s": 3372, "text": "Python map() function" }, { "code": null, "e": 3438, "s": 3394, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3480, "s": 3438, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3502, "s": 3480, "text": "Enumerate() in Python" }, { "code": null, "e": 3537, "s": 3502, "text": "Read a file line by line in Python" }, { "code": null, "e": 3563, "s": 3537, "text": "Python String | replace()" }, { "code": null, "e": 3595, "s": 3563, "text": "How to Install PIP on Windows ?" } ]
How to create Right Aligned Menu Links using HTML and CSS ?
21 Nov, 2019 The right-aligned menu links are used on many websites. Like hotels website that contains lots of options in the menu section but in case of emergency to make contact with them need specific attention. In that case, you can put all the menu options on the left side of the navigation bar and display contact us option on the right side of the bar. This design will make the website more attractive than the regular menu links. To create the right align menu links you just need HTML and CSS. Menu links should contain an important menu list that you want to display on the right side. The below example will illustrate the approach of the concept. Creating the Structure: In this section, we will create a basic website structure to create a right-aligned menu links. HTML code to make the structure:<!DOCTYPE html><html> <head> <title> How To Create Right Aligned Menu Links using HTML and CSS ? </title> <meta name="viewport" content="width=device-width, initial-scale=1"></head> <body> <!-- Navbar items --> <div id="navlist"> <a href="#">Home</a> <a href="#">Our Products</a> <a href="#">Careers</a> <div class="navlist-right"> <a href="#">About Us</a> <a href="#">Contact Us</a> </div> </div> <!-- logo with tag --> <div class="content"> <h1 style="color:green; padding-top:40px;"> GeeksforGeeks </h1> <b>A Computer Science Portal for Geeks</b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html> <!DOCTYPE html><html> <head> <title> How To Create Right Aligned Menu Links using HTML and CSS ? </title> <meta name="viewport" content="width=device-width, initial-scale=1"></head> <body> <!-- Navbar items --> <div id="navlist"> <a href="#">Home</a> <a href="#">Our Products</a> <a href="#">Careers</a> <div class="navlist-right"> <a href="#">About Us</a> <a href="#">Contact Us</a> </div> </div> <!-- logo with tag --> <div class="content"> <h1 style="color:green; padding-top:40px;"> GeeksforGeeks </h1> <b>A Computer Science Portal for Geeks</b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html> Designing the Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the navigation bar. CSS code of structure:<style> /* styling navlist */ #navlist { background-color: #0074D9; position: absolute; width: 100%; } /* styling navlist anchor element */ #navlist a { float:left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } .navlist-right{ float:right; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; }</style> <style> /* styling navlist */ #navlist { background-color: #0074D9; position: absolute; width: 100%; } /* styling navlist anchor element */ #navlist a { float:left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } .navlist-right{ float:right; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; }</style> Combining the HTML and CSS code: This is the final code after combining the above two sections. You can see that Home, Careers and Our Products align-left as default but About us and Contact us aligned right. <!DOCTYPE html><html> <head> <title> How To Create Right Aligned Menu Links using HTML and CSS ? </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> /* styling navlist */ #navlist { background-color: #0074D9; position: absolute; width: 100%; } /* styling navlist anchor element */ #navlist a { float:left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } .navlist-right{ float:right; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; } </style></head> <body> <!-- Navbar items --> <div id="navlist"> <a href="#">Home</a> <a href="#">Our Products</a> <a href="#">Careers</a> <div class="navlist-right"> <a href="#">About Us</a> <a href="#">Contact Us</a> </div> </div> <!-- logo with tag --> <div class="content"> <h1 style="color:green; padding-top:40px;"> GeeksforGeeks </h1> <b>A Computer Science Portal for Geeks</b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html> Output: CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2019" }, { "code": null, "e": 676, "s": 28, "text": "The right-aligned menu links are used on many websites. Like hotels website that contains lots of options in the menu section but in case of emergency to make contact with them need specific attention. In that case, you can put all the menu options on the left side of the navigation bar and display contact us option on the right side of the bar. This design will make the website more attractive than the regular menu links. To create the right align menu links you just need HTML and CSS. Menu links should contain an important menu list that you want to display on the right side. The below example will illustrate the approach of the concept." }, { "code": null, "e": 796, "s": 676, "text": "Creating the Structure: In this section, we will create a basic website structure to create a right-aligned menu links." }, { "code": null, "e": 1945, "s": 796, "text": "HTML code to make the structure:<!DOCTYPE html><html> <head> <title> How To Create Right Aligned Menu Links using HTML and CSS ? </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head> <body> <!-- Navbar items --> <div id=\"navlist\"> <a href=\"#\">Home</a> <a href=\"#\">Our Products</a> <a href=\"#\">Careers</a> <div class=\"navlist-right\"> <a href=\"#\">About Us</a> <a href=\"#\">Contact Us</a> </div> </div> <!-- logo with tag --> <div class=\"content\"> <h1 style=\"color:green; padding-top:40px;\"> GeeksforGeeks </h1> <b>A Computer Science Portal for Geeks</b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> How To Create Right Aligned Menu Links using HTML and CSS ? </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head> <body> <!-- Navbar items --> <div id=\"navlist\"> <a href=\"#\">Home</a> <a href=\"#\">Our Products</a> <a href=\"#\">Careers</a> <div class=\"navlist-right\"> <a href=\"#\">About Us</a> <a href=\"#\">Contact Us</a> </div> </div> <!-- logo with tag --> <div class=\"content\"> <h1 style=\"color:green; padding-top:40px;\"> GeeksforGeeks </h1> <b>A Computer Science Portal for Geeks</b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html>", "e": 3062, "s": 1945, "text": null }, { "code": null, "e": 3234, "s": 3062, "text": "Designing the Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the navigation bar." }, { "code": null, "e": 3822, "s": 3234, "text": "CSS code of structure:<style> /* styling navlist */ #navlist { background-color: #0074D9; position: absolute; width: 100%; } /* styling navlist anchor element */ #navlist a { float:left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } .navlist-right{ float:right; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; }</style>" }, { "code": "<style> /* styling navlist */ #navlist { background-color: #0074D9; position: absolute; width: 100%; } /* styling navlist anchor element */ #navlist a { float:left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } .navlist-right{ float:right; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; }</style>", "e": 4388, "s": 3822, "text": null }, { "code": null, "e": 4597, "s": 4388, "text": "Combining the HTML and CSS code: This is the final code after combining the above two sections. You can see that Home, Careers and Our Products align-left as default but About us and Contact us aligned right." }, { "code": "<!DOCTYPE html><html> <head> <title> How To Create Right Aligned Menu Links using HTML and CSS ? </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> /* styling navlist */ #navlist { background-color: #0074D9; position: absolute; width: 100%; } /* styling navlist anchor element */ #navlist a { float:left; display: block; color: #f2f2f2; text-align: center; padding: 12px; text-decoration: none; font-size: 15px; } .navlist-right{ float:right; } /* hover effect of navlist anchor element */ #navlist a:hover { background-color: #ddd; color: black; } </style></head> <body> <!-- Navbar items --> <div id=\"navlist\"> <a href=\"#\">Home</a> <a href=\"#\">Our Products</a> <a href=\"#\">Careers</a> <div class=\"navlist-right\"> <a href=\"#\">About Us</a> <a href=\"#\">Contact Us</a> </div> </div> <!-- logo with tag --> <div class=\"content\"> <h1 style=\"color:green; padding-top:40px;\"> GeeksforGeeks </h1> <b>A Computer Science Portal for Geeks</b> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div></body> </html>", "e": 6393, "s": 4597, "text": null }, { "code": null, "e": 6401, "s": 6393, "text": "Output:" }, { "code": null, "e": 6410, "s": 6401, "text": "CSS-Misc" }, { "code": null, "e": 6420, "s": 6410, "text": "HTML-Misc" }, { "code": null, "e": 6424, "s": 6420, "text": "CSS" }, { "code": null, "e": 6429, "s": 6424, "text": "HTML" }, { "code": null, "e": 6446, "s": 6429, "text": "Web Technologies" }, { "code": null, "e": 6473, "s": 6446, "text": "Web technologies Questions" }, { "code": null, "e": 6478, "s": 6473, "text": "HTML" } ]
Read and Write operations in Memory
24 Jan, 2022 A memory unit stores binary information in groups of bits called words. Data input lines provide the information to be stored into the memory, Data output lines carry the information out from the memory. The control lines Read and write specifies the direction of transfer of data. Basically, in the memory organization, there are memory locations indexing from 0 to where l is the address buses. We can describe the memory in terms of the bytes using the following formula: Where,l is the total address busesN is the memory in bytes For example, some storage can be described below in terms of bytes using the above formula: 1kB= 210 Bytes 64 kB = 26 x 210 Bytes = 216 Bytes 4 GB = 22 x 210(kB) x 210(MB) x 210 (GB) = 232 Bytes Memory Address Register (MAR) is the address register which is used to store the address of the memory location where the operation is being performed.Memory Data Register (MDR) is the data register which is used to store the data on which the operation is being performed. Memory Read Operation:Memory read operation transfers the desired word to address lines and activates the read control line.Description of memory read operation is given below:In the above diagram initially, MDR can contain any garbage value and MAR is containing 2003 memory address. After the execution of read instruction, the data of memory location 2003 will be read and the MDR will get updated by the value of the 2003 memory location (3D).Memory Write Operation:Memory write operation transfers the address of the desired word to the address lines, transfers the data bits to be stored in memory to the data input lines. Then it activates the write control line. Description of the write operation is given below:In the above diagram, the MAR contains 2003 and MDR contains 3D. After the execution of write instruction 3D will be written at 2003 memory location. Memory Read Operation:Memory read operation transfers the desired word to address lines and activates the read control line.Description of memory read operation is given below:In the above diagram initially, MDR can contain any garbage value and MAR is containing 2003 memory address. After the execution of read instruction, the data of memory location 2003 will be read and the MDR will get updated by the value of the 2003 memory location (3D). In the above diagram initially, MDR can contain any garbage value and MAR is containing 2003 memory address. After the execution of read instruction, the data of memory location 2003 will be read and the MDR will get updated by the value of the 2003 memory location (3D). Memory Write Operation:Memory write operation transfers the address of the desired word to the address lines, transfers the data bits to be stored in memory to the data input lines. Then it activates the write control line. Description of the write operation is given below:In the above diagram, the MAR contains 2003 and MDR contains 3D. After the execution of write instruction 3D will be written at 2003 memory location. In the above diagram, the MAR contains 2003 and MDR contains 3D. After the execution of write instruction 3D will be written at 2003 memory location. VaibhavRai3 tanwarsinghvaibhav Computer Organization & Architecture GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Decimal to Binary Conversion Logical and Physical Address in Operating System Direct Access Media (DMA) Controller in Computer Architecture Interrupts Architecture of 8085 microprocessor Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jan, 2022" }, { "code": null, "e": 529, "s": 52, "text": "A memory unit stores binary information in groups of bits called words. Data input lines provide the information to be stored into the memory, Data output lines carry the information out from the memory. The control lines Read and write specifies the direction of transfer of data. Basically, in the memory organization, there are memory locations indexing from 0 to where l is the address buses. We can describe the memory in terms of the bytes using the following formula:" }, { "code": null, "e": 588, "s": 529, "text": "Where,l is the total address busesN is the memory in bytes" }, { "code": null, "e": 680, "s": 588, "text": "For example, some storage can be described below in terms of bytes using the above formula:" }, { "code": null, "e": 800, "s": 680, "text": " 1kB= 210 Bytes\n 64 kB = 26 x 210 Bytes\n = 216 Bytes\n 4 GB = 22 x 210(kB) x 210(MB) x 210 (GB)\n = 232 Bytes\n" }, { "code": null, "e": 1074, "s": 800, "text": "Memory Address Register (MAR) is the address register which is used to store the address of the memory location where the operation is being performed.Memory Data Register (MDR) is the data register which is used to store the data on which the operation is being performed." }, { "code": null, "e": 1945, "s": 1074, "text": "Memory Read Operation:Memory read operation transfers the desired word to address lines and activates the read control line.Description of memory read operation is given below:In the above diagram initially, MDR can contain any garbage value and MAR is containing 2003 memory address. After the execution of read instruction, the data of memory location 2003 will be read and the MDR will get updated by the value of the 2003 memory location (3D).Memory Write Operation:Memory write operation transfers the address of the desired word to the address lines, transfers the data bits to be stored in memory to the data input lines. Then it activates the write control line. Description of the write operation is given below:In the above diagram, the MAR contains 2003 and MDR contains 3D. After the execution of write instruction 3D will be written at 2003 memory location." }, { "code": null, "e": 2393, "s": 1945, "text": "Memory Read Operation:Memory read operation transfers the desired word to address lines and activates the read control line.Description of memory read operation is given below:In the above diagram initially, MDR can contain any garbage value and MAR is containing 2003 memory address. After the execution of read instruction, the data of memory location 2003 will be read and the MDR will get updated by the value of the 2003 memory location (3D)." }, { "code": null, "e": 2665, "s": 2393, "text": "In the above diagram initially, MDR can contain any garbage value and MAR is containing 2003 memory address. After the execution of read instruction, the data of memory location 2003 will be read and the MDR will get updated by the value of the 2003 memory location (3D)." }, { "code": null, "e": 3089, "s": 2665, "text": "Memory Write Operation:Memory write operation transfers the address of the desired word to the address lines, transfers the data bits to be stored in memory to the data input lines. Then it activates the write control line. Description of the write operation is given below:In the above diagram, the MAR contains 2003 and MDR contains 3D. After the execution of write instruction 3D will be written at 2003 memory location." }, { "code": null, "e": 3239, "s": 3089, "text": "In the above diagram, the MAR contains 2003 and MDR contains 3D. After the execution of write instruction 3D will be written at 2003 memory location." }, { "code": null, "e": 3251, "s": 3239, "text": "VaibhavRai3" }, { "code": null, "e": 3270, "s": 3251, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 3307, "s": 3270, "text": "Computer Organization & Architecture" }, { "code": null, "e": 3315, "s": 3307, "text": "GATE CS" }, { "code": null, "e": 3413, "s": 3315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3454, "s": 3413, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 3503, "s": 3454, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 3565, "s": 3503, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 3576, "s": 3565, "text": "Interrupts" }, { "code": null, "e": 3612, "s": 3576, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 3632, "s": 3612, "text": "Layers of OSI Model" }, { "code": null, "e": 3656, "s": 3632, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3669, "s": 3656, "text": "TCP/IP Model" }, { "code": null, "e": 3696, "s": 3669, "text": "Types of Operating Systems" } ]
Remove duplicates from an unsorted linked list
14 Jun, 2022 Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43. METHOD 1 (Using two loops) This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and the inner loop compares the picked element with the rest of the elements. Thanks to Gaurav Saxena for his help in writing this code. C++ Java Python3 C# Javascript /* C++ Program to remove duplicates in an unsorted linked list */#include <bits/stdc++.h>using namespace std; /* A linked list node */struct Node { int data; struct Node* next;}; // Utility function to create a new Nodestruct Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Function to remove duplicates from a unsorted linked list */void removeDuplicates(struct Node* start){ struct Node *ptr1, *ptr2, *dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2->next != NULL) { /* If duplicate then delete it */ if (ptr1->data == ptr2->next->data) { /* sequence of steps is important here */ dup = ptr2->next; ptr2->next = ptr2->next->next; delete (dup); } else /* This is tricky */ ptr2 = ptr2->next; } ptr1 = ptr1->next; }} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ /* The constructed linked list is: 10->12->11->11->12->11->10*/ struct Node* start = newNode(10); start->next = newNode(12); start->next->next = newNode(11); start->next->next->next = newNode(11); start->next->next->next->next = newNode(12); start->next->next->next->next->next = newNode(11); start->next->next->next->next->next->next = newNode(10); printf("Linked list before removing duplicates "); printList(start); removeDuplicates(start); printf("\nLinked list after removing duplicates "); printList(start); return 0;} // Java program to remove duplicates from unsorted// linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to remove duplicates from an unsorted linked list */ void remove_duplicates() { Node ptr1 = null, ptr2 = null, dup = null; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2.next != null) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ ptr2.next = ptr2.next.next; System.gc(); } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(10); list.head.next = new Node(12); list.head.next.next = new Node(11); list.head.next.next.next = new Node(11); list.head.next.next.next.next = new Node(12); list.head.next.next.next.next.next = new Node(11); list.head.next.next.next.next.next.next = new Node(10); System.out.println( "Linked List before removing duplicates : \n "); list.printList(head); list.remove_duplicates(); System.out.println(""); System.out.println( "Linked List after removing duplicates : \n "); list.printList(head); }}// This code has been contributed by Mayank Jaiswal # Python3 program to remove duplicates# from unsorted linked list class Node(): def __init__(self, data): self.data = data self.next = None class LinkedList(): def __init__(self): # Head of list self.head = None def remove_duplicates(self): ptr1 = None ptr2 = None dup = None ptr1 = self.head # Pick elements one by one while (ptr1 != None and ptr1.next != None): ptr2 = ptr1 # Compare the picked element with rest # of the elements while (ptr2.next != None): # If duplicate then delete it if (ptr1.data == ptr2.next.data): # Sequence of steps is important here dup = ptr2.next ptr2.next = ptr2.next.next else: ptr2 = ptr2.next ptr1 = ptr1.next # Function to print nodes in a # given linked list def printList(self): temp = self.head while(temp != None): print(temp.data, end=" ") temp = temp.next print() # Driver codelist = LinkedList()list.head = Node(10)list.head.next = Node(12)list.head.next.next = Node(11)list.head.next.next.next = Node(11)list.head.next.next.next.next = Node(12)list.head.next.next.next.next.next = Node(11)list.head.next.next.next.next.next.next = Node(10) print("Linked List before removing duplicates :")list.printList()list.remove_duplicates()print()print("Linked List after removing duplicates :")list.printList() # This code is contributed by maheshwaripiyush9 // C# program to remove duplicates from unsorted// linked listusing System;class List_ { Node head; class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to remove duplicates from an unsorted linked list */ void remove_duplicates() { Node ptr1 = null, ptr2 = null, dup = null; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2.next != null) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ dup = ptr2.next; ptr2.next = ptr2.next.next; } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Driver Code public static void Main(String[] args) { List_ list = new List_(); list.head = new Node(10); list.head.next = new Node(12); list.head.next.next = new Node(11); list.head.next.next.next = new Node(11); list.head.next.next.next.next = new Node(12); list.head.next.next.next.next.next = new Node(11); list.head.next.next.next.next.next.next = new Node(10); Console.WriteLine( "Linked List_ before removing duplicates : \n "); list.printList(list.head); list.remove_duplicates(); Console.WriteLine(""); Console.WriteLine( "Linked List_ after removing duplicates : \n "); list.printList(list.head); }} // This code is contributed by gauravrajput1 <script>// javascript program to remove duplicates from unsorted// linked list var head; class Node { constructor(val) { this.data = val; this.next = null; } } /* * Function to remove duplicates from an unsorted linked list */ function remove_duplicates() { var ptr1 = null, ptr2 = null, dup = null; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; /* * Compare the picked element with rest of the elements */ while (ptr2.next != null) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ dup = ptr2.next; ptr2.next = ptr2.next.next; } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } function printList( node) { while (node != null) { document.write(node.data + " "); node = node.next; } } head = new Node(10); head.next = new Node(12); head.next.next = new Node(11); head.next.next.next = new Node(11); head.next.next.next.next = new Node(12); head.next.next.next.next.next = new Node(11); head.next.next.next.next.next.next = new Node(10); document.write("Linked List before removing duplicates : <br/> "); printList(head); remove_duplicates(); document.write("<br/>"); document.write("Linked List after removing duplicates : <br/> "); printList(head); // This code contributed by aashish1995</script> Linked list before removing duplicates 10 12 11 11 12 11 10 Linked list after removing duplicates 10 12 11 Time Complexity: O(n^2) Auxiliary Space: O(1) METHOD 2 (Use Sorting) In general, Merge Sort is the best-suited sorting algorithm for sorting linked lists efficiently. 1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked list. O(nLogn) 2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n) Please note that this method doesn’t preserve the original order of elements.Time Complexity: O(nLogn) METHOD 3 (Use Hashing) We traverse the link list from head to end. For every newly encountered element, we check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table. C++ Java Python3 C# Javascript /* C++ Program to remove duplicates in an unsorted linked list */#include <bits/stdc++.h>using namespace std; /* A linked list node */struct Node { int data; struct Node* next;}; // Utility function to create a new Nodestruct Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Function to remove duplicates from a unsorted linked list */void removeDuplicates(struct Node* start){ // Hash to store seen values unordered_set<int> seen; /* Pick elements one by one */ struct Node* curr = start; struct Node* prev = NULL; while (curr != NULL) { // If current value is seen before if (seen.find(curr->data) != seen.end()) { prev->next = curr->next; delete (curr); } else { seen.insert(curr->data); prev = curr; } curr = prev->next; }} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ /* The constructed linked list is: 10->12->11->11->12->11->10*/ struct Node* start = newNode(10); start->next = newNode(12); start->next->next = newNode(11); start->next->next->next = newNode(11); start->next->next->next->next = newNode(12); start->next->next->next->next->next = newNode(11); start->next->next->next->next->next->next = newNode(10); printf("Linked list before removing duplicates : \n"); printList(start); removeDuplicates(start); printf("\nLinked list after removing duplicates : \n"); printList(start); return 0;} // Java program to remove duplicates// from unsorted linkedlist import java.util.HashSet; public class removeDuplicates { static class node { int val; node next; public node(int val) { this.val = val; } } /* Function to remove duplicates from a unsorted linked list */ static void removeDuplicate(node head) { // Hash to store seen values HashSet<Integer> hs = new HashSet<>(); /* Pick elements one by one */ node current = head; node prev = null; while (current != null) { int curval = current.val; // If current value is seen before if (hs.contains(curval)) { prev.next = current.next; } else { hs.add(curval); prev = current; } current = current.next; } } /* Function to print nodes in a given linked list */ static void printList(node head) { while (head != null) { System.out.print(head.val + " "); head = head.next; } } public static void main(String[] args) { /* The constructed linked list is: 10->12->11->11->12->11->10*/ node start = new node(10); start.next = new node(12); start.next.next = new node(11); start.next.next.next = new node(11); start.next.next.next.next = new node(12); start.next.next.next.next.next = new node(11); start.next.next.next.next.next.next = new node(10); System.out.println( "Linked list before removing duplicates :"); printList(start); removeDuplicate(start); System.out.println( "\nLinked list after removing duplicates :"); printList(start); }} // This code is contributed by Rishabh Mahrsee # Python3 program to remove duplicates# from unsorted linkedlist class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Function to print nodes in a # given linked list def printlist(self): temp = self.head while (temp): print(temp.data, end=" ") temp = temp.next # Function to remove duplicates from a # unsorted linked list def removeDuplicates(self, head): # Base case of empty list or # list with only one element if self.head is None or self.head.next is None: return head # Hash to store seen values hash = set() current = head hash.add(self.head.data) while current.next is not None: if current.next.data in hash: current.next = current.next.next else: hash.add(current.next.data) current = current.next return head # Driver codeif __name__ == "__main__": # Creating Empty list llist = LinkedList() llist.head = Node(10) second = Node(12) third = Node(11) fourth = Node(11) fifth = Node(12) sixth = Node(11) seventh = Node(10) # Connecting second and third llist.head.next = second second.next = third third.next = fourth fourth.next = fifth fifth.next = sixth sixth.next = seventh # Printing data print("Linked List before removing Duplicates.") llist.printlist() llist.removeDuplicates(llist.head) print("\nLinked List after removing duplicates.") llist.printlist() # This code is contributed by rajataro0 // C# program to remove duplicates// from unsorted linkedlistusing System;using System.Collections.Generic; class removeDuplicates { class node { public int val; public node next; public node(int val) { this.val = val; } } // Function to remove duplicates from a // unsorted linked list static void removeDuplicate(node head) { // Hash to store seen values HashSet<int> hs = new HashSet<int>(); // Pick elements one by one node current = head; node prev = null; while (current != null) { int curval = current.val; // If current value is seen before if (hs.Contains(curval)) { prev.next = current.next; } else { hs.Add(curval); prev = current; } current = current.next; } } // Function to print nodes in a // given linked list static void printList(node head) { while (head != null) { Console.Write(head.val + " "); head = head.next; } } // Driver code public static void Main(String[] args) { // The constructed linked list is: // 10->12->11->11->12->11->10 node start = new node(10); start.next = new node(12); start.next.next = new node(11); start.next.next.next = new node(11); start.next.next.next.next = new node(12); start.next.next.next.next.next = new node(11); start.next.next.next.next.next.next = new node(10); Console.WriteLine("Linked list before removing " + "duplicates :"); printList(start); removeDuplicate(start); Console.WriteLine("\nLinked list after removing " + "duplicates :"); printList(start); }} // This code is contributed by amal kumar choubey <script> // JavaScript program to remove duplicates// from unsorted linkedlist class node { constructor(val) { this.val = val; this.next = null; } } /* Function to remove duplicates from a unsorted linked list */ function removeDuplicate( head) { // Hash to store seen values var hs = new Set(); /* Pick elements one by one */ var current = head; var prev = null; while (current != null) { var curval = current.val; // If current value is seen before if (hs.has(curval)) { prev.next = current.next; } else { hs.add(curval); prev = current; } current = current.next; } } /* Function to print nodes in a given linked list */ function printList( head) { while (head != null) { document.write(head.val + " "); head = head.next; } } /* * The constructed linked list is: 10->12->11->11->12->11->10 */ start = new node(10); start.next = new node(12); start.next.next = new node(11); start.next.next.next = new node(11); start.next.next.next.next = new node(12); start.next.next.next.next.next = new node(11); start.next.next.next.next.next.next = new node(10); document.write( "Linked list before removing duplicates :<br/>" ); printList(start); removeDuplicate(start); document.write( "<br/>Linked list after removing duplicates :<br/>" ); printList(start); // This code is contributed by todaysgaurav </script> Linked list before removing duplicates : 10 12 11 11 12 11 10 Linked list after removing duplicates : 10 12 11 Thanks to bearwang for suggesting this method.Time Complexity: O(N) on average (assuming that hash table access time is O(1) on average). Auxiliary Space : O(N) As extra space is used to store the elements in the stack. –oI4Please write comments if you find any of the above explanations/algorithms incorrect, or a better ways to solve the same problem. GauravRajput1 Amal Kumar Choubey rajataro0 simranarora5sos aashish1995 todaysgaurav maheswaripiyush9 coder229coder mohitsinghal63 abhijeet19403 Amazon Merge Sort Linked List Amazon Linked List Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Implementing a Linked List in Java using Class Detect and Remove Loop in a Linked List Add two numbers represented by linked lists | Set 1 Queue - Linked List Implementation Function to check if a singly linked list is palindrome Implement a stack using singly linked list
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 311, "s": 52, "text": "Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43. " }, { "code": null, "e": 575, "s": 311, "text": "METHOD 1 (Using two loops) This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and the inner loop compares the picked element with the rest of the elements. Thanks to Gaurav Saxena for his help in writing this code." }, { "code": null, "e": 579, "s": 575, "text": "C++" }, { "code": null, "e": 584, "s": 579, "text": "Java" }, { "code": null, "e": 592, "s": 584, "text": "Python3" }, { "code": null, "e": 595, "s": 592, "text": "C#" }, { "code": null, "e": 606, "s": 595, "text": "Javascript" }, { "code": "/* C++ Program to remove duplicates in an unsorted linked list */#include <bits/stdc++.h>using namespace std; /* A linked list node */struct Node { int data; struct Node* next;}; // Utility function to create a new Nodestruct Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Function to remove duplicates from a unsorted linked list */void removeDuplicates(struct Node* start){ struct Node *ptr1, *ptr2, *dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2->next != NULL) { /* If duplicate then delete it */ if (ptr1->data == ptr2->next->data) { /* sequence of steps is important here */ dup = ptr2->next; ptr2->next = ptr2->next->next; delete (dup); } else /* This is tricky */ ptr2 = ptr2->next; } ptr1 = ptr1->next; }} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ /* The constructed linked list is: 10->12->11->11->12->11->10*/ struct Node* start = newNode(10); start->next = newNode(12); start->next->next = newNode(11); start->next->next->next = newNode(11); start->next->next->next->next = newNode(12); start->next->next->next->next->next = newNode(11); start->next->next->next->next->next->next = newNode(10); printf(\"Linked list before removing duplicates \"); printList(start); removeDuplicates(start); printf(\"\\nLinked list after removing duplicates \"); printList(start); return 0;}", "e": 2521, "s": 606, "text": null }, { "code": "// Java program to remove duplicates from unsorted// linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to remove duplicates from an unsorted linked list */ void remove_duplicates() { Node ptr1 = null, ptr2 = null, dup = null; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2.next != null) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ ptr2.next = ptr2.next.next; System.gc(); } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(10); list.head.next = new Node(12); list.head.next.next = new Node(11); list.head.next.next.next = new Node(11); list.head.next.next.next.next = new Node(12); list.head.next.next.next.next.next = new Node(11); list.head.next.next.next.next.next.next = new Node(10); System.out.println( \"Linked List before removing duplicates : \\n \"); list.printList(head); list.remove_duplicates(); System.out.println(\"\"); System.out.println( \"Linked List after removing duplicates : \\n \"); list.printList(head); }}// This code has been contributed by Mayank Jaiswal", "e": 4569, "s": 2521, "text": null }, { "code": "# Python3 program to remove duplicates# from unsorted linked list class Node(): def __init__(self, data): self.data = data self.next = None class LinkedList(): def __init__(self): # Head of list self.head = None def remove_duplicates(self): ptr1 = None ptr2 = None dup = None ptr1 = self.head # Pick elements one by one while (ptr1 != None and ptr1.next != None): ptr2 = ptr1 # Compare the picked element with rest # of the elements while (ptr2.next != None): # If duplicate then delete it if (ptr1.data == ptr2.next.data): # Sequence of steps is important here dup = ptr2.next ptr2.next = ptr2.next.next else: ptr2 = ptr2.next ptr1 = ptr1.next # Function to print nodes in a # given linked list def printList(self): temp = self.head while(temp != None): print(temp.data, end=\" \") temp = temp.next print() # Driver codelist = LinkedList()list.head = Node(10)list.head.next = Node(12)list.head.next.next = Node(11)list.head.next.next.next = Node(11)list.head.next.next.next.next = Node(12)list.head.next.next.next.next.next = Node(11)list.head.next.next.next.next.next.next = Node(10) print(\"Linked List before removing duplicates :\")list.printList()list.remove_duplicates()print()print(\"Linked List after removing duplicates :\")list.printList() # This code is contributed by maheshwaripiyush9", "e": 6187, "s": 4569, "text": null }, { "code": "// C# program to remove duplicates from unsorted// linked listusing System;class List_ { Node head; class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to remove duplicates from an unsorted linked list */ void remove_duplicates() { Node ptr1 = null, ptr2 = null, dup = null; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2.next != null) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ dup = ptr2.next; ptr2.next = ptr2.next.next; } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Driver Code public static void Main(String[] args) { List_ list = new List_(); list.head = new Node(10); list.head.next = new Node(12); list.head.next.next = new Node(11); list.head.next.next.next = new Node(11); list.head.next.next.next.next = new Node(12); list.head.next.next.next.next.next = new Node(11); list.head.next.next.next.next.next.next = new Node(10); Console.WriteLine( \"Linked List_ before removing duplicates : \\n \"); list.printList(list.head); list.remove_duplicates(); Console.WriteLine(\"\"); Console.WriteLine( \"Linked List_ after removing duplicates : \\n \"); list.printList(list.head); }} // This code is contributed by gauravrajput1", "e": 8294, "s": 6187, "text": null }, { "code": "<script>// javascript program to remove duplicates from unsorted// linked list var head; class Node { constructor(val) { this.data = val; this.next = null; } } /* * Function to remove duplicates from an unsorted linked list */ function remove_duplicates() { var ptr1 = null, ptr2 = null, dup = null; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null) { ptr2 = ptr1; /* * Compare the picked element with rest of the elements */ while (ptr2.next != null) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ dup = ptr2.next; ptr2.next = ptr2.next.next; } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } function printList( node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } head = new Node(10); head.next = new Node(12); head.next.next = new Node(11); head.next.next.next = new Node(11); head.next.next.next.next = new Node(12); head.next.next.next.next.next = new Node(11); head.next.next.next.next.next.next = new Node(10); document.write(\"Linked List before removing duplicates : <br/> \"); printList(head); remove_duplicates(); document.write(\"<br/>\"); document.write(\"Linked List after removing duplicates : <br/> \"); printList(head); // This code contributed by aashish1995</script>", "e": 10101, "s": 8294, "text": null }, { "code": null, "e": 10210, "s": 10101, "text": "Linked list before removing duplicates 10 12 11 11 12 11 10 \nLinked list after removing duplicates 10 12 11 " }, { "code": null, "e": 10234, "s": 10210, "text": "Time Complexity: O(n^2)" }, { "code": null, "e": 10256, "s": 10234, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 10696, "s": 10256, "text": "METHOD 2 (Use Sorting) In general, Merge Sort is the best-suited sorting algorithm for sorting linked lists efficiently. 1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked list. O(nLogn) 2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n) Please note that this method doesn’t preserve the original order of elements.Time Complexity: O(nLogn)" }, { "code": null, "e": 10903, "s": 10696, "text": "METHOD 3 (Use Hashing) We traverse the link list from head to end. For every newly encountered element, we check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table." }, { "code": null, "e": 10907, "s": 10903, "text": "C++" }, { "code": null, "e": 10912, "s": 10907, "text": "Java" }, { "code": null, "e": 10920, "s": 10912, "text": "Python3" }, { "code": null, "e": 10923, "s": 10920, "text": "C#" }, { "code": null, "e": 10934, "s": 10923, "text": "Javascript" }, { "code": "/* C++ Program to remove duplicates in an unsorted linked list */#include <bits/stdc++.h>using namespace std; /* A linked list node */struct Node { int data; struct Node* next;}; // Utility function to create a new Nodestruct Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} /* Function to remove duplicates from a unsorted linked list */void removeDuplicates(struct Node* start){ // Hash to store seen values unordered_set<int> seen; /* Pick elements one by one */ struct Node* curr = start; struct Node* prev = NULL; while (curr != NULL) { // If current value is seen before if (seen.find(curr->data) != seen.end()) { prev->next = curr->next; delete (curr); } else { seen.insert(curr->data); prev = curr; } curr = prev->next; }} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ /* The constructed linked list is: 10->12->11->11->12->11->10*/ struct Node* start = newNode(10); start->next = newNode(12); start->next->next = newNode(11); start->next->next->next = newNode(11); start->next->next->next->next = newNode(12); start->next->next->next->next->next = newNode(11); start->next->next->next->next->next->next = newNode(10); printf(\"Linked list before removing duplicates : \\n\"); printList(start); removeDuplicates(start); printf(\"\\nLinked list after removing duplicates : \\n\"); printList(start); return 0;}", "e": 12663, "s": 10934, "text": null }, { "code": "// Java program to remove duplicates// from unsorted linkedlist import java.util.HashSet; public class removeDuplicates { static class node { int val; node next; public node(int val) { this.val = val; } } /* Function to remove duplicates from a unsorted linked list */ static void removeDuplicate(node head) { // Hash to store seen values HashSet<Integer> hs = new HashSet<>(); /* Pick elements one by one */ node current = head; node prev = null; while (current != null) { int curval = current.val; // If current value is seen before if (hs.contains(curval)) { prev.next = current.next; } else { hs.add(curval); prev = current; } current = current.next; } } /* Function to print nodes in a given linked list */ static void printList(node head) { while (head != null) { System.out.print(head.val + \" \"); head = head.next; } } public static void main(String[] args) { /* The constructed linked list is: 10->12->11->11->12->11->10*/ node start = new node(10); start.next = new node(12); start.next.next = new node(11); start.next.next.next = new node(11); start.next.next.next.next = new node(12); start.next.next.next.next.next = new node(11); start.next.next.next.next.next.next = new node(10); System.out.println( \"Linked list before removing duplicates :\"); printList(start); removeDuplicate(start); System.out.println( \"\\nLinked list after removing duplicates :\"); printList(start); }} // This code is contributed by Rishabh Mahrsee", "e": 14502, "s": 12663, "text": null }, { "code": "# Python3 program to remove duplicates# from unsorted linkedlist class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Function to print nodes in a # given linked list def printlist(self): temp = self.head while (temp): print(temp.data, end=\" \") temp = temp.next # Function to remove duplicates from a # unsorted linked list def removeDuplicates(self, head): # Base case of empty list or # list with only one element if self.head is None or self.head.next is None: return head # Hash to store seen values hash = set() current = head hash.add(self.head.data) while current.next is not None: if current.next.data in hash: current.next = current.next.next else: hash.add(current.next.data) current = current.next return head # Driver codeif __name__ == \"__main__\": # Creating Empty list llist = LinkedList() llist.head = Node(10) second = Node(12) third = Node(11) fourth = Node(11) fifth = Node(12) sixth = Node(11) seventh = Node(10) # Connecting second and third llist.head.next = second second.next = third third.next = fourth fourth.next = fifth fifth.next = sixth sixth.next = seventh # Printing data print(\"Linked List before removing Duplicates.\") llist.printlist() llist.removeDuplicates(llist.head) print(\"\\nLinked List after removing duplicates.\") llist.printlist() # This code is contributed by rajataro0", "e": 16199, "s": 14502, "text": null }, { "code": "// C# program to remove duplicates// from unsorted linkedlistusing System;using System.Collections.Generic; class removeDuplicates { class node { public int val; public node next; public node(int val) { this.val = val; } } // Function to remove duplicates from a // unsorted linked list static void removeDuplicate(node head) { // Hash to store seen values HashSet<int> hs = new HashSet<int>(); // Pick elements one by one node current = head; node prev = null; while (current != null) { int curval = current.val; // If current value is seen before if (hs.Contains(curval)) { prev.next = current.next; } else { hs.Add(curval); prev = current; } current = current.next; } } // Function to print nodes in a // given linked list static void printList(node head) { while (head != null) { Console.Write(head.val + \" \"); head = head.next; } } // Driver code public static void Main(String[] args) { // The constructed linked list is: // 10->12->11->11->12->11->10 node start = new node(10); start.next = new node(12); start.next.next = new node(11); start.next.next.next = new node(11); start.next.next.next.next = new node(12); start.next.next.next.next.next = new node(11); start.next.next.next.next.next.next = new node(10); Console.WriteLine(\"Linked list before removing \" + \"duplicates :\"); printList(start); removeDuplicate(start); Console.WriteLine(\"\\nLinked list after removing \" + \"duplicates :\"); printList(start); }} // This code is contributed by amal kumar choubey", "e": 18106, "s": 16199, "text": null }, { "code": "<script> // JavaScript program to remove duplicates// from unsorted linkedlist class node { constructor(val) { this.val = val; this.next = null; } } /* Function to remove duplicates from a unsorted linked list */ function removeDuplicate( head) { // Hash to store seen values var hs = new Set(); /* Pick elements one by one */ var current = head; var prev = null; while (current != null) { var curval = current.val; // If current value is seen before if (hs.has(curval)) { prev.next = current.next; } else { hs.add(curval); prev = current; } current = current.next; } } /* Function to print nodes in a given linked list */ function printList( head) { while (head != null) { document.write(head.val + \" \"); head = head.next; } } /* * The constructed linked list is: 10->12->11->11->12->11->10 */ start = new node(10); start.next = new node(12); start.next.next = new node(11); start.next.next.next = new node(11); start.next.next.next.next = new node(12); start.next.next.next.next.next = new node(11); start.next.next.next.next.next.next = new node(10); document.write( \"Linked list before removing duplicates :<br/>\" ); printList(start); removeDuplicate(start); document.write( \"<br/>Linked list after removing duplicates :<br/>\" ); printList(start); // This code is contributed by todaysgaurav </script>", "e": 19845, "s": 18106, "text": null }, { "code": null, "e": 19960, "s": 19845, "text": "Linked list before removing duplicates : \n10 12 11 11 12 11 10 \nLinked list after removing duplicates : \n10 12 11 " }, { "code": null, "e": 20040, "s": 19960, "text": "Thanks to bearwang for suggesting this method.Time Complexity: O(N) on average " }, { "code": null, "e": 20101, "s": 20040, "text": "(assuming that hash table access time is O(1) on average). " }, { "code": null, "e": 20124, "s": 20101, "text": "Auxiliary Space : O(N)" }, { "code": null, "e": 20183, "s": 20124, "text": "As extra space is used to store the elements in the stack." }, { "code": null, "e": 20318, "s": 20183, "text": "–oI4Please write comments if you find any of the above explanations/algorithms incorrect, or a better ways to solve the same problem. " }, { "code": null, "e": 20334, "s": 20320, "text": "GauravRajput1" }, { "code": null, "e": 20353, "s": 20334, "text": "Amal Kumar Choubey" }, { "code": null, "e": 20363, "s": 20353, "text": "rajataro0" }, { "code": null, "e": 20379, "s": 20363, "text": "simranarora5sos" }, { "code": null, "e": 20391, "s": 20379, "text": "aashish1995" }, { "code": null, "e": 20404, "s": 20391, "text": "todaysgaurav" }, { "code": null, "e": 20421, "s": 20404, "text": "maheswaripiyush9" }, { "code": null, "e": 20435, "s": 20421, "text": "coder229coder" }, { "code": null, "e": 20450, "s": 20435, "text": "mohitsinghal63" }, { "code": null, "e": 20464, "s": 20450, "text": "abhijeet19403" }, { "code": null, "e": 20471, "s": 20464, "text": "Amazon" }, { "code": null, "e": 20482, "s": 20471, "text": "Merge Sort" }, { "code": null, "e": 20494, "s": 20482, "text": "Linked List" }, { "code": null, "e": 20501, "s": 20494, "text": "Amazon" }, { "code": null, "e": 20513, "s": 20501, "text": "Linked List" }, { "code": null, "e": 20524, "s": 20513, "text": "Merge Sort" }, { "code": null, "e": 20622, "s": 20524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20670, "s": 20622, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 20689, "s": 20670, "text": "LinkedList in Java" }, { "code": null, "e": 20721, "s": 20689, "text": "Introduction to Data Structures" }, { "code": null, "e": 20785, "s": 20721, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20832, "s": 20785, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 20872, "s": 20832, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 20924, "s": 20872, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 20959, "s": 20924, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 21015, "s": 20959, "text": "Function to check if a singly linked list is palindrome" } ]
Bash Scripting – While Loop
16 Feb, 2022 A while loop is a statement that iterates over a block of code till the condition specified is evaluated to true. We can use this statement or loop in our program when do not know how many times the condition is going to evaluate to false before evaluating to true. The syntax of a while loop in BASH is something like below: while [ condition ]; do # statements # commands done If the condition is false then the commands inside the while block are executed and are iterated again after checking the condition. Also if the condition is true the statements inside the while block are skipped and the statements after the while block are executed. The example of a while loop is as follows: #!/usr/bin/bash a=7 while [ $a -gt 4 ]; do echo $a ((a--)) done echo "Out of the loop" As we can see that the loop is iterated till the condition is true. As soon as the variable a becomes 4, the condition is evaluated to true and the loop skips the command block and starts executing the commands after the block. We can read a file with a while loop in BASH. By parsing certain parameters to the while loop condition, we can iterate over the file line by line or by other groups like characters or words. #!/usr/bin/bash file=temp.txt while read -r line; do echo $line done < "$file" We use the command read to actually fetch the lines or characters from the file. The read command is passed with -r argument which ignores the escaping of characters if the \ appears and hence it is parsed as its. We read a line from a file mentioned after the done statement. The read command reads a line from the mentioned file and the while loops end when the last line from the file is read ( no line is left to read). This is how we can read the contents of the file using a while loop in BASH. To create an infinite loop using a while loop statement. We don’t need to put any condition in the while loop and hence the loop iterates infinitely. The below is the example of an infinite while loop: #!/usr/bin/bash while : do echo "An Infinite loop" # We can press Ctrl + C to exit the script done Thus the while loop in the script is going to iterate for infinite time. We can manually break the loop or the script by CTRL + C. We can use a while loop to iterate over a fixed number of times, we can set the condition to be -le or less than equal to a number, and the loop will iterate till the iterator is less than or equal to the number provided in the condition. Also, we need to increment the iterator manually so to keep the loop iterator ticking, or else the loop will go on forever. #!/usr/bin/bash i=1 # the number 4 can be the limit to # iterate the loop while [ $i -le 4 ]; do echo $i ((i++)) done In the above example, we can see that the loop iterates a defined number of times. As we have initialized the counter to 1 and the condition is to iterate the loop till the iterator is less than or equal to the number in this case 4. Thus, we can change the number in the condition as per our requirement. We can use get ops options to read the input from the command line and if there are multiple arguments, we can check them and parse them one by one using a while loop. getopts is a tool to get user input from the command line, We can have multiple options to parse from the command line, and using getopts and while loops, we can make a professional-looking user input program. #!/bin/bash while getopts n:a: OPT do case "${OPT}" in n) name=${OPTARG};; a) age=${OPTARG};; *) echo "Invalid option" exit 1;; esac done printf "My name is $name and am $age years old\n" In this case, we have two options namely, the name and the age, you can have multiple options. We need to specify which option are we gonna use the switch case statements and from the command line using -shorthand option. In this case, we have used -n for name and -a for age. We also have a default or invalid case check to endure we do not parse wrong arguments. We can assign the value of the option using the OPTARG variable which parses the value provided to the option. The while loop here is used to iterate till there are no options passed from the command line. We check for the -n and -a option and iterate till the carriage return or enter key is pressed and there are no further options to be parsed. We can use C-styled while loop in BASH, the variables need to be evaluated with BASH style but the overall syntax feels like C. We can use the operators like <,>,<= and so on in the condition of the while loop and hence it is called like the C-styled while loop. #!/bin/bash i=0 while((i < 12)) do echo $i ((i+=2)) done In this example, we can see that the while loop has a condition with non-bash operators like -le, -ge, etc instead we use the C-styled operators in the condition. The rest of the loop is the basic loop as in BASH, the variable or iterator i is incremented by two as we can see in the last statement of the loop body. Thus the loop iterates over 5 times. We can perform operations on a file, like reading only a particular part of a file. If we have columns that are formatted in a particular fashion, we can use variables to assign them and print them one row data time. #!/bin/bash while read a b c do echo $b - $a done < wh.txt In this example, we have three rows, we read the contents by assigning them to the variables a,b, and c, it can be anything you like but remember to use them in the loop body. We can select a particular column like b and a and can print or perform any operations on them. This won’t be reflected in the file though as they are just the local script variables. We can write to a file by user input in a while loop. We can use the while loop to iterate till we manually exit out of the loop using CTRL + D by saving changes to the file or by CTRL + C for avoiding writing to the file. We use the read command to input the text from the command line and parse it to the file. #! /bin/bash file=wh.txt echo "Enter the content into the file $file" while read line do echo $line >> $file done So from the example above, we were able to enter text into a file using a while loop and read command. To exit out of the loop and save changes to the file, we use the CTRL+ D keys, and to exit out of the loop without saving anything into the file we can use the CTRL + C keys. Thus we enter the text from the command line to the text file using the read command and a while loop. Break and continue are essential in a program that deals with loop statements as they control the flow of the loop statements without any explicit conditions. We use break statements to exit out of the loop without waiting for the condition of the while loop to evaluate to true. This statement can be used within a loop block. This can be used to exit out of an infinite loop with a programmatic condition inside the loop and thus maintain the control of the loop. For example, we have a script that counts from 1 and forever. But we can programmatically break out of the loop using a break statement inside the body of the loop with a condition. #!/usr/bin/bash i=1 while : do echo $i if [ $i -eq 20 ]; then echo "This is end of the loop" break if ((i++)) done From the script and the execution, we can see that we were able to break or exit an infinite loop with a conditional statement and the break statement. Thus the break statement is used to get the control flow of a program/script from inside a while loop to break out of the loop without the loop condition evaluating to true. We can use the continue statement to do the opposite of the break statement. It will jump to the start of the loop block and iterate again. This can be used for skipping over certain commands for certain conditions and hence allows a change in the flow of the loop. For example, If we have a variable initialized to 1 and we want to display only the numbers divisible by five or in a certain pattern following a condition, we can use continue statements to do just that. This allows iterating over the loop in the desired manner. #!/usr/bin/bash i=1 while [ $i -lt 30 ]; do ((i++)) if [[ $(( $i % 5 )) -ne 0 ]]; then continue if echo $i done As we can see the continue statement, jumps to the beginning of the block and starts the execution of the commands by skipping the next commands inside the block. The while loop iterates for only the value of variable i being less than 30, thus the if condition checks if the variable i is divisible by 5, and if it’s not we iterate over again using continue and increment the value of the variable i. The variable i only gets echoed if it’s divisible by 5, thus the if condition is evaluated to false and we do not encounter a continue statement and carry with the normal flow of the loop. This is done to avoid logging of every number and only print the numbers which do not follow a pattern or condition in the if statement or other conditional statements. rkbhola5 Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples Conditional Statements | Shell Script Tail command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction UDP Server-Client implementation in C Cat command in Linux with examples echo command in Linux with Examples touch command in Linux with Examples chown command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Feb, 2022" }, { "code": null, "e": 296, "s": 28, "text": "A while loop is a statement that iterates over a block of code till the condition specified is evaluated to true. We can use this statement or loop in our program when do not know how many times the condition is going to evaluate to false before evaluating to true. " }, { "code": null, "e": 356, "s": 296, "text": "The syntax of a while loop in BASH is something like below:" }, { "code": null, "e": 419, "s": 356, "text": "while [ condition ];\ndo\n # statements\n # commands\ndone " }, { "code": null, "e": 688, "s": 419, "text": "If the condition is false then the commands inside the while block are executed and are iterated again after checking the condition. Also if the condition is true the statements inside the while block are skipped and the statements after the while block are executed. " }, { "code": null, "e": 731, "s": 688, "text": "The example of a while loop is as follows:" }, { "code": null, "e": 829, "s": 731, "text": "#!/usr/bin/bash \n\na=7\nwhile [ $a -gt 4 ];\ndo\n echo $a\n ((a--))\ndone\n\necho \"Out of the loop\"" }, { "code": null, "e": 1057, "s": 829, "text": "As we can see that the loop is iterated till the condition is true. As soon as the variable a becomes 4, the condition is evaluated to true and the loop skips the command block and starts executing the commands after the block." }, { "code": null, "e": 1253, "s": 1057, "text": "We can read a file with a while loop in BASH. By parsing certain parameters to the while loop condition, we can iterate over the file line by line or by other groups like characters or words. " }, { "code": null, "e": 1339, "s": 1253, "text": "#!/usr/bin/bash \n\nfile=temp.txt\n\nwhile read -r line;\ndo\n echo $line\ndone < \"$file\"" }, { "code": null, "e": 1766, "s": 1339, "text": "We use the command read to actually fetch the lines or characters from the file. The read command is passed with -r argument which ignores the escaping of characters if the \\ appears and hence it is parsed as its. We read a line from a file mentioned after the done statement. The read command reads a line from the mentioned file and the while loops end when the last line from the file is read ( no line is left to read). " }, { "code": null, "e": 1844, "s": 1766, "text": "This is how we can read the contents of the file using a while loop in BASH. " }, { "code": null, "e": 2046, "s": 1844, "text": "To create an infinite loop using a while loop statement. We don’t need to put any condition in the while loop and hence the loop iterates infinitely. The below is the example of an infinite while loop:" }, { "code": null, "e": 2151, "s": 2046, "text": "#!/usr/bin/bash \n\nwhile :\ndo\n echo \"An Infinite loop\"\n # We can press Ctrl + C to exit the script\ndone" }, { "code": null, "e": 2282, "s": 2151, "text": "Thus the while loop in the script is going to iterate for infinite time. We can manually break the loop or the script by CTRL + C." }, { "code": null, "e": 2646, "s": 2282, "text": "We can use a while loop to iterate over a fixed number of times, we can set the condition to be -le or less than equal to a number, and the loop will iterate till the iterator is less than or equal to the number provided in the condition. Also, we need to increment the iterator manually so to keep the loop iterator ticking, or else the loop will go on forever. " }, { "code": null, "e": 2776, "s": 2646, "text": "#!/usr/bin/bash \n\ni=1\n\n# the number 4 can be the limit to \n# iterate the loop\nwhile [ $i -le 4 ];\ndo\n echo $i\n ((i++))\ndone" }, { "code": null, "e": 3082, "s": 2776, "text": "In the above example, we can see that the loop iterates a defined number of times. As we have initialized the counter to 1 and the condition is to iterate the loop till the iterator is less than or equal to the number in this case 4. Thus, we can change the number in the condition as per our requirement." }, { "code": null, "e": 3460, "s": 3082, "text": "We can use get ops options to read the input from the command line and if there are multiple arguments, we can check them and parse them one by one using a while loop. getopts is a tool to get user input from the command line, We can have multiple options to parse from the command line, and using getopts and while loops, we can make a professional-looking user input program." }, { "code": null, "e": 3721, "s": 3460, "text": "#!/bin/bash\n\nwhile getopts n:a: OPT\ndo\n case \"${OPT}\"\n in\n n) name=${OPTARG};;\n a) age=${OPTARG};;\n *) echo \"Invalid option\"\n exit 1;;\n esac\ndone\n\nprintf \"My name is $name and am $age years old\\n\"" }, { "code": null, "e": 4198, "s": 3721, "text": "In this case, we have two options namely, the name and the age, you can have multiple options. We need to specify which option are we gonna use the switch case statements and from the command line using -shorthand option. In this case, we have used -n for name and -a for age. We also have a default or invalid case check to endure we do not parse wrong arguments. We can assign the value of the option using the OPTARG variable which parses the value provided to the option. " }, { "code": null, "e": 4436, "s": 4198, "text": "The while loop here is used to iterate till there are no options passed from the command line. We check for the -n and -a option and iterate till the carriage return or enter key is pressed and there are no further options to be parsed. " }, { "code": null, "e": 4700, "s": 4436, "text": "We can use C-styled while loop in BASH, the variables need to be evaluated with BASH style but the overall syntax feels like C. We can use the operators like <,>,<= and so on in the condition of the while loop and hence it is called like the C-styled while loop. " }, { "code": null, "e": 4764, "s": 4700, "text": "#!/bin/bash\n\ni=0\nwhile((i < 12))\ndo\n echo $i\n ((i+=2))\ndone" }, { "code": null, "e": 5118, "s": 4764, "text": "In this example, we can see that the while loop has a condition with non-bash operators like -le, -ge, etc instead we use the C-styled operators in the condition. The rest of the loop is the basic loop as in BASH, the variable or iterator i is incremented by two as we can see in the last statement of the loop body. Thus the loop iterates over 5 times." }, { "code": null, "e": 5336, "s": 5118, "text": "We can perform operations on a file, like reading only a particular part of a file. If we have columns that are formatted in a particular fashion, we can use variables to assign them and print them one row data time. " }, { "code": null, "e": 5401, "s": 5336, "text": "#!/bin/bash\n\nwhile read a b c \ndo\n echo $b - $a\ndone < wh.txt" }, { "code": null, "e": 5761, "s": 5401, "text": "In this example, we have three rows, we read the contents by assigning them to the variables a,b, and c, it can be anything you like but remember to use them in the loop body. We can select a particular column like b and a and can print or perform any operations on them. This won’t be reflected in the file though as they are just the local script variables." }, { "code": null, "e": 6075, "s": 5761, "text": "We can write to a file by user input in a while loop. We can use the while loop to iterate till we manually exit out of the loop using CTRL + D by saving changes to the file or by CTRL + C for avoiding writing to the file. We use the read command to input the text from the command line and parse it to the file. " }, { "code": null, "e": 6194, "s": 6075, "text": "#! /bin/bash\n\nfile=wh.txt\necho \"Enter the content into the file $file\"\nwhile read line\ndo\n echo $line >> $file\ndone" }, { "code": null, "e": 6576, "s": 6194, "text": "So from the example above, we were able to enter text into a file using a while loop and read command. To exit out of the loop and save changes to the file, we use the CTRL+ D keys, and to exit out of the loop without saving anything into the file we can use the CTRL + C keys. Thus we enter the text from the command line to the text file using the read command and a while loop." }, { "code": null, "e": 6736, "s": 6576, "text": "Break and continue are essential in a program that deals with loop statements as they control the flow of the loop statements without any explicit conditions. " }, { "code": null, "e": 7043, "s": 6736, "text": "We use break statements to exit out of the loop without waiting for the condition of the while loop to evaluate to true. This statement can be used within a loop block. This can be used to exit out of an infinite loop with a programmatic condition inside the loop and thus maintain the control of the loop." }, { "code": null, "e": 7226, "s": 7043, "text": "For example, we have a script that counts from 1 and forever. But we can programmatically break out of the loop using a break statement inside the body of the loop with a condition. " }, { "code": null, "e": 7379, "s": 7226, "text": "#!/usr/bin/bash \n\ni=1\nwhile :\ndo\n echo $i\n if [ $i -eq 20 ];\n then\n echo \"This is end of the loop\"\n break\n if\n ((i++))\ndone" }, { "code": null, "e": 7705, "s": 7379, "text": "From the script and the execution, we can see that we were able to break or exit an infinite loop with a conditional statement and the break statement. Thus the break statement is used to get the control flow of a program/script from inside a while loop to break out of the loop without the loop condition evaluating to true." }, { "code": null, "e": 7972, "s": 7705, "text": "We can use the continue statement to do the opposite of the break statement. It will jump to the start of the loop block and iterate again. This can be used for skipping over certain commands for certain conditions and hence allows a change in the flow of the loop. " }, { "code": null, "e": 8236, "s": 7972, "text": "For example, If we have a variable initialized to 1 and we want to display only the numbers divisible by five or in a certain pattern following a condition, we can use continue statements to do just that. This allows iterating over the loop in the desired manner." }, { "code": null, "e": 8378, "s": 8236, "text": "#!/usr/bin/bash \n\ni=1\nwhile [ $i -lt 30 ];\ndo\n ((i++))\n if [[ $(( $i % 5 )) -ne 0 ]];\n then\n continue\n if\n echo $i\ndone" }, { "code": null, "e": 9140, "s": 8378, "text": "As we can see the continue statement, jumps to the beginning of the block and starts the execution of the commands by skipping the next commands inside the block. The while loop iterates for only the value of variable i being less than 30, thus the if condition checks if the variable i is divisible by 5, and if it’s not we iterate over again using continue and increment the value of the variable i. The variable i only gets echoed if it’s divisible by 5, thus the if condition is evaluated to false and we do not encounter a continue statement and carry with the normal flow of the loop. This is done to avoid logging of every number and only print the numbers which do not follow a pattern or condition in the if statement or other conditional statements. " }, { "code": null, "e": 9149, "s": 9140, "text": "rkbhola5" }, { "code": null, "e": 9161, "s": 9149, "text": "Bash-Script" }, { "code": null, "e": 9168, "s": 9161, "text": "Picked" }, { "code": null, "e": 9179, "s": 9168, "text": "Linux-Unix" }, { "code": null, "e": 9277, "s": 9179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9312, "s": 9277, "text": "tar command in Linux with examples" }, { "code": null, "e": 9350, "s": 9312, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 9386, "s": 9350, "text": "Tail command in Linux with examples" }, { "code": null, "e": 9421, "s": 9386, "text": "scp command in Linux with Examples" }, { "code": null, "e": 9447, "s": 9421, "text": "Docker - COPY Instruction" }, { "code": null, "e": 9485, "s": 9447, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 9520, "s": 9485, "text": "Cat command in Linux with examples" }, { "code": null, "e": 9556, "s": 9520, "text": "echo command in Linux with Examples" }, { "code": null, "e": 9593, "s": 9556, "text": "touch command in Linux with Examples" } ]
UUID() function in MySQL
16 Dec, 2020 This function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”.It is designed as a number that is universally unique. Two UUID values are expected to be distinct, even they are generated on two independent servers. In MySQL, a UUID value is a 128-bit number represented as a utf8 string, and the format in hexadecimal number will be as follows. Example – aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee Here, the first three numbers are generated from the low, middle, and high parts of a timestamp. As you can see that in the above format fourth place digits code will preserve temporal uniqueness and fifth place code will provide spatial uniqueness and it is an IEEE 802 node number. Syntax : UUID() Parameter :This method does not any parameter.Returns :It returns a Universal Unique Identifier number. Example-1 :Generating a Universal Unique Identifier value with the help of UUID Function. SELECT UUID() AS UUID_Value ; Output : Example-2 :Whenever we will use UUID function we will get different Universal Unique Identifier value. Lets check it. SELECT UUID() AS UUID_VALUE1, UUID() AS UUID_VALUE2, UUID() AS UUID_VALUE3 ; Output : Example-3 :In this example, we will use UUID as a primary key in a table. To demonstrate create a table named OrderDetails. CREATE TABLE OrderDetails( OrderId BINARY(16) PRIMARY KEY, ProductName VARCHAR(100) NOT NULL, Price DECIMAL(10, 2) NOT NULL, ExpectedDelivery DATE NOT NULL ); Now, inserting data into OrderDetails table. Here, We will use UUID and UUID_TO_BIN() functions to assign the value in OrderId Column. INSERT INTO OrderDetails(OrderId, ProductName, Price, ExpectedDelivery) VALUES(UUID_TO_BIN(UUID()), 'Asus Rog', 90000.00, '2020-12-20'), (UUID_TO_BIN(UUID()), 'Acer Predator', 100000.00, '2020-12-18'), (UUID_TO_BIN(UUID()), 'Lenovo Legion', 85000.00, '2020-12-19'), (UUID_TO_BIN(UUID()), 'Hp Omen', 70000.00, '2020-12-18'), (UUID_TO_BIN(UUID()), 'Dell Inspiron', 65000.00, '2020-12-23'), (UUID_TO_BIN(UUID()), 'Acer Nitro', 60000.00, '2020-12-22'), (UUID_TO_BIN(UUID()), 'Asus Tuf', 80000.00, '2020-12-19'); Next we will use the following command to check the table. SELECT * from OrderDetails; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2020" }, { "code": null, "e": 476, "s": 28, "text": "This function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”.It is designed as a number that is universally unique. Two UUID values are expected to be distinct, even they are generated on two independent servers. In MySQL, a UUID value is a 128-bit number represented as a utf8 string, and the format in hexadecimal number will be as follows." }, { "code": null, "e": 486, "s": 476, "text": "Example –" }, { "code": null, "e": 524, "s": 486, "text": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\n" }, { "code": null, "e": 808, "s": 524, "text": "Here, the first three numbers are generated from the low, middle, and high parts of a timestamp. As you can see that in the above format fourth place digits code will preserve temporal uniqueness and fifth place code will provide spatial uniqueness and it is an IEEE 802 node number." }, { "code": null, "e": 817, "s": 808, "text": "Syntax :" }, { "code": null, "e": 824, "s": 817, "text": "UUID()" }, { "code": null, "e": 928, "s": 824, "text": "Parameter :This method does not any parameter.Returns :It returns a Universal Unique Identifier number." }, { "code": null, "e": 1018, "s": 928, "text": "Example-1 :Generating a Universal Unique Identifier value with the help of UUID Function." }, { "code": null, "e": 1049, "s": 1018, "text": "SELECT UUID() \nAS UUID_Value ;" }, { "code": null, "e": 1058, "s": 1049, "text": "Output :" }, { "code": null, "e": 1176, "s": 1058, "text": "Example-2 :Whenever we will use UUID function we will get different Universal Unique Identifier value. Lets check it." }, { "code": null, "e": 1262, "s": 1176, "text": " SELECT UUID() \nAS \nUUID_VALUE1, \nUUID() \nAS UUID_VALUE2, \nUUID() \nAS UUID_VALUE3 ;" }, { "code": null, "e": 1271, "s": 1262, "text": "Output :" }, { "code": null, "e": 1395, "s": 1271, "text": "Example-3 :In this example, we will use UUID as a primary key in a table. To demonstrate create a table named OrderDetails." }, { "code": null, "e": 1567, "s": 1395, "text": "CREATE TABLE OrderDetails(\n OrderId BINARY(16) PRIMARY KEY,\n ProductName VARCHAR(100) NOT NULL,\n Price DECIMAL(10, 2) NOT NULL,\n ExpectedDelivery DATE NOT NULL\n);\n" }, { "code": null, "e": 1702, "s": 1567, "text": "Now, inserting data into OrderDetails table. Here, We will use UUID and UUID_TO_BIN() functions to assign the value in OrderId Column." }, { "code": null, "e": 2246, "s": 1702, "text": "INSERT INTO OrderDetails(OrderId, ProductName, Price, ExpectedDelivery)\nVALUES(UUID_TO_BIN(UUID()), 'Asus Rog', 90000.00, '2020-12-20'),\n (UUID_TO_BIN(UUID()), 'Acer Predator', 100000.00, '2020-12-18'),\n (UUID_TO_BIN(UUID()), 'Lenovo Legion', 85000.00, '2020-12-19'),\n (UUID_TO_BIN(UUID()), 'Hp Omen', 70000.00, '2020-12-18'),\n (UUID_TO_BIN(UUID()), 'Dell Inspiron', 65000.00, '2020-12-23'),\n (UUID_TO_BIN(UUID()), 'Acer Nitro', 60000.00, '2020-12-22'),\n (UUID_TO_BIN(UUID()), 'Asus Tuf', 80000.00, '2020-12-19');" }, { "code": null, "e": 2305, "s": 2246, "text": "Next we will use the following command to check the table." }, { "code": null, "e": 2334, "s": 2305, "text": "SELECT * from OrderDetails;" }, { "code": null, "e": 2343, "s": 2334, "text": "Output :" }, { "code": null, "e": 2352, "s": 2343, "text": "DBMS-SQL" }, { "code": null, "e": 2358, "s": 2352, "text": "mysql" }, { "code": null, "e": 2362, "s": 2358, "text": "SQL" }, { "code": null, "e": 2366, "s": 2362, "text": "SQL" } ]
unordered_multiset and its uses
19 Oct, 2021 We have discussed about unordered_set in our previous post the problem with unordered_set is that, it is not possible to store duplicate entries in that data structure. For example if we have some value v already in unordered_set, inserting v again will have no effect. To handle this duplication unordered_multiset should be used, it can store duplicate elements also. Internally when an existing value is inserted, the data structure increases its count which is associated with each value. As count of each value is stored in unordered_multiset, it takes more space than unordered_set (if all values are distinct). The internal implementation of unordered_multiset is same as that of unordered_set and also uses hash table for searching, just the count value is associated with each value in former one. Due to hashing of elements it has no particular order of storing the elements so all element can come in any order but duplicate element comes together. All operation on unordered_multiset takes constant time on average but can go upto linear in worst case. Unordered_multiset supports many function which are demonstrated in below code : C // C++ program to demonstrate various function// of unordered_multiset#include <bits/stdc++.h>using namespace std; // making typedef for short declarationtypedef unordered_multiset<int>::iterator umit; // Utility function to print unordered_multisetvoid printUset(unordered_multiset<int> ums){ // begin() returns iterator to first element of set umit it = ums.begin(); for (; it != ums.end(); it++) cout << *it << " "; cout << endl;} // Driver program to check all functionint main(){ // empty initialization unordered_multiset<int> ums1; // Initialization by intializer list unordered_multiset<int> ums2 ({1, 3, 1, 7, 2, 3, 4, 1, 6}); // Initialization by assignment ums1 = {2, 7, 2, 5, 0, 3, 7, 5}; // empty() function return true if set is empty // otherwise false if (ums1.empty()) cout << "unordered multiset 1 is empty\n"; else cout << "unordered multiset 1 is not empty\n"; // size() function returns total number of elements // in data structure cout << "The size of unordered multiset 2 is : " << ums2.size() << endl; printUset(ums1); ums1.insert(7); printUset(ums1); int val = 3; // find function returns iterator to first position // of val, if exist otherwise it returns iterator // to end if (ums1.find(val) != ums1.end()) cout << "unordered multiset 1 contains " << val << endl; else cout << "unordered multiset 1 does not contains " << val << endl; // count function returns total number of occurrence in set val = 5; int cnt = ums1.count(val); cout << val << " appears " << cnt << " times in unordered multiset 1 \n"; val = 9; // if count return >0 value then element exist otherwise not if (ums1.count(val)) cout << "unordered multiset 1 contains " << val << endl; else cout << "unordered multiset 1 does not contains " << val << endl; val = 1; // equal_range returns a pair, where first is iterator // to first position of val and second it iterator to // last position to val pair<umit, umit> erange_it = ums2.equal_range(val); if (erange_it.first != erange_it.second) cout << val << " appeared atleast once in " "unoredered_multiset \n"; printUset(ums2); // erase function deletes all instances of val ums2.erase(val); printUset(ums2); // clear function deletes all entries from set ums1.clear(); ums2.clear(); if (ums1.empty()) cout << "unordered multiset 1 is empty\n"; else cout << "unordered multiset 1 is not empty\n";} Output : unordered multiset 1 is not empty The size of unordered multiset 2 is : 9 3 0 5 5 7 7 2 2 3 0 5 5 7 7 7 2 2 unordered multiset 1 contains 3 5 appears 2 times in unordered multiset 1 unordered multiset 1 does not contains 9 1 appeared atleast once in unoredered_multiset 6 4 2 7 3 3 1 1 1 6 4 2 7 3 3 unordered multiset 1 is empty As we can see most of the operation work similar to that of unordered_set but some things to note are: equal_range(val) function returns a pair of type where first iterator points to first position of val and second points to last position of val in data structure. erase(val) function deletes all its instances from the data structure for example if some value v has occurred t times in unordered_multiset and when erase is called, v is deleted completely which is not a expected behavior many times.We can delete only one copy of some value by using find function and iterator version of erase, as find function returns iterator to first position of found value we can pass this iterator to erase instead of actual value to delete only one copy, the code for doing this is shown below : CPP // C++ program to delete one copy from unordered set#include <bits/stdc++.h>using namespace std; // making typedef for short declarationtypedef unordered_multiset<int>::iterator umit; // Utility function to print unordered_multisetvoid printUset(unordered_multiset<int> ums){ // begin() returns iterator to first element of // set umit it = ums.begin(); for (; it != ums.end(); it++) cout << *it << " "; cout << endl;} // function to delete one copy of val from setvoid erase_one_entry(unordered_multiset<int>& ums, int val){ // find returns iterator to first position umit it = ums.find(val); // if element is there then erasing that if (it != ums.end()) ums.erase(it);} // Driver program to check above functionint main(){ // initializing multiset by initializer list unordered_multiset<int> ums ({1, 3, 1, 7, 2, 3, 4, 1, 6}); int val = 1; printUset(ums); erase_one_entry(ums, val); printUset(ums);} Output : 6 4 2 7 3 3 1 1 1 6 4 2 7 3 3 1 1 Methods of unordered_multiset: insert()– Inserts new elements in the unordered_multiset. Thus increases the container size. begin()– Returns an iterator pointing to the first element in the container or to the first element in one of its bucket. end()– Returns an iterator pointing to the position immediately after the last element in the container or to the position immediately after the last element in one of its bucket. empty()– It returns true if the unordered_multiset container is empty. Otherwise, it returns false. find()– Returns an iterator which points to the position which has the element val. cbegin()– Returns a constant iterator pointing to the first element in the container or to the first element in one of its bucket. cend()– Returns a constant iterator pointing to the position immediately after the last element in the container or to the position immediately after the last element in one of its bucket. equal_range()– Returns the range in which all the elements are equal to a given value. emplace()– Inserts a new element in the unordered_multiset container. clear()– Clears the contents of the unordered_multiset container. count()– Returns the count of elements in the unordered_multiset container which is equal to a given value. size()– The size() method of unordered_multiset is used to count the number of elements of unordered_set it is called with. max_size– The max_size() of unordered_multiset takes the maximum number of elements that the unordered_multiset container is able to hold. swap()– Swaps the contents of two unordered_multiset containers. erase() – Used to remove either a single element or, all elements with a definite value or, a range of elements ranging from start(inclusive) to end(exclusive). bucket()– Returns the bucket number in which a given element is. Bucket size varies from 0 to bucket_count-1. bucket_size()– Returns the number of elements in the bucket which has the element val. reserve()– The reverse() function of unordered_multiset sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements. max_bucket_count()– Returns the maximum number of buckets that the unordered multiset container can have. load_factor()– Returns the current load factor in the unordered_multiset container. max_load_factor()– Returns the maximum load factor of the unordered_multiset container. bucket_count()– Returns the total number of buckets in the unordered_multiset container. hash_function()– This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it. rehash()– Sets the number of buckets in the container to N or more. key_eq()– Returns a boolean value according to the comparison. emplace_hint()– Inserts a new element in the unordered_multiset container. get_allocator– This function gets the stored allocator object and returns the allocator object which is used to construct the container. operator =– The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_multiset to another unordered_multiset and unordered_multiset::operator= is the corresponding operator function. Recent Articles on unordered_multisetThis article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nidhi_biet preethibr1 saurabh1990aror cpp-containers-library CPP-Library cpp-unordered_multiset STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Initialize a vector in C++ (7 different ways) vector erase() and clear() in C++ Inheritance in C++ Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Oct, 2021" }, { "code": null, "e": 1200, "s": 52, "text": "We have discussed about unordered_set in our previous post the problem with unordered_set is that, it is not possible to store duplicate entries in that data structure. For example if we have some value v already in unordered_set, inserting v again will have no effect. To handle this duplication unordered_multiset should be used, it can store duplicate elements also. Internally when an existing value is inserted, the data structure increases its count which is associated with each value. As count of each value is stored in unordered_multiset, it takes more space than unordered_set (if all values are distinct). The internal implementation of unordered_multiset is same as that of unordered_set and also uses hash table for searching, just the count value is associated with each value in former one. Due to hashing of elements it has no particular order of storing the elements so all element can come in any order but duplicate element comes together. All operation on unordered_multiset takes constant time on average but can go upto linear in worst case. Unordered_multiset supports many function which are demonstrated in below code : " }, { "code": null, "e": 1202, "s": 1200, "text": "C" }, { "code": "// C++ program to demonstrate various function// of unordered_multiset#include <bits/stdc++.h>using namespace std; // making typedef for short declarationtypedef unordered_multiset<int>::iterator umit; // Utility function to print unordered_multisetvoid printUset(unordered_multiset<int> ums){ // begin() returns iterator to first element of set umit it = ums.begin(); for (; it != ums.end(); it++) cout << *it << \" \"; cout << endl;} // Driver program to check all functionint main(){ // empty initialization unordered_multiset<int> ums1; // Initialization by intializer list unordered_multiset<int> ums2 ({1, 3, 1, 7, 2, 3, 4, 1, 6}); // Initialization by assignment ums1 = {2, 7, 2, 5, 0, 3, 7, 5}; // empty() function return true if set is empty // otherwise false if (ums1.empty()) cout << \"unordered multiset 1 is empty\\n\"; else cout << \"unordered multiset 1 is not empty\\n\"; // size() function returns total number of elements // in data structure cout << \"The size of unordered multiset 2 is : \" << ums2.size() << endl; printUset(ums1); ums1.insert(7); printUset(ums1); int val = 3; // find function returns iterator to first position // of val, if exist otherwise it returns iterator // to end if (ums1.find(val) != ums1.end()) cout << \"unordered multiset 1 contains \" << val << endl; else cout << \"unordered multiset 1 does not contains \" << val << endl; // count function returns total number of occurrence in set val = 5; int cnt = ums1.count(val); cout << val << \" appears \" << cnt << \" times in unordered multiset 1 \\n\"; val = 9; // if count return >0 value then element exist otherwise not if (ums1.count(val)) cout << \"unordered multiset 1 contains \" << val << endl; else cout << \"unordered multiset 1 does not contains \" << val << endl; val = 1; // equal_range returns a pair, where first is iterator // to first position of val and second it iterator to // last position to val pair<umit, umit> erange_it = ums2.equal_range(val); if (erange_it.first != erange_it.second) cout << val << \" appeared atleast once in \" \"unoredered_multiset \\n\"; printUset(ums2); // erase function deletes all instances of val ums2.erase(val); printUset(ums2); // clear function deletes all entries from set ums1.clear(); ums2.clear(); if (ums1.empty()) cout << \"unordered multiset 1 is empty\\n\"; else cout << \"unordered multiset 1 is not empty\\n\";}", "e": 3915, "s": 1202, "text": null }, { "code": null, "e": 3925, "s": 3915, "text": "Output : " }, { "code": null, "e": 4261, "s": 3925, "text": "unordered multiset 1 is not empty\nThe size of unordered multiset 2 is : 9\n3 0 5 5 7 7 2 2 \n3 0 5 5 7 7 7 2 2 \nunordered multiset 1 contains 3\n5 appears 2 times in unordered multiset 1 \nunordered multiset 1 does not contains 9\n1 appeared atleast once in unoredered_multiset \n6 4 2 7 3 3 1 1 1 \n6 4 2 7 3 3 \nunordered multiset 1 is empty" }, { "code": null, "e": 5052, "s": 4261, "text": "As we can see most of the operation work similar to that of unordered_set but some things to note are: equal_range(val) function returns a pair of type where first iterator points to first position of val and second points to last position of val in data structure. erase(val) function deletes all its instances from the data structure for example if some value v has occurred t times in unordered_multiset and when erase is called, v is deleted completely which is not a expected behavior many times.We can delete only one copy of some value by using find function and iterator version of erase, as find function returns iterator to first position of found value we can pass this iterator to erase instead of actual value to delete only one copy, the code for doing this is shown below : " }, { "code": null, "e": 5056, "s": 5052, "text": "CPP" }, { "code": "// C++ program to delete one copy from unordered set#include <bits/stdc++.h>using namespace std; // making typedef for short declarationtypedef unordered_multiset<int>::iterator umit; // Utility function to print unordered_multisetvoid printUset(unordered_multiset<int> ums){ // begin() returns iterator to first element of // set umit it = ums.begin(); for (; it != ums.end(); it++) cout << *it << \" \"; cout << endl;} // function to delete one copy of val from setvoid erase_one_entry(unordered_multiset<int>& ums, int val){ // find returns iterator to first position umit it = ums.find(val); // if element is there then erasing that if (it != ums.end()) ums.erase(it);} // Driver program to check above functionint main(){ // initializing multiset by initializer list unordered_multiset<int> ums ({1, 3, 1, 7, 2, 3, 4, 1, 6}); int val = 1; printUset(ums); erase_one_entry(ums, val); printUset(ums);}", "e": 6077, "s": 5056, "text": null }, { "code": null, "e": 6086, "s": 6077, "text": "Output :" }, { "code": null, "e": 6122, "s": 6086, "text": "6 4 2 7 3 3 1 1 1 \n6 4 2 7 3 3 1 1 " }, { "code": null, "e": 6155, "s": 6122, "text": "Methods of unordered_multiset: " }, { "code": null, "e": 6248, "s": 6155, "text": "insert()– Inserts new elements in the unordered_multiset. Thus increases the container size." }, { "code": null, "e": 6370, "s": 6248, "text": "begin()– Returns an iterator pointing to the first element in the container or to the first element in one of its bucket." }, { "code": null, "e": 6550, "s": 6370, "text": "end()– Returns an iterator pointing to the position immediately after the last element in the container or to the position immediately after the last element in one of its bucket." }, { "code": null, "e": 6650, "s": 6550, "text": "empty()– It returns true if the unordered_multiset container is empty. Otherwise, it returns false." }, { "code": null, "e": 6734, "s": 6650, "text": "find()– Returns an iterator which points to the position which has the element val." }, { "code": null, "e": 6865, "s": 6734, "text": "cbegin()– Returns a constant iterator pointing to the first element in the container or to the first element in one of its bucket." }, { "code": null, "e": 7054, "s": 6865, "text": "cend()– Returns a constant iterator pointing to the position immediately after the last element in the container or to the position immediately after the last element in one of its bucket." }, { "code": null, "e": 7141, "s": 7054, "text": "equal_range()– Returns the range in which all the elements are equal to a given value." }, { "code": null, "e": 7211, "s": 7141, "text": "emplace()– Inserts a new element in the unordered_multiset container." }, { "code": null, "e": 7277, "s": 7211, "text": "clear()– Clears the contents of the unordered_multiset container." }, { "code": null, "e": 7385, "s": 7277, "text": "count()– Returns the count of elements in the unordered_multiset container which is equal to a given value." }, { "code": null, "e": 7509, "s": 7385, "text": "size()– The size() method of unordered_multiset is used to count the number of elements of unordered_set it is called with." }, { "code": null, "e": 7648, "s": 7509, "text": "max_size– The max_size() of unordered_multiset takes the maximum number of elements that the unordered_multiset container is able to hold." }, { "code": null, "e": 7713, "s": 7648, "text": "swap()– Swaps the contents of two unordered_multiset containers." }, { "code": null, "e": 7874, "s": 7713, "text": "erase() – Used to remove either a single element or, all elements with a definite value or, a range of elements ranging from start(inclusive) to end(exclusive)." }, { "code": null, "e": 7984, "s": 7874, "text": "bucket()– Returns the bucket number in which a given element is. Bucket size varies from 0 to bucket_count-1." }, { "code": null, "e": 8071, "s": 7984, "text": "bucket_size()– Returns the number of elements in the bucket which has the element val." }, { "code": null, "e": 8242, "s": 8071, "text": "reserve()– The reverse() function of unordered_multiset sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements." }, { "code": null, "e": 8348, "s": 8242, "text": "max_bucket_count()– Returns the maximum number of buckets that the unordered multiset container can have." }, { "code": null, "e": 8432, "s": 8348, "text": "load_factor()– Returns the current load factor in the unordered_multiset container." }, { "code": null, "e": 8520, "s": 8432, "text": "max_load_factor()– Returns the maximum load factor of the unordered_multiset container." }, { "code": null, "e": 8609, "s": 8520, "text": "bucket_count()– Returns the total number of buckets in the unordered_multiset container." }, { "code": null, "e": 8755, "s": 8609, "text": "hash_function()– This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it." }, { "code": null, "e": 8823, "s": 8755, "text": "rehash()– Sets the number of buckets in the container to N or more." }, { "code": null, "e": 8886, "s": 8823, "text": "key_eq()– Returns a boolean value according to the comparison." }, { "code": null, "e": 8961, "s": 8886, "text": "emplace_hint()– Inserts a new element in the unordered_multiset container." }, { "code": null, "e": 9098, "s": 8961, "text": "get_allocator– This function gets the stored allocator object and returns the allocator object which is used to construct the container." }, { "code": null, "e": 9294, "s": 9098, "text": "operator =– The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_multiset to another unordered_multiset and unordered_multiset::operator= is the corresponding operator function." }, { "code": null, "e": 9504, "s": 9294, "text": "Recent Articles on unordered_multisetThis article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 9515, "s": 9504, "text": "nidhi_biet" }, { "code": null, "e": 9526, "s": 9515, "text": "preethibr1" }, { "code": null, "e": 9542, "s": 9526, "text": "saurabh1990aror" }, { "code": null, "e": 9565, "s": 9542, "text": "cpp-containers-library" }, { "code": null, "e": 9577, "s": 9565, "text": "CPP-Library" }, { "code": null, "e": 9600, "s": 9577, "text": "cpp-unordered_multiset" }, { "code": null, "e": 9604, "s": 9600, "text": "STL" }, { "code": null, "e": 9615, "s": 9604, "text": "C Language" }, { "code": null, "e": 9619, "s": 9615, "text": "C++" }, { "code": null, "e": 9623, "s": 9619, "text": "STL" }, { "code": null, "e": 9627, "s": 9623, "text": "CPP" }, { "code": null, "e": 9725, "s": 9627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9742, "s": 9725, "text": "Substring in C++" }, { "code": null, "e": 9764, "s": 9742, "text": "Function Pointer in C" }, { "code": null, "e": 9799, "s": 9764, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 9845, "s": 9799, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 9890, "s": 9845, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 9908, "s": 9890, "text": "Vector in C++ STL" }, { "code": null, "e": 9954, "s": 9908, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 9988, "s": 9954, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 10007, "s": 9988, "text": "Inheritance in C++" } ]
LinkedList element() method in Java with Examples
10 Dec, 2018 The element() method of java.util.LinkedList class retrieves, but does not remove, the head (first element) of this list. Syntax: public E element() Return Value: This method returns the head of this list. Below are the examples to illustrate the element() method Example 1: // Java program to demonstrate// element() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of LinkedList<Integer> LinkedList<Integer> list = new LinkedList<Integer>(); // add some elements to list list.add(10); list.add(20); list.add(30); // print the linked list System.out.println("LinkedList : " + list); // getting the head of list // using element() method int value = list.element(); // print the head of list System.out.println("Head of list : " + value); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} LinkedList : [10, 20, 30] Head of list : 10 Example 2: // Java program to demonstrate// element() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of LinkedList<String> LinkedList<String> list = new LinkedList<String>(); // add some elements to list list.add("A"); list.add("B"); list.add("C"); // print the linked list System.out.println("LinkedList : " + list); // getting the head of list // using element() method String value = list.element(); // print the head of list System.out.println("Head of list : " + value); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} LinkedList : [A, B, C] Head of list : A Java - util package Java-Collections Java-Functions java-LinkedList Java Java Java-Collections 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": "\n10 Dec, 2018" }, { "code": null, "e": 150, "s": 28, "text": "The element() method of java.util.LinkedList class retrieves, but does not remove, the head (first element) of this list." }, { "code": null, "e": 158, "s": 150, "text": "Syntax:" }, { "code": null, "e": 177, "s": 158, "text": "public E element()" }, { "code": null, "e": 234, "s": 177, "text": "Return Value: This method returns the head of this list." }, { "code": null, "e": 292, "s": 234, "text": "Below are the examples to illustrate the element() method" }, { "code": null, "e": 303, "s": 292, "text": "Example 1:" }, { "code": "// Java program to demonstrate// element() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of LinkedList<Integer> LinkedList<Integer> list = new LinkedList<Integer>(); // add some elements to list list.add(10); list.add(20); list.add(30); // print the linked list System.out.println(\"LinkedList : \" + list); // getting the head of list // using element() method int value = list.element(); // print the head of list System.out.println(\"Head of list : \" + value); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 1162, "s": 303, "text": null }, { "code": null, "e": 1207, "s": 1162, "text": "LinkedList : [10, 20, 30]\nHead of list : 10\n" }, { "code": null, "e": 1218, "s": 1207, "text": "Example 2:" }, { "code": "// Java program to demonstrate// element() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of LinkedList<String> LinkedList<String> list = new LinkedList<String>(); // add some elements to list list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); // print the linked list System.out.println(\"LinkedList : \" + list); // getting the head of list // using element() method String value = list.element(); // print the head of list System.out.println(\"Head of list : \" + value); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 2079, "s": 1218, "text": null }, { "code": null, "e": 2120, "s": 2079, "text": "LinkedList : [A, B, C]\nHead of list : A\n" }, { "code": null, "e": 2140, "s": 2120, "text": "Java - util package" }, { "code": null, "e": 2157, "s": 2140, "text": "Java-Collections" }, { "code": null, "e": 2172, "s": 2157, "text": "Java-Functions" }, { "code": null, "e": 2188, "s": 2172, "text": "java-LinkedList" }, { "code": null, "e": 2193, "s": 2188, "text": "Java" }, { "code": null, "e": 2198, "s": 2193, "text": "Java" }, { "code": null, "e": 2215, "s": 2198, "text": "Java-Collections" }, { "code": null, "e": 2313, "s": 2215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2328, "s": 2313, "text": "Stream In Java" }, { "code": null, "e": 2349, "s": 2328, "text": "Introduction to Java" }, { "code": null, "e": 2370, "s": 2349, "text": "Constructors in Java" }, { "code": null, "e": 2389, "s": 2370, "text": "Exceptions in Java" }, { "code": null, "e": 2406, "s": 2389, "text": "Generics in Java" }, { "code": null, "e": 2436, "s": 2406, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2462, "s": 2436, "text": "Java Programming Examples" }, { "code": null, "e": 2478, "s": 2462, "text": "Strings in Java" }, { "code": null, "e": 2515, "s": 2478, "text": "Differences between JDK, JRE and JVM" } ]
Understanding “register” keyword in C
21 Aug, 2019 Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in register. 1) If you use & operator with a register variable then compiler may give an error or warning (depending upon the compiler you are using), because when we say a variable is a register, it may be stored in a register instead of memory and accessing address of a register is invalid. Try below program. #include<stdio.h> int main(){ register int i = 10; int* a = &i; printf("%d", *a); getchar(); return 0;} 2) register keyword can be used with pointer variables. Obviously, a register can have address of a memory location. There would not be any problem with the below program. #include<stdio.h> int main(){ int i = 10; register int* a = &i; printf("%d", *a); getchar(); return 0;} 3) Register is a storage class, and C doesn’t allow multiple storage class specifiers for a variable. So, register can not be used with static . Try below program. #include<stdio.h> int main(){ int i = 10; register static int* a = &i; printf("%d", *a); getchar(); return 0;} 4) Register can only be used within a block (local), it can not be used in the global scope (outside main). 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. #include <stdio.h> // error (global scope)register int x = 10;int main(){ // works (inside a block) register int i = 10; printf("%d\n", i); printf("%d", x); return 0;} Compile Errors: prog.c:3:14: error: register name not specified for 'x' register int x = 10;//error (global scope) ^ 5) There is no limit on number of register variables in a C program, but the point is compiler may put some variables in register and some not. Please write comments if you find anything incorrect in the above article or you want to share more information about register keyword. AnasKhedr Ankur Trivedi c-puzzle C-Storage Classes and Type Qualifiers Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity SQL Interview Questions SQL | Views Java Tutorial Docker - COPY Instruction std::sort() in C++ STL Bitwise Operators in C/C++ Arrays in C/C++ Substring in C++ Function Pointer in C
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Aug, 2019" }, { "code": null, "e": 433, "s": 52, "text": "Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in register." }, { "code": null, "e": 733, "s": 433, "text": "1) If you use & operator with a register variable then compiler may give an error or warning (depending upon the compiler you are using), because when we say a variable is a register, it may be stored in a register instead of memory and accessing address of a register is invalid. Try below program." }, { "code": "#include<stdio.h> int main(){ register int i = 10; int* a = &i; printf(\"%d\", *a); getchar(); return 0;}", "e": 855, "s": 733, "text": null }, { "code": null, "e": 1027, "s": 855, "text": "2) register keyword can be used with pointer variables. Obviously, a register can have address of a memory location. There would not be any problem with the below program." }, { "code": "#include<stdio.h> int main(){ int i = 10; register int* a = &i; printf(\"%d\", *a); getchar(); return 0;}", "e": 1147, "s": 1027, "text": null }, { "code": null, "e": 1311, "s": 1147, "text": "3) Register is a storage class, and C doesn’t allow multiple storage class specifiers for a variable. So, register can not be used with static . Try below program." }, { "code": "#include<stdio.h> int main(){ int i = 10; register static int* a = &i; printf(\"%d\", *a); getchar(); return 0;}", "e": 1438, "s": 1311, "text": null }, { "code": null, "e": 1546, "s": 1438, "text": "4) Register can only be used within a block (local), it can not be used in the global scope (outside main)." }, { "code": null, "e": 1555, "s": 1546, "text": "Chapters" }, { "code": null, "e": 1582, "s": 1555, "text": "descriptions off, selected" }, { "code": null, "e": 1632, "s": 1582, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1655, "s": 1632, "text": "captions off, selected" }, { "code": null, "e": 1663, "s": 1655, "text": "English" }, { "code": null, "e": 1687, "s": 1663, "text": "This is a modal window." }, { "code": null, "e": 1756, "s": 1687, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1778, "s": 1756, "text": "End of dialog window." }, { "code": "#include <stdio.h> // error (global scope)register int x = 10;int main(){ // works (inside a block) register int i = 10; printf(\"%d\\n\", i); printf(\"%d\", x); return 0;}", "e": 1962, "s": 1778, "text": null }, { "code": null, "e": 1978, "s": 1962, "text": "Compile Errors:" }, { "code": null, "e": 2095, "s": 1978, "text": "prog.c:3:14: error: register name not specified for 'x'\n register int x = 10;//error (global scope)\n ^\n" }, { "code": null, "e": 2239, "s": 2095, "text": "5) There is no limit on number of register variables in a C program, but the point is compiler may put some variables in register and some not." }, { "code": null, "e": 2375, "s": 2239, "text": "Please write comments if you find anything incorrect in the above article or you want to share more information about register keyword." }, { "code": null, "e": 2385, "s": 2375, "text": "AnasKhedr" }, { "code": null, "e": 2399, "s": 2385, "text": "Ankur Trivedi" }, { "code": null, "e": 2408, "s": 2399, "text": "c-puzzle" }, { "code": null, "e": 2446, "s": 2408, "text": "C-Storage Classes and Type Qualifiers" }, { "code": null, "e": 2455, "s": 2446, "text": "Articles" }, { "code": null, "e": 2466, "s": 2455, "text": "C Language" }, { "code": null, "e": 2564, "s": 2466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2601, "s": 2564, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 2625, "s": 2601, "text": "SQL Interview Questions" }, { "code": null, "e": 2637, "s": 2625, "text": "SQL | Views" }, { "code": null, "e": 2651, "s": 2637, "text": "Java Tutorial" }, { "code": null, "e": 2677, "s": 2651, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2700, "s": 2677, "text": "std::sort() in C++ STL" }, { "code": null, "e": 2727, "s": 2700, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 2743, "s": 2727, "text": "Arrays in C/C++" }, { "code": null, "e": 2760, "s": 2743, "text": "Substring in C++" } ]
Introduction to Microsoft Azure | A cloud computing service
03 Jun, 2022 What is Azure? Azure is Microsoft’s cloud platform, just like Google has it’s Google Cloud and Amazon has it’s Amazon Web Service or AWS.000. Generally, it is a platform through which we can use Microsoft’s resource. For example, to set up a huge server, we will require huge investment, effort, physical space and so on. In such situations, Microsoft Azure comes to our rescue. It will provide us with virtual machines, fast processing of data, analytical and monitoring tools and so on to make our work simpler. The pricing of Azure is also simpler and cost-effective. Popularly termed as “Pay As You Go”, which means how much you use, pay only for that. Azure History Microsoft unveiled Windows Azure in early October 2008 but it went to live after February 2010. Later in 2014, Microsoft changed its name from Windows Azure to Microsoft Azure. Azure provided a service platform for .NET services, SQL Services, and many Live Services. Many people were still very skeptical about “the cloud”. As an industry, we were entering a brave new world with many possibilities. Microsoft Azure is getting bigger and better in coming days. More tools and more functionalities are getting added. It has two releases as of now. It’s famous version Microsoft Azure v1 and later Microsoft Azure v2. Microsoft Azure v1 was more like JSON script driven then the new version v2, which has interactive UI for simplification and easy learning. Microsoft Azure v2 is still in the preview version. How Azure can help in business? Azure can help in our business in the following ways- Capital less: We don’t have to worry about the capital as Azure cuts out the high cost of hardware. You simply pay as you go and enjoy a subscription-based model that’s kind to your cash flow. Also, to set up an Azure account is very easy. You simply register in Azure Portal and select your required subscription and get going. Less Operational Cost: Azure has low operational cost because it runs on its own servers whose only job is to make the cloud functional and bug-free, it’s usually a whole lot more reliable than your own, on-location server. Cost Effective: If we set up a server on our own, we need to hire a tech support team to monitor them and make sure things are working fine. Also, there might be a situation where the tech support team is taking too much time to solve the issue incurred in the server. So, in this regard is way too pocket-friendly. Easy Back Up and Recovery options: Azure keep backups of all your valuable data. In disaster situations, you can recover all your data in a single click without your business getting affected. Cloud-based backup and recovery solutions save time, avoid large up-front investment and roll up third-party expertise as part of the deal. Easy to implement: It is very easy to implement your business models in Azure. With a couple of on-click activities, you are good to go. Even there are several tutorials to make you learn and deploy faster. Better Security: Azure provides more security than local servers. Be carefree about your critical data and business applications. As it stays safe in the Azure Cloud. Even, in natural disasters, where the resources can be harmed, Azure is a rescue. The cloud is always on. Work from anywhere: Azure gives you the freedom to work from anywhere and everywhere. It just requires a network connection and credentials. And with most serious Azure cloud services offering mobile apps, you’re not restricted to which device you’ve got to hand. Increased collaboration: With Azure, teams can access, edit and share documents anytime, from anywhere. They can work and achieve future goals hand in hand. Another advantage of the Azure is that it preserves records of activity and data. Timestamps are one example of the Azure’s record keeping. Timestamps improve team collaboration by establishing transparency and increasing accountability. Microsoft Azure Services Some following are the services of Microsoft Azure offers: Compute: Includes Virtual Machines, Virtual Machine Scale Sets, Functions for serverless computing, Batch for containerized batch workloads, Service Fabric for microservices and container orchestration, and Cloud Services for building cloud-based apps and APIs.Networking: With Azure you can use variety of networking tools, like the Virtual Network, which can connect to on-premise data centers; Load Balancer; Application Gateway; VPN Gateway; Azure DNS for domain hosting, Content Delivery Network, Traffic Manager, ExpressRoute dedicated private network fiber connections; and Network Watcher monitoring and diagnosticsStorage: Includes Blob, Queue, File and Disk Storage, as well as a Data Lake Store, Backup and Site Recovery, among others.Web + Mobile: Creating Web + Mobile applications is very easy as it includes several services for building and deploying applications.Containers: Azure has a property which includes Container Service, which supports Kubernetes, DC/OS or Docker Swarm, and Container Registry, as well as tools for microservices.Databases: Azure has also includes several SQL-based databases and related tools.Data + Analytics: Azure has some big data tools like HDInsight for Hadoop Spark, R Server, HBase and Storm clustersAI + Cognitive Services: With Azure developing applications with artificial intelligence capabilities, like the Computer Vision API, Face API, Bing Web Search, Video Indexer, Language Understanding Intelligent.Internet of Things: Includes IoT Hub and IoT Edge services that can be combined with a variety of machine learning, analytics, and communications services.Security + Identity: Includes Security Center, Azure Active Directory, Key Vault and Multi-Factor Authentication Services.Developer Tools: Includes cloud development services like Visual Studio Team Services, Azure DevTest Labs, HockeyApp mobile app deployment and monitoring, Xamarin cross-platform mobile development and more. Compute: Includes Virtual Machines, Virtual Machine Scale Sets, Functions for serverless computing, Batch for containerized batch workloads, Service Fabric for microservices and container orchestration, and Cloud Services for building cloud-based apps and APIs. Networking: With Azure you can use variety of networking tools, like the Virtual Network, which can connect to on-premise data centers; Load Balancer; Application Gateway; VPN Gateway; Azure DNS for domain hosting, Content Delivery Network, Traffic Manager, ExpressRoute dedicated private network fiber connections; and Network Watcher monitoring and diagnostics Storage: Includes Blob, Queue, File and Disk Storage, as well as a Data Lake Store, Backup and Site Recovery, among others. Web + Mobile: Creating Web + Mobile applications is very easy as it includes several services for building and deploying applications. Containers: Azure has a property which includes Container Service, which supports Kubernetes, DC/OS or Docker Swarm, and Container Registry, as well as tools for microservices. Databases: Azure has also includes several SQL-based databases and related tools. Data + Analytics: Azure has some big data tools like HDInsight for Hadoop Spark, R Server, HBase and Storm clusters AI + Cognitive Services: With Azure developing applications with artificial intelligence capabilities, like the Computer Vision API, Face API, Bing Web Search, Video Indexer, Language Understanding Intelligent. Internet of Things: Includes IoT Hub and IoT Edge services that can be combined with a variety of machine learning, analytics, and communications services. Security + Identity: Includes Security Center, Azure Active Directory, Key Vault and Multi-Factor Authentication Services. Developer Tools: Includes cloud development services like Visual Studio Team Services, Azure DevTest Labs, HockeyApp mobile app deployment and monitoring, Xamarin cross-platform mobile development and more. Difference between AWS (Amazon Web Services), Google Cloud and Azure simmytarika5 keerthikarathan123 Cloud-Computing Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2022" }, { "code": null, "e": 43, "s": 28, "text": "What is Azure?" }, { "code": null, "e": 685, "s": 43, "text": "Azure is Microsoft’s cloud platform, just like Google has it’s Google Cloud and Amazon has it’s Amazon Web Service or AWS.000. Generally, it is a platform through which we can use Microsoft’s resource. For example, to set up a huge server, we will require huge investment, effort, physical space and so on. In such situations, Microsoft Azure comes to our rescue. It will provide us with virtual machines, fast processing of data, analytical and monitoring tools and so on to make our work simpler. The pricing of Azure is also simpler and cost-effective. Popularly termed as “Pay As You Go”, which means how much you use, pay only for that." }, { "code": null, "e": 699, "s": 685, "text": "Azure History" }, { "code": null, "e": 1508, "s": 699, "text": "Microsoft unveiled Windows Azure in early October 2008 but it went to live after February 2010. Later in 2014, Microsoft changed its name from Windows Azure to Microsoft Azure. Azure provided a service platform for .NET services, SQL Services, and many Live Services. Many people were still very skeptical about “the cloud”. As an industry, we were entering a brave new world with many possibilities. Microsoft Azure is getting bigger and better in coming days. More tools and more functionalities are getting added. It has two releases as of now. It’s famous version Microsoft Azure v1 and later Microsoft Azure v2. Microsoft Azure v1 was more like JSON script driven then the new version v2, which has interactive UI for simplification and easy learning. Microsoft Azure v2 is still in the preview version." }, { "code": null, "e": 1540, "s": 1508, "text": "How Azure can help in business?" }, { "code": null, "e": 1594, "s": 1540, "text": "Azure can help in our business in the following ways-" }, { "code": null, "e": 1923, "s": 1594, "text": "Capital less: We don’t have to worry about the capital as Azure cuts out the high cost of hardware. You simply pay as you go and enjoy a subscription-based model that’s kind to your cash flow. Also, to set up an Azure account is very easy. You simply register in Azure Portal and select your required subscription and get going." }, { "code": null, "e": 2147, "s": 1923, "text": "Less Operational Cost: Azure has low operational cost because it runs on its own servers whose only job is to make the cloud functional and bug-free, it’s usually a whole lot more reliable than your own, on-location server." }, { "code": null, "e": 2463, "s": 2147, "text": "Cost Effective: If we set up a server on our own, we need to hire a tech support team to monitor them and make sure things are working fine. Also, there might be a situation where the tech support team is taking too much time to solve the issue incurred in the server. So, in this regard is way too pocket-friendly." }, { "code": null, "e": 2796, "s": 2463, "text": "Easy Back Up and Recovery options: Azure keep backups of all your valuable data. In disaster situations, you can recover all your data in a single click without your business getting affected. Cloud-based backup and recovery solutions save time, avoid large up-front investment and roll up third-party expertise as part of the deal." }, { "code": null, "e": 3003, "s": 2796, "text": "Easy to implement: It is very easy to implement your business models in Azure. With a couple of on-click activities, you are good to go. Even there are several tutorials to make you learn and deploy faster." }, { "code": null, "e": 3276, "s": 3003, "text": "Better Security: Azure provides more security than local servers. Be carefree about your critical data and business applications. As it stays safe in the Azure Cloud. Even, in natural disasters, where the resources can be harmed, Azure is a rescue. The cloud is always on." }, { "code": null, "e": 3540, "s": 3276, "text": "Work from anywhere: Azure gives you the freedom to work from anywhere and everywhere. It just requires a network connection and credentials. And with most serious Azure cloud services offering mobile apps, you’re not restricted to which device you’ve got to hand." }, { "code": null, "e": 3935, "s": 3540, "text": "Increased collaboration: With Azure, teams can access, edit and share documents anytime, from anywhere. They can work and achieve future goals hand in hand. Another advantage of the Azure is that it preserves records of activity and data. Timestamps are one example of the Azure’s record keeping. Timestamps improve team collaboration by establishing transparency and increasing accountability." }, { "code": null, "e": 3960, "s": 3935, "text": "Microsoft Azure Services" }, { "code": null, "e": 4019, "s": 3960, "text": "Some following are the services of Microsoft Azure offers:" }, { "code": null, "e": 5965, "s": 4019, "text": "Compute: Includes Virtual Machines, Virtual Machine Scale Sets, Functions for serverless computing, Batch for containerized batch workloads, Service Fabric for microservices and container orchestration, and Cloud Services for building cloud-based apps and APIs.Networking: With Azure you can use variety of networking tools, like the Virtual Network, which can connect to on-premise data centers; Load Balancer; Application Gateway; VPN Gateway; Azure DNS for domain hosting, Content Delivery Network, Traffic Manager, ExpressRoute dedicated private network fiber connections; and Network Watcher monitoring and diagnosticsStorage: Includes Blob, Queue, File and Disk Storage, as well as a Data Lake Store, Backup and Site Recovery, among others.Web + Mobile: Creating Web + Mobile applications is very easy as it includes several services for building and deploying applications.Containers: Azure has a property which includes Container Service, which supports Kubernetes, DC/OS or Docker Swarm, and Container Registry, as well as tools for microservices.Databases: Azure has also includes several SQL-based databases and related tools.Data + Analytics: Azure has some big data tools like HDInsight for Hadoop Spark, R Server, HBase and Storm clustersAI + Cognitive Services: With Azure developing applications with artificial intelligence capabilities, like the Computer Vision API, Face API, Bing Web Search, Video Indexer, Language Understanding Intelligent.Internet of Things: Includes IoT Hub and IoT Edge services that can be combined with a variety of machine learning, analytics, and communications services.Security + Identity: Includes Security Center, Azure Active Directory, Key Vault and Multi-Factor Authentication Services.Developer Tools: Includes cloud development services like Visual Studio Team Services, Azure DevTest Labs, HockeyApp mobile app deployment and monitoring, Xamarin cross-platform mobile development and more." }, { "code": null, "e": 6227, "s": 5965, "text": "Compute: Includes Virtual Machines, Virtual Machine Scale Sets, Functions for serverless computing, Batch for containerized batch workloads, Service Fabric for microservices and container orchestration, and Cloud Services for building cloud-based apps and APIs." }, { "code": null, "e": 6590, "s": 6227, "text": "Networking: With Azure you can use variety of networking tools, like the Virtual Network, which can connect to on-premise data centers; Load Balancer; Application Gateway; VPN Gateway; Azure DNS for domain hosting, Content Delivery Network, Traffic Manager, ExpressRoute dedicated private network fiber connections; and Network Watcher monitoring and diagnostics" }, { "code": null, "e": 6714, "s": 6590, "text": "Storage: Includes Blob, Queue, File and Disk Storage, as well as a Data Lake Store, Backup and Site Recovery, among others." }, { "code": null, "e": 6849, "s": 6714, "text": "Web + Mobile: Creating Web + Mobile applications is very easy as it includes several services for building and deploying applications." }, { "code": null, "e": 7026, "s": 6849, "text": "Containers: Azure has a property which includes Container Service, which supports Kubernetes, DC/OS or Docker Swarm, and Container Registry, as well as tools for microservices." }, { "code": null, "e": 7108, "s": 7026, "text": "Databases: Azure has also includes several SQL-based databases and related tools." }, { "code": null, "e": 7224, "s": 7108, "text": "Data + Analytics: Azure has some big data tools like HDInsight for Hadoop Spark, R Server, HBase and Storm clusters" }, { "code": null, "e": 7435, "s": 7224, "text": "AI + Cognitive Services: With Azure developing applications with artificial intelligence capabilities, like the Computer Vision API, Face API, Bing Web Search, Video Indexer, Language Understanding Intelligent." }, { "code": null, "e": 7591, "s": 7435, "text": "Internet of Things: Includes IoT Hub and IoT Edge services that can be combined with a variety of machine learning, analytics, and communications services." }, { "code": null, "e": 7714, "s": 7591, "text": "Security + Identity: Includes Security Center, Azure Active Directory, Key Vault and Multi-Factor Authentication Services." }, { "code": null, "e": 7921, "s": 7714, "text": "Developer Tools: Includes cloud development services like Visual Studio Team Services, Azure DevTest Labs, HockeyApp mobile app deployment and monitoring, Xamarin cross-platform mobile development and more." }, { "code": null, "e": 7990, "s": 7921, "text": "Difference between AWS (Amazon Web Services), Google Cloud and Azure" }, { "code": null, "e": 8003, "s": 7990, "text": "simmytarika5" }, { "code": null, "e": 8022, "s": 8003, "text": "keerthikarathan123" }, { "code": null, "e": 8038, "s": 8022, "text": "Cloud-Computing" }, { "code": null, "e": 8047, "s": 8038, "text": "Articles" } ]
How to Install a local module using npm?
06 Oct, 2021 This article shows how to install local module using npm. Local modules are modules created locally in your Node.js application to create user-required functionality. These local modules include different functionalities of your application in separate files and folders. To link the local module first you must have the local module directory or package directory. npm (Node Package Manager) is the default package manager for Node.js, know more about npm here. Why do we use local modules? We use local modules to create the user required functionality in an application made using Node.js. Know more about Node.js here. How to install local modules?Using npm-link Go to the local module directory ( package you want to install ) and enter this command.npm linkoutput of the above commandGo to the project directory where you want to install the local module and enter this command. npm link package-nameoutput of the above commandExample: Let the local-dir is the local directory and project-dir is the project directory and local_module is the local module package you want to install, first go to the local-dir and type npm link and next go to the project directory and type npm link <local_module> this will link your local module to your project.Using npm installWe need to provide <folder> argument to npm install, The argument should be the local folder where the package is present, Path is the location of the folder containing the package ( local_module ) you want to installnpm install /pathoutput of the above codeExample: Let the path where your local module stored is C:\Users\engineer\Desktop\package. Now go the project directory and type the command npm install C:\Users\engineer\Desktop\packageNOTE: Just provide the package folder name but not the package name, it will automatically link it to your project. Using npm-link Go to the local module directory ( package you want to install ) and enter this command.npm linkoutput of the above commandGo to the project directory where you want to install the local module and enter this command. npm link package-nameoutput of the above commandExample: Let the local-dir is the local directory and project-dir is the project directory and local_module is the local module package you want to install, first go to the local-dir and type npm link and next go to the project directory and type npm link <local_module> this will link your local module to your project. Go to the local module directory ( package you want to install ) and enter this command. npm link output of the above command Go to the project directory where you want to install the local module and enter this command. npm link package-name output of the above command Example: Let the local-dir is the local directory and project-dir is the project directory and local_module is the local module package you want to install, first go to the local-dir and type npm link and next go to the project directory and type npm link <local_module> this will link your local module to your project. Using npm installWe need to provide <folder> argument to npm install, The argument should be the local folder where the package is present, Path is the location of the folder containing the package ( local_module ) you want to installnpm install /pathoutput of the above codeExample: Let the path where your local module stored is C:\Users\engineer\Desktop\package. Now go the project directory and type the command npm install C:\Users\engineer\Desktop\packageNOTE: Just provide the package folder name but not the package name, it will automatically link it to your project. We need to provide <folder> argument to npm install, The argument should be the local folder where the package is present, Path is the location of the folder containing the package ( local_module ) you want to install npm install /path output of the above code Example: Let the path where your local module stored is C:\Users\engineer\Desktop\package. Now go the project directory and type the command npm install C:\Users\engineer\Desktop\package NOTE: Just provide the package folder name but not the package name, it will automatically link it to your project. How to uninstall a package installed with an npm link:The program may be uninstalled using the same uninstall or rm order as is used to delete installed packages. The only thing to note is that the connection must be uninstalled globally the global flag must be defined. The following command can be used to remove the globally connected foo kit npm rm --global foo ankit_kumar_ how-to-install Node-npm NodeJS-Questions Picked Technical Scripter 2020 How To Installation Guide Node.js Technical Scripter 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": "\n06 Oct, 2021" }, { "code": null, "e": 86, "s": 28, "text": "This article shows how to install local module using npm." }, { "code": null, "e": 395, "s": 86, "text": "Local modules are modules created locally in your Node.js application to create user-required functionality. These local modules include different functionalities of your application in separate files and folders. To link the local module first you must have the local module directory or package directory. " }, { "code": null, "e": 492, "s": 395, "text": "npm (Node Package Manager) is the default package manager for Node.js, know more about npm here." }, { "code": null, "e": 521, "s": 492, "text": "Why do we use local modules?" }, { "code": null, "e": 652, "s": 521, "text": "We use local modules to create the user required functionality in an application made using Node.js. Know more about Node.js here." }, { "code": null, "e": 1863, "s": 652, "text": "How to install local modules?Using npm-link Go to the local module directory ( package you want to install ) and enter this command.npm linkoutput of the above commandGo to the project directory where you want to install the local module and enter this command. npm link package-nameoutput of the above commandExample: Let the local-dir is the local directory and project-dir is the project directory and local_module is the local module package you want to install, first go to the local-dir and type npm link and next go to the project directory and type npm link <local_module> this will link your local module to your project.Using npm installWe need to provide <folder> argument to npm install, The argument should be the local folder where the package is present, Path is the location of the folder containing the package ( local_module ) you want to installnpm install /pathoutput of the above codeExample: Let the path where your local module stored is C:\\Users\\engineer\\Desktop\\package. Now go the project directory and type the command npm install C:\\Users\\engineer\\Desktop\\packageNOTE: Just provide the package folder name but not the package name, it will automatically link it to your project." }, { "code": null, "e": 2469, "s": 1863, "text": "Using npm-link Go to the local module directory ( package you want to install ) and enter this command.npm linkoutput of the above commandGo to the project directory where you want to install the local module and enter this command. npm link package-nameoutput of the above commandExample: Let the local-dir is the local directory and project-dir is the project directory and local_module is the local module package you want to install, first go to the local-dir and type npm link and next go to the project directory and type npm link <local_module> this will link your local module to your project." }, { "code": null, "e": 2562, "s": 2469, "text": " Go to the local module directory ( package you want to install ) and enter this command." }, { "code": null, "e": 2571, "s": 2562, "text": "npm link" }, { "code": null, "e": 2599, "s": 2571, "text": "output of the above command" }, { "code": null, "e": 2696, "s": 2599, "text": "Go to the project directory where you want to install the local module and enter this command. " }, { "code": null, "e": 2718, "s": 2696, "text": "npm link package-name" }, { "code": null, "e": 2746, "s": 2718, "text": "output of the above command" }, { "code": null, "e": 3067, "s": 2746, "text": "Example: Let the local-dir is the local directory and project-dir is the project directory and local_module is the local module package you want to install, first go to the local-dir and type npm link and next go to the project directory and type npm link <local_module> this will link your local module to your project." }, { "code": null, "e": 3644, "s": 3067, "text": "Using npm installWe need to provide <folder> argument to npm install, The argument should be the local folder where the package is present, Path is the location of the folder containing the package ( local_module ) you want to installnpm install /pathoutput of the above codeExample: Let the path where your local module stored is C:\\Users\\engineer\\Desktop\\package. Now go the project directory and type the command npm install C:\\Users\\engineer\\Desktop\\packageNOTE: Just provide the package folder name but not the package name, it will automatically link it to your project." }, { "code": null, "e": 3862, "s": 3644, "text": "We need to provide <folder> argument to npm install, The argument should be the local folder where the package is present, Path is the location of the folder containing the package ( local_module ) you want to install" }, { "code": null, "e": 3880, "s": 3862, "text": "npm install /path" }, { "code": null, "e": 3905, "s": 3880, "text": "output of the above code" }, { "code": null, "e": 4092, "s": 3905, "text": "Example: Let the path where your local module stored is C:\\Users\\engineer\\Desktop\\package. Now go the project directory and type the command npm install C:\\Users\\engineer\\Desktop\\package" }, { "code": null, "e": 4208, "s": 4092, "text": "NOTE: Just provide the package folder name but not the package name, it will automatically link it to your project." }, { "code": null, "e": 4479, "s": 4208, "text": "How to uninstall a package installed with an npm link:The program may be uninstalled using the same uninstall or rm order as is used to delete installed packages. The only thing to note is that the connection must be uninstalled globally the global flag must be defined." }, { "code": null, "e": 4554, "s": 4479, "text": "The following command can be used to remove the globally connected foo kit" }, { "code": null, "e": 4574, "s": 4554, "text": "npm rm --global foo" }, { "code": null, "e": 4587, "s": 4574, "text": "ankit_kumar_" }, { "code": null, "e": 4602, "s": 4587, "text": "how-to-install" }, { "code": null, "e": 4611, "s": 4602, "text": "Node-npm" }, { "code": null, "e": 4628, "s": 4611, "text": "NodeJS-Questions" }, { "code": null, "e": 4635, "s": 4628, "text": "Picked" }, { "code": null, "e": 4659, "s": 4635, "text": "Technical Scripter 2020" }, { "code": null, "e": 4666, "s": 4659, "text": "How To" }, { "code": null, "e": 4685, "s": 4666, "text": "Installation Guide" }, { "code": null, "e": 4693, "s": 4685, "text": "Node.js" }, { "code": null, "e": 4712, "s": 4693, "text": "Technical Scripter" }, { "code": null, "e": 4729, "s": 4712, "text": "Web Technologies" } ]
Word Wrap Problem | DP-19
12 May, 2022 Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width.The word processors like MS Word do task of placing line breaks. The idea is to have balanced lines. In other words, not have few lines with lots of extra spaces and some lines with small amount of extra spaces. The extra spaces includes spaces put at the end of every line except the last one. The problem is to minimize the following total cost. Cost of a line = (Number of extra spaces in the line)^3 Total Cost = Sum of costs for all lines For example, consider the following string and line width M = 15 "Geeks for Geeks presents word wrap problem" Following is the optimized arrangement of words in 3 lines Geeks for Geeks presents word wrap problem The total extra spaces in line 1, line 2 and line 3 are 0, 2 and 3 respectively. So optimal value of total cost is 0 + 2*2*2 + 3*3*3 = 35 Please note that the total cost function is not sum of extra spaces, but sum of cubes (or square is also used) of extra spaces. The idea behind this cost function is to balance the spaces among lines. For example, consider the following two arrangement of same set of words:1) There are 3 lines. One line has 3 extra spaces and all other lines have 0 extra spaces. Total extra spaces = 3 + 0 + 0 = 3. Total cost = 3*3*3 + 0*0*0 + 0*0*0 = 27.2) There are 3 lines. Each of the 3 lines has one extra space. Total extra spaces = 1 + 1 + 1 = 3. Total cost = 1*1*1 + 1*1*1 + 1*1*1 = 3.Total extra spaces are 3 in both scenarios, but second arrangement should be preferred because extra spaces are balanced in all three lines. The cost function with cubic sum serves the purpose because the value of total cost in second scenario is less. Method 1 (Greedy Solution) The greedy solution is to place as many words as possible in the first line. Then do the same thing for the second line and so on until all words are placed. This solution gives optimal solution for many cases, but doesn’t give optimal solution in all cases. For example, consider the following string “aaa bb cc ddddd” and line width as 6. Greedy method will produce following output. aaa bb cc ddddd Extra spaces in the above 3 lines are 0, 4 and 1 respectively. So total cost is 0 + 64 + 1 = 65.But the above solution is not the best solution. Following arrangement has more balanced spaces. Therefore less value of total cost function. aaa bb cc ddddd Extra spaces in the above 3 lines are 3, 1 and 1 respectively. So total cost is 27 + 1 + 1 = 29.Despite being sub-optimal in some cases, the greedy approach is used by many word processors like MS Word and OpenOffice.org Writer. Method 2 (Recursive Approach with memoization) The problem can be solved using a divide and conquer (recursive) approach. The algorithm for the same is mentioned below: 1. We recur for each word starting with first word, and remaining length of the line (initially k). 2. The last word would be the base case: We check if we can put it on same line: if yes, then we return cost as 0. if no, we return cost of current line based on its remaining length. 3. For non-last words, we have to check if it can fit in the current line: if yes, then we have two choices i.e. whether to put it in same line or next line. if we put it on next line: cost1 = square(remLength) + cost of putting word on next line. if we put it on same line: cost2 = cost of putting word on same line. return min(cost1, cost2) if no, then we have to put it on next line: return cost of putting word on next line 4. We use memoization table of size n (number of words) * k (line length), to keep track of already visited positions. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int solveWordWrapUsingMemo(int words[], int n, int length, int wordIndex, int remLength, vector<vector<int> > memo); int square(int n) { return n * n; } int solveWordWrapUtil(int words[], int n, int length, int wordIndex, int remLength, vector<vector<int> > memo){ // base case for last word if (wordIndex == n - 1) { memo[wordIndex][remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex][remLength]; } int currWord = words[wordIndex]; // if word can fit in the remaining line if (currWord < remLength) { return min(solveWordWrapUsingMemo( words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo)); } else { // if word is kept on next line return square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo); }} int solveWordWrapUsingMemo(int words[], int n, int length, int wordIndex, int remLength, vector<vector<int> > memo){ if (memo[wordIndex][remLength] != -1) { return memo[wordIndex][remLength]; } memo[wordIndex][remLength] = solveWordWrapUtil( words, n, length, wordIndex, remLength, memo); return memo[wordIndex][remLength];} int solveWordWrap(int words[], int n, int k){ vector<vector<int> > memo(n, vector<int>(k + 1, -1)); return solveWordWrapUsingMemo(words, n, k, 0, k, memo);}int main(){ int words[] = { 3, 2, 2, 5 }; int n = sizeof(words) / sizeof(words[0]); int k = 6; cout << solveWordWrap(words, n, k); return 0;}/* This Code is contributed by Tapesh (tapeshdua420) */ /*package whatever //do not write package name here */ import java.io.*;import java.util.Arrays; public class WordWrapDpMemo { private int solveWordWrap(int[] nums, int k) { int[][] memo = new int[nums.length][k + 1]; for (int i = 0; i < nums.length; i++) { Arrays.fill(memo[i], -1); } return solveWordWrapUsingMemo(nums, nums.length, k, 0, k, memo); } private int solveWordWrap(int[] words, int n, int length, int wordIndex, int remLength, int[][] memo) { //base case for last word if (wordIndex == n - 1) { memo[wordIndex][remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex][remLength]; } int currWord = words[wordIndex]; //if word can fit in the remaining line if (currWord < remLength) { return Math.min( //if word is kept on same line solveWordWrapUsingMemo(words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), //if word is kept on next line square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo) ); } else { //if word is kept on next line return square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo); } } private int solveWordWrapUsingMemo(int[] words, int n, int length, int wordIndex, int remLength, int[][] memo) { if (memo[wordIndex][remLength] != -1) { return memo[wordIndex][remLength]; } memo[wordIndex][remLength] = solveWordWrap(words, n, length, wordIndex, remLength, memo); return memo[wordIndex][remLength]; } private int square(int n) { return n * n; } public static void main(String[] args) { System.out.println(new WordWrapDpMemo().solveWordWrap(new int[]{3, 2, 2, 5}, 6)); }} # Python program for the above approachdef square(n) : return n * n def solveWordWrapUtil(words, n, length, wordIndex, remLength, memo) : # base case for last word if (wordIndex == n - 1) : memo[wordIndex][remLength] = 0 if (words[wordIndex] < remLength) else square(remLength) return memo[wordIndex][remLength] currWord = words[wordIndex] # if word can fit in the remaining line if (currWord < remLength) : return min(solveWordWrapUsingMemo( words, n, length, wordIndex + 1, remLength - currWord if (remLength == length) else remLength - currWord - 1, memo), square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo)) else : # if word is kept on next line return (square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo)) def solveWordWrapUsingMemo(words, n, length, wordIndex, remLength, memo) : if (memo[wordIndex][remLength] != -1) : return memo[wordIndex][remLength] memo[wordIndex][remLength] = (solveWordWrapUtil( words, n, length, wordIndex, remLength, memo)) return memo[wordIndex][remLength] def solveWordWrap(words, n, k) : memo = [[10]* (k + 1)]* n return solveWordWrapUsingMemo(words, n, k, 0, k, memo) # Driver Codeif __name__ == "__main__": words = [ 3, 2, 2, 5 ] n = len(words) k = 6 print(solveWordWrap(words, n, k)) # This code is contributed by sanjoy_62. /*package whatever //do not write package name here */using System;using System.Collections.Generic; public class WordWrapDpMemo { private int solveWordWrap(int[] nums, int k) { int[,] memo = new int[nums.Length ,k + 1]; for (int i = 0; i < memo.GetLength(0); i++) { for(int j = 0; j < memo.GetLength(1); j++) memo[i, j] = -1; } return solveWordWrapUsingMemo(nums, nums.Length, k, 0, k, memo); } private int solveWordWrap(int[] words, int n, int length, int wordIndex, int remLength, int[,] memo) { // base case for last word if (wordIndex == n - 1) { memo[wordIndex, remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex, remLength]; } int currWord = words[wordIndex]; // if word can fit in the remaining line if (currWord < remLength) { return Math.Min( // if word is kept on same line solveWordWrapUsingMemo(words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), // if word is kept on next line square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo)); } else { // if word is kept on next line return square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo); } } private int solveWordWrapUsingMemo(int[] words, int n, int length, int wordIndex, int remLength, int[,] memo) { if (memo[wordIndex,remLength] != -1) { return memo[wordIndex,remLength]; } memo[wordIndex,remLength] = solveWordWrap(words, n, length, wordIndex, remLength, memo); return memo[wordIndex, remLength]; } private int square(int n) { return n * n; } public static void Main(String[] args) { Console.WriteLine(new WordWrapDpMemo(). solveWordWrap(new int[] { 3, 2, 2, 5 }, 6)); }} // This code is contributed by gauravrajput1 <script>/*package whatever //do not write package name here */function solveWordWrap(nums , k) { var memo = Array(nums.length).fill().map(()=>Array(k + 1).fill(-1)); return solveWordWrapUsingMemo(nums, nums.length, k, 0, k, memo); } function solveWordWrap1(words , n , length , wordIndex , remLength, memo) { // base case for last word if (wordIndex == n - 1) { memo[wordIndex][remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex][remLength]; } var currWord = words[wordIndex]; // if word can fit in the remaining line if (currWord < remLength) { return Math.min( // if word is kept on same line solveWordWrapUsingMemo(words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), // if word is kept on next line square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo)); } else { // if word is kept on next line return square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo); } } function solveWordWrapUsingMemo(words , n , length , wordIndex , remLength, memo) { //if (memo[wordIndex][remLength] != -1) { // return memo[wordIndex][remLength]; //} memo[wordIndex][remLength] = solveWordWrap1(words, n, length, wordIndex, remLength, memo); return memo[wordIndex][remLength]; } function square(n) { return n * n; } var arr = [ 3, 2, 2, 5 ]; document.write(solveWordWrap(arr, 6)); // This code is contributed by gauravrajput1</script> 10 Method 3 (Dynamic Programming) The following Dynamic approach strictly follows the algorithm given in solution of Cormen book. First we compute costs of all possible lines in a 2D table lc[][]. The value lc[i][j] indicates the cost to put words from i to j in a single line where i and j are indexes of words in the input sequences. If a sequence of words from i to j cannot fit in a single line, then lc[i][j] is considered infinite (to avoid it from being a part of the solution). Once we have the lc[][] table constructed, we can calculate total cost using following recursive formula. In the following formula, C[j] is the optimized total cost for arranging words from 1 to j. The above recursion has overlapping subproblem property. For example, the solution of subproblem c(2) is used by c(3), C(4) and so on. So Dynamic Programming is used to store the results of subproblems. The array c[] can be computed from left to right, since each value depends only on earlier values. To print the output, we keep track of what words go on what lines, we can keep a parallel p array that points to where each c value came from. The last line starts at word p[n] and goes through word n. The previous line starts at word p[p[n]] and goes through word p[n] – 1, etc. The function printSolution() uses p[] to print the solution. In the below program, input is an array l[] that represents lengths of words in a sequence. The value l[i] indicates length of the ith word (i starts from 1) in theinput sequence. C++ C Java Python3 C# Javascript // A Dynamic programming solution for Word Wrap Problem#include <bits/stdc++.h>using namespace std;#define INF INT_MAX // A utility function to print the solutionint printSolution (int p[], int n); // l[] represents lengths of different words in input sequence.// For example, l[] = {3, 2, 2, 5} is for a sentence like// "aaa bb cc ddddd". n is size of l[] and M is line width// (maximum no. of characters that can fit in a line)void solveWordWrap (int l[], int n, int M){ // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line int extras[n+1][n+1]; // lc[i][j] will have cost of a line which has words from // i to j int lc[n+1][n+1]; // c[i] will have total cost of optimal arrangement of words // from 1 to i int c[n+1]; // p[] is used to print the solution. int p[n+1]; int i, j; // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = INF; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (j = 1; j <= n; j++) { c[j] = INF; for (i = 1; i <= j; i++) { if (c[i-1] != INF && lc[i][j] != INF && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n);} int printSolution (int p[], int n){ int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; cout<<"Line number "<<k<<": From word no. "<<p[n]<<" to "<<n<<endl; return k;} // Driver program to test above functionsint main(){ int l[] = {3, 2, 2, 5}; int n = sizeof(l)/sizeof(l[0]); int M = 6; solveWordWrap (l, n, M); return 0;} //This is code is contributed by rathbhupendra // A Dynamic programming solution for Word Wrap Problem#include <limits.h>#include <stdio.h>#define INF INT_MAX // A utility function to print the solutionint printSolution (int p[], int n); // l[] represents lengths of different words in input sequence.// For example, l[] = {3, 2, 2, 5} is for a sentence like// "aaa bb cc ddddd". n is size of l[] and M is line width// (maximum no. of characters that can fit in a line)void solveWordWrap (int l[], int n, int M){ // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line int extras[n+1][n+1]; // lc[i][j] will have cost of a line which has words from // i to j int lc[n+1][n+1]; // c[i] will have total cost of optimal arrangement of words // from 1 to i int c[n+1]; // p[] is used to print the solution. int p[n+1]; int i, j; // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = INF; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (j = 1; j <= n; j++) { c[j] = INF; for (i = 1; i <= j; i++) { if (c[i-1] != INF && lc[i][j] != INF && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n);} int printSolution (int p[], int n){ int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; printf ("Line number %d: From word no. %d to %d \n", k, p[n], n); return k;} // Driver program to test above functionsint main(){ int l[] = {3, 2, 2, 5}; int n = sizeof(l)/sizeof(l[0]); int M = 6; solveWordWrap (l, n, M); return 0;} // A Dynamic programming solution for// Word Wrap Problem in Javapublic class WordWrap{ final int MAX = Integer.MAX_VALUE; // A utility function to print the solution int printSolution (int p[], int n) { int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; System.out.println("Line number" + " " + k + ": " + "From word no." +" "+ p[n] + " " + "to" + " " + n); return k; } // l[] represents lengths of different words in input sequence.// For example, l[] = {3, 2, 2, 5} is for a sentence like// "aaa bb cc ddddd". n is size of l[] and M is line width// (maximum no. of characters that can fit in a line) void solveWordWrap (int l[], int n, int M) { // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line int extras[][] = new int[n+1][n+1]; // lc[i][j] will have cost of a line which has words from // i to j int lc[][]= new int[n+1][n+1]; // c[i] will have total cost of optimal arrangement of words // from 1 to i int c[] = new int[n+1]; // p[] is used to print the solution. int p[] =new int[n+1]; // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (int i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (int j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = MAX; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (int j = 1; j <= n; j++) { c[j] = MAX; for (int i = 1; i <= j; i++) { if (c[i-1] != MAX && lc[i][j] != MAX && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n); } public static void main(String args[]) { WordWrap w = new WordWrap(); int l[] = {3, 2, 2, 5}; int n = l.length; int M = 6; w.solveWordWrap (l, n, M); }} // This code is contributed by Saket Kumar # A Dynamic programming solution# for Word Wrap Problem # A utility function to print# the solution# l[] represents lengths of different# words in input sequence. For example,# l[] = {3, 2, 2, 5} is for a sentence# like "aaa bb cc ddddd". n is size of# l[] and M is line width (maximum no.# of characters that can fit in a line)INF = 2147483647def printSolution(p, n): k = 0 if p[n] == 1: k = 1 else: k = printSolution(p, p[n] - 1) + 1 print('Line number ', k, ': From word no. ', p[n], 'to ', n) return k def solveWordWrap (l, n, M): # For simplicity, 1 extra space is # used in all below arrays # extras[i][j] will have number # of extra spaces if words from i # to j are put in a single line extras = [[0 for i in range(n + 1)] for i in range(n + 1)] # lc[i][j] will have cost of a line # which has words from i to j lc = [[0 for i in range(n + 1)] for i in range(n + 1)] # c[i] will have total cost of # optimal arrangement of words # from 1 to i c = [0 for i in range(n + 1)] # p[] is used to print the solution. p = [0 for i in range(n + 1)] # calculate extra spaces in a single # line. The value extra[i][j] indicates # extra spaces if words from word number # i to j are placed in a single line for i in range(n + 1): extras[i][i] = M - l[i - 1] for j in range(i + 1, n + 1): extras[i][j] = (extras[i][j - 1] - l[j - 1] - 1) # Calculate line cost corresponding # to the above calculated extra # spaces. The value lc[i][j] indicates # cost of putting words from word number # i to j in a single line for i in range(n + 1): for j in range(i, n + 1): if extras[i][j] < 0: lc[i][j] = INF; elif j == n and extras[i][j] >= 0: lc[i][j] = 0 else: lc[i][j] = (extras[i][j] * extras[i][j]) # Calculate minimum cost and find # minimum cost arrangement. The value # c[j] indicates optimized cost to # arrange words from word number 1 to j. c[0] = 0 for j in range(1, n + 1): c[j] = INF for i in range(1, j + 1): if (c[i - 1] != INF and lc[i][j] != INF and ((c[i - 1] + lc[i][j]) < c[j])): c[j] = c[i-1] + lc[i][j] p[j] = i printSolution(p, n) # Driver Codel = [3, 2, 2, 5]n = len(l)M = 6solveWordWrap(l, n, M) # This code is contributed by sahil shelangia // A Dynamic programming solution for Word Wrap// Problem in Javausing System; public class GFG { static int MAX = int.MaxValue; // A utility function to print the solution static int printSolution (int []p, int n) { int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; Console.WriteLine("Line number" + " " + k + ": From word no." + " " + p[n] + " " + "to" + " " + n); return k; } // l[] represents lengths of different // words in input sequence. For example, // l[] = {3, 2, 2, 5} is for a sentence // like "aaa bb cc ddddd". n is size of // l[] and M is line width (maximum no. // of characters that can fit in a line) static void solveWordWrap (int []l, int n, int M) { // For simplicity, 1 extra space // is used in all below arrays // extras[i][j] will have number of // extra spaces if words from i // to j are put in a single line int [,]extras = new int[n+1,n+1]; // lc[i][j] will have cost of a line // which has words from i to j int [,]lc = new int[n+1,n+1]; // c[i] will have total cost of // optimal arrangement of words // from 1 to i int []c = new int[n+1]; // p[] is used to print the solution. int []p = new int[n+1]; // calculate extra spaces in a single // line. The value extra[i][j] indicates // extra spaces if words from word number // i to j are placed in a single line for (int i = 1; i <= n; i++) { extras[i,i] = M - l[i-1]; for (int j = i+1; j <= n; j++) extras[i,j] = extras[i,j-1] - l[j-1] - 1; } // Calculate line cost corresponding to // the above calculated extra spaces. The // value lc[i][j] indicates cost of // putting words from word number i to // j in a single line for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { if (extras[i,j] < 0) lc[i,j] = MAX; else if (j == n && extras[i,j] >= 0) lc[i,j] = 0; else lc[i,j] = extras[i,j] * extras[i,j]; } } // Calculate minimum cost and find // minimum cost arrangement. The value // c[j] indicates optimized cost to // arrange words from word number // 1 to j. c[0] = 0; for (int j = 1; j <= n; j++) { c[j] = MAX; for (int i = 1; i <= j; i++) { if (c[i-1] != MAX && lc[i,j] != MAX && (c[i-1] + lc[i,j] < c[j])) { c[j] = c[i-1] + lc[i,j]; p[j] = i; } } } printSolution(p, n); } // Driver code public static void Main() { int []l = {3, 2, 2, 5}; int n = l.Length; int M = 6; solveWordWrap (l, n, M); }} // This code is contributed by nitin mittal. <script> // A Dynamic programming solution for // Word Wrap Problem in Javascript let MAX = Number.MAX_VALUE; // A utility function to print the solution function printSolution (p, n) { let k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; document.write("Line number" + " " + k + ": " + "From word no." +" "+ p[n] + " " + "to" + " " + n + "</br>"); return k; } // l[] represents lengths of different words in input sequence. // For example, l[] = {3, 2, 2, 5} is for a sentence like // "aaa bb cc ddddd". n is size of l[] and M is line width // (maximum no. of characters that can fit in a line) function solveWordWrap (l, n, M) { // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line let extras = new Array(n+1); // lc[i][j] will have cost of a line which has words from // i to j let lc = new Array(n+1); for(let i = 0; i < n + 1; i++) { extras[i] = new Array(n + 1); lc[i] = new Array(n + 1); for(let j = 0; j < n + 1; j++) { extras[i][j] = 0; lc[i][j] = 0; } } // c[i] will have total cost of optimal arrangement of words // from 1 to i let c = new Array(n+1); // p[] is used to print the solution. let p = new Array(n+1); // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (let i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (let j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (let i = 1; i <= n; i++) { for (let j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = MAX; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (let j = 1; j <= n; j++) { c[j] = MAX; for (let i = 1; i <= j; i++) { if (c[i-1] != MAX && lc[i][j] != MAX && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n); } let l = [3, 2, 2, 5]; let n = l.length; let M = 6; solveWordWrap (l, n, M); // This code is contributed by mukesh07.</script> Line number 1: From word no. 1 to 1 Line number 2: From word no. 2 to 3 Line number 3: From word no. 4 to 4 Time Complexity: O(n^2) Auxiliary Space: O(n^2) The auxiliary space used in the above program cane be optimized to O(n) (See the reference 2 for details)Word Wrap problem ( Space optimized solution )References: http://en.wikipedia.org/wiki/Word_wrapPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal sahilshelangia rathbhupendra mukesh07 aaditya pandilwar GauravRajput1 hardikgulati96 tapeshdua420 sanjoy_62 Microsoft Dynamic Programming Microsoft Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Sieve of Eratosthenes Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Minimum number of jumps to reach end Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find minimum number of coins that make a given value
[ { "code": null, "e": 54, "s": 26, "text": "\n12 May, 2022" }, { "code": null, "e": 522, "s": 54, "text": "Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width.The word processors like MS Word do task of placing line breaks. The idea is to have balanced lines. In other words, not have few lines with lots of extra spaces and some lines with small amount of extra spaces. " }, { "code": null, "e": 1120, "s": 522, "text": "The extra spaces includes spaces put at the end of every line except the last one. \nThe problem is to minimize the following total cost.\n Cost of a line = (Number of extra spaces in the line)^3\n Total Cost = Sum of costs for all lines\n\nFor example, consider the following string and line width M = 15\n \"Geeks for Geeks presents word wrap problem\" \n \nFollowing is the optimized arrangement of words in 3 lines\nGeeks for Geeks\npresents word\nwrap problem \n\nThe total extra spaces in line 1, line 2 and line 3 are 0, 2 and 3 respectively. \nSo optimal value of total cost is 0 + 2*2*2 + 3*3*3 = 35" }, { "code": null, "e": 1953, "s": 1120, "text": "Please note that the total cost function is not sum of extra spaces, but sum of cubes (or square is also used) of extra spaces. The idea behind this cost function is to balance the spaces among lines. For example, consider the following two arrangement of same set of words:1) There are 3 lines. One line has 3 extra spaces and all other lines have 0 extra spaces. Total extra spaces = 3 + 0 + 0 = 3. Total cost = 3*3*3 + 0*0*0 + 0*0*0 = 27.2) There are 3 lines. Each of the 3 lines has one extra space. Total extra spaces = 1 + 1 + 1 = 3. Total cost = 1*1*1 + 1*1*1 + 1*1*1 = 3.Total extra spaces are 3 in both scenarios, but second arrangement should be preferred because extra spaces are balanced in all three lines. The cost function with cubic sum serves the purpose because the value of total cost in second scenario is less. " }, { "code": null, "e": 2367, "s": 1953, "text": "Method 1 (Greedy Solution) The greedy solution is to place as many words as possible in the first line. Then do the same thing for the second line and so on until all words are placed. This solution gives optimal solution for many cases, but doesn’t give optimal solution in all cases. For example, consider the following string “aaa bb cc ddddd” and line width as 6. Greedy method will produce following output. " }, { "code": null, "e": 2385, "s": 2367, "text": "aaa bb \ncc \nddddd" }, { "code": null, "e": 2623, "s": 2385, "text": "Extra spaces in the above 3 lines are 0, 4 and 1 respectively. So total cost is 0 + 64 + 1 = 65.But the above solution is not the best solution. Following arrangement has more balanced spaces. Therefore less value of total cost function." }, { "code": null, "e": 2639, "s": 2623, "text": "aaa\nbb cc\nddddd" }, { "code": null, "e": 2868, "s": 2639, "text": "Extra spaces in the above 3 lines are 3, 1 and 1 respectively. So total cost is 27 + 1 + 1 = 29.Despite being sub-optimal in some cases, the greedy approach is used by many word processors like MS Word and OpenOffice.org Writer." }, { "code": null, "e": 2915, "s": 2868, "text": "Method 2 (Recursive Approach with memoization)" }, { "code": null, "e": 3037, "s": 2915, "text": "The problem can be solved using a divide and conquer (recursive) approach. The algorithm for the same is mentioned below:" }, { "code": null, "e": 3928, "s": 3037, "text": "1. We recur for each word starting with first word, and remaining length of the line (initially k).\n2. The last word would be the base case:\n We check if we can put it on same line:\n if yes, then we return cost as 0.\n if no, we return cost of current line based on its remaining length.\n3. For non-last words, we have to check if it can fit in the current line:\n if yes, then we have two choices i.e. whether to put it in same line or next line.\n if we put it on next line: cost1 = square(remLength) + cost of putting word on next line.\n if we put it on same line: cost2 = cost of putting word on same line.\n return min(cost1, cost2)\n if no, then we have to put it on next line:\n return cost of putting word on next line\n4. We use memoization table of size n (number of words) * k (line length), to keep track of already visited positions." }, { "code": null, "e": 3932, "s": 3928, "text": "C++" }, { "code": null, "e": 3937, "s": 3932, "text": "Java" }, { "code": null, "e": 3945, "s": 3937, "text": "Python3" }, { "code": null, "e": 3948, "s": 3945, "text": "C#" }, { "code": null, "e": 3959, "s": 3948, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int solveWordWrapUsingMemo(int words[], int n, int length, int wordIndex, int remLength, vector<vector<int> > memo); int square(int n) { return n * n; } int solveWordWrapUtil(int words[], int n, int length, int wordIndex, int remLength, vector<vector<int> > memo){ // base case for last word if (wordIndex == n - 1) { memo[wordIndex][remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex][remLength]; } int currWord = words[wordIndex]; // if word can fit in the remaining line if (currWord < remLength) { return min(solveWordWrapUsingMemo( words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo)); } else { // if word is kept on next line return square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo); }} int solveWordWrapUsingMemo(int words[], int n, int length, int wordIndex, int remLength, vector<vector<int> > memo){ if (memo[wordIndex][remLength] != -1) { return memo[wordIndex][remLength]; } memo[wordIndex][remLength] = solveWordWrapUtil( words, n, length, wordIndex, remLength, memo); return memo[wordIndex][remLength];} int solveWordWrap(int words[], int n, int k){ vector<vector<int> > memo(n, vector<int>(k + 1, -1)); return solveWordWrapUsingMemo(words, n, k, 0, k, memo);}int main(){ int words[] = { 3, 2, 2, 5 }; int n = sizeof(words) / sizeof(words[0]); int k = 6; cout << solveWordWrap(words, n, k); return 0;}/* This Code is contributed by Tapesh (tapeshdua420) */", "e": 6193, "s": 3959, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.Arrays; public class WordWrapDpMemo { private int solveWordWrap(int[] nums, int k) { int[][] memo = new int[nums.length][k + 1]; for (int i = 0; i < nums.length; i++) { Arrays.fill(memo[i], -1); } return solveWordWrapUsingMemo(nums, nums.length, k, 0, k, memo); } private int solveWordWrap(int[] words, int n, int length, int wordIndex, int remLength, int[][] memo) { //base case for last word if (wordIndex == n - 1) { memo[wordIndex][remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex][remLength]; } int currWord = words[wordIndex]; //if word can fit in the remaining line if (currWord < remLength) { return Math.min( //if word is kept on same line solveWordWrapUsingMemo(words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), //if word is kept on next line square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo) ); } else { //if word is kept on next line return square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo); } } private int solveWordWrapUsingMemo(int[] words, int n, int length, int wordIndex, int remLength, int[][] memo) { if (memo[wordIndex][remLength] != -1) { return memo[wordIndex][remLength]; } memo[wordIndex][remLength] = solveWordWrap(words, n, length, wordIndex, remLength, memo); return memo[wordIndex][remLength]; } private int square(int n) { return n * n; } public static void main(String[] args) { System.out.println(new WordWrapDpMemo().solveWordWrap(new int[]{3, 2, 2, 5}, 6)); }}", "e": 8208, "s": 6193, "text": null }, { "code": "# Python program for the above approachdef square(n) : return n * n def solveWordWrapUtil(words, n, length, wordIndex, remLength, memo) : # base case for last word if (wordIndex == n - 1) : memo[wordIndex][remLength] = 0 if (words[wordIndex] < remLength) else square(remLength) return memo[wordIndex][remLength] currWord = words[wordIndex] # if word can fit in the remaining line if (currWord < remLength) : return min(solveWordWrapUsingMemo( words, n, length, wordIndex + 1, remLength - currWord if (remLength == length) else remLength - currWord - 1, memo), square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo)) else : # if word is kept on next line return (square(remLength) + solveWordWrapUsingMemo( words, n, length, wordIndex + 1, length - currWord, memo)) def solveWordWrapUsingMemo(words, n, length, wordIndex, remLength, memo) : if (memo[wordIndex][remLength] != -1) : return memo[wordIndex][remLength] memo[wordIndex][remLength] = (solveWordWrapUtil( words, n, length, wordIndex, remLength, memo)) return memo[wordIndex][remLength] def solveWordWrap(words, n, k) : memo = [[10]* (k + 1)]* n return solveWordWrapUsingMemo(words, n, k, 0, k, memo) # Driver Codeif __name__ == \"__main__\": words = [ 3, 2, 2, 5 ] n = len(words) k = 6 print(solveWordWrap(words, n, k)) # This code is contributed by sanjoy_62.", "e": 9989, "s": 8208, "text": null }, { "code": "/*package whatever //do not write package name here */using System;using System.Collections.Generic; public class WordWrapDpMemo { private int solveWordWrap(int[] nums, int k) { int[,] memo = new int[nums.Length ,k + 1]; for (int i = 0; i < memo.GetLength(0); i++) { for(int j = 0; j < memo.GetLength(1); j++) memo[i, j] = -1; } return solveWordWrapUsingMemo(nums, nums.Length, k, 0, k, memo); } private int solveWordWrap(int[] words, int n, int length, int wordIndex, int remLength, int[,] memo) { // base case for last word if (wordIndex == n - 1) { memo[wordIndex, remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex, remLength]; } int currWord = words[wordIndex]; // if word can fit in the remaining line if (currWord < remLength) { return Math.Min( // if word is kept on same line solveWordWrapUsingMemo(words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), // if word is kept on next line square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo)); } else { // if word is kept on next line return square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo); } } private int solveWordWrapUsingMemo(int[] words, int n, int length, int wordIndex, int remLength, int[,] memo) { if (memo[wordIndex,remLength] != -1) { return memo[wordIndex,remLength]; } memo[wordIndex,remLength] = solveWordWrap(words, n, length, wordIndex, remLength, memo); return memo[wordIndex, remLength]; } private int square(int n) { return n * n; } public static void Main(String[] args) { Console.WriteLine(new WordWrapDpMemo(). solveWordWrap(new int[] { 3, 2, 2, 5 }, 6)); }} // This code is contributed by gauravrajput1", "e": 12941, "s": 9989, "text": null }, { "code": "<script>/*package whatever //do not write package name here */function solveWordWrap(nums , k) { var memo = Array(nums.length).fill().map(()=>Array(k + 1).fill(-1)); return solveWordWrapUsingMemo(nums, nums.length, k, 0, k, memo); } function solveWordWrap1(words , n , length , wordIndex , remLength, memo) { // base case for last word if (wordIndex == n - 1) { memo[wordIndex][remLength] = words[wordIndex] < remLength ? 0 : square(remLength); return memo[wordIndex][remLength]; } var currWord = words[wordIndex]; // if word can fit in the remaining line if (currWord < remLength) { return Math.min( // if word is kept on same line solveWordWrapUsingMemo(words, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, memo), // if word is kept on next line square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo)); } else { // if word is kept on next line return square(remLength) + solveWordWrapUsingMemo(words, n, length, wordIndex + 1, length - currWord, memo); } } function solveWordWrapUsingMemo(words , n , length , wordIndex , remLength, memo) { //if (memo[wordIndex][remLength] != -1) { // return memo[wordIndex][remLength]; //} memo[wordIndex][remLength] = solveWordWrap1(words, n, length, wordIndex, remLength, memo); return memo[wordIndex][remLength]; } function square(n) { return n * n; } var arr = [ 3, 2, 2, 5 ]; document.write(solveWordWrap(arr, 6)); // This code is contributed by gauravrajput1</script>", "e": 14789, "s": 12941, "text": null }, { "code": null, "e": 14792, "s": 14789, "text": "10" }, { "code": null, "e": 15477, "s": 14794, "text": "Method 3 (Dynamic Programming) The following Dynamic approach strictly follows the algorithm given in solution of Cormen book. First we compute costs of all possible lines in a 2D table lc[][]. The value lc[i][j] indicates the cost to put words from i to j in a single line where i and j are indexes of words in the input sequences. If a sequence of words from i to j cannot fit in a single line, then lc[i][j] is considered infinite (to avoid it from being a part of the solution). Once we have the lc[][] table constructed, we can calculate total cost using following recursive formula. In the following formula, C[j] is the optimized total cost for arranging words from 1 to j. " }, { "code": null, "e": 16303, "s": 15477, "text": "The above recursion has overlapping subproblem property. For example, the solution of subproblem c(2) is used by c(3), C(4) and so on. So Dynamic Programming is used to store the results of subproblems. The array c[] can be computed from left to right, since each value depends only on earlier values. To print the output, we keep track of what words go on what lines, we can keep a parallel p array that points to where each c value came from. The last line starts at word p[n] and goes through word n. The previous line starts at word p[p[n]] and goes through word p[n] – 1, etc. The function printSolution() uses p[] to print the solution. In the below program, input is an array l[] that represents lengths of words in a sequence. The value l[i] indicates length of the ith word (i starts from 1) in theinput sequence. " }, { "code": null, "e": 16307, "s": 16303, "text": "C++" }, { "code": null, "e": 16309, "s": 16307, "text": "C" }, { "code": null, "e": 16314, "s": 16309, "text": "Java" }, { "code": null, "e": 16322, "s": 16314, "text": "Python3" }, { "code": null, "e": 16325, "s": 16322, "text": "C#" }, { "code": null, "e": 16336, "s": 16325, "text": "Javascript" }, { "code": "// A Dynamic programming solution for Word Wrap Problem#include <bits/stdc++.h>using namespace std;#define INF INT_MAX // A utility function to print the solutionint printSolution (int p[], int n); // l[] represents lengths of different words in input sequence.// For example, l[] = {3, 2, 2, 5} is for a sentence like// \"aaa bb cc ddddd\". n is size of l[] and M is line width// (maximum no. of characters that can fit in a line)void solveWordWrap (int l[], int n, int M){ // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line int extras[n+1][n+1]; // lc[i][j] will have cost of a line which has words from // i to j int lc[n+1][n+1]; // c[i] will have total cost of optimal arrangement of words // from 1 to i int c[n+1]; // p[] is used to print the solution. int p[n+1]; int i, j; // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = INF; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (j = 1; j <= n; j++) { c[j] = INF; for (i = 1; i <= j; i++) { if (c[i-1] != INF && lc[i][j] != INF && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n);} int printSolution (int p[], int n){ int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; cout<<\"Line number \"<<k<<\": From word no. \"<<p[n]<<\" to \"<<n<<endl; return k;} // Driver program to test above functionsint main(){ int l[] = {3, 2, 2, 5}; int n = sizeof(l)/sizeof(l[0]); int M = 6; solveWordWrap (l, n, M); return 0;} //This is code is contributed by rathbhupendra", "e": 19011, "s": 16336, "text": null }, { "code": "// A Dynamic programming solution for Word Wrap Problem#include <limits.h>#include <stdio.h>#define INF INT_MAX // A utility function to print the solutionint printSolution (int p[], int n); // l[] represents lengths of different words in input sequence.// For example, l[] = {3, 2, 2, 5} is for a sentence like// \"aaa bb cc ddddd\". n is size of l[] and M is line width// (maximum no. of characters that can fit in a line)void solveWordWrap (int l[], int n, int M){ // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line int extras[n+1][n+1]; // lc[i][j] will have cost of a line which has words from // i to j int lc[n+1][n+1]; // c[i] will have total cost of optimal arrangement of words // from 1 to i int c[n+1]; // p[] is used to print the solution. int p[n+1]; int i, j; // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = INF; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (j = 1; j <= n; j++) { c[j] = INF; for (i = 1; i <= j; i++) { if (c[i-1] != INF && lc[i][j] != INF && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n);} int printSolution (int p[], int n){ int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; printf (\"Line number %d: From word no. %d to %d \\n\", k, p[n], n); return k;} // Driver program to test above functionsint main(){ int l[] = {3, 2, 2, 5}; int n = sizeof(l)/sizeof(l[0]); int M = 6; solveWordWrap (l, n, M); return 0;}", "e": 21622, "s": 19011, "text": null }, { "code": "// A Dynamic programming solution for// Word Wrap Problem in Javapublic class WordWrap{ final int MAX = Integer.MAX_VALUE; // A utility function to print the solution int printSolution (int p[], int n) { int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; System.out.println(\"Line number\" + \" \" + k + \": \" + \"From word no.\" +\" \"+ p[n] + \" \" + \"to\" + \" \" + n); return k; } // l[] represents lengths of different words in input sequence.// For example, l[] = {3, 2, 2, 5} is for a sentence like// \"aaa bb cc ddddd\". n is size of l[] and M is line width// (maximum no. of characters that can fit in a line) void solveWordWrap (int l[], int n, int M) { // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line int extras[][] = new int[n+1][n+1]; // lc[i][j] will have cost of a line which has words from // i to j int lc[][]= new int[n+1][n+1]; // c[i] will have total cost of optimal arrangement of words // from 1 to i int c[] = new int[n+1]; // p[] is used to print the solution. int p[] =new int[n+1]; // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (int i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (int j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = MAX; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (int j = 1; j <= n; j++) { c[j] = MAX; for (int i = 1; i <= j; i++) { if (c[i-1] != MAX && lc[i][j] != MAX && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n); } public static void main(String args[]) { WordWrap w = new WordWrap(); int l[] = {3, 2, 2, 5}; int n = l.length; int M = 6; w.solveWordWrap (l, n, M); }} // This code is contributed by Saket Kumar", "e": 24698, "s": 21622, "text": null }, { "code": "# A Dynamic programming solution# for Word Wrap Problem # A utility function to print# the solution# l[] represents lengths of different# words in input sequence. For example,# l[] = {3, 2, 2, 5} is for a sentence# like \"aaa bb cc ddddd\". n is size of# l[] and M is line width (maximum no.# of characters that can fit in a line)INF = 2147483647def printSolution(p, n): k = 0 if p[n] == 1: k = 1 else: k = printSolution(p, p[n] - 1) + 1 print('Line number ', k, ': From word no. ', p[n], 'to ', n) return k def solveWordWrap (l, n, M): # For simplicity, 1 extra space is # used in all below arrays # extras[i][j] will have number # of extra spaces if words from i # to j are put in a single line extras = [[0 for i in range(n + 1)] for i in range(n + 1)] # lc[i][j] will have cost of a line # which has words from i to j lc = [[0 for i in range(n + 1)] for i in range(n + 1)] # c[i] will have total cost of # optimal arrangement of words # from 1 to i c = [0 for i in range(n + 1)] # p[] is used to print the solution. p = [0 for i in range(n + 1)] # calculate extra spaces in a single # line. The value extra[i][j] indicates # extra spaces if words from word number # i to j are placed in a single line for i in range(n + 1): extras[i][i] = M - l[i - 1] for j in range(i + 1, n + 1): extras[i][j] = (extras[i][j - 1] - l[j - 1] - 1) # Calculate line cost corresponding # to the above calculated extra # spaces. The value lc[i][j] indicates # cost of putting words from word number # i to j in a single line for i in range(n + 1): for j in range(i, n + 1): if extras[i][j] < 0: lc[i][j] = INF; elif j == n and extras[i][j] >= 0: lc[i][j] = 0 else: lc[i][j] = (extras[i][j] * extras[i][j]) # Calculate minimum cost and find # minimum cost arrangement. The value # c[j] indicates optimized cost to # arrange words from word number 1 to j. c[0] = 0 for j in range(1, n + 1): c[j] = INF for i in range(1, j + 1): if (c[i - 1] != INF and lc[i][j] != INF and ((c[i - 1] + lc[i][j]) < c[j])): c[j] = c[i-1] + lc[i][j] p[j] = i printSolution(p, n) # Driver Codel = [3, 2, 2, 5]n = len(l)M = 6solveWordWrap(l, n, M) # This code is contributed by sahil shelangia", "e": 27385, "s": 24698, "text": null }, { "code": "// A Dynamic programming solution for Word Wrap// Problem in Javausing System; public class GFG { static int MAX = int.MaxValue; // A utility function to print the solution static int printSolution (int []p, int n) { int k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; Console.WriteLine(\"Line number\" + \" \" + k + \": From word no.\" + \" \" + p[n] + \" \" + \"to\" + \" \" + n); return k; } // l[] represents lengths of different // words in input sequence. For example, // l[] = {3, 2, 2, 5} is for a sentence // like \"aaa bb cc ddddd\". n is size of // l[] and M is line width (maximum no. // of characters that can fit in a line) static void solveWordWrap (int []l, int n, int M) { // For simplicity, 1 extra space // is used in all below arrays // extras[i][j] will have number of // extra spaces if words from i // to j are put in a single line int [,]extras = new int[n+1,n+1]; // lc[i][j] will have cost of a line // which has words from i to j int [,]lc = new int[n+1,n+1]; // c[i] will have total cost of // optimal arrangement of words // from 1 to i int []c = new int[n+1]; // p[] is used to print the solution. int []p = new int[n+1]; // calculate extra spaces in a single // line. The value extra[i][j] indicates // extra spaces if words from word number // i to j are placed in a single line for (int i = 1; i <= n; i++) { extras[i,i] = M - l[i-1]; for (int j = i+1; j <= n; j++) extras[i,j] = extras[i,j-1] - l[j-1] - 1; } // Calculate line cost corresponding to // the above calculated extra spaces. The // value lc[i][j] indicates cost of // putting words from word number i to // j in a single line for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { if (extras[i,j] < 0) lc[i,j] = MAX; else if (j == n && extras[i,j] >= 0) lc[i,j] = 0; else lc[i,j] = extras[i,j] * extras[i,j]; } } // Calculate minimum cost and find // minimum cost arrangement. The value // c[j] indicates optimized cost to // arrange words from word number // 1 to j. c[0] = 0; for (int j = 1; j <= n; j++) { c[j] = MAX; for (int i = 1; i <= j; i++) { if (c[i-1] != MAX && lc[i,j] != MAX && (c[i-1] + lc[i,j] < c[j])) { c[j] = c[i-1] + lc[i,j]; p[j] = i; } } } printSolution(p, n); } // Driver code public static void Main() { int []l = {3, 2, 2, 5}; int n = l.Length; int M = 6; solveWordWrap (l, n, M); }} // This code is contributed by nitin mittal.", "e": 30779, "s": 27385, "text": null }, { "code": "<script> // A Dynamic programming solution for // Word Wrap Problem in Javascript let MAX = Number.MAX_VALUE; // A utility function to print the solution function printSolution (p, n) { let k; if (p[n] == 1) k = 1; else k = printSolution (p, p[n]-1) + 1; document.write(\"Line number\" + \" \" + k + \": \" + \"From word no.\" +\" \"+ p[n] + \" \" + \"to\" + \" \" + n + \"</br>\"); return k; } // l[] represents lengths of different words in input sequence. // For example, l[] = {3, 2, 2, 5} is for a sentence like // \"aaa bb cc ddddd\". n is size of l[] and M is line width // (maximum no. of characters that can fit in a line) function solveWordWrap (l, n, M) { // For simplicity, 1 extra space is used in all below arrays // extras[i][j] will have number of extra spaces if words from i // to j are put in a single line let extras = new Array(n+1); // lc[i][j] will have cost of a line which has words from // i to j let lc = new Array(n+1); for(let i = 0; i < n + 1; i++) { extras[i] = new Array(n + 1); lc[i] = new Array(n + 1); for(let j = 0; j < n + 1; j++) { extras[i][j] = 0; lc[i][j] = 0; } } // c[i] will have total cost of optimal arrangement of words // from 1 to i let c = new Array(n+1); // p[] is used to print the solution. let p = new Array(n+1); // calculate extra spaces in a single line. The value extra[i][j] // indicates extra spaces if words from word number i to j are // placed in a single line for (let i = 1; i <= n; i++) { extras[i][i] = M - l[i-1]; for (let j = i+1; j <= n; j++) extras[i][j] = extras[i][j-1] - l[j-1] - 1; } // Calculate line cost corresponding to the above calculated extra // spaces. The value lc[i][j] indicates cost of putting words from // word number i to j in a single line for (let i = 1; i <= n; i++) { for (let j = i; j <= n; j++) { if (extras[i][j] < 0) lc[i][j] = MAX; else if (j == n && extras[i][j] >= 0) lc[i][j] = 0; else lc[i][j] = extras[i][j]*extras[i][j]; } } // Calculate minimum cost and find minimum cost arrangement. // The value c[j] indicates optimized cost to arrange words // from word number 1 to j. c[0] = 0; for (let j = 1; j <= n; j++) { c[j] = MAX; for (let i = 1; i <= j; i++) { if (c[i-1] != MAX && lc[i][j] != MAX && (c[i-1] + lc[i][j] < c[j])) { c[j] = c[i-1] + lc[i][j]; p[j] = i; } } } printSolution(p, n); } let l = [3, 2, 2, 5]; let n = l.length; let M = 6; solveWordWrap (l, n, M); // This code is contributed by mukesh07.</script>", "e": 34062, "s": 30779, "text": null }, { "code": null, "e": 34170, "s": 34062, "text": "Line number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 3\nLine number 3: From word no. 4 to 4" }, { "code": null, "e": 34545, "s": 34170, "text": "Time Complexity: O(n^2) Auxiliary Space: O(n^2) The auxiliary space used in the above program cane be optimized to O(n) (See the reference 2 for details)Word Wrap problem ( Space optimized solution )References: http://en.wikipedia.org/wiki/Word_wrapPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34558, "s": 34545, "text": "nitin mittal" }, { "code": null, "e": 34573, "s": 34558, "text": "sahilshelangia" }, { "code": null, "e": 34587, "s": 34573, "text": "rathbhupendra" }, { "code": null, "e": 34596, "s": 34587, "text": "mukesh07" }, { "code": null, "e": 34614, "s": 34596, "text": "aaditya pandilwar" }, { "code": null, "e": 34628, "s": 34614, "text": "GauravRajput1" }, { "code": null, "e": 34643, "s": 34628, "text": "hardikgulati96" }, { "code": null, "e": 34656, "s": 34643, "text": "tapeshdua420" }, { "code": null, "e": 34666, "s": 34656, "text": "sanjoy_62" }, { "code": null, "e": 34676, "s": 34666, "text": "Microsoft" }, { "code": null, "e": 34696, "s": 34676, "text": "Dynamic Programming" }, { "code": null, "e": 34706, "s": 34696, "text": "Microsoft" }, { "code": null, "e": 34726, "s": 34706, "text": "Dynamic Programming" }, { "code": null, "e": 34824, "s": 34726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34851, "s": 34824, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 34889, "s": 34851, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 34922, "s": 34889, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 34941, "s": 34922, "text": "Coin Change | DP-7" }, { "code": null, "e": 34963, "s": 34941, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 34998, "s": 34963, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 35029, "s": 34998, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 35066, "s": 35029, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 35134, "s": 35066, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" } ]
Thread Pools in Java
30 Jul, 2020 Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service this new request in the newly created thread. While this approach seems simple to implement, it has significant disadvantages. A server that creates a new thread for every request would spend more time and consume more system resources in creating and destroying threads than processing actual requests. Since active threads consume system resources, a JVM creating too many threads at the same time can cause the system to run out of memory. This necessitates the need to limit the number of threads being created. What is ThreadPool in Java? A thread pool reuses previously created threads to execute current tasks and offers a solution to the problem of thread cycle overhead and resource thrashing. Since the thread is already existing when the request arrives, the delay introduced by thread creation is eliminated, making the application more responsive. Java provides the Executor framework which is centered around the Executor interface, its sub-interface –ExecutorService and the class-ThreadPoolExecutor, which implements both of these interfaces. By using the executor, one only has to implement the Runnable objects and send them to the executor to execute. They allow you to take advantage of threading, but focus on the tasks that you want the thread to perform, instead of thread mechanics. To use thread pools, we first create a object of ExecutorService and pass a set of tasks to it. ThreadPoolExecutor class allows to set the core and maximum pool size.The runnables that are run by a particular thread are executed sequentially.Thread Pool Initialization with size = 3 threads. Task Queue = 5 Runnable Objects Thread Pool Initialization with size = 3 threads. Task Queue = 5 Runnable Objects Executor Thread Pool Methods Method Description newFixedThreadPool(int) Creates a fixed size thread pool. newCachedThreadPool() Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available newSingleThreadExecutor() Creates a single thread. In case of a fixed thread pool, if all threads are being currently run by the executor then the pending tasks are placed in a queue and are executed when a thread becomes idle. Thread Pool Example In the following tutorial, we will look at a basic example of thread pool executor- FixedThreadPool. Steps to be followed 1. Create a task(Runnable Object) to execute 2. Create Executor Pool using Executors 3. Pass tasks to Executor Pool 4. Shutdown the Executor Pool // Java program to illustrate // ThreadPoolimport java.text.SimpleDateFormat; import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; // Task class to be executed (Step 1)class Task implements Runnable { private String name; public Task(String s) { name = s; } // Prints task name and sleeps for 1s // This Whole process is repeated 5 times public void run() { try { for (int i = 0; i<=5; i++) { if (i==0) { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println("Initialization Time for" + " task name - "+ name +" = " +ft.format(d)); //prints the initialization time for every task } else { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println("Executing Time for task name - "+ name +" = " +ft.format(d)); // prints the execution time for every task } Thread.sleep(1000); } System.out.println(name+" complete"); } catch(InterruptedException e) { e.printStackTrace(); } }}public class Test{ // Maximum number of threads in thread pool static final int MAX_T = 3; public static void main(String[] args) { // creates five tasks Runnable r1 = new Task("task 1"); Runnable r2 = new Task("task 2"); Runnable r3 = new Task("task 3"); Runnable r4 = new Task("task 4"); Runnable r5 = new Task("task 5"); // creates a thread pool with MAX_T no. of // threads as the fixed pool size(Step 2) ExecutorService pool = Executors.newFixedThreadPool(MAX_T); // passes the Task objects to the pool to execute (Step 3) pool.execute(r1); pool.execute(r2); pool.execute(r3); pool.execute(r4); pool.execute(r5); // pool shutdown ( Step 4) pool.shutdown(); }} Sample Execution Output: Initialization Time for task name - task 2 = 02:32:56 Initialization Time for task name - task 1 = 02:32:56 Initialization Time for task name - task 3 = 02:32:56 Executing Time for task name - task 1 = 02:32:57 Executing Time for task name - task 2 = 02:32:57 Executing Time for task name - task 3 = 02:32:57 Executing Time for task name - task 1 = 02:32:58 Executing Time for task name - task 2 = 02:32:58 Executing Time for task name - task 3 = 02:32:58 Executing Time for task name - task 1 = 02:32:59 Executing Time for task name - task 2 = 02:32:59 Executing Time for task name - task 3 = 02:32:59 Executing Time for task name - task 1 = 02:33:00 Executing Time for task name - task 3 = 02:33:00 Executing Time for task name - task 2 = 02:33:00 Executing Time for task name - task 2 = 02:33:01 Executing Time for task name - task 1 = 02:33:01 Executing Time for task name - task 3 = 02:33:01 task 2 complete task 1 complete task 3 complete Initialization Time for task name - task 5 = 02:33:02 Initialization Time for task name - task 4 = 02:33:02 Executing Time for task name - task 4 = 02:33:03 Executing Time for task name - task 5 = 02:33:03 Executing Time for task name - task 5 = 02:33:04 Executing Time for task name - task 4 = 02:33:04 Executing Time for task name - task 4 = 02:33:05 Executing Time for task name - task 5 = 02:33:05 Executing Time for task name - task 5 = 02:33:06 Executing Time for task name - task 4 = 02:33:06 Executing Time for task name - task 5 = 02:33:07 Executing Time for task name - task 4 = 02:33:07 task 5 complete task 4 complete As seen in the execution of the program, the task 4 or task 5 are executed only when a thread in the pool becomes idle. Until then, the extra tasks are placed in a queue. Thread Pool executing first three tasks Thread Pool executing task 4 and 5 One of the main advantages of using this approach is when you want to process 100 requests at a time, but do not want to create 100 Threads for the same, so as to reduce JVM overload. You can use this approach to create a ThreadPool of 10 Threads and you can submit 100 requests to this ThreadPool. ThreadPool will create maximum of 10 threads to process 10 requests at a time. After process completion of any single Thread, ThreadPool will internally allocate the 11th request to this Thread and will keep on doing the same to all the remaining requests. Risks in using Thread Pools Deadlock : While deadlock can occur in any multi-threaded program, thread pools introduce another case of deadlock, one in which all the executing threads are waiting for the results from the blocked threads waiting in the queue due to the unavailability of threads for execution.Thread Leakage :Thread Leakage occurs if a thread is removed from the pool to execute a task but not returned to it when the task completed. As an example, if the thread throws an exception and pool class does not catch this exception, then the thread will simply exit, reducing the size of the thread pool by one. If this repeats many times, then the pool would eventually become empty and no threads would be available to execute other requests.Resource Thrashing :If the thread pool size is very large then time is wasted in context switching between threads. Having more threads than the optimal number may cause starvation problem leading to resource thrashing as explained. Deadlock : While deadlock can occur in any multi-threaded program, thread pools introduce another case of deadlock, one in which all the executing threads are waiting for the results from the blocked threads waiting in the queue due to the unavailability of threads for execution. Thread Leakage :Thread Leakage occurs if a thread is removed from the pool to execute a task but not returned to it when the task completed. As an example, if the thread throws an exception and pool class does not catch this exception, then the thread will simply exit, reducing the size of the thread pool by one. If this repeats many times, then the pool would eventually become empty and no threads would be available to execute other requests. Resource Thrashing :If the thread pool size is very large then time is wasted in context switching between threads. Having more threads than the optimal number may cause starvation problem leading to resource thrashing as explained. Important Points Don’t queue tasks that concurrently wait for results from other tasks. This can lead to a situation of deadlock as described above.Be careful while using threads for a long lived operation. It might result in the thread waiting forever and would eventually lead to resource leakage.The Thread Pool has to be ended explicitly at the end. If this is not done, then the program goes on executing and never ends. Call shutdown() on the pool to end the executor. If you try to send another task to the executor after shutdown, it will throw a RejectedExecutionException.One needs to understand the tasks to effectively tune the thread pool. If the tasks are very contrasting then it makes sense to use different thread pools for different types of tasks so as to tune them properly.You can restrict maximum number of threads that can run in JVM, reducing chances of JVM running out of memory.If you need to implement your loop to create new threads for processing, using ThreadPool will help to process faster, as ThreadPool does not create new Threads after it reached it’s max limit.After completion of Thread Processing, ThreadPool can use the same Thread to do another process(so saving the time and resources to create another Thread.) Don’t queue tasks that concurrently wait for results from other tasks. This can lead to a situation of deadlock as described above. Be careful while using threads for a long lived operation. It might result in the thread waiting forever and would eventually lead to resource leakage. The Thread Pool has to be ended explicitly at the end. If this is not done, then the program goes on executing and never ends. Call shutdown() on the pool to end the executor. If you try to send another task to the executor after shutdown, it will throw a RejectedExecutionException. One needs to understand the tasks to effectively tune the thread pool. If the tasks are very contrasting then it makes sense to use different thread pools for different types of tasks so as to tune them properly. You can restrict maximum number of threads that can run in JVM, reducing chances of JVM running out of memory. If you need to implement your loop to create new threads for processing, using ThreadPool will help to process faster, as ThreadPool does not create new Threads after it reached it’s max limit. After completion of Thread Processing, ThreadPool can use the same Thread to do another process(so saving the time and resources to create another Thread.) Tuning Thread Pool The optimum size of the thread pool depends on the number of processors available and the nature of the tasks. On a N processor system for a queue of only computation type processes, a maximum thread pool size of N or N+1 will achieve the maximum efficiency.But tasks may wait for I/O and in such a case we take into account the ratio of waiting time(W) and service time(S) for a request; resulting in a maximum pool size of N*(1+ W/S) for maximum efficiency. The thread pool is a useful tool for organizing server applications. It is quite straightforward in concept, but there are several issues to watch for when implementing and using one, such as deadlock, resource thrashing. Use of executor service makes it easier to implement. This article is contributed by Abhishek. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. lehanshukhatri Akanksha_Rai Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initialize an ArrayList in Java Initializing a List in Java Generics in Java Java Programming Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jul, 2020" }, { "code": null, "e": 65, "s": 54, "text": "Background" }, { "code": null, "e": 658, "s": 65, "text": "Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service this new request in the newly created thread. While this approach seems simple to implement, it has significant disadvantages. A server that creates a new thread for every request would spend more time and consume more system resources in creating and destroying threads than processing actual requests." }, { "code": null, "e": 870, "s": 658, "text": "Since active threads consume system resources, a JVM creating too many threads at the same time can cause the system to run out of memory. This necessitates the need to limit the number of threads being created." }, { "code": null, "e": 898, "s": 870, "text": "What is ThreadPool in Java?" }, { "code": null, "e": 1215, "s": 898, "text": "A thread pool reuses previously created threads to execute current tasks and offers a solution to the problem of thread cycle overhead and resource thrashing. Since the thread is already existing when the request arrives, the delay introduced by thread creation is eliminated, making the application more responsive." }, { "code": null, "e": 1525, "s": 1215, "text": "Java provides the Executor framework which is centered around the Executor interface, its sub-interface –ExecutorService and the class-ThreadPoolExecutor, which implements both of these interfaces. By using the executor, one only has to implement the Runnable objects and send them to the executor to execute." }, { "code": null, "e": 1661, "s": 1525, "text": "They allow you to take advantage of threading, but focus on the tasks that you want the thread to perform, instead of thread mechanics." }, { "code": null, "e": 1985, "s": 1661, "text": "To use thread pools, we first create a object of ExecutorService and pass a set of tasks to it. ThreadPoolExecutor class allows to set the core and maximum pool size.The runnables that are run by a particular thread are executed sequentially.Thread Pool Initialization with size = 3 threads. Task Queue = 5 Runnable Objects" }, { "code": null, "e": 2067, "s": 1985, "text": "Thread Pool Initialization with size = 3 threads. Task Queue = 5 Runnable Objects" }, { "code": null, "e": 2096, "s": 2067, "text": "Executor Thread Pool Methods" }, { "code": null, "e": 2500, "s": 2096, "text": "Method Description\nnewFixedThreadPool(int) Creates a fixed size thread pool.\nnewCachedThreadPool() Creates a thread pool that creates new \n threads as needed, but will reuse previously \n constructed threads when they are available\nnewSingleThreadExecutor() Creates a single thread. \n" }, { "code": null, "e": 2677, "s": 2500, "text": "In case of a fixed thread pool, if all threads are being currently run by the executor then the pending tasks are placed in a queue and are executed when a thread becomes idle." }, { "code": null, "e": 2697, "s": 2677, "text": "Thread Pool Example" }, { "code": null, "e": 2798, "s": 2697, "text": "In the following tutorial, we will look at a basic example of thread pool executor- FixedThreadPool." }, { "code": null, "e": 2819, "s": 2798, "text": "Steps to be followed" }, { "code": null, "e": 2966, "s": 2819, "text": "1. Create a task(Runnable Object) to execute\n2. Create Executor Pool using Executors\n3. Pass tasks to Executor Pool\n4. Shutdown the Executor Pool\n" }, { "code": "// Java program to illustrate // ThreadPoolimport java.text.SimpleDateFormat; import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; // Task class to be executed (Step 1)class Task implements Runnable { private String name; public Task(String s) { name = s; } // Prints task name and sleeps for 1s // This Whole process is repeated 5 times public void run() { try { for (int i = 0; i<=5; i++) { if (i==0) { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat(\"hh:mm:ss\"); System.out.println(\"Initialization Time for\" + \" task name - \"+ name +\" = \" +ft.format(d)); //prints the initialization time for every task } else { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat(\"hh:mm:ss\"); System.out.println(\"Executing Time for task name - \"+ name +\" = \" +ft.format(d)); // prints the execution time for every task } Thread.sleep(1000); } System.out.println(name+\" complete\"); } catch(InterruptedException e) { e.printStackTrace(); } }}public class Test{ // Maximum number of threads in thread pool static final int MAX_T = 3; public static void main(String[] args) { // creates five tasks Runnable r1 = new Task(\"task 1\"); Runnable r2 = new Task(\"task 2\"); Runnable r3 = new Task(\"task 3\"); Runnable r4 = new Task(\"task 4\"); Runnable r5 = new Task(\"task 5\"); // creates a thread pool with MAX_T no. of // threads as the fixed pool size(Step 2) ExecutorService pool = Executors.newFixedThreadPool(MAX_T); // passes the Task objects to the pool to execute (Step 3) pool.execute(r1); pool.execute(r2); pool.execute(r3); pool.execute(r4); pool.execute(r5); // pool shutdown ( Step 4) pool.shutdown(); }}", "e": 5306, "s": 2966, "text": null }, { "code": null, "e": 5323, "s": 5306, "text": "Sample Execution" }, { "code": null, "e": 6907, "s": 5323, "text": "Output:\nInitialization Time for task name - task 2 = 02:32:56\nInitialization Time for task name - task 1 = 02:32:56\nInitialization Time for task name - task 3 = 02:32:56\nExecuting Time for task name - task 1 = 02:32:57\nExecuting Time for task name - task 2 = 02:32:57\nExecuting Time for task name - task 3 = 02:32:57\nExecuting Time for task name - task 1 = 02:32:58\nExecuting Time for task name - task 2 = 02:32:58\nExecuting Time for task name - task 3 = 02:32:58\nExecuting Time for task name - task 1 = 02:32:59\nExecuting Time for task name - task 2 = 02:32:59\nExecuting Time for task name - task 3 = 02:32:59\nExecuting Time for task name - task 1 = 02:33:00\nExecuting Time for task name - task 3 = 02:33:00\nExecuting Time for task name - task 2 = 02:33:00\nExecuting Time for task name - task 2 = 02:33:01\nExecuting Time for task name - task 1 = 02:33:01\nExecuting Time for task name - task 3 = 02:33:01\ntask 2 complete\ntask 1 complete\ntask 3 complete\nInitialization Time for task name - task 5 = 02:33:02\nInitialization Time for task name - task 4 = 02:33:02\nExecuting Time for task name - task 4 = 02:33:03\nExecuting Time for task name - task 5 = 02:33:03\nExecuting Time for task name - task 5 = 02:33:04\nExecuting Time for task name - task 4 = 02:33:04\nExecuting Time for task name - task 4 = 02:33:05\nExecuting Time for task name - task 5 = 02:33:05\nExecuting Time for task name - task 5 = 02:33:06\nExecuting Time for task name - task 4 = 02:33:06\nExecuting Time for task name - task 5 = 02:33:07\nExecuting Time for task name - task 4 = 02:33:07\ntask 5 complete\ntask 4 complete\n" }, { "code": null, "e": 7078, "s": 6907, "text": "As seen in the execution of the program, the task 4 or task 5 are executed only when a thread in the pool becomes idle. Until then, the extra tasks are placed in a queue." }, { "code": null, "e": 7118, "s": 7078, "text": "Thread Pool executing first three tasks" }, { "code": null, "e": 7153, "s": 7118, "text": "Thread Pool executing task 4 and 5" }, { "code": null, "e": 7714, "s": 7153, "text": "One of the main advantages of using this approach is when you want to process 100 requests at a time, but do not want to create 100 Threads for the same, so as to reduce JVM overload. You can use this approach to create a ThreadPool of 10 Threads and you can submit 100 requests to this ThreadPool. \nThreadPool will create maximum of 10 threads to process 10 requests at a time. After process completion of any single Thread, \nThreadPool will internally allocate the 11th request to this Thread \nand will keep on doing the same to all the remaining requests.\n" }, { "code": null, "e": 7742, "s": 7714, "text": "Risks in using Thread Pools" }, { "code": null, "e": 8702, "s": 7742, "text": "Deadlock : While deadlock can occur in any multi-threaded program, thread pools introduce another case of deadlock, one in which all the executing threads are waiting for the results from the blocked threads waiting in the queue due to the unavailability of threads for execution.Thread Leakage :Thread Leakage occurs if a thread is removed from the pool to execute a task but not returned to it when the task completed. As an example, if the thread throws an exception and pool class does not catch this exception, then the thread will simply exit, reducing the size of the thread pool by one. If this repeats many times, then the pool would eventually become empty and no threads would be available to execute other requests.Resource Thrashing :If the thread pool size is very large then time is wasted in context switching between threads. Having more threads than the optimal number may cause starvation problem leading to resource thrashing as explained." }, { "code": null, "e": 8983, "s": 8702, "text": "Deadlock : While deadlock can occur in any multi-threaded program, thread pools introduce another case of deadlock, one in which all the executing threads are waiting for the results from the blocked threads waiting in the queue due to the unavailability of threads for execution." }, { "code": null, "e": 9431, "s": 8983, "text": "Thread Leakage :Thread Leakage occurs if a thread is removed from the pool to execute a task but not returned to it when the task completed. As an example, if the thread throws an exception and pool class does not catch this exception, then the thread will simply exit, reducing the size of the thread pool by one. If this repeats many times, then the pool would eventually become empty and no threads would be available to execute other requests." }, { "code": null, "e": 9664, "s": 9431, "text": "Resource Thrashing :If the thread pool size is very large then time is wasted in context switching between threads. Having more threads than the optimal number may cause starvation problem leading to resource thrashing as explained." }, { "code": null, "e": 9681, "s": 9664, "text": "Important Points" }, { "code": null, "e": 10917, "s": 9681, "text": "Don’t queue tasks that concurrently wait for results from other tasks. This can lead to a situation of deadlock as described above.Be careful while using threads for a long lived operation. It might result in the thread waiting forever and would eventually lead to resource leakage.The Thread Pool has to be ended explicitly at the end. If this is not done, then the program goes on executing and never ends. Call shutdown() on the pool to end the executor. If you try to send another task to the executor after shutdown, it will throw a RejectedExecutionException.One needs to understand the tasks to effectively tune the thread pool. If the tasks are very contrasting then it makes sense to use different thread pools for different types of tasks so as to tune them properly.You can restrict maximum number of threads that can run in JVM, reducing chances of JVM running out of memory.If you need to implement your loop to create new threads for processing, using ThreadPool will help to process faster, as ThreadPool does not create new Threads after it reached it’s max limit.After completion of Thread Processing, ThreadPool can use the same Thread to do another process(so saving the time and resources to create another Thread.)" }, { "code": null, "e": 11049, "s": 10917, "text": "Don’t queue tasks that concurrently wait for results from other tasks. This can lead to a situation of deadlock as described above." }, { "code": null, "e": 11201, "s": 11049, "text": "Be careful while using threads for a long lived operation. It might result in the thread waiting forever and would eventually lead to resource leakage." }, { "code": null, "e": 11485, "s": 11201, "text": "The Thread Pool has to be ended explicitly at the end. If this is not done, then the program goes on executing and never ends. Call shutdown() on the pool to end the executor. If you try to send another task to the executor after shutdown, it will throw a RejectedExecutionException." }, { "code": null, "e": 11698, "s": 11485, "text": "One needs to understand the tasks to effectively tune the thread pool. If the tasks are very contrasting then it makes sense to use different thread pools for different types of tasks so as to tune them properly." }, { "code": null, "e": 11809, "s": 11698, "text": "You can restrict maximum number of threads that can run in JVM, reducing chances of JVM running out of memory." }, { "code": null, "e": 12003, "s": 11809, "text": "If you need to implement your loop to create new threads for processing, using ThreadPool will help to process faster, as ThreadPool does not create new Threads after it reached it’s max limit." }, { "code": null, "e": 12159, "s": 12003, "text": "After completion of Thread Processing, ThreadPool can use the same Thread to do another process(so saving the time and resources to create another Thread.)" }, { "code": null, "e": 12178, "s": 12159, "text": "Tuning Thread Pool" }, { "code": null, "e": 12638, "s": 12178, "text": "The optimum size of the thread pool depends on the number of processors available and the nature of the tasks. On a N processor system for a queue of only computation type processes, a maximum thread pool size of N or N+1 will achieve the maximum efficiency.But tasks may wait for I/O and in such a case we take into account the ratio of waiting time(W) and service time(S) for a request; resulting in a maximum pool size of N*(1+ W/S) for maximum efficiency." }, { "code": null, "e": 12914, "s": 12638, "text": "The thread pool is a useful tool for organizing server applications. It is quite straightforward in concept, but there are several issues to watch for when implementing and using one, such as deadlock, resource thrashing. Use of executor service makes it easier to implement." }, { "code": null, "e": 13210, "s": 12914, "text": "This article is contributed by Abhishek. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 13335, "s": 13210, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 13350, "s": 13335, "text": "lehanshukhatri" }, { "code": null, "e": 13363, "s": 13350, "text": "Akanksha_Rai" }, { "code": null, "e": 13383, "s": 13363, "text": "Java-Multithreading" }, { "code": null, "e": 13388, "s": 13383, "text": "Java" }, { "code": null, "e": 13393, "s": 13388, "text": "Java" }, { "code": null, "e": 13491, "s": 13393, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13527, "s": 13491, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 13571, "s": 13527, "text": "Split() String method in Java with examples" }, { "code": null, "e": 13596, "s": 13571, "text": "Reverse a string in Java" }, { "code": null, "e": 13627, "s": 13596, "text": "How to iterate any Map in Java" }, { "code": null, "e": 13642, "s": 13627, "text": "Stream In Java" }, { "code": null, "e": 13666, "s": 13642, "text": "Singleton Class in Java" }, { "code": null, "e": 13698, "s": 13666, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 13726, "s": 13698, "text": "Initializing a List in Java" }, { "code": null, "e": 13743, "s": 13726, "text": "Generics in Java" } ]
How to display records having sum between a specific range using GROUP BY, HAVING and ORDER BY in a single MySQL query?
Let us first create a table − mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(20), ProductPrice int ); Query OK, 0 rows affected (0.70 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',600); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(CustomerName,ProductPrice) values('David',450); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',980); Query OK, 1 row affected (0.40 sec) mysql> insert into DemoTable(CustomerName,ProductPrice) values('Mike',1200); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',400); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(CustomerName,ProductPrice) values('David',1200); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----+--------------+--------------+ | Id | CustomerName | ProductPrice | +----+--------------+--------------+ | 1 | Chris | 600 | | 2 | David | 450 | | 3 | Chris | 980 | | 4 | Mike | 1200 | | 5 | Chris | 400 | | 6 | David | 1200 | +----+--------------+--------------+ 6 rows in set (0.00 sec) Following is the query to display a specific range of numbers − mysql> select CustomerName,sum(ProductPrice) AS Total_Price from DemoTable group by CustomerName having sum(ProductPrice) between 1600 and 2000 order by CustomerName DESC; This will produce the following output − +--------------+-------------+ | CustomerName | Total_Price | +--------------+-------------+ | David | 1650 | | Chris | 1980 | +--------------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1260, "s": 1092, "text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n CustomerName varchar(20),\n ProductPrice int\n);\nQuery OK, 0 rows affected (0.70 sec)" }, { "code": null, "e": 1316, "s": 1260, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1995, "s": 1316, "text": "mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',600);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable(CustomerName,ProductPrice) values('David',450);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',980);\nQuery OK, 1 row affected (0.40 sec)\nmysql> insert into DemoTable(CustomerName,ProductPrice) values('Mike',1200);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',400);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable(CustomerName,ProductPrice) values('David',1200);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2055, "s": 1995, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2086, "s": 2055, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2127, "s": 2086, "text": "This will produce the following output −" }, { "code": null, "e": 2522, "s": 2127, "text": "+----+--------------+--------------+\n| Id | CustomerName | ProductPrice |\n+----+--------------+--------------+\n| 1 | Chris | 600 |\n| 2 | David | 450 |\n| 3 | Chris | 980 |\n| 4 | Mike | 1200 |\n| 5 | Chris | 400 |\n| 6 | David | 1200 |\n+----+--------------+--------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2586, "s": 2522, "text": "Following is the query to display a specific range of numbers −" }, { "code": null, "e": 2770, "s": 2586, "text": "mysql> select CustomerName,sum(ProductPrice) AS Total_Price\n from DemoTable\n group by CustomerName\n having sum(ProductPrice) between 1600 and 2000\n order by CustomerName DESC;" }, { "code": null, "e": 2811, "s": 2770, "text": "This will produce the following output −" }, { "code": null, "e": 3022, "s": 2811, "text": "+--------------+-------------+\n| CustomerName | Total_Price |\n+--------------+-------------+\n| David | 1650 |\n| Chris | 1980 |\n+--------------+-------------+\n2 rows in set (0.00 sec)" } ]
Python MySQL - Join
When you have divided the data in two tables you can fetch combined records from these two tables using Joins. Suppose we have created a table with name EMPLOYEE and populated data into it as shown below − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT, CONTACT INT ); Query OK, 0 rows affected (0.36 sec) INSERT INTO Employee VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000, 101), ('Vinay', 'Bhattacharya', 20, 'M', 6000, 102), ('Sharukh', 'Sheik', 25, 'M', 8300, 103), ('Sarmista', 'Sharma', 26, 'F', 10000, 104), ('Trupthi', 'Mishra', 24, 'F', 6000, 105); Query OK, 5 rows affected (0.08 sec) Records: 5 Duplicates: 0 Warnings: 0 Then, if we have created another table and populated it as − CREATE TABLE CONTACT( ID INT NOT NULL, EMAIL CHAR(20) NOT NULL, PHONE LONG, CITY CHAR(20) ); Query OK, 0 rows affected (0.49 sec) INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES (101, 'Krishna@mymail.com', 'Hyderabad'), (102, 'Raja@mymail.com', 'Vishakhapatnam'), (103, 'Krishna@mymail.com', 'Pune'), (104, 'Raja@mymail.com', 'Mumbai'); Query OK, 4 rows affected (0.10 sec) Records: 4 Duplicates: 0 Warnings: 0 Following statement retrieves data combining the values in these two tables − mysql> SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID; +------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | CONTACT | ID | EMAIL | PHONE | CITY | +------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+ | Ramya | Rama Priya | 27 | F | 9000 | 101 | 101 | Krishna@mymail.com | NULL | Hyderabad | | Vinay | Bhattacharya | 20 | M | 6000 | 102 | 102 | Raja@mymail.com | NULL | Vishakhapatnam | | Sharukh | Sheik | 25 | M | 8300 | 103 | 103 | Krishna@mymail.com | NULL | Pune | | Sarmista | Sharma | 26 | F | 10000 | 104 | 104 | Raja@mymail.com | NULL | Mumbai | +------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+ 4 rows in set (0.00 sec) Following example retrieves data from the above two tables combined by contact column of the EMPLOYEE table and ID column of the CONTACT table. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Closing the connection conn.close() [('Krishna', 'Sharma', 26, 'M', 2000, 101, 101, 'Krishna@mymail.com', 9848022338, 'Hyderabad'), ('Raj', 'Kandukuri', 20, 'M', 7000, 102, 102, 'Raja@mymail.com', 9848022339, 'Vishakhapatnam'), ('Ramya', 'Ramapriya', 29, 'F', 5000, 103, 103, 'Krishna@mymail.com', 9848022337, 'Pune'), ('Mac', 'Mohan', 26, 'M', 2000, 104, 104, 'Raja@mymail.com', 9848022330, 'Mumbai')] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3316, "s": 3205, "text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins." }, { "code": null, "e": 3411, "s": 3316, "text": "Suppose we have created a table with name EMPLOYEE and populated data into it as shown below −" }, { "code": null, "e": 3937, "s": 3411, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT,\n CONTACT INT\n);\nQuery OK, 0 rows affected (0.36 sec)\nINSERT INTO Employee VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000, 101), \n ('Vinay', 'Bhattacharya', 20, 'M', 6000, 102), \n ('Sharukh', 'Sheik', 25, 'M', 8300, 103), \n ('Sarmista', 'Sharma', 26, 'F', 10000, 104), \n ('Trupthi', 'Mishra', 24, 'F', 6000, 105);\nQuery OK, 5 rows affected (0.08 sec)\nRecords: 5 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 3998, "s": 3937, "text": "Then, if we have created another table and populated it as −" }, { "code": null, "e": 4140, "s": 3998, "text": "CREATE TABLE CONTACT(\n ID INT NOT NULL,\n EMAIL CHAR(20) NOT NULL,\n PHONE LONG,\n CITY CHAR(20)\n);\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 4434, "s": 4140, "text": "INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES \n (101, 'Krishna@mymail.com', 'Hyderabad'), \n (102, 'Raja@mymail.com', 'Vishakhapatnam'), \n (103, 'Krishna@mymail.com', 'Pune'), \n (104, 'Raja@mymail.com', 'Mumbai');\nQuery OK, 4 rows affected (0.10 sec)\nRecords: 4 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 4512, "s": 4434, "text": "Following statement retrieves data combining the values in these two tables −" }, { "code": null, "e": 5541, "s": 4512, "text": "mysql> SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID;\n+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | CONTACT | ID | EMAIL | PHONE | CITY |\n+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+\n| Ramya | Rama Priya | 27 | F | 9000 | 101 | 101 | Krishna@mymail.com | NULL | Hyderabad |\n| Vinay | Bhattacharya | 20 | M | 6000 | 102 | 102 | Raja@mymail.com | NULL | Vishakhapatnam |\n| Sharukh | Sheik | 25 | M | 8300 | 103 | 103 | Krishna@mymail.com | NULL | Pune |\n| Sarmista | Sharma | 26 | F | 10000 | 104 | 104 | Raja@mymail.com | NULL | Mumbai |\n+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 5685, "s": 5541, "text": "Following example retrieves data from the above two tables combined by contact column of the EMPLOYEE table and ID column of the CONTACT table." }, { "code": null, "e": 6186, "s": 5685, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb'\n)\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 6566, "s": 6186, "text": "[('Krishna', 'Sharma', 26, 'M', 2000, 101, 101, 'Krishna@mymail.com', 9848022338, 'Hyderabad'), \n ('Raj', 'Kandukuri', 20, 'M', 7000, 102, 102, 'Raja@mymail.com', 9848022339, 'Vishakhapatnam'), \n ('Ramya', 'Ramapriya', 29, 'F', 5000, 103, 103, 'Krishna@mymail.com', 9848022337, 'Pune'), \n ('Mac', 'Mohan', 26, 'M', 2000, 104, 104, 'Raja@mymail.com', 9848022330, 'Mumbai')]\n" }, { "code": null, "e": 6603, "s": 6566, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6619, "s": 6603, "text": " Malhar Lathkar" }, { "code": null, "e": 6652, "s": 6619, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6671, "s": 6652, "text": " Arnab Chakraborty" }, { "code": null, "e": 6706, "s": 6671, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6728, "s": 6706, "text": " In28Minutes Official" }, { "code": null, "e": 6762, "s": 6728, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6790, "s": 6762, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6825, "s": 6790, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6839, "s": 6825, "text": " Lets Kode It" }, { "code": null, "e": 6872, "s": 6839, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6889, "s": 6872, "text": " Abhilash Nelson" }, { "code": null, "e": 6896, "s": 6889, "text": " Print" }, { "code": null, "e": 6907, "s": 6896, "text": " Add Notes" } ]
JIRA - Quick Guide
JIRA is an Incident Management Tool used for Project Management, Bug Tracking, Issue Tracking and Workflow. JIRA is based on the following three concepts – Project, Issue and Workflow. The following points explain some interesting details of JIRA. JIRA is an incident management tool. JIRA is an incident management tool. JIRA is developed by Atlassian Inc., an Australian Company. JIRA is developed by Atlassian Inc., an Australian Company. JIRA is a platform independent tool; it can be used with any OS. JIRA is a platform independent tool; it can be used with any OS. JIRA is multi-lingual tool − English, French, German, Japanese, Spanish, etc. JIRA is multi-lingual tool − English, French, German, Japanese, Spanish, etc. JIRA supports MySQL, Oracle, PostgreSQL and SQL server in the backend. JIRA supports MySQL, Oracle, PostgreSQL and SQL server in the backend. JIRA can be integrated with many other tools − Subversion, GIT, Clearcase, Team Foundation Software, Mercury, Concurrent Version System and many more. JIRA can be integrated with many other tools − Subversion, GIT, Clearcase, Team Foundation Software, Mercury, Concurrent Version System and many more. The following points describes the legalities of the JIRA Tool. JIRA is a commercial tool and available as a Trial version for a limited time. JIRA is a commercial tool and available as a Trial version for a limited time. To utilize JIRA services, a license is required. To utilize JIRA services, a license is required. JIRA provides free license for academic projects. JIRA provides free license for academic projects. A 15-day trial version is available for an individual person to use. A 15-day trial version is available for an individual person to use. Following are some of the most significant uses of JIRA. JIRA is used in Bugs, Issues and Change Request Tracking. JIRA is used in Bugs, Issues and Change Request Tracking. JIRA can be used in Help desk, Support and Customer Services to create tickets and track the resolution and status of the created tickets. JIRA can be used in Help desk, Support and Customer Services to create tickets and track the resolution and status of the created tickets. JIRA is useful in Project Management, Task Tracking and Requirement Management. JIRA is useful in Project Management, Task Tracking and Requirement Management. JIRA is very useful in Workflow and Process management. JIRA is very useful in Workflow and Process management. The following table explains some of the most important and commonly used features in detail for better understanding. Boards JIRA supports Scrum and Kanban boards. These boards provide an immediate snapshot of the project to the team. Helps to quickly review the progress of the project and see the status of the individual tasks. Board workflow can be customized to fulfil the way a team wants to proceed. Business Project Template JIRA supports n number of business templates to manage simple tasks and complex tasks like workflow. Template can be customized based on the team and their approach. Ex: Workflow can be customized based on each team's approach. Every step is accounted and team can move to achieve their goals. Task Details Tasks can be defined at the individual level to track the progress. Status of every task, comment, attachment and due dates are stored in one place. Notifications An email can be sent for a particular task to the users. Voting and watching features to keep an eye on the progress for the stakeholders. Use @mention to get the attention of a specific team member at Comments/Description. User will instantly notify if something is assigned or if any feedback is required. Power Search JIRA supports a powerful search functionality with Basic, Quick and Advanced features. Use the search tool to find answers like due date, when a task was last updated, what items a team member still needs to finish. Project information at one place, search within a project. Reports JIRA supports more than a dozen reports to track progress over a specific timeframe, deadlines, individual’s contribution, etc. Easy to understand and generate different reports those help to analyze how the team is going on. Easy to configure these reports and display the matrices to the stakeholders. Scale with Team Growth JIRA supports any business team and any project irrespective of size and complexity. Add -Ins JIRA supports more than 100 add-ins to connect with different software to make work easy. Wide range of add-ins makes it as universal across the globe. Multilingual JIRA supports more than 10 languages those are widely used as English (US, UK, India), French, German, Portuguese, Spanish, Korean, Japanese and Russian. Mobile App JIRA is available as a Mobile Application as well. It is available on Google Play Store and App Store (iTunes) of Apple. Easy to stay connected with the team while moving anywhere with notification, comments and project activity. A Project contains issues; a JIRA project can be called as a collection of issues. A JIRA Project can be of several types. For example − Software Development Project Marketing Project Migration to other platform project Help Desk Tracking Project Leave Request Management System Employee Performance System Website Enhancement To create a project, the user should login as a JIRA Service Desk Admin and then Click on Project → Create Project. The following screenshot shows how to reach to the Create Project button from the Dashboard. Choose the type of Project that suits your requirement and the process it should follow. The following screenshot displays the type of projects available in JIRA. Once the type of project is selected, click on Next. The user will see the flow of the project based on the selection. Here, we have selected Basic Software development. The following screenshot displays the available issue types and the workflow for the chosen project in the step mentioned above − Click on the Select button, enter the name of the project and confirm the Key that the user wants to display as a reference in all the issues. Once this is done, click on the Submit button. The following screenshot displays the fields to provide details before the creation of a project. The page having issues will display. The following screenshot displays whether any issues are linked with a new created project. JIRA is a project management tool and uses issues to track all the tasks. An issue helps to track all works that underlie in a project. In real time, every work or task either technical, non-technical, support or any other type of a project in JIRA are logged as an issue. An issue can be dependent on the organization and requirements − Story of a project Task of a story Sub-task of a story A defect or bug can be an issue Helpdesk Ticket can be logged as issue Leave Request The following screen shot shows the basic page and information of an open issue − In JIRA, workflow is used to track the lifecycle of an Issue. Workflow is a record of statuses and transitions of an issue during its lifecycle. A status represents the stage of an issue at a particular point. An issue can be in only one status at a given point of time like Opened, To Do, Done, Closed, Assigned, etc. A transition is a link between two statuses when an issue moves from one status to another. For an issue to move between two statuses, a transition must exist. In a simple way, a transition is some kind of work done on the issue, while status is the impact of work on that issue. As of now, an issue is created and opened. When the assignee starts working on the issue, the issue moves to the In Progress status. Here, the transition is starting the work, while the status of the issue is now progressive. JIRA workflow has the following stages to track as soon as an issue is created − Open Issue − After creation, the issue is open and can be assigned to the assignee to start working on it. Open Issue − After creation, the issue is open and can be assigned to the assignee to start working on it. In Progress Issue − The assignee has actively started to work on the issue. In Progress Issue − The assignee has actively started to work on the issue. Resolved Issue − All sub-tasks and works of that Issue are completed. Now, the issue is waiting to be verified by the reporter. If verification is successful, it will be closed or re-opened, if any further changes are required. Resolved Issue − All sub-tasks and works of that Issue are completed. Now, the issue is waiting to be verified by the reporter. If verification is successful, it will be closed or re-opened, if any further changes are required. Reopened Issue − This issue was resolved previously, but the resolution was either incorrect or missed a few things or some modifications are required. From Reopened stage, issues are marked either as assigned or resolved. Reopened Issue − This issue was resolved previously, but the resolution was either incorrect or missed a few things or some modifications are required. From Reopened stage, issues are marked either as assigned or resolved. Close Issue − The issue is considered as finished, resolution is correct as of now. Closed issues can be re-opened later based on the requirement. Close Issue − The issue is considered as finished, resolution is correct as of now. Closed issues can be re-opened later based on the requirement. JIRA Workflow can be referred as a Defect Lifecycle. It follows the same concepts; the only difference is that it is generic for all issues rather than limited to Defects only. The following diagram shows a standard workflow − A transition is a one-way link, if an issue moves back and forth between two statuses; two transitions should be created. Example − There are two-way transitions between closed and re-opened statuses. A closed issue can be reopened if any modifications are required at any time until the project completes, while a re-opened issue can be closed directly if additional work is taken care in another issue and no specific work has been done on the re-opened issue. In this chapter, we will learn how to install JIRA on your system. JIRA is a web application that provides a private website to an individual or a set of requested users belonging to the same company/project. JIRA is a web application that provides a private website to an individual or a set of requested users belonging to the same company/project. JIRA can be run as a Windows Service at the server side. JIRA can be run as a Windows Service at the server side. JIRA is a pure Java based application and supports all OS platforms like Windows, Linux of different versions or MAC, etc., those satisfy JDK/JRE requirements. JIRA is a pure Java based application and supports all OS platforms like Windows, Linux of different versions or MAC, etc., those satisfy JDK/JRE requirements. JIRA supports all famous browsers like Chrome, IE, Mozilla and Safari. JIRA supports all famous browsers like Chrome, IE, Mozilla and Safari. It supports Mobile browsers as well in mobile views. It supports Mobile browsers as well in mobile views. Since JIRA is a web-application, it follows the concept of client/server. It means that JIRA can be installed centrally on a server and users can interact with it through web-browsers using a website from any computer. Browser − JavaScript should be enabled, the user is recommended not to use any script-blocking tool like NoScript to access full functionality of JIRA. Browser − JavaScript should be enabled, the user is recommended not to use any script-blocking tool like NoScript to access full functionality of JIRA. JDK/JRE − It is recommended to update JRE/JDK with the latest version. JIRA 6.4 recommends using JRE/JDK version 8. JDK/JRE − It is recommended to update JRE/JDK with the latest version. JIRA 6.4 recommends using JRE/JDK version 8. Since our scope is to consume the JIRA application as end users, we can ignore the server side requirements. JIRA follows the Client/Server concept. At the server side, JIRA must be installed before using it as end user. JIRA follows the Client/Server concept. At the server side, JIRA must be installed before using it as end user. At the server side, JIRA must connect with relation database to store issues/application data. At the server side, JIRA must connect with relation database to store issues/application data. Download the JIRA Windows Installer.exe file from the following link − https://www.atlassian.com/software/jira/download?_ga=1.28526460.1787473978.1 488778536. Download the JIRA Windows Installer.exe file from the following link − https://www.atlassian.com/software/jira/download?_ga=1.28526460.1787473978.1 488778536. Select the OS type and click on Download. Select the OS type and click on Download. The following screenshot shows how to download the .exe file for a specific OS. Run the .exe file to run the installation wizard. The following screenshot shows the downloaded .exe file. After clicking the .exe file, the Run confirmation pop-up displays, click on RUN. The following screenshot shows the RUN confirmation pop-up. The following JIRA installation wizard displays, click on Next. Choose the appropriate installation option as shown in following screenshot and then click on Next. The installation summary is displayed with the Destination Directory, Home Directory, TCP Ports, etc., as shown in the following screenshot. Click on Install. JIRA will start installing as displayed in following screenshot. It takes a couple of minutes to finish the installation. After installation, JIRA will be started automatically if the check box to “Start JIRA Software 7.3.4 now” is checked. Then click on Next, if not, it can be accessed using the appropriate Windows Start Menu shortcut. Click the Finish button. The installer will create the following shortcuts on the start menu − Access JIRA Start JIRA Server Stop JIRA server Uninstall JIRA The following screenshot shows the above-mentioned shortcuts − Select the license type and enter organization name as shown in following screenshot − Click on Generate License A confirmation pop-up will display as shown in the following screenshot. Click on Yes. Set up the administration account as displayed in the following screenshot. JIRA will automatically finish the setting-up as shown below − Once JIRA finishes the setup and starts running in the server, the user can access it from a browser on any computer with network access to the JIRA server. JIRA provides 15 days to 1-month free trials of basic features. JIRA has other plans as well with different advanced features and add-ins. The cost depends on the number of users. By visiting https://www.atlassian.com/software/jira/try, a user can see different available plans for trying purposes. To setup a free trial, the user has to Sign up on the following link − https://id.atlassian.com/signup?application=&tenant=&continue or login if he already has an account. The following screenshot shows required fields to sign up in Atlassian account. The user has to log into the email account and verifies the account by clicking on the link sent by JIRA-Atlassian. The next step is to go to https://www.atlassian.com/software/jira/try and click on Create now button, which is at the bottom right hand of the webpage. The following screenshot shows different plans available for trial of JIRA. The following screenshot shows the details of the chosen plan for a free trial. Once the user fills in all the details along with the sample website name, user has to click on the Start now button. The following screenshot shows how to claim your site and provide your credentials to start it. It will take a few minutes to start the requested sample JIRA website. Once it is done, the JIRA login page will display and the user can see the given sample website name in the browser’s address bar. The user can now directly access this link to navigate to JIRA. The following screenshot shows the login page of JIRA. To login to JIRA, go to your sample website. It will open a login page. Fill in your registered email address/username and Password. Click on the Login button. The following screenshot shows how to login into JIRA using your credentials. In case of any unsuccessful login, an error message displays. The following screenshot shows the error message a user receives, if the credentials are not matching or incorrect. To rectify this scenario, click on “Unable to access your account”, then select the appropriate option and fill in the details. Click on email. The following screenshot shows how to recover the username, in case the user has forgotten it. The user will get an email with the details of his username or a link to reset the password. On a successful login, the system dashboard will display if the account is associated with any project by the admin, or if a user can create a sample project as explained in the earlier chapters. The following screenshot displays the welcome page/dashboard of JIRA on a successful login. After logging into JIRA, the Dashboard is the first page that shows up. The Dashboard is customized by the Admin. Based on the roles, the admin can set the access of JIRA. Even the admin has the right to change colors and the logo of JIRA. Following are some of the most significant points the users should understand before using the JIRA Dashboard − The navigation bar, present at the top of the JIRA page, will be the same across all the pages/screens of JIRA. Dashboard, Projects, Issues, Boards and Create are the main links. These links have many sub-links to navigate other functionalities. The navigation bar, present at the top of the JIRA page, will be the same across all the pages/screens of JIRA. Dashboard, Projects, Issues, Boards and Create are the main links. These links have many sub-links to navigate other functionalities. Navigation bar contains links that provides a quick access to the most useful functions of JIRA. Navigation bar contains links that provides a quick access to the most useful functions of JIRA. Just under navigation bar, there is a System Dashboard. Just under navigation bar, there is a System Dashboard. The information provided in the system dashboard area can be customized by the Admin. The information provided in the system dashboard area can be customized by the Admin. By default, it has three main sections – Introduction, Assigned to Me (displays Issues list assigned to users) and Activity Stream (Activities done by the users). By default, it has three main sections – Introduction, Assigned to Me (displays Issues list assigned to users) and Activity Stream (Activities done by the users). The following screenshot shows the overview of the Dashboard page of JIRA − The Projects link has several sub-links, which are explained in detail for better understanding − Current Project − It displays the name of the Project where the user is currently in or is viewing the dashboard of the project. By clicking at Project name, it will display the list of issues associated with the project. Current Project − It displays the name of the Project where the user is currently in or is viewing the dashboard of the project. By clicking at Project name, it will display the list of issues associated with the project. Recent Project − It displays the name of the recent project that the user has accessed, if exists, where the user can navigate by clicking on the project listed under this header. Recent Project − It displays the name of the recent project that the user has accessed, if exists, where the user can navigate by clicking on the project listed under this header. Software − It is the sub-link to navigate the list of projects, which are listed in the Project Type as Software. Software − It is the sub-link to navigate the list of projects, which are listed in the Project Type as Software. Business − It is also a project-type. By clicking here, it will display the list of business project types. Business − It is also a project-type. By clicking here, it will display the list of business project types. View all Projects − It displays all the projects, which are associated with the logged in user. View all Projects − It displays all the projects, which are associated with the logged in user. Create Project − This link is usually accessed by the Admin or it depends on various roles. If this link is visible, a user can create a new project by following the instructions given there. Create Project − This link is usually accessed by the Admin or it depends on various roles. If this link is visible, a user can create a new project by following the instructions given there. The following screenshot shows the different sub-links under the Project category. It has many sub links to access other functionalities. The following screenshot shows different available sub-links under Issue navigation. Search for Issues − It navigates to the search page, where the user can provide search criteria to narrow down the results. Search for Issues − It navigates to the search page, where the user can provide search criteria to narrow down the results. Recent Issues − It displays the list of issues that are recently viewed by the user. Recent Issues − It displays the list of issues that are recently viewed by the user. Import issue from CSV − This feature allows the user to import the details of issues by uploading a CSV file and mapping the fields. Import issue from CSV − This feature allows the user to import the details of issues by uploading a CSV file and mapping the fields. My open issues − It is the filter section, which displays issues those are open and assigned to the logged-in user. My open issues − It is the filter section, which displays issues those are open and assigned to the logged-in user. Reported by me − This filter section displays the issues, which are already created by the logged-in user. Reported by me − This filter section displays the issues, which are already created by the logged-in user. Manage filters − It helps to customize the filter and narrow down the results. It displays any saved filters/ favorites filters. Manage filters − It helps to customize the filter and narrow down the results. It displays any saved filters/ favorites filters. Boards are showcase of process that is followed by Project. It could be the most famous Agile Board if the project is following the agile methodology or it might be the Kanban board as well. Recent Board − It displays the recent project board accessed by the user. Recent Board − It displays the recent project board accessed by the user. View all boards − It displays all available project boards. View all boards − It displays all available project boards. The following screenshot shows the different sub-links available under the board section. By clicking on the Create button, it displays the create form to log an issue. The following screenshot shows required fields and other fields to create an issue − There is a feedback link at the right side of the navigation bar (as highlighted in the following screenshot). By clicking on link, user gets a form where he can provide feedback by entering Summary, Description, Name and email. The following screenshot shows the location of the Feedback link present in the Dashboard. The following screenshot shows the required and optional fields to provide feedback. Once all the fields are filled, click on Submit, it successfully posts the feedback. The Help link provides different useful documentation about JIRA. It provides the details of JIRA as well by clicking on “About JIRA”. Similarly, this link also provides new release features by clicking on “What’s new”. Keyboard shortcuts have much useful keyboard navigation for users that saves time. The following screenshot shows the Help link and different sub-links available in it. By clicking on the profile link, the user can view his profile details and manage this section. By clicking on Logout, the user will get back to the login page and will not be able to access the project details without logging in again. The following screenshot shows available functionality under User-Profile section − By clicking on the edit symbol, the user will be able to edit profile details like – Summary Details, Preferences, etc. The following screenshot shows how to edit the profile by clicking on the Edit (highlighted in red outline) icon at each section. On the right side, the user can see the activity stream performed by the logged in user. Since JIRA tracks all the tasks, the sub-tasks or even a work as an Issue, there are several types of Issues to identify the work and categorize the similar issues. An Issue is classified as follows − Sub-Task − This is the sub-task of an issue. In a logged issue, there can be different tasks to resolve it, which are called as sub-tasks. Sub-Task − This is the sub-task of an issue. In a logged issue, there can be different tasks to resolve it, which are called as sub-tasks. Bug − A problem that impairs or prevents the functions of the product. Bug − A problem that impairs or prevents the functions of the product. Epic − A big user story that needs to be broken down. Created by JIRA Software - do not edit or delete. Epic − A big user story that needs to be broken down. Created by JIRA Software - do not edit or delete. Improvement − An improvement or enhancement to an existing feature or task. Improvement − An improvement or enhancement to an existing feature or task. New Feature − A new feature of the product, which is yet to be developed. New Feature − A new feature of the product, which is yet to be developed. Story − A user story. Created by JIRA Software - do not edit or delete. Story − A user story. Created by JIRA Software - do not edit or delete. Task − A task that needs to be done to achieve team’s goal. Task − A task that needs to be done to achieve team’s goal. If a user logs in as Admin and navigate to Settings → JIRA Administrator → Issues, all the listed issue types will display. The following screenshot shows all the available issue types in JIRA. An issue type scheme determines which issue types will be available to a project or set of projects. It also manages specifying the order in which the issue types will present in the user interface of JIRA, while creating an Issue. An issue type scheme generates as soon as the project is added in the JIRA. Here, one scheme is by default named as the Default Issue Type Scheme and others are project schemes. The default issue type scheme is the list of global issue types. All newly created issue types will automatically be added to this scheme. The following screenshot shows Issue type schemes of different projects. By clicking on the Add Issue Type Scheme button at the top right hand corner, the user can add a user defined scheme. Enter the Name, Description and Select the Issue Type for the Current scheme from the Available issue type list. The following screenshot shows how to add a new type schema by providing the required and optional fields. Click on Save. The new schema will appear in the list. The Following screenshot shows how the page display after adding a new Issue Type schema − By clicking on Edit, the user can edit the details. By clicking on Associate, the user can associate this scheme to a project. Copy and Delete is used for copying and deletion of the same scheme. It is the arrangement and representation of fields to display in UI whenever a new issue is created or existing issues are modified and issue transitioned through one status to another. If a user logs in as Admin and navigate to Settings → Issues → Screens, he will be able to see all the available screens. The following screenshot shows the available screen for different projects. By clicking on configure, the user will be able to see all the available fields with this screen. Whereas, in the organized/arranged way of order, it will display at the UI. The following screenshot shows how to configure the screen fields. Screen schemes provides an option to choose fields, which should display when a particular issue type is selected. A screen scheme is mapped with issue type using the Issue Type Screen Scheme. It can be associated with one or more project. A screen scheme can be deleted only when it is not used by any Issue Type screen scheme. The user can add a new screen scheme by clicking on the Add Screen Scheme button. The following screenshot shows the different screen schemes available for the listed projects. Provide all details and the click on the ADD button. The following screenshot shows how to add a new screen scheme. To create an issue in JIRA, the user should have Create Issue permission in the project. Admin can add/remove the permission. Click on the Create button in the navigation bar to open the create issue dialogue box. To complete the process of creating an issue, we should follow the pointers given below. Select the Project where the issue is. Select the Project where the issue is. Select the type of issue, whether it is a bug/new feature/story, etc. Select the type of issue, whether it is a bug/new feature/story, etc. Write a one-line summary to provide the overall idea about the issue. Write a one-line summary to provide the overall idea about the issue. Write the details of the issue in the Description field. Explain the issue, so that stockholders can understand every detail of the issue. Write the details of the issue in the Description field. Explain the issue, so that stockholders can understand every detail of the issue. To create a similar type of issue in the same project and issue type, check the checkbox of “Create another” otherwise keep it as unchecked. To create a similar type of issue in the same project and issue type, check the checkbox of “Create another” otherwise keep it as unchecked. After entering all the details, click on the Create button. After entering all the details, click on the Create button. The following screenshot shows how to create an issue by providing the required and optional details. If the “Create another” checkbox is not checked, after clicking on the Create button, the user will have to navigate to the Dashboard and a pop-up will display on the right side with an issue id and summary. The following screenshot shows how to know whether the issue is successfully created or not. If the “Create another” checkbox is checked while clicking on the Create button, the user will get a new create issue page along with the issue id. The following screenshot shows the page, if the user has checked the “Create another” box. To add other fields in the Create Issue form, click on “Configure fields” at the top right hand side of the page. The following screenshot shows how to configure the fields in the Create Issue page. After clicking on the Configure fields button, a drop down box will be displayed, click on Custom. The following screenshot shows the available fields under the Custom tab. By checking and unchecking the checkboxes to show and hide, fields will be added or cleared from the form. The following screenshot shows the available fields under the All tab. Now navigate to Create Issue, all fields based on choices will be displayed in the form that shows up. The following screenshot shows the configured fields in the Create Issue page. The fields in the Create Issue form are explained below. Priority − Issue creator can set the priority to resolve the issue as High, Medium, Low, and Lowest. Priority − Issue creator can set the priority to resolve the issue as High, Medium, Low, and Lowest. Labels − It is similar to Tag; it helps in filtering out specific types of issues. Labels − It is similar to Tag; it helps in filtering out specific types of issues. Linked Issue − It links other issues that are either dependent on this issue or this issue is dependent on them. Options in dropdowns are – block, is blocked by, duplicate, clone, etc. Linked Issue − It links other issues that are either dependent on this issue or this issue is dependent on them. Options in dropdowns are – block, is blocked by, duplicate, clone, etc. Issue − User can link the issue by the Typing ID or summary of those that are related to the linked issue field. Issue − User can link the issue by the Typing ID or summary of those that are related to the linked issue field. Assignee − The person who is responsible to fix this issue. Assignee name can be entered by the issue creator. Assignee − The person who is responsible to fix this issue. Assignee name can be entered by the issue creator. Epic Link − An Issue creator can provide an epic link, if the issue belongs to any of those. Epic Link − An Issue creator can provide an epic link, if the issue belongs to any of those. Sprint − The user can define in which sprint, this issue belongs to, when this issue should be addressed. Sprint − The user can define in which sprint, this issue belongs to, when this issue should be addressed. In the next chapter, we will learn how to clone an issue. Cloning means to copy. To clone an issue means to create a duplicate issue within the same project. A cloned issue can be treated as a new issue and edited like other issues. We should consider the following points while cloning an issue. A cloned issue is completely a separate issue from the original issue. A cloned issue is completely a separate issue from the original issue. Any action or operation taken on the original issue does not have any impact on the clone issue and vice-versa. Any action or operation taken on the original issue does not have any impact on the clone issue and vice-versa. The only connection between the original and clone is the link that is created. The only connection between the original and clone is the link that is created. Information that is carried from the original issue to clone issue is as follows − Information that is carried from the original issue to clone issue is as follows − Summary Summary Description Description Assignee Assignee Environment Environment Priority Priority Issue Type Issue Type Security Security Component Component Reporter Reporter Affects Version Affects Version Fix Version Fix Version Attachment Attachment Projects Projects Content of custom fields are also cloned Content of custom fields are also cloned Information that is not cloned − Information that is not cloned − Time Tracking Time Tracking Comments Comments Issue History Issue History Links to confluence pages Links to confluence pages Open a JIRA issue that is supposed to be cloned. Select More → Clone when the screen appears. The following screenshot shows how to access the Clone functionality. In the clone screen, there are a few options given to the users, which are as follows − A user can change the summary while cloning it. A user can change the summary while cloning it. If the issue contains links to other issues, a user can check the checkbox to contain the clone issue or uncheck if the user does not want to be a part of the clone issue. If the issue contains links to other issues, a user can check the checkbox to contain the clone issue or uncheck if the user does not want to be a part of the clone issue. If the issue has sub-tasks, the user can select/deselect the checkbox to contain the sub-tasks in clone or not. If the issue has sub-tasks, the user can select/deselect the checkbox to contain the sub-tasks in clone or not. The same is applicable for attachment as well. The same is applicable for attachment as well. It also gives an option, whether to carry or not – the sprint value to the new clone issue. It also gives an option, whether to carry or not – the sprint value to the new clone issue. The following screenshot shows how to clone an issue by providing the necessary details. The next step is to click on Create. It will display the clone issue details. If the user does not change the clone words while creating, it can be visible in the summary, links and sub-tasks. The following screenshot shows how a cloned issue is displayed. An issue can be completed by performing many tasks with different persons like Dev, QA, UAT, Business, Support, etc. To track the progress in each department, sub-tasks are created in an issue and assigned to the concern person. Once all the sub-tasks are resolved, the issue can be marked as completed. The following points are to be considered when creating a subtask. All subtasks are an essential part of their parent issue. All subtasks are an essential part of their parent issue. All subtasks are visible on the main screen of the parent issue. All subtasks are visible on the main screen of the parent issue. Subtasks always belong to the same project as their parent issue. Subtasks always belong to the same project as their parent issue. Subtask has all fields that are present in the standard issue. Subtask has all fields that are present in the standard issue. Subtasks cannot have a subtask of their own. Subtasks cannot have a subtask of their own. We should consider the following steps when creating a subtask. Open an issue where subtasks should be created. Open an issue where subtasks should be created. Select More → Create Subtask. Create subtask page will display. Select More → Create Subtask. Create subtask page will display. The following screenshot shows how to access the Create Subtask functionality. Enter the details in all the required fields and then click on Create. The following screenshot shows the Create Subtask Form with the required and optional fields. Once a subtask is created, it will be available on the Main Issue page → Subtask section. The following screenshot shows how to view a subtask in an issue. In this chapter, we will understand how to convert an issue to a subtask. For doing this, we should follow the procedure given below. To begin with, navigate and click to the issue, which needs to be converted into a subtask. Select More → Convert to subtask. The following screenshot shows how to navigate to convert to sub-task. Choose the parent issue in which this subtask will be tagged. The following screenshot shows how to convert the issue into a sub-task. Click on Next. If the status of the issue is not an allowed status for the new issue type. Select – New Status will be displayed. Select a new status and click on the Next button. Update Fields screen will be prompted to enter any additional fields, if they are required. Otherwise, a message will be prompted as – 'All fields will be updated automatically'. Click on Next. The following screenshot shows how to convert the issue in sub-tasks. The Confirmation screen is displayed. It will display the original values and the new values. Click on Finish. The following screenshot shows how to convert the issue in sub-tasks. The original issue will be displayed. Now it is a sub-task. The parent's issue number is now displayed at the top of the screen. The following screenshot shows how the sub-task displays after successful conversion from an issue. We should consider the following points while converting an issue to a subtask. An issue cannot be converted into a subtask if it has its own subtask. An issue cannot be converted into a subtask if it has its own subtask. To convert such an issue into a subtask, we should first convert all the subtasks of issues into a standard issue and after that convert the issue into a subtask. To convert such an issue into a subtask, we should first convert all the subtasks of issues into a standard issue and after that convert the issue into a subtask. Subtasks cannot be moved from one issue to another directly. Subtasks cannot be moved from one issue to another directly. To move a subtask from one issue to another, first convert all sub-tasks into issues and then again, convert issues to subtasks by giving the parent issue name while converting. To move a subtask from one issue to another, first convert all sub-tasks into issues and then again, convert issues to subtasks by giving the parent issue name while converting. In the next chapter, we will learn how to covert a subtask to an issue. To convert a subtask to an issue, we should first navigate to the subtask that needs to be converted into an issue. Then, Select More → Convert to issue. The following screenshot shows how to navigate at Convert to Issue. To begin with, click on the drop down box of the Select Issue Type option, choose the type of the issue (i.e., a standard issue type) and click on the Next button. The following screenshot shows how to convert a sub-task to an issue. If the status of the subtask is not an allowed status for the new issue type, then the Select New Status screen is displayed. Select a new status and click on the Next button. In the next step, the Update Fields screen will be prompted to enter any additional fields if they are required. Otherwise, a message will display stating – 'All fields will be updated automatically'. Click on Next. The following screenshot shows how to convert a subtask in to an issue. The Confirmation screen is displayed. It will display the original values and the new values. Click on Finish. The following screenshot shows how to convert a subtask to an issue. The issue will be displayed. It is no longer a subtask. There is no longer a parent issue number displayed at the top of the screen. The following screenshot shows how the issue will display after conversion from a subtask. A User can create multiple issues at a time using Comma separated file known as CSV. The CSV files are text files those represent tabulated data and separate different sections by commas. They have two-step process that requires importing the data from a CSV, while a third optional step is also present, which are listed below. Prepare a CSV file. Import the CSV file into the system. Save the configuration for future use. While creating a CSV file the following points must be considered. Each CSV file should have a heading row with a summary column. The first row is the heading row and represents the fields of the create issue page. Example − Summary, Assignee, Reporter, Priority, Description, sprint, “Test Suite”, Ashish, Ashish, 1, etc. Use double quote marks (“) in the CSV file to capture data that appears in multip.le lines. For Example − upon import, JIRA will treat the following CSV as a single record: Summary, Description, Status, "Login issue", "This is on a new line", Open Use double quote marks (“) in the CSV file to capture data that appears in multip.le lines. For Example − upon import, JIRA will treat the following CSV as a single record: Summary, Description, Status, "Login issue", "This is on a new line", Open While importing issues from a CSV file, the Project Name and Project Key are important columns in CSV. In addition, the name of these fields should match exactly as they are present in JIRA. While importing issues from a CSV file, the Project Name and Project Key are important columns in CSV. In addition, the name of these fields should match exactly as they are present in JIRA. To import the CSV file, we should follow the steps given below. Step 1 − Select Issues → Import Issues from CSV to open the Bulk Create Setup page. The following screenshot shows how to access the Import issues from the CSV functionality. Step 2 − On the Setup page, select CSV Source File. Do not check the “Use an existing configuration file” check box, if you do not have a configuration file or if you want to create a new configuration file. Configuration files specify a mapping between column names in the CSV file's header row and fields in the JIRA application. The following screenshot shows the Bulk create setup page, where the user browses and uploads the CSV file. Step 3 − If the user checks the checkbox of “Use an existing configuration file”, JIRA will ask to specify an Existing Configuration File. The following screenshot shows how to use an existing configuration file. Step 4 − If the user does not select this option, then at the end of the CSV file import wizard, JIRA will ask to create a configuration file, which can be used for subsequent CSV imports. Click on the Next button → the Settings step of the CSV file import wizard will display. Complete the required fields. If the CSV file uses a different separator character other than a comma, specify that character in the CSV Delimiter field. If the separator is a 'Tab', this can be entered using the format '/t'. The following screenshot shows how to provide settings of csv file − Step 5 − Click on the Next button to proceed to the Map field’s step of the CSV file import wizard. Here, the user has to map the column headers of the CSV file to the fields in the selected JIRA project. After selection, tick the check box for Map field value. A CSV field should map to the JIRA summary field. This ensures the issues created have a summary. The following screenshot shows how to map CSV fields with JIRA fields − Step 6 − Click on the Next button, the Map values step of the CSV file import wizard will display. On this step of the import wizard, the user can select which specific CSV field values to map to which specific JIRA field value. Fields whose Map Field Value check boxes were selected in the previous step will be presented on this page. Fields whose Map Field Value check boxes were selected in the previous step will be presented on this page. If the CSV field has a username (e.g. Reporter or Assignee) and does not select the Map Field Value check box for this field in the previous step of the CSV file import wizard, then the importer will map imported usernames from the CSV file to (lowercase) JIRA usernames. If the CSV field has a username (e.g. Reporter or Assignee) and does not select the Map Field Value check box for this field in the previous step of the CSV file import wizard, then the importer will map imported usernames from the CSV file to (lowercase) JIRA usernames. The following screenshot shows how to map values. Step 7 − Click on the Validate button, it will validate the imported data and display if any errors or warnings are required, otherwise it will display how many successful imports are possible with the file. The following screenshot shows the successful validation of CSV file. Step 8 − Now, Click the Begin Import button. The importer will display updates like import is in progress, then a success message when the import is completed. Following screenshot shows how many issues are created using CSV file − Step 9 − Click on the Check Created issues, it will display the list of issues those are created using the CSV. The following screenshot shows the list of newly created issues using the CSV file. To edit an issue in JIRA, the user has to navigate to the issue, which is required to edit and the click on the issue to open the page. The next step is to click on the Edit button, which is present at the top left hand side of the view issue page. It will open the edit issue page that is similar to the create page. The following screenshot shows how to access the Edit functionality. Or, hover the mouse over the field and click on the Pencil Icon to edit the specific field inline. The following screenshot shows how to edit a specific field without clicking on main edit button − Modify the issue details in the corresponding field of the edit Issue page. The Following screenshot shows the edit page to update details of an issue. Once the update is completed, click on the Update button. The user will be able to see the edited text/fields in the View Issue Page. The Following screenshot shows the updated details − In this chapter, we will learn how to email an issue in JIRA. A user can email an issue to other JIRA users. There are two ways to do it − By share an issue and By mention these users in issue’s Description or Comment field. Let us now discuss each of these in detail. To begin with, the user should navigate to the issue that is required to share and click to view the issue. Click on the Share Symbol on the top right hand side of the page. The following screenshot shows where the sharing option present at issue page − You can write the JIRA users’ name by typing their usernames or partially/all of their full names as registered with JIRA or type the email addresses of the individuals with whom you would like to share the issues. When the user starts typing a JIRA user's username or name, or a previously specified email address, an auto-complete dropdown list of users appears. The Following screenshot shows how to provide email addresses or select from the auto-completion suggestions. Add optional note. Click on the Share button present in the Share wizard section. The following screenshot shows how to share/email an issue to a user. In the issue's Description or the Comment field, type '@' and then the first few characters of the JIRA user's username or partially/all of their full name as registered with JIRA. As the user starts typing, a list of suggested users will appear in a dropdown list below the field. The user should select based on the referenced users by completely typing the JIRA user's username or choose from the list of suggested users in the dropdown list. The following screenshot shows how to mention the user’s name/email in the description. Click on submit the field. JIRA will send that user an email message indicating that you mentioned them on that issue. The following screenshot shows how to submit mentioning the user’s email in the description. A Label is used to categorize an issue. It is similar to the hashtag (#) used in twitter, Facebook or other social sites. It also helps while searching an issue. While viewing an issue, the label appears in the detail section of the issue. The following screenshot shows where the labels are present in the issue detail page. Once the user clicks on the label i.e. WFT, it will display the list of issues having the same label. The following screenshot shows how to search issues using label names − To add or remove labels, a user has to go to the View Issue page and select the issue that needs to add labels. Click on More → Labels. A dialogue box will appear. The following screenshot shows how to access the Label features. Start typing the label and select from the suggestions. The following screenshot shows how to add labels. To ‘Delete’ a label, click on the close (x) sign, which appears beside the label name. The following screenshot shows how to delete an existing label − Click on the Update button. Labels are added / removed from an issue and can be verified in the Detail Section of the View Issue Page. The following screenshot shows where to verify the updated labels. This feature is very useful when two issues have some type of a dependency on each other as if they are duplicates or relate to each other, upstream downstream dependency or blocking issues. For creating a link to another issue, the user has to navigate to the issue and click on the View Issue Page. After that, click More → Link to display link dialogue page. The following screenshot shows how to access Link feature − Select JIRA Issue item in the left side of the dialogue and select “This issue” field from the dropdown list. The following screenshot shows how to link an issue by providing the details. The next step is to select/search issue. The following screenshot shows how to add an issue as a link in another issue. Add the comment; it is optional and then Click on Link. The View Issue page shows up and the user can go down and verify whether the linked issue is displayed or not under the Section Issue links. The following screenshot shows how to view linked issue in parent issue − To delete a link, a user should go to the View Issue page and to that issue which contains the links. Scroll down and go to Issue Links section. Hover the mouse over the link that should be deleted and then click on the Delete icon. The following screenshot shows how to delete a link − A confirmation pop-up will display; click on the Delete button. The following screenshot shows the confirmation pop-up for deletion. JIRA has a feature to move an issue from one project to another project. Let us understand with the following steps, how a user can do it. Go to the View Issue page that needs to move into another project. Select More → Move. The following screenshot shows how to access Move feature − In the first step of the Move Issue wizard, select the new project where the issue will move, and if required/desired, change the issue type. Click on Next to continue. The following screenshot shows Select Project and Issues step to move − If there is a need to change the status of the issue, the user can go to Select Status page. Select the new status for the issue and click on the Next button to continue. If required to specify the values for any required custom fields, the Update Fields page is displayed. Specify the desired values for each field, and click on Next to continue. The following screenshot shows the Update Fields step, if required before moving an issue. The confirmation page will display with all the changes. If a user wants to revise any of the changes, click the appropriate step in the left hand side menu to return to that page of the wizard. After that, click on the Move button to move the issue to the target project. The following screenshot shows confirmation step to confirm details before moving − The Issue will be moved to the target project and displayed on screen. This Issue can be further edited to make additional changes. The following screenshot shows a new project and an issue type after the successful moving an issue. In this chapter, we will learn how to view and change history in JIRAN. History is the record of all the activities performed on issues. Some of the most common instances are − Creator of the issue Changes to an issue field Attachment of a file Deletion of comment/Work log Addition/deletion of links In a history record, a user can view the following information. User name who made the changes Time while the changes was made If an issue field is changed, new and old values of that field To view history in JIRA, the user should follow the steps given below. Go to View Issue Page to see change history Scroll down to Activity section Click on History tab The following screenshot shows how to view History. In this chapter, we will understand how Voting and Watching is done on an issue in JIRA. JIRA has a feature called as Vote to provide the opinion on the preference for that issue, whether it is resolved or completed. Admin needs to add permission for users to use this feature. Go to the View Issue page where voting is required. Click Vote for this issue to instantly vote for that issue. The following screenshot shows where Votes field is present at issue detail page − Note − Since the user does not have permission here to vote, the user is not able to view the link beside Votes field. JIRA has a feature that allows users/stakeholders to keep an eye on the issue, whenever there is any update or changes in that issue. If there is any the issue, it sends notification/emails to those who are listed as watchers for that specific issue. Admin needs to add permission for users to use this feature. Go to the view issue page that the user wants to watch. Click on the “Start Watching this issue” link to be listed as watchers. The following screenshot shows where the Watchers field is present in the Issue Detail page. Now instead of zero watchers, there will be 1 (watcher) displayed along with the link “Stop watching this issue” to delist as watchers. The following screenshot shows the updated number of watchers − The user can click on 1, it allows to add other users as well to the list as watchers. Start typing the user name in the Add watchers box and select from the autocomplete box. The user will be listed as watchers. The following screenshot shows how to add a new watcher by providing the user’s detail. JIRA has powerful and very efficient search functionalities. A user can search issues across Projects, Versions and Components using various search types. JIRA allows saving the search criteria to utilize next time as filters; even these filters can be shared by others as well. JIRA has a couple of fundamental ways to search issues. The most important ones are as follows. Basic Search Quick Search Let us now understand both of these search types in detail. Basic Search in JIRA is a user-friendly interface that can be used easily to find out the issues. It uses the JQL queries in the backend. To do a basic search in JIRA, the user has to follow the steps given below. Step 1 − Navigate to issues → Search Issues. The following screenshot shows how to access the Search for Issues feature − Step 2 − A search page displays. If it has any existing Search criteria, then click on the New Filter to reset it. The following screenshot shows how to define a new search criteria. Step 3 − Set the search criteria against different fields like Project, Type, Status and Assigned. Then click on More and select any field to search with additional fields. The following screenshot shows what all criteria’s can be set to search issues. Step 4 − If the user wants to search against any specific text, keywords, start typing in the Contains text box. The following screenshot shows how to search specific text in issues. Step 5 − A user can use wildcards or operators in all text based fields to search specific strings. For example − Single character wildcard - te?t Multiple characters wildcard – win* Boolean operators - "atlassian jira" || confluence Based on different search criteria, the following result is displayed. The following screenshot shows the list of searched issues. To save the searched criteria, the user should follow the steps given below. Step 1 − Click on Save As at the top of the page. The following screenshot shows how to save the search criteria for future use. Step 2 − Type the filter name and click on Submit. The following screenshot shows how to provide a name of new search criteria before saving. Step 3 − A Filter will appear on the left side of the Search Page under the Favourite filters and it will have a few options like – Rename, Delete, Copy and Remove from Favourites. The following screenshot shows the saved search criteria and the available actions to perform. The quick search is the fastest way to define search criteria. It is a text box where the user enters the key, text or anything and it starts searching for the exact matches in the current project and provides the result. The Quick Search box is available on the top right hand corner of the navigator. The following screenshot shows how to access the Quick Search feature. The quick search option performs smart searches with minimal typing. It recognizes the following word and gives out several options to the user to choose. my − This word searches issues assigned to the logged-in user. my − This word searches issues assigned to the logged-in user. The following screenshot shows different smart querying in a quick search. Some of the most commonly used smart querying options are as follows − r:me − Finds issues reported by the logged-in user. r:me − Finds issues reported by the logged-in user. r:abc − Finds issues reported by user – abc. r:abc − Finds issues reported by user – abc. r:none − Finds issues with no reporter. r:none − Finds issues with no reporter. <project name> or <project key> − Finds issues within the given project name or finds issues having the same project key. <project name> or <project key> − Finds issues within the given project name or finds issues having the same project key. Overdue − Finds issues those are overdue before today. Overdue − Finds issues those are overdue before today. Created:, updated:, due: − These smart searches finds issues with Created, Updated, or Due Date using the prefixes created:, updated:, or due:, respectively. For the date range, use today, tomorrow, yesterday, a single date range (e.g. '-1w'), or two date ranges (e.g. '-1w,1w'). Date ranges cannot have spaces between them. Valid date/time abbreviations are: 'w' (week), 'd' (day), 'h' (hour), 'm' (minute). Created:, updated:, due: − These smart searches finds issues with Created, Updated, or Due Date using the prefixes created:, updated:, or due:, respectively. For the date range, use today, tomorrow, yesterday, a single date range (e.g. '-1w'), or two date ranges (e.g. '-1w,1w'). Date ranges cannot have spaces between them. Valid date/time abbreviations are: 'w' (week), 'd' (day), 'h' (hour), 'm' (minute). C: − Finds issues with a particular component. C: − Finds issues with a particular component. V: − Finds issues with a particular version. V: − Finds issues with a particular version. Ff: − Finds issues with a Fixed For version. Ff: − Finds issues with a Fixed For version. * − Wildcard can be utilized with any of the above queries to find issues. * − Wildcard can be utilized with any of the above queries to find issues. Apart from the type of searches explained in the previous chapter, JIRA also has a few advanced search options, which can be performed using the following three ways. Using Field Reference Using Keyword Reference Using Operators Reference These above-mentioned three ways have been explained in detail below. The user should consider the following points while performing any advanced search. Advanced search uses structured queries to search for JIRA issues. Advanced search uses structured queries to search for JIRA issues. Search results displays in the Issue Navigator. Search results displays in the Issue Navigator. Search results can be exported to MS Excel and many other available formats. Search results can be exported to MS Excel and many other available formats. Save and Subscribe features are available to advanced searches. Save and Subscribe features are available to advanced searches. An advanced search uses the JIRA Query Language known as JQL. An advanced search uses the JIRA Query Language known as JQL. A simple query in JQL consists of a field, operator, followed by one or more values or functions. For example, the following simple query will find all issues in the "WFT" project − A simple query in JQL consists of a field, operator, followed by one or more values or functions. For example, the following simple query will find all issues in the "WFT" project − Project = "WFT" JQL supports SQL like syntax such as ORDER BY, GROUP BY, ISNULL() functions, but JQL is not a Database Query Language. JQL supports SQL like syntax such as ORDER BY, GROUP BY, ISNULL() functions, but JQL is not a Database Query Language. A field reference means a word that represents the field name in the JIRA issue including the custom fields. The syntax is − <field name> <operators like =,>, <> “values” or “functions” The operator compares the value of the field with value presents at right side such that only true results are retrieved by query. Go to Issues → Search for Issues in the navigator bar. The following screenshot shows how to navigate the Search section. If there is an existing search criterion, click on the New Filter button to reset the criteria. The following screenshot shows how to start with a new criteria − Type the query using the Field, Operator and Values like issueKey = “WFT-107”. There are other fields as well – Affected Version, Assignee, Attachments, Category, Comment, Component, Created, Creator, Description, Due, Environment, etc. As soon as the user starts typing, the auto-complete functionality helps to write in the defined format. The following screenshot shows how to add Field Name criteria using advanced features. Operator selection − The following screenshot shows how to select operators. The next step is to enter the value and then click on the Search symbol. The following screenshot shows how to add values and search. The following screenshot shows the search result based on criteria set. Here, we will understand how to use a keyword reference and what its advantages are A keyword in JQL − joins two or more queries together to form a complex JQL query. alters the logic of one or more queries. alters the logic of operators. has an explicit definition in a JQL query. performs a specific function that defines the results of a JQL query. List of Keywords − AND − ex - status = open AND priority = urgent And assignee = Ashish. OR − ex – duedate < now() or duedate is empty. NOT − ex – not assignee = Ashish . EMPTY − ex - affectedVersion is empty / affectedVersion = empty. NULL − ex – assignee is null. ORDER BY − ex – duedate = empty order by created, priority desc. Similar to field reference, as soon as the user starts typing, the auto-complete functionality helps to get the correct syntax. The following screenshot shows how to add keywords. Click on the Search symbol and it will provide the search results. The following screenshot shows the result based on a criteria set. Operators are used to compare values of the left side with the right side, such that only true results display as the search result. Equals: = Not Equals: != Greater Than: > Less Than: < Greater Than Equals: => Less than equals: =< IN NOT IN CONTAINS: ~ Does Not contain: ! ~ IS IS NOT WAS WAS IN WAS NOT IN WAS NOT CHANGED Similar to the Field and the Keyword Reference, these operators can also be used to enhance the search results. JIRA provides different types of reports within a project. It helps to analyze the Progress, Issues, Showstoppers and Timeliness of any Project. It also helps to analyze the resource utilization as well. To access reports in JIRA, the user should go to Project → choose Specific project. The following screenshot shows how to navigate to a specific project. Click on the Reports icon on the left side of the page. It will display all the reports supported by JIRA. The following screenshot shows how to access the Report section. When the user clicks on Switch report, it will display the list of reports. The following screenshot shows list of reports available for quick switch. JIRA has categorized reports in four levels, which are − Agile Issue Analysis Forecast & Management Others Let us now discuss the features of the above-mentioned report categories in detail. Following are the list of features of Agile Reports. Burn down Chart − Track the total work remaining, also whether sprint is achieving the project goal or not. Burn down Chart − Track the total work remaining, also whether sprint is achieving the project goal or not. Sprint Chart − Track the work completed or pushed back to the backlog in each sprint. Sprint Chart − Track the work completed or pushed back to the backlog in each sprint. Velocity Chart − Track the amount of work completed from sprint to sprint. Velocity Chart − Track the amount of work completed from sprint to sprint. Cumulative Flow Diagram − Shows the statuses of issues over time. It helps to identify high-risk issues or unresolved important issues. Cumulative Flow Diagram − Shows the statuses of issues over time. It helps to identify high-risk issues or unresolved important issues. Version Report − Track the projected release date for a version. Version Report − Track the projected release date for a version. Epic Report − Shows the progress towards completing an epic over a given time. Epic Report − Shows the progress towards completing an epic over a given time. Control Chart − Shows the cycle time for the product, its version or the sprint. It helps to identify whether data from the current process can be used to determine future performance. Control Chart − Shows the cycle time for the product, its version or the sprint. It helps to identify whether data from the current process can be used to determine future performance. Epic Burn Down − Track the projected number of sprints required to complete the epic. Epic Burn Down − Track the projected number of sprints required to complete the epic. Release Burn Down − Track the projected release date for a version. It helps to monitor whether the version will release on time, so mandatory action can be taken if work is falling behind. Release Burn Down − Track the projected release date for a version. It helps to monitor whether the version will release on time, so mandatory action can be taken if work is falling behind. Following are the list of features of Issue Analysis. Average Age Report − Displays the average age in days of unresolved issues. Average Age Report − Displays the average age in days of unresolved issues. Created Vs Resolved Issue Report − Display the number of issues created vs the number of issues resolved in given period. Created Vs Resolved Issue Report − Display the number of issues created vs the number of issues resolved in given period. Pie chart Report − Shows a pie chart of issues for a project grouped by a specified field. Pie chart Report − Shows a pie chart of issues for a project grouped by a specified field. Recently Created Issue Report − Shows the number of issues created over a time-period for a project and how many of those were resolved. Recently Created Issue Report − Shows the number of issues created over a time-period for a project and how many of those were resolved. Resolution Time Report − Displays the average time taken to resolve issues. Resolution Time Report − Displays the average time taken to resolve issues. Single Level Group by Report − .It helps to group the search results by a field and see the overall status of each group. Single Level Group by Report − .It helps to group the search results by a field and see the overall status of each group. Time since Issues Report − It helps to track how many issues were created, updated, resolved, etc., over a time-period. Time since Issues Report − It helps to track how many issues were created, updated, resolved, etc., over a time-period. Following are the list of features of Forecast and Management type of reports. Time Tracking Report − Shows the original and current time estimates for issues in the current project. It can help to determine whether work is on track for those issues. Time Tracking Report − Shows the original and current time estimates for issues in the current project. It can help to determine whether work is on track for those issues. User Workload Report − Shows the time estimates for all unresolved issues assigned to a user across projects. It helps to understand how much a user is occupied, whether overburdened or has less work. User Workload Report − Shows the time estimates for all unresolved issues assigned to a user across projects. It helps to understand how much a user is occupied, whether overburdened or has less work. Version Workload Report − Displays how much outstanding work is remaining per user and per issue. It helps to understand the remaining work of a version. Version Workload Report − Displays how much outstanding work is remaining per user and per issue. It helps to understand the remaining work of a version. In addition to these, there are other types of reports that generally have a pie chart in them, which we will discuss in detail in the subsequent chapters. A workload pie chart displays a pie chart showing all the issues for a specific project. Let us understand how to use it in JIRA. To generate a report, the user should follow the steps given below. Step 1 − Go to Project → choose the Specific project. Click on the Report icon on the left side of the menu. Go to ‘Others’ section and click on Workload Pie Chart Report as shown in the following screenshot. Step 2 − Select Project or issue filter for which to generate the report. In the Statistic Type, select the field name on which the pie chart will be formed. Select the Time Field to report on as Current Estimate, Original Estimate or Time Spent. The following screenshot shows how to generate a report by providing details. Step 3 − Click on Next to generate the report. The following screenshot shows how the generated report looks like. It displays the number of created issues versus resolved issues over a given time-period. It helps to understand whether the overall backlog is moving towards resolution or not. To generate a report, the user should follow the steps given below. Step 1 − Go to Project → choose a specific project. Click on the Report icon on the left side of the menu. Go to Issue Analysis and click on Created Vs Resolved Issues Report. The following screenshot shows how to access the Created Vs Resolved issues report − Step 2 − Select the Project or the issue filter for which the report has to be generated. Select the time-period to see reports like Daily, Weekly, Monthly, Quarterly, Annually, etc., available in the dropdown box. Enter the number of days in the Days Previously field to show in the graph. Select Yes or No for Cumulative totals. Select Display Versions as All Versions from the dropdown list. The following screenshot shows how to generate report by selecting different available fields. Step 3 − Click on Next to generate the reports. The following screenshot shows how the generated report looks like. The created issues are displayed in red, while the resolved issues are in green color. It displays the total work remaining to achieve the sprint goal for a given time to sprint. It helps the team to manage the progress and respond accordingly. This chart is an important feature of Agile – Scrum methodology. To generate a report, the user should follow the steps given below. Step 1 − Go to Project → choose a Specific project. Click on the Report icon on the left side of the menu. Go to Agile and click on Burndown chart. The following screenshot shows how to access a Burndown Chart. Step 2 − It displays the Burndown chart of the sprint like how the team is progressing towards a committed task. The red line displays how much work is remaining, while the grey line shows the committed tasks. The team can see where they stand in terms of the progress of sprint as compared to the commitment at the starting of that sprint. The user can change the Sprint and Y-axis by selection from a dropdown. The following screenshot shows how the Burndown chart looks like sprint wise. Step 3 − In the second part of the report, it displays data like what is the sprint start date, what all issues were added, day by day how many issues resolved, what story points of the issues are, and day-by-day how many story points are remaining. This data is utilized to create the chart. The following screenshot shows the data that is used to generate the chart. Note − Quite similar to these reports, other reports can also be generated. 6 Lectures 5 hours Frahaan Hussain 6 Lectures 5 hours Manu Mitra 41 Lectures 3.5 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2380, "s": 2195, "text": "JIRA is an Incident Management Tool used for Project Management, Bug Tracking, Issue Tracking and Workflow. JIRA is based on the following three concepts – Project, Issue and Workflow." }, { "code": null, "e": 2443, "s": 2380, "text": "The following points explain some interesting details of JIRA." }, { "code": null, "e": 2480, "s": 2443, "text": "JIRA is an incident management tool." }, { "code": null, "e": 2517, "s": 2480, "text": "JIRA is an incident management tool." }, { "code": null, "e": 2577, "s": 2517, "text": "JIRA is developed by Atlassian Inc., an Australian Company." }, { "code": null, "e": 2637, "s": 2577, "text": "JIRA is developed by Atlassian Inc., an Australian Company." }, { "code": null, "e": 2702, "s": 2637, "text": "JIRA is a platform independent tool; it can be used with any OS." }, { "code": null, "e": 2767, "s": 2702, "text": "JIRA is a platform independent tool; it can be used with any OS." }, { "code": null, "e": 2845, "s": 2767, "text": "JIRA is multi-lingual tool − English, French, German, Japanese, Spanish, etc." }, { "code": null, "e": 2923, "s": 2845, "text": "JIRA is multi-lingual tool − English, French, German, Japanese, Spanish, etc." }, { "code": null, "e": 2994, "s": 2923, "text": "JIRA supports MySQL, Oracle, PostgreSQL and SQL server in the backend." }, { "code": null, "e": 3065, "s": 2994, "text": "JIRA supports MySQL, Oracle, PostgreSQL and SQL server in the backend." }, { "code": null, "e": 3216, "s": 3065, "text": "JIRA can be integrated with many other tools − Subversion, GIT, Clearcase, Team Foundation Software, Mercury, Concurrent Version System and many more." }, { "code": null, "e": 3367, "s": 3216, "text": "JIRA can be integrated with many other tools − Subversion, GIT, Clearcase, Team Foundation Software, Mercury, Concurrent Version System and many more." }, { "code": null, "e": 3431, "s": 3367, "text": "The following points describes the legalities of the JIRA Tool." }, { "code": null, "e": 3510, "s": 3431, "text": "JIRA is a commercial tool and available as a Trial version for a limited time." }, { "code": null, "e": 3589, "s": 3510, "text": "JIRA is a commercial tool and available as a Trial version for a limited time." }, { "code": null, "e": 3638, "s": 3589, "text": "To utilize JIRA services, a license is required." }, { "code": null, "e": 3687, "s": 3638, "text": "To utilize JIRA services, a license is required." }, { "code": null, "e": 3737, "s": 3687, "text": "JIRA provides free license for academic projects." }, { "code": null, "e": 3787, "s": 3737, "text": "JIRA provides free license for academic projects." }, { "code": null, "e": 3856, "s": 3787, "text": "A 15-day trial version is available for an individual person to use." }, { "code": null, "e": 3925, "s": 3856, "text": "A 15-day trial version is available for an individual person to use." }, { "code": null, "e": 3982, "s": 3925, "text": "Following are some of the most significant uses of JIRA." }, { "code": null, "e": 4040, "s": 3982, "text": "JIRA is used in Bugs, Issues and Change Request Tracking." }, { "code": null, "e": 4098, "s": 4040, "text": "JIRA is used in Bugs, Issues and Change Request Tracking." }, { "code": null, "e": 4237, "s": 4098, "text": "JIRA can be used in Help desk, Support and Customer Services to create tickets and track the resolution and status of the created tickets." }, { "code": null, "e": 4376, "s": 4237, "text": "JIRA can be used in Help desk, Support and Customer Services to create tickets and track the resolution and status of the created tickets." }, { "code": null, "e": 4456, "s": 4376, "text": "JIRA is useful in Project Management, Task Tracking and Requirement Management." }, { "code": null, "e": 4536, "s": 4456, "text": "JIRA is useful in Project Management, Task Tracking and Requirement Management." }, { "code": null, "e": 4592, "s": 4536, "text": "JIRA is very useful in Workflow and Process management." }, { "code": null, "e": 4648, "s": 4592, "text": "JIRA is very useful in Workflow and Process management." }, { "code": null, "e": 4767, "s": 4648, "text": "The following table explains some of the most important and commonly used features in detail for better understanding." }, { "code": null, "e": 4774, "s": 4767, "text": "Boards" }, { "code": null, "e": 4813, "s": 4774, "text": "JIRA supports Scrum and Kanban boards." }, { "code": null, "e": 4884, "s": 4813, "text": "These boards provide an immediate snapshot of the project to the team." }, { "code": null, "e": 4980, "s": 4884, "text": "Helps to quickly review the progress of the project and see the status of the individual tasks." }, { "code": null, "e": 5056, "s": 4980, "text": "Board workflow can be customized to fulfil the way a team wants to proceed." }, { "code": null, "e": 5082, "s": 5056, "text": "Business Project Template" }, { "code": null, "e": 5183, "s": 5082, "text": "JIRA supports n number of business templates to manage simple tasks and complex tasks like workflow." }, { "code": null, "e": 5310, "s": 5183, "text": "Template can be customized based on the team and their approach. Ex: Workflow can be customized based on each team's approach." }, { "code": null, "e": 5376, "s": 5310, "text": "Every step is accounted and team can move to achieve their goals." }, { "code": null, "e": 5389, "s": 5376, "text": "Task Details" }, { "code": null, "e": 5457, "s": 5389, "text": "Tasks can be defined at the individual level to track the progress." }, { "code": null, "e": 5538, "s": 5457, "text": "Status of every task, comment, attachment and due dates are stored in one place." }, { "code": null, "e": 5552, "s": 5538, "text": "Notifications" }, { "code": null, "e": 5609, "s": 5552, "text": "An email can be sent for a particular task to the users." }, { "code": null, "e": 5691, "s": 5609, "text": "Voting and watching features to keep an eye on the progress for the stakeholders." }, { "code": null, "e": 5776, "s": 5691, "text": "Use @mention to get the attention of a specific team member at Comments/Description." }, { "code": null, "e": 5860, "s": 5776, "text": "User will instantly notify if something is assigned or if any feedback is required." }, { "code": null, "e": 5873, "s": 5860, "text": "Power Search" }, { "code": null, "e": 5960, "s": 5873, "text": "JIRA supports a powerful search functionality with Basic, Quick and Advanced features." }, { "code": null, "e": 6089, "s": 5960, "text": "Use the search tool to find answers like due date, when a task was last updated, what items a team member still needs to finish." }, { "code": null, "e": 6148, "s": 6089, "text": "Project information at one place, search within a project." }, { "code": null, "e": 6156, "s": 6148, "text": "Reports" }, { "code": null, "e": 6284, "s": 6156, "text": "JIRA supports more than a dozen reports to track progress over a specific timeframe, deadlines, individual’s contribution, etc." }, { "code": null, "e": 6382, "s": 6284, "text": "Easy to understand and generate different reports those help to analyze how the team is going on." }, { "code": null, "e": 6460, "s": 6382, "text": "Easy to configure these reports and display the matrices to the stakeholders." }, { "code": null, "e": 6483, "s": 6460, "text": "Scale with Team Growth" }, { "code": null, "e": 6568, "s": 6483, "text": "JIRA supports any business team and any project irrespective of size and complexity." }, { "code": null, "e": 6577, "s": 6568, "text": "Add -Ins" }, { "code": null, "e": 6667, "s": 6577, "text": "JIRA supports more than 100 add-ins to connect with different software to make work easy." }, { "code": null, "e": 6729, "s": 6667, "text": "Wide range of add-ins makes it as universal across the globe." }, { "code": null, "e": 6742, "s": 6729, "text": "Multilingual" }, { "code": null, "e": 6896, "s": 6742, "text": "JIRA supports more than 10 languages those are widely used as English (US, UK, India), French, German, Portuguese, Spanish, Korean, Japanese and Russian." }, { "code": null, "e": 6907, "s": 6896, "text": "Mobile App" }, { "code": null, "e": 6958, "s": 6907, "text": "JIRA is available as a Mobile Application as well." }, { "code": null, "e": 7028, "s": 6958, "text": "It is available on Google Play Store and App Store (iTunes) of Apple." }, { "code": null, "e": 7137, "s": 7028, "text": "Easy to stay connected with the team while moving anywhere with notification, comments and project activity." }, { "code": null, "e": 7274, "s": 7137, "text": "A Project contains issues; a JIRA project can be called as a collection of issues. A JIRA Project can be of several types. For example −" }, { "code": null, "e": 7303, "s": 7274, "text": "Software Development Project" }, { "code": null, "e": 7321, "s": 7303, "text": "Marketing Project" }, { "code": null, "e": 7357, "s": 7321, "text": "Migration to other platform project" }, { "code": null, "e": 7384, "s": 7357, "text": "Help Desk Tracking Project" }, { "code": null, "e": 7416, "s": 7384, "text": "Leave Request Management System" }, { "code": null, "e": 7444, "s": 7416, "text": "Employee Performance System" }, { "code": null, "e": 7464, "s": 7444, "text": "Website Enhancement" }, { "code": null, "e": 7580, "s": 7464, "text": "To create a project, the user should login as a JIRA Service Desk Admin and then Click on Project → Create Project." }, { "code": null, "e": 7673, "s": 7580, "text": "The following screenshot shows how to reach to the Create Project button from the Dashboard." }, { "code": null, "e": 7762, "s": 7673, "text": "Choose the type of Project that suits your requirement and the process it should follow." }, { "code": null, "e": 7836, "s": 7762, "text": "The following screenshot displays the type of projects available in JIRA." }, { "code": null, "e": 8006, "s": 7836, "text": "Once the type of project is selected, click on Next. The user will see the flow of the project based on the selection. Here, we have selected Basic Software development." }, { "code": null, "e": 8136, "s": 8006, "text": "The following screenshot displays the available issue types and the workflow for the chosen project in the step mentioned above −" }, { "code": null, "e": 8326, "s": 8136, "text": "Click on the Select button, enter the name of the project and confirm the Key that the user wants to display as a reference in all the issues. Once this is done, click on the Submit button." }, { "code": null, "e": 8424, "s": 8326, "text": "The following screenshot displays the fields to provide details before the creation of a project." }, { "code": null, "e": 8553, "s": 8424, "text": "The page having issues will display. The following screenshot displays whether any issues are linked with a new created project." }, { "code": null, "e": 8826, "s": 8553, "text": "JIRA is a project management tool and uses issues to track all the tasks. An issue helps to track all works that underlie in a project. In real time, every work or task either technical, non-technical, support or any other type of a project in JIRA are logged as an issue." }, { "code": null, "e": 8891, "s": 8826, "text": "An issue can be dependent on the organization and requirements −" }, { "code": null, "e": 8910, "s": 8891, "text": "Story of a project" }, { "code": null, "e": 8926, "s": 8910, "text": "Task of a story" }, { "code": null, "e": 8946, "s": 8926, "text": "Sub-task of a story" }, { "code": null, "e": 8978, "s": 8946, "text": "A defect or bug can be an issue" }, { "code": null, "e": 9017, "s": 8978, "text": "Helpdesk Ticket can be logged as issue" }, { "code": null, "e": 9031, "s": 9017, "text": "Leave Request" }, { "code": null, "e": 9113, "s": 9031, "text": "The following screen shot shows the basic page and information of an open issue −" }, { "code": null, "e": 9432, "s": 9113, "text": "In JIRA, workflow is used to track the lifecycle of an Issue. Workflow is a record of statuses and transitions of an issue during its lifecycle. A status represents the stage of an issue at a particular point. An issue can be in only one status at a given point of time like Opened, To Do, Done, Closed, Assigned, etc." }, { "code": null, "e": 9712, "s": 9432, "text": "A transition is a link between two statuses when an issue moves from one status to another. For an issue to move between two statuses, a transition must exist. In a simple way, a transition is some kind of work done on the issue, while status is the impact of work on that issue." }, { "code": null, "e": 9938, "s": 9712, "text": "As of now, an issue is created and opened. When the assignee starts working on the issue, the issue moves to the In Progress status. Here, the transition is starting the work, while the status of the issue is now progressive." }, { "code": null, "e": 10019, "s": 9938, "text": "JIRA workflow has the following stages to track as soon as an issue is created −" }, { "code": null, "e": 10126, "s": 10019, "text": "Open Issue − After creation, the issue is open and can be assigned to the assignee to start working on it." }, { "code": null, "e": 10233, "s": 10126, "text": "Open Issue − After creation, the issue is open and can be assigned to the assignee to start working on it." }, { "code": null, "e": 10309, "s": 10233, "text": "In Progress Issue − The assignee has actively started to work on the issue." }, { "code": null, "e": 10385, "s": 10309, "text": "In Progress Issue − The assignee has actively started to work on the issue." }, { "code": null, "e": 10613, "s": 10385, "text": "Resolved Issue − All sub-tasks and works of that Issue are completed. Now, the issue is waiting to be verified by the reporter. If verification is successful, it will be closed or re-opened, if any further changes are required." }, { "code": null, "e": 10841, "s": 10613, "text": "Resolved Issue − All sub-tasks and works of that Issue are completed. Now, the issue is waiting to be verified by the reporter. If verification is successful, it will be closed or re-opened, if any further changes are required." }, { "code": null, "e": 11064, "s": 10841, "text": "Reopened Issue − This issue was resolved previously, but the resolution was either incorrect or missed a few things or some modifications are required. From Reopened stage, issues are marked either as assigned or resolved." }, { "code": null, "e": 11287, "s": 11064, "text": "Reopened Issue − This issue was resolved previously, but the resolution was either incorrect or missed a few things or some modifications are required. From Reopened stage, issues are marked either as assigned or resolved." }, { "code": null, "e": 11434, "s": 11287, "text": "Close Issue − The issue is considered as finished, resolution is correct as of now. Closed issues can be re-opened later based on the requirement." }, { "code": null, "e": 11581, "s": 11434, "text": "Close Issue − The issue is considered as finished, resolution is correct as of now. Closed issues can be re-opened later based on the requirement." }, { "code": null, "e": 11758, "s": 11581, "text": "JIRA Workflow can be referred as a Defect Lifecycle. It follows the same concepts; the only difference is that it is generic for all issues rather than limited to Defects only." }, { "code": null, "e": 11808, "s": 11758, "text": "The following diagram shows a standard workflow −" }, { "code": null, "e": 11930, "s": 11808, "text": "A transition is a one-way link, if an issue moves back and forth between two statuses; two transitions should be created." }, { "code": null, "e": 12271, "s": 11930, "text": "Example − There are two-way transitions between closed and re-opened statuses. A closed issue can be reopened if any modifications are required at any time until the project completes, while a re-opened issue can be closed directly if additional work is taken care in another issue and no specific work has been done on the re-opened issue." }, { "code": null, "e": 12338, "s": 12271, "text": "In this chapter, we will learn how to install JIRA on your system." }, { "code": null, "e": 12480, "s": 12338, "text": "JIRA is a web application that provides a private website to an individual or a set of requested users belonging to the same company/project." }, { "code": null, "e": 12622, "s": 12480, "text": "JIRA is a web application that provides a private website to an individual or a set of requested users belonging to the same company/project." }, { "code": null, "e": 12679, "s": 12622, "text": "JIRA can be run as a Windows Service at the server side." }, { "code": null, "e": 12736, "s": 12679, "text": "JIRA can be run as a Windows Service at the server side." }, { "code": null, "e": 12896, "s": 12736, "text": "JIRA is a pure Java based application and supports all OS platforms like Windows, Linux of different versions or MAC, etc., those satisfy JDK/JRE requirements." }, { "code": null, "e": 13056, "s": 12896, "text": "JIRA is a pure Java based application and supports all OS platforms like Windows, Linux of different versions or MAC, etc., those satisfy JDK/JRE requirements." }, { "code": null, "e": 13127, "s": 13056, "text": "JIRA supports all famous browsers like Chrome, IE, Mozilla and Safari." }, { "code": null, "e": 13198, "s": 13127, "text": "JIRA supports all famous browsers like Chrome, IE, Mozilla and Safari." }, { "code": null, "e": 13251, "s": 13198, "text": "It supports Mobile browsers as well in mobile views." }, { "code": null, "e": 13304, "s": 13251, "text": "It supports Mobile browsers as well in mobile views." }, { "code": null, "e": 13523, "s": 13304, "text": "Since JIRA is a web-application, it follows the concept of client/server. It means that JIRA can be installed centrally on a server and users can interact with it through web-browsers using a website from any computer." }, { "code": null, "e": 13675, "s": 13523, "text": "Browser − JavaScript should be enabled, the user is recommended not to use any script-blocking tool like NoScript to access full functionality of JIRA." }, { "code": null, "e": 13827, "s": 13675, "text": "Browser − JavaScript should be enabled, the user is recommended not to use any script-blocking tool like NoScript to access full functionality of JIRA." }, { "code": null, "e": 13943, "s": 13827, "text": "JDK/JRE − It is recommended to update JRE/JDK with the latest version. JIRA 6.4 recommends using JRE/JDK version 8." }, { "code": null, "e": 14059, "s": 13943, "text": "JDK/JRE − It is recommended to update JRE/JDK with the latest version. JIRA 6.4 recommends using JRE/JDK version 8." }, { "code": null, "e": 14168, "s": 14059, "text": "Since our scope is to consume the JIRA application as end users, we can ignore the server side requirements." }, { "code": null, "e": 14280, "s": 14168, "text": "JIRA follows the Client/Server concept. At the server side, JIRA must be installed before using it as end user." }, { "code": null, "e": 14392, "s": 14280, "text": "JIRA follows the Client/Server concept. At the server side, JIRA must be installed before using it as end user." }, { "code": null, "e": 14487, "s": 14392, "text": "At the server side, JIRA must connect with relation database to store issues/application data." }, { "code": null, "e": 14582, "s": 14487, "text": "At the server side, JIRA must connect with relation database to store issues/application data." }, { "code": null, "e": 14741, "s": 14582, "text": "Download the JIRA Windows Installer.exe file from the following link − https://www.atlassian.com/software/jira/download?_ga=1.28526460.1787473978.1 488778536." }, { "code": null, "e": 14900, "s": 14741, "text": "Download the JIRA Windows Installer.exe file from the following link − https://www.atlassian.com/software/jira/download?_ga=1.28526460.1787473978.1 488778536." }, { "code": null, "e": 14942, "s": 14900, "text": "Select the OS type and click on Download." }, { "code": null, "e": 14984, "s": 14942, "text": "Select the OS type and click on Download." }, { "code": null, "e": 15064, "s": 14984, "text": "The following screenshot shows how to download the .exe file for a specific OS." }, { "code": null, "e": 15171, "s": 15064, "text": "Run the .exe file to run the installation wizard. The following screenshot shows the downloaded .exe file." }, { "code": null, "e": 15313, "s": 15171, "text": "After clicking the .exe file, the Run confirmation pop-up displays, click on RUN. The following screenshot shows the RUN confirmation pop-up." }, { "code": null, "e": 15377, "s": 15313, "text": "The following JIRA installation wizard displays, click on Next." }, { "code": null, "e": 15477, "s": 15377, "text": "Choose the appropriate installation option as shown in following screenshot and then click on Next." }, { "code": null, "e": 15618, "s": 15477, "text": "The installation summary is displayed with the Destination Directory, Home Directory, TCP Ports, etc., as shown in the following screenshot." }, { "code": null, "e": 15758, "s": 15618, "text": "Click on Install. JIRA will start installing as displayed in following screenshot. It takes a couple of minutes to finish the installation." }, { "code": null, "e": 15975, "s": 15758, "text": "After installation, JIRA will be started automatically if the check box to “Start JIRA Software 7.3.4 now” is checked. Then click on Next, if not, it can be accessed using the appropriate Windows Start Menu shortcut." }, { "code": null, "e": 16000, "s": 15975, "text": "Click the Finish button." }, { "code": null, "e": 16070, "s": 16000, "text": "The installer will create the following shortcuts on the start menu −" }, { "code": null, "e": 16082, "s": 16070, "text": "Access JIRA" }, { "code": null, "e": 16100, "s": 16082, "text": "Start JIRA Server" }, { "code": null, "e": 16117, "s": 16100, "text": "Stop JIRA server" }, { "code": null, "e": 16132, "s": 16117, "text": "Uninstall JIRA" }, { "code": null, "e": 16195, "s": 16132, "text": "The following screenshot shows the above-mentioned shortcuts −" }, { "code": null, "e": 16282, "s": 16195, "text": "Select the license type and enter organization name as shown in following screenshot −" }, { "code": null, "e": 16308, "s": 16282, "text": "Click on Generate License" }, { "code": null, "e": 16395, "s": 16308, "text": "A confirmation pop-up will display as shown in the following screenshot. Click on Yes." }, { "code": null, "e": 16471, "s": 16395, "text": "Set up the administration account as displayed in the following screenshot." }, { "code": null, "e": 16534, "s": 16471, "text": "JIRA will automatically finish the setting-up as shown below −" }, { "code": null, "e": 16691, "s": 16534, "text": "Once JIRA finishes the setup and starts running in the server, the user can access it from a browser on any computer with network access to the JIRA server." }, { "code": null, "e": 16871, "s": 16691, "text": "JIRA provides 15 days to 1-month free trials of basic features. JIRA has other plans as well with different advanced features and add-ins. The cost depends on the number of users." }, { "code": null, "e": 16990, "s": 16871, "text": "By visiting https://www.atlassian.com/software/jira/try, a user can see different available plans for trying purposes." }, { "code": null, "e": 17162, "s": 16990, "text": "To setup a free trial, the user has to Sign up on the following link − https://id.atlassian.com/signup?application=&tenant=&continue or login if he already has an account." }, { "code": null, "e": 17242, "s": 17162, "text": "The following screenshot shows required fields to sign up in Atlassian account." }, { "code": null, "e": 17510, "s": 17242, "text": "The user has to log into the email account and verifies the account by clicking on the link sent by JIRA-Atlassian. The next step is to go to https://www.atlassian.com/software/jira/try and click on Create now button, which is at the bottom right hand of the webpage." }, { "code": null, "e": 17586, "s": 17510, "text": "The following screenshot shows different plans available for trial of JIRA." }, { "code": null, "e": 17666, "s": 17586, "text": "The following screenshot shows the details of the chosen plan for a free trial." }, { "code": null, "e": 17880, "s": 17666, "text": "Once the user fills in all the details along with the sample website name, user has to click on the Start now button. The following screenshot shows how to claim your site and provide your credentials to start it." }, { "code": null, "e": 18201, "s": 17880, "text": "It will take a few minutes to start the requested sample JIRA website. Once it is done, the JIRA login page will display and the user can see the given sample website name in the browser’s address bar. The user can now directly access this link to navigate to JIRA. The following screenshot shows the login page of JIRA." }, { "code": null, "e": 18439, "s": 18201, "text": "To login to JIRA, go to your sample website. It will open a login page. Fill in your registered email address/username and Password. Click on the Login button. The following screenshot shows how to login into JIRA using your credentials." }, { "code": null, "e": 18617, "s": 18439, "text": "In case of any unsuccessful login, an error message displays. The following screenshot shows the error message a user receives, if the credentials are not matching or incorrect." }, { "code": null, "e": 18856, "s": 18617, "text": "To rectify this scenario, click on “Unable to access your account”, then select the appropriate option and fill in the details. Click on email. The following screenshot shows how to recover the username, in case the user has forgotten it." }, { "code": null, "e": 18949, "s": 18856, "text": "The user will get an email with the details of his username or a link to reset the password." }, { "code": null, "e": 19145, "s": 18949, "text": "On a successful login, the system dashboard will display if the account is associated with any project by the admin, or if a user can create a sample project as explained in the earlier chapters." }, { "code": null, "e": 19237, "s": 19145, "text": "The following screenshot displays the welcome page/dashboard of JIRA on a successful login." }, { "code": null, "e": 19477, "s": 19237, "text": "After logging into JIRA, the Dashboard is the first page that shows up. The Dashboard is customized by the Admin. Based on the roles, the admin can set the access of JIRA. Even the admin has the right to change colors and the logo of JIRA." }, { "code": null, "e": 19589, "s": 19477, "text": "Following are some of the most significant points the users should understand before using the JIRA Dashboard −" }, { "code": null, "e": 19835, "s": 19589, "text": "The navigation bar, present at the top of the JIRA page, will be the same across all the pages/screens of JIRA. Dashboard, Projects, Issues, Boards and Create are the main links. These links have many sub-links to navigate other functionalities." }, { "code": null, "e": 20081, "s": 19835, "text": "The navigation bar, present at the top of the JIRA page, will be the same across all the pages/screens of JIRA. Dashboard, Projects, Issues, Boards and Create are the main links. These links have many sub-links to navigate other functionalities." }, { "code": null, "e": 20178, "s": 20081, "text": "Navigation bar contains links that provides a quick access to the most useful functions of JIRA." }, { "code": null, "e": 20275, "s": 20178, "text": "Navigation bar contains links that provides a quick access to the most useful functions of JIRA." }, { "code": null, "e": 20331, "s": 20275, "text": "Just under navigation bar, there is a System Dashboard." }, { "code": null, "e": 20387, "s": 20331, "text": "Just under navigation bar, there is a System Dashboard." }, { "code": null, "e": 20473, "s": 20387, "text": "The information provided in the system dashboard area can be customized by the Admin." }, { "code": null, "e": 20559, "s": 20473, "text": "The information provided in the system dashboard area can be customized by the Admin." }, { "code": null, "e": 20722, "s": 20559, "text": "By default, it has three main sections – Introduction, Assigned to Me (displays Issues list assigned to users) and Activity Stream (Activities done by the users)." }, { "code": null, "e": 20885, "s": 20722, "text": "By default, it has three main sections – Introduction, Assigned to Me (displays Issues list assigned to users) and Activity Stream (Activities done by the users)." }, { "code": null, "e": 20961, "s": 20885, "text": "The following screenshot shows the overview of the Dashboard page of JIRA −" }, { "code": null, "e": 21059, "s": 20961, "text": "The Projects link has several sub-links, which are explained in detail for better understanding −" }, { "code": null, "e": 21281, "s": 21059, "text": "Current Project − It displays the name of the Project where the user is currently in or is viewing the dashboard of the project. By clicking at Project name, it will display the list of issues associated with the project." }, { "code": null, "e": 21503, "s": 21281, "text": "Current Project − It displays the name of the Project where the user is currently in or is viewing the dashboard of the project. By clicking at Project name, it will display the list of issues associated with the project." }, { "code": null, "e": 21683, "s": 21503, "text": "Recent Project − It displays the name of the recent project that the user has accessed, if exists, where the user can navigate by clicking on the project listed under this header." }, { "code": null, "e": 21863, "s": 21683, "text": "Recent Project − It displays the name of the recent project that the user has accessed, if exists, where the user can navigate by clicking on the project listed under this header." }, { "code": null, "e": 21977, "s": 21863, "text": "Software − It is the sub-link to navigate the list of projects, which are listed in the Project Type as Software." }, { "code": null, "e": 22091, "s": 21977, "text": "Software − It is the sub-link to navigate the list of projects, which are listed in the Project Type as Software." }, { "code": null, "e": 22199, "s": 22091, "text": "Business − It is also a project-type. By clicking here, it will display the list of business project types." }, { "code": null, "e": 22307, "s": 22199, "text": "Business − It is also a project-type. By clicking here, it will display the list of business project types." }, { "code": null, "e": 22403, "s": 22307, "text": "View all Projects − It displays all the projects, which are associated with the logged in user." }, { "code": null, "e": 22499, "s": 22403, "text": "View all Projects − It displays all the projects, which are associated with the logged in user." }, { "code": null, "e": 22691, "s": 22499, "text": "Create Project − This link is usually accessed by the Admin or it depends on various roles. If this link is visible, a user can create a new project by following the instructions given there." }, { "code": null, "e": 22883, "s": 22691, "text": "Create Project − This link is usually accessed by the Admin or it depends on various roles. If this link is visible, a user can create a new project by following the instructions given there." }, { "code": null, "e": 22966, "s": 22883, "text": "The following screenshot shows the different sub-links under the Project category." }, { "code": null, "e": 23106, "s": 22966, "text": "It has many sub links to access other functionalities. The following screenshot shows different available sub-links under Issue navigation." }, { "code": null, "e": 23230, "s": 23106, "text": "Search for Issues − It navigates to the search page, where the user can provide search criteria to narrow down the results." }, { "code": null, "e": 23354, "s": 23230, "text": "Search for Issues − It navigates to the search page, where the user can provide search criteria to narrow down the results." }, { "code": null, "e": 23439, "s": 23354, "text": "Recent Issues − It displays the list of issues that are recently viewed by the user." }, { "code": null, "e": 23524, "s": 23439, "text": "Recent Issues − It displays the list of issues that are recently viewed by the user." }, { "code": null, "e": 23657, "s": 23524, "text": "Import issue from CSV − This feature allows the user to import the details of issues by uploading a CSV file and mapping the fields." }, { "code": null, "e": 23790, "s": 23657, "text": "Import issue from CSV − This feature allows the user to import the details of issues by uploading a CSV file and mapping the fields." }, { "code": null, "e": 23906, "s": 23790, "text": "My open issues − It is the filter section, which displays issues those are open and assigned to the logged-in user." }, { "code": null, "e": 24022, "s": 23906, "text": "My open issues − It is the filter section, which displays issues those are open and assigned to the logged-in user." }, { "code": null, "e": 24129, "s": 24022, "text": "Reported by me − This filter section displays the issues, which are already created by the logged-in user." }, { "code": null, "e": 24236, "s": 24129, "text": "Reported by me − This filter section displays the issues, which are already created by the logged-in user." }, { "code": null, "e": 24365, "s": 24236, "text": "Manage filters − It helps to customize the filter and narrow down the results. It displays any saved filters/ favorites filters." }, { "code": null, "e": 24494, "s": 24365, "text": "Manage filters − It helps to customize the filter and narrow down the results. It displays any saved filters/ favorites filters." }, { "code": null, "e": 24685, "s": 24494, "text": "Boards are showcase of process that is followed by Project. It could be the most famous Agile Board if the project is following the agile methodology or it might be the Kanban board as well." }, { "code": null, "e": 24759, "s": 24685, "text": "Recent Board − It displays the recent project board accessed by the user." }, { "code": null, "e": 24833, "s": 24759, "text": "Recent Board − It displays the recent project board accessed by the user." }, { "code": null, "e": 24893, "s": 24833, "text": "View all boards − It displays all available project boards." }, { "code": null, "e": 24953, "s": 24893, "text": "View all boards − It displays all available project boards." }, { "code": null, "e": 25043, "s": 24953, "text": "The following screenshot shows the different sub-links available under the board section." }, { "code": null, "e": 25122, "s": 25043, "text": "By clicking on the Create button, it displays the create form to log an issue." }, { "code": null, "e": 25207, "s": 25122, "text": "The following screenshot shows required fields and other fields to create an issue −" }, { "code": null, "e": 25436, "s": 25207, "text": "There is a feedback link at the right side of the navigation bar (as highlighted in the following screenshot). By clicking on link, user gets a form where he can provide feedback by entering Summary, Description, Name and email." }, { "code": null, "e": 25527, "s": 25436, "text": "The following screenshot shows the location of the Feedback link present in the Dashboard." }, { "code": null, "e": 25612, "s": 25527, "text": "The following screenshot shows the required and optional fields to provide feedback." }, { "code": null, "e": 25697, "s": 25612, "text": "Once all the fields are filled, click on Submit, it successfully posts the feedback." }, { "code": null, "e": 26086, "s": 25697, "text": "The Help link provides different useful documentation about JIRA. It provides the details of JIRA as well by clicking on “About JIRA”. Similarly, this link also provides new release features by clicking on “What’s new”. Keyboard shortcuts have much useful keyboard navigation for users that saves time. The following screenshot shows the Help link and different sub-links available in it." }, { "code": null, "e": 26323, "s": 26086, "text": "By clicking on the profile link, the user can view his profile details and manage this section. By clicking on Logout, the user will get back to the login page and will not be able to access the project details without logging in again." }, { "code": null, "e": 26407, "s": 26323, "text": "The following screenshot shows available functionality under User-Profile section −" }, { "code": null, "e": 26657, "s": 26407, "text": "By clicking on the edit symbol, the user will be able to edit profile details like – Summary Details, Preferences, etc. The following screenshot shows how to edit the profile by clicking on the Edit (highlighted in red outline) icon at each section." }, { "code": null, "e": 26746, "s": 26657, "text": "On the right side, the user can see the activity stream performed by the logged in user." }, { "code": null, "e": 26911, "s": 26746, "text": "Since JIRA tracks all the tasks, the sub-tasks or even a work as an Issue, there are several types of Issues to identify the work and categorize the similar issues." }, { "code": null, "e": 26947, "s": 26911, "text": "An Issue is classified as follows −" }, { "code": null, "e": 27086, "s": 26947, "text": "Sub-Task − This is the sub-task of an issue. In a logged issue, there can be different tasks to resolve it, which are called as sub-tasks." }, { "code": null, "e": 27225, "s": 27086, "text": "Sub-Task − This is the sub-task of an issue. In a logged issue, there can be different tasks to resolve it, which are called as sub-tasks." }, { "code": null, "e": 27296, "s": 27225, "text": "Bug − A problem that impairs or prevents the functions of the product." }, { "code": null, "e": 27367, "s": 27296, "text": "Bug − A problem that impairs or prevents the functions of the product." }, { "code": null, "e": 27471, "s": 27367, "text": "Epic − A big user story that needs to be broken down. Created by JIRA Software - do not edit or delete." }, { "code": null, "e": 27575, "s": 27471, "text": "Epic − A big user story that needs to be broken down. Created by JIRA Software - do not edit or delete." }, { "code": null, "e": 27651, "s": 27575, "text": "Improvement − An improvement or enhancement to an existing feature or task." }, { "code": null, "e": 27727, "s": 27651, "text": "Improvement − An improvement or enhancement to an existing feature or task." }, { "code": null, "e": 27801, "s": 27727, "text": "New Feature − A new feature of the product, which is yet to be developed." }, { "code": null, "e": 27875, "s": 27801, "text": "New Feature − A new feature of the product, which is yet to be developed." }, { "code": null, "e": 27947, "s": 27875, "text": "Story − A user story. Created by JIRA Software - do not edit or delete." }, { "code": null, "e": 28019, "s": 27947, "text": "Story − A user story. Created by JIRA Software - do not edit or delete." }, { "code": null, "e": 28079, "s": 28019, "text": "Task − A task that needs to be done to achieve team’s goal." }, { "code": null, "e": 28139, "s": 28079, "text": "Task − A task that needs to be done to achieve team’s goal." }, { "code": null, "e": 28333, "s": 28139, "text": "If a user logs in as Admin and navigate to Settings → JIRA Administrator → Issues, all the listed issue types will display. The following screenshot shows all the available issue types in JIRA." }, { "code": null, "e": 28641, "s": 28333, "text": "An issue type scheme determines which issue types will be available to a project or set of projects. It also manages specifying the order in which the issue types will present in the user interface of JIRA, while creating an Issue. An issue type scheme generates as soon as the project is added in the JIRA." }, { "code": null, "e": 28955, "s": 28641, "text": "Here, one scheme is by default named as the Default Issue Type Scheme and others are project schemes. The default issue type scheme is the list of global issue types. All newly created issue types will automatically be added to this scheme. The following screenshot shows Issue type schemes of different projects." }, { "code": null, "e": 29073, "s": 28955, "text": "By clicking on the Add Issue Type Scheme button at the top right hand corner, the user can add a user defined scheme." }, { "code": null, "e": 29293, "s": 29073, "text": "Enter the Name, Description and Select the Issue Type for the Current scheme from the Available issue type list. The following screenshot shows how to add a new type schema by providing the required and optional fields." }, { "code": null, "e": 29439, "s": 29293, "text": "Click on Save. The new schema will appear in the list. The Following screenshot shows how the page display after adding a new Issue Type schema −" }, { "code": null, "e": 29635, "s": 29439, "text": "By clicking on Edit, the user can edit the details. By clicking on Associate, the user can associate this scheme to a project. Copy and Delete is used for copying and deletion of the same scheme." }, { "code": null, "e": 30019, "s": 29635, "text": "It is the arrangement and representation of fields to display in UI whenever a new issue is created or existing issues are modified and issue transitioned through one status to another. If a user logs in as Admin and navigate to Settings → Issues → Screens, he will be able to see all the available screens. The following screenshot shows the available screen for different projects." }, { "code": null, "e": 30260, "s": 30019, "text": "By clicking on configure, the user will be able to see all the available fields with this screen. Whereas, in the organized/arranged way of order, it will display at the UI. The following screenshot shows how to configure the screen fields." }, { "code": null, "e": 30766, "s": 30260, "text": "Screen schemes provides an option to choose fields, which should display when a particular issue type is selected. A screen scheme is mapped with issue type using the Issue Type Screen Scheme. It can be associated with one or more project. A screen scheme can be deleted only when it is not used by any Issue Type screen scheme. The user can add a new screen scheme by clicking on the Add Screen Scheme button. The following screenshot shows the different screen schemes available for the listed projects." }, { "code": null, "e": 30882, "s": 30766, "text": "Provide all details and the click on the ADD button. The following screenshot shows how to add a new screen scheme." }, { "code": null, "e": 31008, "s": 30882, "text": "To create an issue in JIRA, the user should have Create Issue permission in the project. Admin can add/remove the permission." }, { "code": null, "e": 31096, "s": 31008, "text": "Click on the Create button in the navigation bar to open the create issue dialogue box." }, { "code": null, "e": 31185, "s": 31096, "text": "To complete the process of creating an issue, we should follow the pointers given below." }, { "code": null, "e": 31224, "s": 31185, "text": "Select the Project where the issue is." }, { "code": null, "e": 31263, "s": 31224, "text": "Select the Project where the issue is." }, { "code": null, "e": 31333, "s": 31263, "text": "Select the type of issue, whether it is a bug/new feature/story, etc." }, { "code": null, "e": 31403, "s": 31333, "text": "Select the type of issue, whether it is a bug/new feature/story, etc." }, { "code": null, "e": 31473, "s": 31403, "text": "Write a one-line summary to provide the overall idea about the issue." }, { "code": null, "e": 31543, "s": 31473, "text": "Write a one-line summary to provide the overall idea about the issue." }, { "code": null, "e": 31682, "s": 31543, "text": "Write the details of the issue in the Description field. Explain the issue, so that stockholders can understand every detail of the issue." }, { "code": null, "e": 31821, "s": 31682, "text": "Write the details of the issue in the Description field. Explain the issue, so that stockholders can understand every detail of the issue." }, { "code": null, "e": 31962, "s": 31821, "text": "To create a similar type of issue in the same project and issue type, check the checkbox of “Create another” otherwise keep it as unchecked." }, { "code": null, "e": 32103, "s": 31962, "text": "To create a similar type of issue in the same project and issue type, check the checkbox of “Create another” otherwise keep it as unchecked." }, { "code": null, "e": 32163, "s": 32103, "text": "After entering all the details, click on the Create button." }, { "code": null, "e": 32223, "s": 32163, "text": "After entering all the details, click on the Create button." }, { "code": null, "e": 32325, "s": 32223, "text": "The following screenshot shows how to create an issue by providing the required and optional details." }, { "code": null, "e": 32533, "s": 32325, "text": "If the “Create another” checkbox is not checked, after clicking on the Create button, the user will have to navigate to the Dashboard and a pop-up will display on the right side with an issue id and summary." }, { "code": null, "e": 32626, "s": 32533, "text": "The following screenshot shows how to know whether the issue is successfully created or not." }, { "code": null, "e": 32774, "s": 32626, "text": "If the “Create another” checkbox is checked while clicking on the Create button, the user will get a new create issue page along with the issue id." }, { "code": null, "e": 32865, "s": 32774, "text": "The following screenshot shows the page, if the user has checked the “Create another” box." }, { "code": null, "e": 33064, "s": 32865, "text": "To add other fields in the Create Issue form, click on “Configure fields” at the top right hand side of the page. The following screenshot shows how to configure the fields in the Create Issue page." }, { "code": null, "e": 33237, "s": 33064, "text": "After clicking on the Configure fields button, a drop down box will be displayed, click on Custom. The following screenshot shows the available fields under the Custom tab." }, { "code": null, "e": 33415, "s": 33237, "text": "By checking and unchecking the checkboxes to show and hide, fields will be added or cleared from the form. The following screenshot shows the available fields under the All tab." }, { "code": null, "e": 33597, "s": 33415, "text": "Now navigate to Create Issue, all fields based on choices will be displayed in the form that shows up. The following screenshot shows the configured fields in the Create Issue page." }, { "code": null, "e": 33654, "s": 33597, "text": "The fields in the Create Issue form are explained below." }, { "code": null, "e": 33755, "s": 33654, "text": "Priority − Issue creator can set the priority to resolve the issue as High, Medium, Low, and Lowest." }, { "code": null, "e": 33856, "s": 33755, "text": "Priority − Issue creator can set the priority to resolve the issue as High, Medium, Low, and Lowest." }, { "code": null, "e": 33939, "s": 33856, "text": "Labels − It is similar to Tag; it helps in filtering out specific types of issues." }, { "code": null, "e": 34022, "s": 33939, "text": "Labels − It is similar to Tag; it helps in filtering out specific types of issues." }, { "code": null, "e": 34207, "s": 34022, "text": "Linked Issue − It links other issues that are either dependent on this issue or this issue is dependent on them. Options in dropdowns are – block, is blocked by, duplicate, clone, etc." }, { "code": null, "e": 34392, "s": 34207, "text": "Linked Issue − It links other issues that are either dependent on this issue or this issue is dependent on them. Options in dropdowns are – block, is blocked by, duplicate, clone, etc." }, { "code": null, "e": 34505, "s": 34392, "text": "Issue − User can link the issue by the Typing ID or summary of those that are related to the linked issue field." }, { "code": null, "e": 34618, "s": 34505, "text": "Issue − User can link the issue by the Typing ID or summary of those that are related to the linked issue field." }, { "code": null, "e": 34729, "s": 34618, "text": "Assignee − The person who is responsible to fix this issue. Assignee name can be entered by the issue creator." }, { "code": null, "e": 34840, "s": 34729, "text": "Assignee − The person who is responsible to fix this issue. Assignee name can be entered by the issue creator." }, { "code": null, "e": 34933, "s": 34840, "text": "Epic Link − An Issue creator can provide an epic link, if the issue belongs to any of those." }, { "code": null, "e": 35026, "s": 34933, "text": "Epic Link − An Issue creator can provide an epic link, if the issue belongs to any of those." }, { "code": null, "e": 35132, "s": 35026, "text": "Sprint − The user can define in which sprint, this issue belongs to, when this issue should be addressed." }, { "code": null, "e": 35238, "s": 35132, "text": "Sprint − The user can define in which sprint, this issue belongs to, when this issue should be addressed." }, { "code": null, "e": 35296, "s": 35238, "text": "In the next chapter, we will learn how to clone an issue." }, { "code": null, "e": 35471, "s": 35296, "text": "Cloning means to copy. To clone an issue means to create a duplicate issue within the same project. A cloned issue can be treated as a new issue and edited like other issues." }, { "code": null, "e": 35535, "s": 35471, "text": "We should consider the following points while cloning an issue." }, { "code": null, "e": 35606, "s": 35535, "text": "A cloned issue is completely a separate issue from the original issue." }, { "code": null, "e": 35677, "s": 35606, "text": "A cloned issue is completely a separate issue from the original issue." }, { "code": null, "e": 35789, "s": 35677, "text": "Any action or operation taken on the original issue does not have any impact on the clone issue and vice-versa." }, { "code": null, "e": 35901, "s": 35789, "text": "Any action or operation taken on the original issue does not have any impact on the clone issue and vice-versa." }, { "code": null, "e": 35981, "s": 35901, "text": "The only connection between the original and clone is the link that is created." }, { "code": null, "e": 36061, "s": 35981, "text": "The only connection between the original and clone is the link that is created." }, { "code": null, "e": 36144, "s": 36061, "text": "Information that is carried from the original issue to clone issue is as follows −" }, { "code": null, "e": 36227, "s": 36144, "text": "Information that is carried from the original issue to clone issue is as follows −" }, { "code": null, "e": 36235, "s": 36227, "text": "Summary" }, { "code": null, "e": 36243, "s": 36235, "text": "Summary" }, { "code": null, "e": 36255, "s": 36243, "text": "Description" }, { "code": null, "e": 36267, "s": 36255, "text": "Description" }, { "code": null, "e": 36276, "s": 36267, "text": "Assignee" }, { "code": null, "e": 36285, "s": 36276, "text": "Assignee" }, { "code": null, "e": 36297, "s": 36285, "text": "Environment" }, { "code": null, "e": 36309, "s": 36297, "text": "Environment" }, { "code": null, "e": 36318, "s": 36309, "text": "Priority" }, { "code": null, "e": 36327, "s": 36318, "text": "Priority" }, { "code": null, "e": 36338, "s": 36327, "text": "Issue Type" }, { "code": null, "e": 36349, "s": 36338, "text": "Issue Type" }, { "code": null, "e": 36358, "s": 36349, "text": "Security" }, { "code": null, "e": 36367, "s": 36358, "text": "Security" }, { "code": null, "e": 36377, "s": 36367, "text": "Component" }, { "code": null, "e": 36387, "s": 36377, "text": "Component" }, { "code": null, "e": 36396, "s": 36387, "text": "Reporter" }, { "code": null, "e": 36405, "s": 36396, "text": "Reporter" }, { "code": null, "e": 36421, "s": 36405, "text": "Affects Version" }, { "code": null, "e": 36437, "s": 36421, "text": "Affects Version" }, { "code": null, "e": 36449, "s": 36437, "text": "Fix Version" }, { "code": null, "e": 36461, "s": 36449, "text": "Fix Version" }, { "code": null, "e": 36472, "s": 36461, "text": "Attachment" }, { "code": null, "e": 36483, "s": 36472, "text": "Attachment" }, { "code": null, "e": 36492, "s": 36483, "text": "Projects" }, { "code": null, "e": 36501, "s": 36492, "text": "Projects" }, { "code": null, "e": 36542, "s": 36501, "text": "Content of custom fields are also cloned" }, { "code": null, "e": 36583, "s": 36542, "text": "Content of custom fields are also cloned" }, { "code": null, "e": 36616, "s": 36583, "text": "Information that is not cloned −" }, { "code": null, "e": 36649, "s": 36616, "text": "Information that is not cloned −" }, { "code": null, "e": 36663, "s": 36649, "text": "Time Tracking" }, { "code": null, "e": 36677, "s": 36663, "text": "Time Tracking" }, { "code": null, "e": 36686, "s": 36677, "text": "Comments" }, { "code": null, "e": 36695, "s": 36686, "text": "Comments" }, { "code": null, "e": 36709, "s": 36695, "text": "Issue History" }, { "code": null, "e": 36723, "s": 36709, "text": "Issue History" }, { "code": null, "e": 36749, "s": 36723, "text": "Links to confluence pages" }, { "code": null, "e": 36775, "s": 36749, "text": "Links to confluence pages" }, { "code": null, "e": 36939, "s": 36775, "text": "Open a JIRA issue that is supposed to be cloned. Select More → Clone when the screen appears. The following screenshot shows how to access the Clone functionality." }, { "code": null, "e": 37027, "s": 36939, "text": "In the clone screen, there are a few options given to the users, which are as follows −" }, { "code": null, "e": 37075, "s": 37027, "text": "A user can change the summary while cloning it." }, { "code": null, "e": 37123, "s": 37075, "text": "A user can change the summary while cloning it." }, { "code": null, "e": 37295, "s": 37123, "text": "If the issue contains links to other issues, a user can check the checkbox to contain the clone issue or uncheck if the user does not want to be a part of the clone issue." }, { "code": null, "e": 37467, "s": 37295, "text": "If the issue contains links to other issues, a user can check the checkbox to contain the clone issue or uncheck if the user does not want to be a part of the clone issue." }, { "code": null, "e": 37579, "s": 37467, "text": "If the issue has sub-tasks, the user can select/deselect the checkbox to contain the sub-tasks in clone or not." }, { "code": null, "e": 37691, "s": 37579, "text": "If the issue has sub-tasks, the user can select/deselect the checkbox to contain the sub-tasks in clone or not." }, { "code": null, "e": 37738, "s": 37691, "text": "The same is applicable for attachment as well." }, { "code": null, "e": 37785, "s": 37738, "text": "The same is applicable for attachment as well." }, { "code": null, "e": 37877, "s": 37785, "text": "It also gives an option, whether to carry or not – the sprint value to the new clone issue." }, { "code": null, "e": 37969, "s": 37877, "text": "It also gives an option, whether to carry or not – the sprint value to the new clone issue." }, { "code": null, "e": 38058, "s": 37969, "text": "The following screenshot shows how to clone an issue by providing the necessary details." }, { "code": null, "e": 38315, "s": 38058, "text": "The next step is to click on Create. It will display the clone issue details. If the user does not change the clone words while creating, it can be visible in the summary, links and sub-tasks. The following screenshot shows how a cloned issue is displayed." }, { "code": null, "e": 38619, "s": 38315, "text": "An issue can be completed by performing many tasks with different persons like Dev, QA, UAT, Business, Support, etc. To track the progress in each department, sub-tasks are created in an issue and assigned to the concern person. Once all the sub-tasks are resolved, the issue can be marked as completed." }, { "code": null, "e": 38686, "s": 38619, "text": "The following points are to be considered when creating a subtask." }, { "code": null, "e": 38744, "s": 38686, "text": "All subtasks are an essential part of their parent issue." }, { "code": null, "e": 38802, "s": 38744, "text": "All subtasks are an essential part of their parent issue." }, { "code": null, "e": 38867, "s": 38802, "text": "All subtasks are visible on the main screen of the parent issue." }, { "code": null, "e": 38932, "s": 38867, "text": "All subtasks are visible on the main screen of the parent issue." }, { "code": null, "e": 38998, "s": 38932, "text": "Subtasks always belong to the same project as their parent issue." }, { "code": null, "e": 39064, "s": 38998, "text": "Subtasks always belong to the same project as their parent issue." }, { "code": null, "e": 39127, "s": 39064, "text": "Subtask has all fields that are present in the standard issue." }, { "code": null, "e": 39190, "s": 39127, "text": "Subtask has all fields that are present in the standard issue." }, { "code": null, "e": 39235, "s": 39190, "text": "Subtasks cannot have a subtask of their own." }, { "code": null, "e": 39280, "s": 39235, "text": "Subtasks cannot have a subtask of their own." }, { "code": null, "e": 39344, "s": 39280, "text": "We should consider the following steps when creating a subtask." }, { "code": null, "e": 39394, "s": 39344, "text": "Open an issue where subtasks should be created. \n" }, { "code": null, "e": 39443, "s": 39394, "text": "Open an issue where subtasks should be created. " }, { "code": null, "e": 39507, "s": 39443, "text": "Select More → Create Subtask. Create subtask page will display." }, { "code": null, "e": 39571, "s": 39507, "text": "Select More → Create Subtask. Create subtask page will display." }, { "code": null, "e": 39650, "s": 39571, "text": "The following screenshot shows how to access the Create Subtask functionality." }, { "code": null, "e": 39815, "s": 39650, "text": "Enter the details in all the required fields and then click on Create. The following screenshot shows the Create Subtask Form with the required and optional fields." }, { "code": null, "e": 39971, "s": 39815, "text": "Once a subtask is created, it will be available on the Main Issue page → Subtask section. The following screenshot shows how to view a subtask in an issue." }, { "code": null, "e": 40105, "s": 39971, "text": "In this chapter, we will understand how to convert an issue to a subtask. For doing this, we should follow the procedure given below." }, { "code": null, "e": 40302, "s": 40105, "text": "To begin with, navigate and click to the issue, which needs to be converted into a subtask. Select More → Convert to subtask. The following screenshot shows how to navigate to convert to sub-task." }, { "code": null, "e": 40437, "s": 40302, "text": "Choose the parent issue in which this subtask will be tagged. The following screenshot shows how to convert the issue into a sub-task." }, { "code": null, "e": 40617, "s": 40437, "text": "Click on Next. If the status of the issue is not an allowed status for the new issue type. Select – New Status will be displayed. Select a new status and click on the Next button." }, { "code": null, "e": 40811, "s": 40617, "text": "Update Fields screen will be prompted to enter any additional fields, if they are required. Otherwise, a message will be prompted as – 'All fields will be updated automatically'. Click on Next." }, { "code": null, "e": 40881, "s": 40811, "text": "The following screenshot shows how to convert the issue in sub-tasks." }, { "code": null, "e": 40992, "s": 40881, "text": "The Confirmation screen is displayed. It will display the original values and the new values. Click on Finish." }, { "code": null, "e": 41062, "s": 40992, "text": "The following screenshot shows how to convert the issue in sub-tasks." }, { "code": null, "e": 41291, "s": 41062, "text": "The original issue will be displayed. Now it is a sub-task. The parent's issue number is now displayed at the top of the screen. The following screenshot shows how the sub-task displays after successful conversion from an issue." }, { "code": null, "e": 41371, "s": 41291, "text": "We should consider the following points while converting an issue to a subtask." }, { "code": null, "e": 41442, "s": 41371, "text": "An issue cannot be converted into a subtask if it has its own subtask." }, { "code": null, "e": 41513, "s": 41442, "text": "An issue cannot be converted into a subtask if it has its own subtask." }, { "code": null, "e": 41676, "s": 41513, "text": "To convert such an issue into a subtask, we should first convert all the subtasks of issues into a standard issue and after that convert the issue into a subtask." }, { "code": null, "e": 41839, "s": 41676, "text": "To convert such an issue into a subtask, we should first convert all the subtasks of issues into a standard issue and after that convert the issue into a subtask." }, { "code": null, "e": 41900, "s": 41839, "text": "Subtasks cannot be moved from one issue to another directly." }, { "code": null, "e": 41961, "s": 41900, "text": "Subtasks cannot be moved from one issue to another directly." }, { "code": null, "e": 42139, "s": 41961, "text": "To move a subtask from one issue to another, first convert all sub-tasks into issues and then again, convert issues to subtasks by giving the parent issue name while converting." }, { "code": null, "e": 42317, "s": 42139, "text": "To move a subtask from one issue to another, first convert all sub-tasks into issues and then again, convert issues to subtasks by giving the parent issue name while converting." }, { "code": null, "e": 42389, "s": 42317, "text": "In the next chapter, we will learn how to covert a subtask to an issue." }, { "code": null, "e": 42611, "s": 42389, "text": "To convert a subtask to an issue, we should first navigate to the subtask that needs to be converted into an issue. Then, Select More → Convert to issue. The following screenshot shows how to navigate at Convert to Issue." }, { "code": null, "e": 42775, "s": 42611, "text": "To begin with, click on the drop down box of the Select Issue Type option, choose the type of the issue (i.e., a standard issue type) and click on the Next button." }, { "code": null, "e": 42845, "s": 42775, "text": "The following screenshot shows how to convert a sub-task to an issue." }, { "code": null, "e": 43021, "s": 42845, "text": "If the status of the subtask is not an allowed status for the new issue type, then the Select New Status screen is displayed. Select a new status and click on the Next button." }, { "code": null, "e": 43237, "s": 43021, "text": "In the next step, the Update Fields screen will be prompted to enter any additional fields if they are required. Otherwise, a message will display stating – 'All fields will be updated automatically'. Click on Next." }, { "code": null, "e": 43309, "s": 43237, "text": "The following screenshot shows how to convert a subtask in to an issue." }, { "code": null, "e": 43420, "s": 43309, "text": "The Confirmation screen is displayed. It will display the original values and the new values. Click on Finish." }, { "code": null, "e": 43489, "s": 43420, "text": "The following screenshot shows how to convert a subtask to an issue." }, { "code": null, "e": 43622, "s": 43489, "text": "The issue will be displayed. It is no longer a subtask. There is no longer a parent issue number displayed at the top of the screen." }, { "code": null, "e": 43713, "s": 43622, "text": "The following screenshot shows how the issue will display after conversion from a subtask." }, { "code": null, "e": 43901, "s": 43713, "text": "A User can create multiple issues at a time using Comma separated file known as CSV. The CSV files are text files those represent tabulated data and separate different sections by commas." }, { "code": null, "e": 44042, "s": 43901, "text": "They have two-step process that requires importing the data from a CSV, while a third optional step is also present, which are listed below." }, { "code": null, "e": 44062, "s": 44042, "text": "Prepare a CSV file." }, { "code": null, "e": 44099, "s": 44062, "text": "Import the CSV file into the system." }, { "code": null, "e": 44138, "s": 44099, "text": "Save the configuration for future use." }, { "code": null, "e": 44205, "s": 44138, "text": "While creating a CSV file the following points must be considered." }, { "code": null, "e": 44461, "s": 44205, "text": "Each CSV file should have a heading row with a summary column. The first row is the heading row and represents the fields of the create issue page. Example − Summary, Assignee, Reporter, Priority, Description, sprint, “Test Suite”, Ashish, Ashish, 1, etc." }, { "code": null, "e": 44709, "s": 44461, "text": "Use double quote marks (“) in the CSV file to capture data that appears in multip.le lines. For Example − upon import, JIRA will treat the following CSV as a single record: Summary, Description, Status, \"Login issue\", \"This is on a new line\", Open" }, { "code": null, "e": 44957, "s": 44709, "text": "Use double quote marks (“) in the CSV file to capture data that appears in multip.le lines. For Example − upon import, JIRA will treat the following CSV as a single record: Summary, Description, Status, \"Login issue\", \"This is on a new line\", Open" }, { "code": null, "e": 45148, "s": 44957, "text": "While importing issues from a CSV file, the Project Name and Project Key are important columns in CSV. In addition, the name of these fields should match exactly as they are present in JIRA." }, { "code": null, "e": 45339, "s": 45148, "text": "While importing issues from a CSV file, the Project Name and Project Key are important columns in CSV. In addition, the name of these fields should match exactly as they are present in JIRA." }, { "code": null, "e": 45403, "s": 45339, "text": "To import the CSV file, we should follow the steps given below." }, { "code": null, "e": 45487, "s": 45403, "text": "Step 1 − Select Issues → Import Issues from CSV to open the Bulk Create Setup page." }, { "code": null, "e": 45578, "s": 45487, "text": "The following screenshot shows how to access the Import issues from the CSV functionality." }, { "code": null, "e": 45786, "s": 45578, "text": "Step 2 − On the Setup page, select CSV Source File. Do not check the “Use an existing configuration file” check box, if you do not have a configuration file or if you want to create a new configuration file." }, { "code": null, "e": 45910, "s": 45786, "text": "Configuration files specify a mapping between column names in the CSV file's header row and fields in the JIRA application." }, { "code": null, "e": 46018, "s": 45910, "text": "The following screenshot shows the Bulk create setup page, where the user browses and uploads the CSV file." }, { "code": null, "e": 46157, "s": 46018, "text": "Step 3 − If the user checks the checkbox of “Use an existing configuration file”, JIRA will ask to specify an Existing Configuration File." }, { "code": null, "e": 46231, "s": 46157, "text": "The following screenshot shows how to use an existing configuration file." }, { "code": null, "e": 46420, "s": 46231, "text": "Step 4 − If the user does not select this option, then at the end of the CSV file import wizard, JIRA will ask to create a configuration file, which can be used for subsequent CSV imports." }, { "code": null, "e": 46735, "s": 46420, "text": "Click on the Next button → the Settings step of the CSV file import wizard will display. Complete the required fields. If the CSV file uses a different separator character other than a comma, specify that character in the CSV Delimiter field. If the separator is a 'Tab', this can be entered using the format '/t'." }, { "code": null, "e": 46804, "s": 46735, "text": "The following screenshot shows how to provide settings of csv file −" }, { "code": null, "e": 47066, "s": 46804, "text": "Step 5 − Click on the Next button to proceed to the Map field’s step of the CSV file import wizard. Here, the user has to map the column headers of the CSV file to the fields in the selected JIRA project. After selection, tick the check box for Map field value." }, { "code": null, "e": 47164, "s": 47066, "text": "A CSV field should map to the JIRA summary field. This ensures the issues created have a summary." }, { "code": null, "e": 47236, "s": 47164, "text": "The following screenshot shows how to map CSV fields with JIRA fields −" }, { "code": null, "e": 47465, "s": 47236, "text": "Step 6 − Click on the Next button, the Map values step of the CSV file import wizard will display. On this step of the import wizard, the user can select which specific CSV field values to map to which specific JIRA field value." }, { "code": null, "e": 47573, "s": 47465, "text": "Fields whose Map Field Value check boxes were selected in the previous step will be presented on this page." }, { "code": null, "e": 47681, "s": 47573, "text": "Fields whose Map Field Value check boxes were selected in the previous step will be presented on this page." }, { "code": null, "e": 47953, "s": 47681, "text": "If the CSV field has a username (e.g. Reporter or Assignee) and does not select the Map Field Value check box for this field in the previous step of the CSV file import wizard, then the importer will map imported usernames from the CSV file to (lowercase) JIRA usernames." }, { "code": null, "e": 48225, "s": 47953, "text": "If the CSV field has a username (e.g. Reporter or Assignee) and does not select the Map Field Value check box for this field in the previous step of the CSV file import wizard, then the importer will map imported usernames from the CSV file to (lowercase) JIRA usernames." }, { "code": null, "e": 48275, "s": 48225, "text": "The following screenshot shows how to map values." }, { "code": null, "e": 48483, "s": 48275, "text": "Step 7 − Click on the Validate button, it will validate the imported data and display if any errors or warnings are required, otherwise it will display how many successful imports are possible with the file." }, { "code": null, "e": 48553, "s": 48483, "text": "The following screenshot shows the successful validation of CSV file." }, { "code": null, "e": 48713, "s": 48553, "text": "Step 8 − Now, Click the Begin Import button. The importer will display updates like import is in progress, then a success message when the import is completed." }, { "code": null, "e": 48785, "s": 48713, "text": "Following screenshot shows how many issues are created using CSV file −" }, { "code": null, "e": 48897, "s": 48785, "text": "Step 9 − Click on the Check Created issues, it will display the list of issues those are created using the CSV." }, { "code": null, "e": 48981, "s": 48897, "text": "The following screenshot shows the list of newly created issues using the CSV file." }, { "code": null, "e": 49299, "s": 48981, "text": "To edit an issue in JIRA, the user has to navigate to the issue, which is required to edit and the click on the issue to open the page. The next step is to click on the Edit button, which is present at the top left hand side of the view issue page. It will open the edit issue page that is similar to the create page." }, { "code": null, "e": 49368, "s": 49299, "text": "The following screenshot shows how to access the Edit functionality." }, { "code": null, "e": 49467, "s": 49368, "text": "Or, hover the mouse over the field and click on the Pencil Icon to edit the specific field inline." }, { "code": null, "e": 49566, "s": 49467, "text": "The following screenshot shows how to edit a specific field without clicking on main edit button −" }, { "code": null, "e": 49718, "s": 49566, "text": "Modify the issue details in the corresponding field of the edit Issue page. The Following screenshot shows the edit page to update details of an issue." }, { "code": null, "e": 49852, "s": 49718, "text": "Once the update is completed, click on the Update button. The user will be able to see the edited text/fields in the View Issue Page." }, { "code": null, "e": 49905, "s": 49852, "text": "The Following screenshot shows the updated details −" }, { "code": null, "e": 50044, "s": 49905, "text": "In this chapter, we will learn how to email an issue in JIRA. A user can email an issue to other JIRA users. There are two ways to do it −" }, { "code": null, "e": 50066, "s": 50044, "text": "By share an issue and" }, { "code": null, "e": 50130, "s": 50066, "text": "By mention these users in issue’s Description or Comment field." }, { "code": null, "e": 50174, "s": 50130, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 50428, "s": 50174, "text": "To begin with, the user should navigate to the issue that is required to share and click to view the issue. Click on the Share Symbol on the top right hand side of the page. The following screenshot shows where the sharing option present at issue page −" }, { "code": null, "e": 50643, "s": 50428, "text": "You can write the JIRA users’ name by typing their usernames or partially/all of their full names as registered with JIRA or type the email addresses of the individuals with whom you would like to share the issues." }, { "code": null, "e": 50793, "s": 50643, "text": "When the user starts typing a JIRA user's username or name, or a previously specified email address, an auto-complete dropdown list of users appears." }, { "code": null, "e": 50903, "s": 50793, "text": "The Following screenshot shows how to provide email addresses or select from the auto-completion suggestions." }, { "code": null, "e": 51055, "s": 50903, "text": "Add optional note. Click on the Share button present in the Share wizard section. The following screenshot shows how to share/email an issue to a user." }, { "code": null, "e": 51236, "s": 51055, "text": "In the issue's Description or the Comment field, type '@' and then the first few characters of the JIRA user's username or partially/all of their full name as registered with JIRA." }, { "code": null, "e": 51501, "s": 51236, "text": "As the user starts typing, a list of suggested users will appear in a dropdown list below the field. The user should select based on the referenced users by completely typing the JIRA user's username or choose from the list of suggested users in the dropdown list." }, { "code": null, "e": 51589, "s": 51501, "text": "The following screenshot shows how to mention the user’s name/email in the description." }, { "code": null, "e": 51708, "s": 51589, "text": "Click on submit the field. JIRA will send that user an email message indicating that you mentioned them on that issue." }, { "code": null, "e": 51801, "s": 51708, "text": "The following screenshot shows how to submit mentioning the user’s email in the description." }, { "code": null, "e": 52041, "s": 51801, "text": "A Label is used to categorize an issue. It is similar to the hashtag (#) used in twitter, Facebook or other social sites. It also helps while searching an issue. While viewing an issue, the label appears in the detail section of the issue." }, { "code": null, "e": 52127, "s": 52041, "text": "The following screenshot shows where the labels are present in the issue detail page." }, { "code": null, "e": 52229, "s": 52127, "text": "Once the user clicks on the label i.e. WFT, it will display the list of issues having the same label." }, { "code": null, "e": 52301, "s": 52229, "text": "The following screenshot shows how to search issues using label names −" }, { "code": null, "e": 52465, "s": 52301, "text": "To add or remove labels, a user has to go to the View Issue page and select the issue that needs to add labels. Click on More → Labels. A dialogue box will appear." }, { "code": null, "e": 52530, "s": 52465, "text": "The following screenshot shows how to access the Label features." }, { "code": null, "e": 52636, "s": 52530, "text": "Start typing the label and select from the suggestions. The following screenshot shows how to add labels." }, { "code": null, "e": 52788, "s": 52636, "text": "To ‘Delete’ a label, click on the close (x) sign, which appears beside the label name. The following screenshot shows how to delete an existing label −" }, { "code": null, "e": 52923, "s": 52788, "text": "Click on the Update button. Labels are added / removed from an issue and can be verified in the Detail Section of the View Issue Page." }, { "code": null, "e": 52990, "s": 52923, "text": "The following screenshot shows where to verify the updated labels." }, { "code": null, "e": 53181, "s": 52990, "text": "This feature is very useful when two issues have some type of a dependency on each other as if they are duplicates or relate to each other, upstream downstream dependency or blocking issues." }, { "code": null, "e": 53352, "s": 53181, "text": "For creating a link to another issue, the user has to navigate to the issue and click on the View Issue Page. After that, click More → Link to display link dialogue page." }, { "code": null, "e": 53412, "s": 53352, "text": "The following screenshot shows how to access Link feature −" }, { "code": null, "e": 53600, "s": 53412, "text": "Select JIRA Issue item in the left side of the dialogue and select “This issue” field from the dropdown list. The following screenshot shows how to link an issue by providing the details." }, { "code": null, "e": 53720, "s": 53600, "text": "The next step is to select/search issue. The following screenshot shows how to add an issue as a link in another issue." }, { "code": null, "e": 53917, "s": 53720, "text": "Add the comment; it is optional and then Click on Link. The View Issue page shows up and the user can go down and verify whether the linked issue is displayed or not under the Section Issue links." }, { "code": null, "e": 53991, "s": 53917, "text": "The following screenshot shows how to view linked issue in parent issue −" }, { "code": null, "e": 54224, "s": 53991, "text": "To delete a link, a user should go to the View Issue page and to that issue which contains the links. Scroll down and go to Issue Links section. Hover the mouse over the link that should be deleted and then click on the Delete icon." }, { "code": null, "e": 54278, "s": 54224, "text": "The following screenshot shows how to delete a link −" }, { "code": null, "e": 54411, "s": 54278, "text": "A confirmation pop-up will display; click on the Delete button. The following screenshot shows the confirmation pop-up for deletion." }, { "code": null, "e": 54550, "s": 54411, "text": "JIRA has a feature to move an issue from one project to another project. Let us understand with the following steps, how a user can do it." }, { "code": null, "e": 54697, "s": 54550, "text": "Go to the View Issue page that needs to move into another project. Select More → Move. The following screenshot shows how to access Move feature −" }, { "code": null, "e": 54866, "s": 54697, "text": "In the first step of the Move Issue wizard, select the new project where the issue will move, and if required/desired, change the issue type. Click on Next to continue." }, { "code": null, "e": 54938, "s": 54866, "text": "The following screenshot shows Select Project and Issues step to move −" }, { "code": null, "e": 55109, "s": 54938, "text": "If there is a need to change the status of the issue, the user can go to Select Status page. Select the new status for the issue and click on the Next button to continue." }, { "code": null, "e": 55286, "s": 55109, "text": "If required to specify the values for any required custom fields, the Update Fields page is displayed. Specify the desired values for each field, and click on Next to continue." }, { "code": null, "e": 55377, "s": 55286, "text": "The following screenshot shows the Update Fields step, if required before moving an issue." }, { "code": null, "e": 55650, "s": 55377, "text": "The confirmation page will display with all the changes. If a user wants to revise any of the changes, click the appropriate step in the left hand side menu to return to that page of the wizard. After that, click on the Move button to move the issue to the target project." }, { "code": null, "e": 55734, "s": 55650, "text": "The following screenshot shows confirmation step to confirm details before moving −" }, { "code": null, "e": 55967, "s": 55734, "text": "The Issue will be moved to the target project and displayed on screen. This Issue can be further edited to make additional changes. The following screenshot shows a new project and an issue type after the successful moving an issue." }, { "code": null, "e": 56144, "s": 55967, "text": "In this chapter, we will learn how to view and change history in JIRAN. History is the record of all the activities performed on issues. Some of the most common instances are −" }, { "code": null, "e": 56165, "s": 56144, "text": "Creator of the issue" }, { "code": null, "e": 56191, "s": 56165, "text": "Changes to an issue field" }, { "code": null, "e": 56212, "s": 56191, "text": "Attachment of a file" }, { "code": null, "e": 56241, "s": 56212, "text": "Deletion of comment/Work log" }, { "code": null, "e": 56268, "s": 56241, "text": "Addition/deletion of links" }, { "code": null, "e": 56332, "s": 56268, "text": "In a history record, a user can view the following information." }, { "code": null, "e": 56363, "s": 56332, "text": "User name who made the changes" }, { "code": null, "e": 56395, "s": 56363, "text": "Time while the changes was made" }, { "code": null, "e": 56458, "s": 56395, "text": "If an issue field is changed, new and old values of that field" }, { "code": null, "e": 56529, "s": 56458, "text": "To view history in JIRA, the user should follow the steps given below." }, { "code": null, "e": 56573, "s": 56529, "text": "Go to View Issue Page to see change history" }, { "code": null, "e": 56605, "s": 56573, "text": "Scroll down to Activity section" }, { "code": null, "e": 56626, "s": 56605, "text": "Click on History tab" }, { "code": null, "e": 56678, "s": 56626, "text": "The following screenshot shows how to view History." }, { "code": null, "e": 56767, "s": 56678, "text": "In this chapter, we will understand how Voting and Watching is done on an issue in JIRA." }, { "code": null, "e": 56895, "s": 56767, "text": "JIRA has a feature called as Vote to provide the opinion on the preference for that issue, whether it is resolved or completed." }, { "code": null, "e": 56956, "s": 56895, "text": "Admin needs to add permission for users to use this feature." }, { "code": null, "e": 57008, "s": 56956, "text": "Go to the View Issue page where voting is required." }, { "code": null, "e": 57068, "s": 57008, "text": "Click Vote for this issue to instantly vote for that issue." }, { "code": null, "e": 57151, "s": 57068, "text": "The following screenshot shows where Votes field is present at issue detail page −" }, { "code": null, "e": 57270, "s": 57151, "text": "Note − Since the user does not have permission here to vote, the user is not able to view the link beside Votes field." }, { "code": null, "e": 57521, "s": 57270, "text": "JIRA has a feature that allows users/stakeholders to keep an eye on the issue, whenever there is any update or changes in that issue. If there is any the issue, it sends notification/emails to those who are listed as watchers for that specific issue." }, { "code": null, "e": 57582, "s": 57521, "text": "Admin needs to add permission for users to use this feature." }, { "code": null, "e": 57638, "s": 57582, "text": "Go to the view issue page that the user wants to watch." }, { "code": null, "e": 57710, "s": 57638, "text": "Click on the “Start Watching this issue” link to be listed as watchers." }, { "code": null, "e": 57803, "s": 57710, "text": "The following screenshot shows where the Watchers field is present in the Issue Detail page." }, { "code": null, "e": 58003, "s": 57803, "text": "Now instead of zero watchers, there will be 1 (watcher) displayed along with the link “Stop watching this issue” to delist as watchers. The following screenshot shows the updated number of watchers −" }, { "code": null, "e": 58216, "s": 58003, "text": "The user can click on 1, it allows to add other users as well to the list as watchers. Start typing the user name in the Add watchers box and select from the autocomplete box. The user will be listed as watchers." }, { "code": null, "e": 58304, "s": 58216, "text": "The following screenshot shows how to add a new watcher by providing the user’s detail." }, { "code": null, "e": 58583, "s": 58304, "text": "JIRA has powerful and very efficient search functionalities. A user can search issues across Projects, Versions and Components using various search types. JIRA allows saving the search criteria to utilize next time as filters; even these filters can be shared by others as well." }, { "code": null, "e": 58679, "s": 58583, "text": "JIRA has a couple of fundamental ways to search issues. The most important ones are as follows." }, { "code": null, "e": 58692, "s": 58679, "text": "Basic Search" }, { "code": null, "e": 58705, "s": 58692, "text": "Quick Search" }, { "code": null, "e": 58765, "s": 58705, "text": "Let us now understand both of these search types in detail." }, { "code": null, "e": 58979, "s": 58765, "text": "Basic Search in JIRA is a user-friendly interface that can be used easily to find out the issues. It uses the JQL queries in the backend. To do a basic search in JIRA, the user has to follow the steps given below." }, { "code": null, "e": 59101, "s": 58979, "text": "Step 1 − Navigate to issues → Search Issues. The following screenshot shows how to access the Search for Issues feature −" }, { "code": null, "e": 59284, "s": 59101, "text": "Step 2 − A search page displays. If it has any existing Search criteria, then click on the New Filter to reset it. The following screenshot shows how to define a new search criteria." }, { "code": null, "e": 59537, "s": 59284, "text": "Step 3 − Set the search criteria against different fields like Project, Type, Status and Assigned. Then click on More and select any field to search with additional fields. The following screenshot shows what all criteria’s can be set to search issues." }, { "code": null, "e": 59720, "s": 59537, "text": "Step 4 − If the user wants to search against any specific text, keywords, start typing in the Contains text box. The following screenshot shows how to search specific text in issues." }, { "code": null, "e": 59834, "s": 59720, "text": "Step 5 − A user can use wildcards or operators in all text based fields to search specific strings. For example −" }, { "code": null, "e": 59867, "s": 59834, "text": "Single character wildcard - te?t" }, { "code": null, "e": 59903, "s": 59867, "text": "Multiple characters wildcard – win*" }, { "code": null, "e": 59954, "s": 59903, "text": "Boolean operators - \"atlassian jira\" || confluence" }, { "code": null, "e": 60085, "s": 59954, "text": "Based on different search criteria, the following result is displayed. The following screenshot shows the list of searched issues." }, { "code": null, "e": 60162, "s": 60085, "text": "To save the searched criteria, the user should follow the steps given below." }, { "code": null, "e": 60291, "s": 60162, "text": "Step 1 − Click on Save As at the top of the page. The following screenshot shows how to save the search criteria for future use." }, { "code": null, "e": 60433, "s": 60291, "text": "Step 2 − Type the filter name and click on Submit. The following screenshot shows how to provide a name of new search criteria before saving." }, { "code": null, "e": 60709, "s": 60433, "text": "Step 3 − A Filter will appear on the left side of the Search Page under the Favourite filters and it will have a few options like – Rename, Delete, Copy and Remove from Favourites. The following screenshot shows the saved search criteria and the available actions to perform." }, { "code": null, "e": 60931, "s": 60709, "text": "The quick search is the fastest way to define search criteria. It is a text box where the user enters the key, text or anything and it starts searching for the exact matches in the current project and provides the result." }, { "code": null, "e": 61083, "s": 60931, "text": "The Quick Search box is available on the top right hand corner of the navigator. The following screenshot shows how to access the Quick Search feature." }, { "code": null, "e": 61238, "s": 61083, "text": "The quick search option performs smart searches with minimal typing. It recognizes the following word and gives out several options to the user to choose." }, { "code": null, "e": 61301, "s": 61238, "text": "my − This word searches issues assigned to the logged-in user." }, { "code": null, "e": 61364, "s": 61301, "text": "my − This word searches issues assigned to the logged-in user." }, { "code": null, "e": 61439, "s": 61364, "text": "The following screenshot shows different smart querying in a quick search." }, { "code": null, "e": 61510, "s": 61439, "text": "Some of the most commonly used smart querying options are as follows −" }, { "code": null, "e": 61562, "s": 61510, "text": "r:me − Finds issues reported by the logged-in user." }, { "code": null, "e": 61614, "s": 61562, "text": "r:me − Finds issues reported by the logged-in user." }, { "code": null, "e": 61659, "s": 61614, "text": "r:abc − Finds issues reported by user – abc." }, { "code": null, "e": 61704, "s": 61659, "text": "r:abc − Finds issues reported by user – abc." }, { "code": null, "e": 61744, "s": 61704, "text": "r:none − Finds issues with no reporter." }, { "code": null, "e": 61784, "s": 61744, "text": "r:none − Finds issues with no reporter." }, { "code": null, "e": 61906, "s": 61784, "text": "<project name> or <project key> − Finds issues within the given project name or finds issues having the same project key." }, { "code": null, "e": 62028, "s": 61906, "text": "<project name> or <project key> − Finds issues within the given project name or finds issues having the same project key." }, { "code": null, "e": 62083, "s": 62028, "text": "Overdue − Finds issues those are overdue before today." }, { "code": null, "e": 62138, "s": 62083, "text": "Overdue − Finds issues those are overdue before today." }, { "code": null, "e": 62547, "s": 62138, "text": "Created:, updated:, due: − These smart searches finds issues with Created, Updated, or Due Date using the prefixes created:, updated:, or due:, respectively. For the date range, use today, tomorrow, yesterday, a single date range (e.g. '-1w'), or two date ranges (e.g. '-1w,1w'). Date ranges cannot have spaces between them. Valid date/time abbreviations are: 'w' (week), 'd' (day), 'h' (hour), 'm' (minute)." }, { "code": null, "e": 62956, "s": 62547, "text": "Created:, updated:, due: − These smart searches finds issues with Created, Updated, or Due Date using the prefixes created:, updated:, or due:, respectively. For the date range, use today, tomorrow, yesterday, a single date range (e.g. '-1w'), or two date ranges (e.g. '-1w,1w'). Date ranges cannot have spaces between them. Valid date/time abbreviations are: 'w' (week), 'd' (day), 'h' (hour), 'm' (minute)." }, { "code": null, "e": 63003, "s": 62956, "text": "C: − Finds issues with a particular component." }, { "code": null, "e": 63050, "s": 63003, "text": "C: − Finds issues with a particular component." }, { "code": null, "e": 63095, "s": 63050, "text": "V: − Finds issues with a particular version." }, { "code": null, "e": 63140, "s": 63095, "text": "V: − Finds issues with a particular version." }, { "code": null, "e": 63185, "s": 63140, "text": "Ff: − Finds issues with a Fixed For version." }, { "code": null, "e": 63230, "s": 63185, "text": "Ff: − Finds issues with a Fixed For version." }, { "code": null, "e": 63305, "s": 63230, "text": "* − Wildcard can be utilized with any of the above queries to find issues." }, { "code": null, "e": 63380, "s": 63305, "text": "* − Wildcard can be utilized with any of the above queries to find issues." }, { "code": null, "e": 63547, "s": 63380, "text": "Apart from the type of searches explained in the previous chapter, JIRA also has a few advanced search options, which can be performed using the following three ways." }, { "code": null, "e": 63569, "s": 63547, "text": "Using Field Reference" }, { "code": null, "e": 63593, "s": 63569, "text": "Using Keyword Reference" }, { "code": null, "e": 63619, "s": 63593, "text": "Using Operators Reference" }, { "code": null, "e": 63689, "s": 63619, "text": "These above-mentioned three ways have been explained in detail below." }, { "code": null, "e": 63773, "s": 63689, "text": "The user should consider the following points while performing any advanced search." }, { "code": null, "e": 63840, "s": 63773, "text": "Advanced search uses structured queries to search for JIRA issues." }, { "code": null, "e": 63907, "s": 63840, "text": "Advanced search uses structured queries to search for JIRA issues." }, { "code": null, "e": 63955, "s": 63907, "text": "Search results displays in the Issue Navigator." }, { "code": null, "e": 64003, "s": 63955, "text": "Search results displays in the Issue Navigator." }, { "code": null, "e": 64080, "s": 64003, "text": "Search results can be exported to MS Excel and many other available formats." }, { "code": null, "e": 64157, "s": 64080, "text": "Search results can be exported to MS Excel and many other available formats." }, { "code": null, "e": 64221, "s": 64157, "text": "Save and Subscribe features are available to advanced searches." }, { "code": null, "e": 64285, "s": 64221, "text": "Save and Subscribe features are available to advanced searches." }, { "code": null, "e": 64347, "s": 64285, "text": "An advanced search uses the JIRA Query Language known as JQL." }, { "code": null, "e": 64409, "s": 64347, "text": "An advanced search uses the JIRA Query Language known as JQL." }, { "code": null, "e": 64591, "s": 64409, "text": "A simple query in JQL consists of a field, operator, followed by one or more values or functions. For example, the following simple query will find all issues in the \"WFT\" project −" }, { "code": null, "e": 64773, "s": 64591, "text": "A simple query in JQL consists of a field, operator, followed by one or more values or functions. For example, the following simple query will find all issues in the \"WFT\" project −" }, { "code": null, "e": 64790, "s": 64773, "text": "Project = \"WFT\"\n" }, { "code": null, "e": 64909, "s": 64790, "text": "JQL supports SQL like syntax such as ORDER BY, GROUP BY, ISNULL() functions, but JQL is not a Database Query Language." }, { "code": null, "e": 65028, "s": 64909, "text": "JQL supports SQL like syntax such as ORDER BY, GROUP BY, ISNULL() functions, but JQL is not a Database Query Language." }, { "code": null, "e": 65153, "s": 65028, "text": "A field reference means a word that represents the field name in the JIRA issue including the custom fields. The syntax is −" }, { "code": null, "e": 65216, "s": 65153, "text": "<field name> <operators like =,>, <> “values” or “functions” \n" }, { "code": null, "e": 65347, "s": 65216, "text": "The operator compares the value of the field with value presents at right side such that only true results are retrieved by query." }, { "code": null, "e": 65402, "s": 65347, "text": "Go to Issues → Search for Issues in the navigator bar." }, { "code": null, "e": 65469, "s": 65402, "text": "The following screenshot shows how to navigate the Search section." }, { "code": null, "e": 65631, "s": 65469, "text": "If there is an existing search criterion, click on the New Filter button to reset the criteria. The following screenshot shows how to start with a new criteria −" }, { "code": null, "e": 65710, "s": 65631, "text": "Type the query using the Field, Operator and Values like issueKey = “WFT-107”." }, { "code": null, "e": 65973, "s": 65710, "text": "There are other fields as well – Affected Version, Assignee, Attachments, Category, Comment, Component, Created, Creator, Description, Due, Environment, etc. As soon as the user starts typing, the auto-complete functionality helps to write in the defined format." }, { "code": null, "e": 66060, "s": 65973, "text": "The following screenshot shows how to add Field Name criteria using advanced features." }, { "code": null, "e": 66137, "s": 66060, "text": "Operator selection − The following screenshot shows how to select operators." }, { "code": null, "e": 66271, "s": 66137, "text": "The next step is to enter the value and then click on the Search symbol. The following screenshot shows how to add values and search." }, { "code": null, "e": 66343, "s": 66271, "text": "The following screenshot shows the search result based on criteria set." }, { "code": null, "e": 66427, "s": 66343, "text": "Here, we will understand how to use a keyword reference and what its advantages are" }, { "code": null, "e": 66446, "s": 66427, "text": "A keyword in JQL −" }, { "code": null, "e": 66510, "s": 66446, "text": "joins two or more queries together to form a complex JQL query." }, { "code": null, "e": 66551, "s": 66510, "text": "alters the logic of one or more queries." }, { "code": null, "e": 66582, "s": 66551, "text": "alters the logic of operators." }, { "code": null, "e": 66625, "s": 66582, "text": "has an explicit definition in a JQL query." }, { "code": null, "e": 66695, "s": 66625, "text": "performs a specific function that defines the results of a JQL query." }, { "code": null, "e": 66714, "s": 66695, "text": "List of Keywords −" }, { "code": null, "e": 66784, "s": 66714, "text": "AND − ex - status = open AND priority = urgent And assignee = Ashish." }, { "code": null, "e": 66831, "s": 66784, "text": "OR − ex – duedate < now() or duedate is empty." }, { "code": null, "e": 66866, "s": 66831, "text": "NOT − ex – not assignee = Ashish ." }, { "code": null, "e": 66931, "s": 66866, "text": "EMPTY − ex - affectedVersion is empty / affectedVersion = empty." }, { "code": null, "e": 66961, "s": 66931, "text": "NULL − ex – assignee is null." }, { "code": null, "e": 67026, "s": 66961, "text": "ORDER BY − ex – duedate = empty order by created, priority desc." }, { "code": null, "e": 67206, "s": 67026, "text": "Similar to field reference, as soon as the user starts typing, the auto-complete functionality helps to get the correct syntax. The following screenshot shows how to add keywords." }, { "code": null, "e": 67340, "s": 67206, "text": "Click on the Search symbol and it will provide the search results. The following screenshot shows the result based on a criteria set." }, { "code": null, "e": 67473, "s": 67340, "text": "Operators are used to compare values of the left side with the right side, such that only true results display as the search result." }, { "code": null, "e": 67484, "s": 67473, "text": "Equals: = " }, { "code": null, "e": 67500, "s": 67484, "text": "Not Equals: != " }, { "code": null, "e": 67516, "s": 67500, "text": "Greater Than: >" }, { "code": null, "e": 67530, "s": 67516, "text": "Less Than: < " }, { "code": null, "e": 67554, "s": 67530, "text": "Greater Than Equals: =>" }, { "code": null, "e": 67575, "s": 67554, "text": "Less than equals: =<" }, { "code": null, "e": 67578, "s": 67575, "text": "IN" }, { "code": null, "e": 67585, "s": 67578, "text": "NOT IN" }, { "code": null, "e": 67597, "s": 67585, "text": "CONTAINS: ~" }, { "code": null, "e": 67619, "s": 67597, "text": "Does Not contain: ! ~" }, { "code": null, "e": 67622, "s": 67619, "text": "IS" }, { "code": null, "e": 67629, "s": 67622, "text": "IS NOT" }, { "code": null, "e": 67633, "s": 67629, "text": "WAS" }, { "code": null, "e": 67640, "s": 67633, "text": "WAS IN" }, { "code": null, "e": 67651, "s": 67640, "text": "WAS NOT IN" }, { "code": null, "e": 67659, "s": 67651, "text": "WAS NOT" }, { "code": null, "e": 67667, "s": 67659, "text": "CHANGED" }, { "code": null, "e": 67779, "s": 67667, "text": "Similar to the Field and the Keyword Reference, these operators can also be used to enhance the search results." }, { "code": null, "e": 67983, "s": 67779, "text": "JIRA provides different types of reports within a project. It helps to analyze the Progress, Issues, Showstoppers and Timeliness of any Project. It also helps to analyze the resource utilization as well." }, { "code": null, "e": 68137, "s": 67983, "text": "To access reports in JIRA, the user should go to Project → choose Specific project. The following screenshot shows how to navigate to a specific project." }, { "code": null, "e": 68309, "s": 68137, "text": "Click on the Reports icon on the left side of the page. It will display all the reports supported by JIRA. The following screenshot shows how to access the Report section." }, { "code": null, "e": 68460, "s": 68309, "text": "When the user clicks on Switch report, it will display the list of reports. The following screenshot shows list of reports available for quick switch." }, { "code": null, "e": 68517, "s": 68460, "text": "JIRA has categorized reports in four levels, which are −" }, { "code": null, "e": 68523, "s": 68517, "text": "Agile" }, { "code": null, "e": 68538, "s": 68523, "text": "Issue Analysis" }, { "code": null, "e": 68560, "s": 68538, "text": "Forecast & Management" }, { "code": null, "e": 68567, "s": 68560, "text": "Others" }, { "code": null, "e": 68651, "s": 68567, "text": "Let us now discuss the features of the above-mentioned report categories in detail." }, { "code": null, "e": 68704, "s": 68651, "text": "Following are the list of features of Agile Reports." }, { "code": null, "e": 68812, "s": 68704, "text": "Burn down Chart − Track the total work remaining, also whether sprint is achieving the project goal or not." }, { "code": null, "e": 68920, "s": 68812, "text": "Burn down Chart − Track the total work remaining, also whether sprint is achieving the project goal or not." }, { "code": null, "e": 69006, "s": 68920, "text": "Sprint Chart − Track the work completed or pushed back to the backlog in each sprint." }, { "code": null, "e": 69092, "s": 69006, "text": "Sprint Chart − Track the work completed or pushed back to the backlog in each sprint." }, { "code": null, "e": 69167, "s": 69092, "text": "Velocity Chart − Track the amount of work completed from sprint to sprint." }, { "code": null, "e": 69242, "s": 69167, "text": "Velocity Chart − Track the amount of work completed from sprint to sprint." }, { "code": null, "e": 69378, "s": 69242, "text": "Cumulative Flow Diagram − Shows the statuses of issues over time. It helps to identify high-risk issues or unresolved important issues." }, { "code": null, "e": 69514, "s": 69378, "text": "Cumulative Flow Diagram − Shows the statuses of issues over time. It helps to identify high-risk issues or unresolved important issues." }, { "code": null, "e": 69579, "s": 69514, "text": "Version Report − Track the projected release date for a version." }, { "code": null, "e": 69644, "s": 69579, "text": "Version Report − Track the projected release date for a version." }, { "code": null, "e": 69723, "s": 69644, "text": "Epic Report − Shows the progress towards completing an epic over a given time." }, { "code": null, "e": 69802, "s": 69723, "text": "Epic Report − Shows the progress towards completing an epic over a given time." }, { "code": null, "e": 69987, "s": 69802, "text": "Control Chart − Shows the cycle time for the product, its version or the sprint. It helps to identify whether data from the current process can be used to determine future performance." }, { "code": null, "e": 70172, "s": 69987, "text": "Control Chart − Shows the cycle time for the product, its version or the sprint. It helps to identify whether data from the current process can be used to determine future performance." }, { "code": null, "e": 70258, "s": 70172, "text": "Epic Burn Down − Track the projected number of sprints required to complete the epic." }, { "code": null, "e": 70344, "s": 70258, "text": "Epic Burn Down − Track the projected number of sprints required to complete the epic." }, { "code": null, "e": 70534, "s": 70344, "text": "Release Burn Down − Track the projected release date for a version. It helps to monitor whether the version will release on time, so mandatory action can be taken if work is falling behind." }, { "code": null, "e": 70724, "s": 70534, "text": "Release Burn Down − Track the projected release date for a version. It helps to monitor whether the version will release on time, so mandatory action can be taken if work is falling behind." }, { "code": null, "e": 70778, "s": 70724, "text": "Following are the list of features of Issue Analysis." }, { "code": null, "e": 70854, "s": 70778, "text": "Average Age Report − Displays the average age in days of unresolved issues." }, { "code": null, "e": 70930, "s": 70854, "text": "Average Age Report − Displays the average age in days of unresolved issues." }, { "code": null, "e": 71052, "s": 70930, "text": "Created Vs Resolved Issue Report − Display the number of issues created vs the number of issues resolved in given period." }, { "code": null, "e": 71174, "s": 71052, "text": "Created Vs Resolved Issue Report − Display the number of issues created vs the number of issues resolved in given period." }, { "code": null, "e": 71265, "s": 71174, "text": "Pie chart Report − Shows a pie chart of issues for a project grouped by a specified field." }, { "code": null, "e": 71356, "s": 71265, "text": "Pie chart Report − Shows a pie chart of issues for a project grouped by a specified field." }, { "code": null, "e": 71493, "s": 71356, "text": "Recently Created Issue Report − Shows the number of issues created over a time-period for a project and how many of those were resolved." }, { "code": null, "e": 71630, "s": 71493, "text": "Recently Created Issue Report − Shows the number of issues created over a time-period for a project and how many of those were resolved." }, { "code": null, "e": 71706, "s": 71630, "text": "Resolution Time Report − Displays the average time taken to resolve issues." }, { "code": null, "e": 71782, "s": 71706, "text": "Resolution Time Report − Displays the average time taken to resolve issues." }, { "code": null, "e": 71904, "s": 71782, "text": "Single Level Group by Report − .It helps to group the search results by a field and see the overall status of each group." }, { "code": null, "e": 72026, "s": 71904, "text": "Single Level Group by Report − .It helps to group the search results by a field and see the overall status of each group." }, { "code": null, "e": 72146, "s": 72026, "text": "Time since Issues Report − It helps to track how many issues were created, updated, resolved, etc., over a time-period." }, { "code": null, "e": 72266, "s": 72146, "text": "Time since Issues Report − It helps to track how many issues were created, updated, resolved, etc., over a time-period." }, { "code": null, "e": 72345, "s": 72266, "text": "Following are the list of features of Forecast and Management type of reports." }, { "code": null, "e": 72517, "s": 72345, "text": "Time Tracking Report − Shows the original and current time estimates for issues in the current project. It can help to determine whether work is on track for those issues." }, { "code": null, "e": 72689, "s": 72517, "text": "Time Tracking Report − Shows the original and current time estimates for issues in the current project. It can help to determine whether work is on track for those issues." }, { "code": null, "e": 72890, "s": 72689, "text": "User Workload Report − Shows the time estimates for all unresolved issues assigned to a user across projects. It helps to understand how much a user is occupied, whether overburdened or has less work." }, { "code": null, "e": 73091, "s": 72890, "text": "User Workload Report − Shows the time estimates for all unresolved issues assigned to a user across projects. It helps to understand how much a user is occupied, whether overburdened or has less work." }, { "code": null, "e": 73245, "s": 73091, "text": "Version Workload Report − Displays how much outstanding work is remaining per user and per issue. It helps to understand the remaining work of a version." }, { "code": null, "e": 73399, "s": 73245, "text": "Version Workload Report − Displays how much outstanding work is remaining per user and per issue. It helps to understand the remaining work of a version." }, { "code": null, "e": 73555, "s": 73399, "text": "In addition to these, there are other types of reports that generally have a pie chart in them, which we will discuss in detail in the subsequent chapters." }, { "code": null, "e": 73685, "s": 73555, "text": "A workload pie chart displays a pie chart showing all the issues for a specific project. Let us understand how to use it in JIRA." }, { "code": null, "e": 73753, "s": 73685, "text": "To generate a report, the user should follow the steps given below." }, { "code": null, "e": 73962, "s": 73753, "text": "Step 1 − Go to Project → choose the Specific project. Click on the Report icon on the left side of the menu. Go to ‘Others’ section and click on Workload Pie Chart Report as shown in the following screenshot." }, { "code": null, "e": 74209, "s": 73962, "text": "Step 2 − Select Project or issue filter for which to generate the report. In the Statistic Type, select the field name on which the pie chart will be formed. Select the Time Field to report on as Current Estimate, Original Estimate or Time Spent." }, { "code": null, "e": 74287, "s": 74209, "text": "The following screenshot shows how to generate a report by providing details." }, { "code": null, "e": 74402, "s": 74287, "text": "Step 3 − Click on Next to generate the report. The following screenshot shows how the generated report looks like." }, { "code": null, "e": 74580, "s": 74402, "text": "It displays the number of created issues versus resolved issues over a given time-period. It helps to understand whether the overall backlog is moving towards resolution or not." }, { "code": null, "e": 74648, "s": 74580, "text": "To generate a report, the user should follow the steps given below." }, { "code": null, "e": 74909, "s": 74648, "text": "Step 1 − Go to Project → choose a specific project. Click on the Report icon on the left side of the menu. Go to Issue Analysis and click on Created Vs Resolved Issues Report. The following screenshot shows how to access the Created Vs Resolved issues report −" }, { "code": null, "e": 75304, "s": 74909, "text": "Step 2 − Select the Project or the issue filter for which the report has to be generated. Select the time-period to see reports like Daily, Weekly, Monthly, Quarterly, Annually, etc., available in the dropdown box. Enter the number of days in the Days Previously field to show in the graph. Select Yes or No for Cumulative totals. Select Display Versions as All Versions from the dropdown list." }, { "code": null, "e": 75399, "s": 75304, "text": "The following screenshot shows how to generate report by selecting different available fields." }, { "code": null, "e": 75515, "s": 75399, "text": "Step 3 − Click on Next to generate the reports. The following screenshot shows how the generated report looks like." }, { "code": null, "e": 75602, "s": 75515, "text": "The created issues are displayed in red, while the resolved issues are in green color." }, { "code": null, "e": 75825, "s": 75602, "text": "It displays the total work remaining to achieve the sprint goal for a given time to sprint. It helps the team to manage the progress and respond accordingly. This chart is an important feature of Agile – Scrum methodology." }, { "code": null, "e": 75893, "s": 75825, "text": "To generate a report, the user should follow the steps given below." }, { "code": null, "e": 76104, "s": 75893, "text": "Step 1 − Go to Project → choose a Specific project. Click on the Report icon on the left side of the menu. Go to Agile and click on Burndown chart. The following screenshot shows how to access a Burndown Chart." }, { "code": null, "e": 76517, "s": 76104, "text": "Step 2 − It displays the Burndown chart of the sprint like how the team is progressing towards a committed task. The red line displays how much work is remaining, while the grey line shows the committed tasks. The team can see where they stand in terms of the progress of sprint as compared to the commitment at the starting of that sprint. The user can change the Sprint and Y-axis by selection from a dropdown." }, { "code": null, "e": 76595, "s": 76517, "text": "The following screenshot shows how the Burndown chart looks like sprint wise." }, { "code": null, "e": 76964, "s": 76595, "text": "Step 3 − In the second part of the report, it displays data like what is the sprint start date, what all issues were added, day by day how many issues resolved, what story points of the issues are, and day-by-day how many story points are remaining. This data is utilized to create the chart. The following screenshot shows the data that is used to generate the chart." }, { "code": null, "e": 77040, "s": 76964, "text": "Note − Quite similar to these reports, other reports can also be generated." }, { "code": null, "e": 77072, "s": 77040, "text": "\n 6 Lectures \n 5 hours \n" }, { "code": null, "e": 77089, "s": 77072, "text": " Frahaan Hussain" }, { "code": null, "e": 77121, "s": 77089, "text": "\n 6 Lectures \n 5 hours \n" }, { "code": null, "e": 77133, "s": 77121, "text": " Manu Mitra" }, { "code": null, "e": 77168, "s": 77133, "text": "\n 41 Lectures \n 3.5 hours \n" }, { "code": null, "e": 77182, "s": 77168, "text": " Simon Sez IT" }, { "code": null, "e": 77189, "s": 77182, "text": " Print" }, { "code": null, "e": 77200, "s": 77189, "text": " Add Notes" } ]
Scala String substring(int beginIndex, int endIndex) method with example - GeeksforGeeks
29 Oct, 2019 The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only difference between the two is that sub-sequence returns CharSequence but the above method returns string. Example: 1# // Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = "GeeksforGeeks".substring(4, 8) // Displays output println(result) }} sfor Example: 2# // Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = "GeeksforGeeks".substring(0, 4) // Displays output println(result) }} Geek Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Class and Object in Scala Break statement in Scala Operators in Scala Scala Constructors How to get the first element of List in Scala HashMap in Scala Enumeration in Scala Scala ListBuffer Hello World in Scala Scala Map get() method with example
[ { "code": null, "e": 23515, "s": 23487, "text": "\n29 Oct, 2019" }, { "code": null, "e": 23672, "s": 23515, "text": "The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified." }, { "code": null, "e": 23738, "s": 23672, "text": "Method Definition: String substring(int beginIndex, int endIndex)" }, { "code": null, "e": 23809, "s": 23738, "text": "Return Type: It returns string which is the part of the stated String." }, { "code": null, "e": 23968, "s": 23809, "text": "Note: It is same as sub-sequence method but the only difference between the two is that sub-sequence returns CharSequence but the above method returns string." }, { "code": null, "e": 23980, "s": 23968, "text": "Example: 1#" }, { "code": "// Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = \"GeeksforGeeks\".substring(4, 8) // Displays output println(result) }} ", "e": 24276, "s": 23980, "text": null }, { "code": null, "e": 24282, "s": 24276, "text": "sfor\n" }, { "code": null, "e": 24294, "s": 24282, "text": "Example: 2#" }, { "code": "// Scala program of substring()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying substring method val result = \"GeeksforGeeks\".substring(0, 4) // Displays output println(result) }} ", "e": 24590, "s": 24294, "text": null }, { "code": null, "e": 24596, "s": 24590, "text": "Geek\n" }, { "code": null, "e": 24602, "s": 24596, "text": "Scala" }, { "code": null, "e": 24615, "s": 24602, "text": "Scala-Method" }, { "code": null, "e": 24629, "s": 24615, "text": "Scala-Strings" }, { "code": null, "e": 24635, "s": 24629, "text": "Scala" }, { "code": null, "e": 24733, "s": 24635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24742, "s": 24733, "text": "Comments" }, { "code": null, "e": 24755, "s": 24742, "text": "Old Comments" }, { "code": null, "e": 24781, "s": 24755, "text": "Class and Object in Scala" }, { "code": null, "e": 24806, "s": 24781, "text": "Break statement in Scala" }, { "code": null, "e": 24825, "s": 24806, "text": "Operators in Scala" }, { "code": null, "e": 24844, "s": 24825, "text": "Scala Constructors" }, { "code": null, "e": 24890, "s": 24844, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 24907, "s": 24890, "text": "HashMap in Scala" }, { "code": null, "e": 24928, "s": 24907, "text": "Enumeration in Scala" }, { "code": null, "e": 24945, "s": 24928, "text": "Scala ListBuffer" }, { "code": null, "e": 24966, "s": 24945, "text": "Hello World in Scala" } ]
How to set the Row Height of a JTree with Java?
To set the row height of a JTree, use the setRowHeight() and as a parameter set the height in pixels − tree.setRowHeight(25); The following is an example to set the row height of a JTree with Java − package my; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Demo"); DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project"); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App"); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website"); DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp"); node.add(node1); node.add(node2); node.add(node3); DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website"); DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website"); DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website"); DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app"); DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app"); DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp"); node1.add(one); node1.add(two); node1.add(three); node2.add(four); node2.add(five); node3.add(six); JTree tree = new JTree(node); tree.setRowHeight(25); frame.add(tree); frame.setSize(550,400); frame.setVisible(true); } }
[ { "code": null, "e": 1165, "s": 1062, "text": "To set the row height of a JTree, use the setRowHeight() and as a parameter set the height in pixels −" }, { "code": null, "e": 1188, "s": 1165, "text": "tree.setRowHeight(25);" }, { "code": null, "e": 1261, "s": 1188, "text": "The following is an example to set the row height of a JTree with Java −" }, { "code": null, "e": 2651, "s": 1261, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(\"Project\");\n DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(\"App\");\n DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(\"Website\");\n DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(\"WebApp\");\n node.add(node1);\n node.add(node2);\n node.add(node3);\n DefaultMutableTreeNode one = new DefaultMutableTreeNode(\"Learning website\");\n DefaultMutableTreeNode two = new DefaultMutableTreeNode(\"Business website\");\n DefaultMutableTreeNode three = new DefaultMutableTreeNode(\"News publishing website\");\n DefaultMutableTreeNode four = new DefaultMutableTreeNode(\"Android app\");\n DefaultMutableTreeNode five = new DefaultMutableTreeNode(\"iOS app\");\n DefaultMutableTreeNode six = new DefaultMutableTreeNode(\"Editor WebApp\");\n node1.add(one);\n node1.add(two);\n node1.add(three);\n node2.add(four);\n node2.add(five);\n node3.add(six);\n JTree tree = new JTree(node);\n tree.setRowHeight(25);\n frame.add(tree);\n frame.setSize(550,400);\n frame.setVisible(true);\n }\n}" } ]
Stream generate() method in Java with examples
06 Dec, 2018 Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc. Syntax : static <T> Stream<T> generate(Supplier<T> s) Where, Stream is an interface and T is the type of stream elements. s is the Supplier of generated elements and the return value is a new infinite sequential unordered Stream. Example 1 : To generate stream of random integer. // Java code for Stream.generate()// to generate an infinite sequential// unordered streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // using Stream.generate() method // to generate 5 random Integer values Stream.generate(new Random()::nextInt) .limit(5).forEach(System.out::println); }} Output : 697197501 50139200 321540264 1042847655 -770409472 Example 2 : To generate stream of random Double. // Java code for Stream.generate()// to generate an infinite sequential// unordered streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // using Stream.generate() method // to generate 8 random Double values Stream.generate(new Random()::nextDouble) .limit(8).forEach(System.out::println); }} Output : 0.5390254520295368 0.8477297185718798 0.23703352435894398 0.09156832989674057 0.9671295321757734 0.9989670394813547 0.8909416330715489 0.08177639888829968 Java - util package Java-Functions java-stream Java-Stream interface 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 Java Programming Examples Functional Interfaces in Java Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 248, "s": 28, "text": "Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc." }, { "code": null, "e": 257, "s": 248, "text": "Syntax :" }, { "code": null, "e": 481, "s": 257, "text": "static <T> Stream<T> generate(Supplier<T> s)\n\nWhere, Stream is an interface and T\nis the type of stream elements.\ns is the Supplier of generated \nelements and the return value is\na new infinite sequential\nunordered Stream.\n" }, { "code": null, "e": 531, "s": 481, "text": "Example 1 : To generate stream of random integer." }, { "code": "// Java code for Stream.generate()// to generate an infinite sequential// unordered streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // using Stream.generate() method // to generate 5 random Integer values Stream.generate(new Random()::nextInt) .limit(5).forEach(System.out::println); }}", "e": 931, "s": 531, "text": null }, { "code": null, "e": 940, "s": 931, "text": "Output :" }, { "code": null, "e": 992, "s": 940, "text": "697197501\n50139200\n321540264\n1042847655\n-770409472\n" }, { "code": null, "e": 1041, "s": 992, "text": "Example 2 : To generate stream of random Double." }, { "code": "// Java code for Stream.generate()// to generate an infinite sequential// unordered streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // using Stream.generate() method // to generate 8 random Double values Stream.generate(new Random()::nextDouble) .limit(8).forEach(System.out::println); }}", "e": 1443, "s": 1041, "text": null }, { "code": null, "e": 1452, "s": 1443, "text": "Output :" }, { "code": null, "e": 1608, "s": 1452, "text": "0.5390254520295368\n0.8477297185718798\n0.23703352435894398\n0.09156832989674057\n0.9671295321757734\n0.9989670394813547\n0.8909416330715489\n0.08177639888829968\n" }, { "code": null, "e": 1628, "s": 1608, "text": "Java - util package" }, { "code": null, "e": 1643, "s": 1628, "text": "Java-Functions" }, { "code": null, "e": 1655, "s": 1643, "text": "java-stream" }, { "code": null, "e": 1677, "s": 1655, "text": "Java-Stream interface" }, { "code": null, "e": 1682, "s": 1677, "text": "Java" }, { "code": null, "e": 1687, "s": 1682, "text": "Java" }, { "code": null, "e": 1785, "s": 1687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1800, "s": 1785, "text": "Stream In Java" }, { "code": null, "e": 1821, "s": 1800, "text": "Introduction to Java" }, { "code": null, "e": 1842, "s": 1821, "text": "Constructors in Java" }, { "code": null, "e": 1861, "s": 1842, "text": "Exceptions in Java" }, { "code": null, "e": 1878, "s": 1861, "text": "Generics in Java" }, { "code": null, "e": 1904, "s": 1878, "text": "Java Programming Examples" }, { "code": null, "e": 1934, "s": 1904, "text": "Functional Interfaces in Java" }, { "code": null, "e": 1950, "s": 1934, "text": "Strings in Java" }, { "code": null, "e": 1987, "s": 1950, "text": "Differences between JDK, JRE and JVM" } ]
How to change colors of a Drawable in Android?
This example demonstrates how to change the colors of a Drawable in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:background="@drawable/background" android:id="@+id/activity_main" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="InvalidId"> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout your_Layout = (LinearLayout) findViewById(R.id.activity_main); AnimationDrawable animationDrawable = (AnimationDrawable) your_Layout.getBackground(); animationDrawable.setEnterFadeDuration(4000); animationDrawable.setExitFadeDuration(4000); animationDrawable.start(); } } Step 4 − Add the following code to res/drawable/background.xml <?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/gradient1" android:duration="4000" /> <item android:drawable="@drawable/gradient2" android:duration="4000" /> </animation-list> Step 5 − Add the following code to res/drawable/gradient1.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="225" android:endColor="#044fab" android:startColor="#21d6d3" /> </shape> Step 6 − Add the following code to res/drawable/gradient2.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="45" android:endColor="#933c94" android:startColor="#517f95" /> </shape> Step 7 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <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 the android studio, open one of your project's activity files and click 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": 1264, "s": 1187, "text": "This example demonstrates how to change the colors of a Drawable in Android." }, { "code": null, "e": 1393, "s": 1264, "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": 1458, "s": 1393, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1946, "s": 1458, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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 android:background=\"@drawable/background\"\n android:id=\"@+id/activity_main\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\"\n tools:ignore=\"InvalidId\">\n</LinearLayout>" }, { "code": null, "e": 2003, "s": 1946, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2719, "s": 2003, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.drawable.AnimationDrawable;\nimport android.os.Bundle;\nimport android.widget.LinearLayout;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n LinearLayout your_Layout = (LinearLayout) findViewById(R.id.activity_main);\n AnimationDrawable animationDrawable = (AnimationDrawable) your_Layout.getBackground();\n animationDrawable.setEnterFadeDuration(4000);\n animationDrawable.setExitFadeDuration(4000);\n animationDrawable.start();\n }\n}" }, { "code": null, "e": 2782, "s": 2719, "text": "Step 4 − Add the following code to res/drawable/background.xml" }, { "code": null, "e": 3089, "s": 2782, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<animation-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item\n android:drawable=\"@drawable/gradient1\"\n android:duration=\"4000\" />\n <item\n android:drawable=\"@drawable/gradient2\"\n android:duration=\"4000\" />\n</animation-list>" }, { "code": null, "e": 3151, "s": 3089, "text": "Step 5 − Add the following code to res/drawable/gradient1.xml" }, { "code": null, "e": 3358, "s": 3151, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <gradient android:angle=\"225\" android:endColor=\"#044fab\" android:startColor=\"#21d6d3\" />\n</shape>" }, { "code": null, "e": 3420, "s": 3358, "text": "Step 6 − Add the following code to res/drawable/gradient2.xml" }, { "code": null, "e": 3626, "s": 3420, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <gradient android:angle=\"45\" android:endColor=\"#933c94\" android:startColor=\"#517f95\" />\n</shape>" }, { "code": null, "e": 3691, "s": 3626, "text": "Step 7 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 4361, "s": 3691, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\">\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": 4712, "s": 4361, "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 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": 4753, "s": 4712, "text": "Click here to download the project code." } ]
Python | Play a video using OpenCV
15 Oct, 2018 OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let’s see how to play a video using the OpenCV Python. To capture a video, we need to create a VideoCapture object. VideoCapture have the device index or the name of a video file. Device index is just the number to specify which camera. If we pass 0 then it is for first camera, 1 for second camera so on. We capture the video frame by frame.Syntax : cv2.VideoCapture(0): Means first camera or webcam. cv2.VideoCapture(1): Means second camera or webcam. cv2.VideoCapture("file name.mp4"): Means video file Below is the implementation: # importing librariesimport cv2import numpy as np # Create a VideoCapture object and read from input filecap = cv2.VideoCapture('tree.mp4') # Check if camera opened successfullyif (cap.isOpened()== False): print("Error opening video file") # Read until video is completedwhile(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() if ret == True: # Display the resulting frame cv2.imshow('Frame', frame) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break # When everything done, release # the video capture objectcap.release() # Closes all the framescv2.destroyAllWindows() Note : Video file should have in same directory where program is executed.Output: Sample Frame of video : Related Article : How to play video in reverse mode. Image-Processing OpenCV Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Oct, 2018" }, { "code": null, "e": 262, "s": 52, "text": "OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos." }, { "code": null, "e": 317, "s": 262, "text": "Let’s see how to play a video using the OpenCV Python." }, { "code": null, "e": 613, "s": 317, "text": "To capture a video, we need to create a VideoCapture object. VideoCapture have the device index or the name of a video file. Device index is just the number to specify which camera. If we pass 0 then it is for first camera, 1 for second camera so on. We capture the video frame by frame.Syntax :" }, { "code": null, "e": 769, "s": 613, "text": "cv2.VideoCapture(0): Means first camera or webcam.\ncv2.VideoCapture(1): Means second camera or webcam.\ncv2.VideoCapture(\"file name.mp4\"): Means video file" }, { "code": null, "e": 798, "s": 769, "text": "Below is the implementation:" }, { "code": "# importing librariesimport cv2import numpy as np # Create a VideoCapture object and read from input filecap = cv2.VideoCapture('tree.mp4') # Check if camera opened successfullyif (cap.isOpened()== False): print(\"Error opening video file\") # Read until video is completedwhile(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() if ret == True: # Display the resulting frame cv2.imshow('Frame', frame) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break # When everything done, release # the video capture objectcap.release() # Closes all the framescv2.destroyAllWindows()", "e": 1492, "s": 798, "text": null }, { "code": null, "e": 1574, "s": 1492, "text": "Note : Video file should have in same directory where program is executed.Output:" }, { "code": null, "e": 1598, "s": 1574, "text": "Sample Frame of video :" }, { "code": null, "e": 1651, "s": 1598, "text": "Related Article : How to play video in reverse mode." }, { "code": null, "e": 1668, "s": 1651, "text": "Image-Processing" }, { "code": null, "e": 1675, "s": 1668, "text": "OpenCV" }, { "code": null, "e": 1699, "s": 1675, "text": "Technical Scripter 2018" }, { "code": null, "e": 1706, "s": 1699, "text": "Python" }, { "code": null, "e": 1725, "s": 1706, "text": "Technical Scripter" }, { "code": null, "e": 1823, "s": 1725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1851, "s": 1823, "text": "Read JSON file using Python" }, { "code": null, "e": 1901, "s": 1851, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1923, "s": 1901, "text": "Python map() function" }, { "code": null, "e": 1967, "s": 1923, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2009, "s": 1967, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2031, "s": 2009, "text": "Enumerate() in Python" }, { "code": null, "e": 2066, "s": 2031, "text": "Read a file line by line in Python" }, { "code": null, "e": 2092, "s": 2066, "text": "Python String | replace()" }, { "code": null, "e": 2124, "s": 2092, "text": "How to Install PIP on Windows ?" } ]
Print multiplication table of a given number in C
Print multiplication table of a given number Accept any number from the User for which we need to form multiplication table. Multiply the given number starting with the value of I (=1) Multiply the given number by incrementing the value of I till the I value is lesser than or equal to 12. /* Program to print the multiplication table of a given number */ #include <stdio.h> int main() { int number, i; clrscr(); printf("Please enter any number to find multiplication table:"); scanf("%d", &number); printf("Multiplication table for the given number %d: ", number); printf("\n"); for(i=1;i<=12;i++){ printf("%d x %d = %d", number, i, number * i); printf("\n"); } getch(); return 0; }
[ { "code": null, "e": 1232, "s": 1187, "text": "Print multiplication table of a given number" }, { "code": null, "e": 1312, "s": 1232, "text": "Accept any number from the User for which we need to form multiplication table." }, { "code": null, "e": 1372, "s": 1312, "text": "Multiply the given number starting with the value of I (=1)" }, { "code": null, "e": 1477, "s": 1372, "text": "Multiply the given number by incrementing the value of I till the I value is lesser than or equal to 12." }, { "code": null, "e": 1913, "s": 1477, "text": "/* Program to print the multiplication table of a given number */\n#include <stdio.h>\nint main() {\n int number, i;\n clrscr();\n printf(\"Please enter any number to find multiplication table:\");\n scanf(\"%d\", &number);\n printf(\"Multiplication table for the given number %d: \", number);\n printf(\"\\n\");\n for(i=1;i<=12;i++){\n printf(\"%d x %d = %d\", number, i, number * i);\n printf(\"\\n\");\n }\n getch();\n return 0;\n}" } ]
How to Make a Bell Curve in R?
24 Feb, 2021 To make a bell curve in R we will be using the help of normal distribution which will lead to a bell curve that will be symmetrical about the mean. Half of the data will fall to the left of the mean and half will fall to the right. In probability theory, a normal distribution is a type of continuous probability distribution for a real-valued random variable. Mathematical formula: Where, is mean is standard deviation. For the normal distribution, we use dnorm() function to get the value of the probability density function for the normal distribution given parameters for x, μ, and σ. Syntax: dnorm(x, mean, sd) (sd=Standard Deviation) Parameters:- X is a vector of numbers. Mean is the mean value of the sample data. Its default value is zero. Sd is the standard deviation. Its default value is 1. Returns:-The probability distribution at each point for a given mean and standard deviation. Approach Create a sequence of numbers Get probability distribution at each point for a given mean and standard deviation Plot data with appropriate attributes Example 1: R # sequence of numbers between -10 and 10 incrementing by 0.1.x <- seq(-12, 12, by = .1) # getting probability distribution for each pointy <- dnorm(x, mean = 5, sd = 1) # Plot graphplot(x,y) Output: Example 2: R # sequence of numbers between -10 and 10 incrementing by 0.1.x <- seq(-5, 5, by = .5) # getting probability distributiony <- dnorm(x, mean = 1, sd = 1.5) # plot dataplot(x,y, col="red") Output: Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Feb, 2021" }, { "code": null, "e": 284, "s": 52, "text": "To make a bell curve in R we will be using the help of normal distribution which will lead to a bell curve that will be symmetrical about the mean. Half of the data will fall to the left of the mean and half will fall to the right." }, { "code": null, "e": 414, "s": 284, "text": "In probability theory, a normal distribution is a type of continuous probability distribution for a real-valued random variable. " }, { "code": null, "e": 436, "s": 414, "text": "Mathematical formula:" }, { "code": null, "e": 443, "s": 436, "text": "Where," }, { "code": null, "e": 452, "s": 443, "text": " is mean" }, { "code": null, "e": 476, "s": 452, "text": " is standard deviation." }, { "code": null, "e": 644, "s": 476, "text": "For the normal distribution, we use dnorm() function to get the value of the probability density function for the normal distribution given parameters for x, μ, and σ." }, { "code": null, "e": 695, "s": 644, "text": "Syntax: dnorm(x, mean, sd) (sd=Standard Deviation)" }, { "code": null, "e": 708, "s": 695, "text": "Parameters:-" }, { "code": null, "e": 734, "s": 708, "text": "X is a vector of numbers." }, { "code": null, "e": 804, "s": 734, "text": "Mean is the mean value of the sample data. Its default value is zero." }, { "code": null, "e": 858, "s": 804, "text": "Sd is the standard deviation. Its default value is 1." }, { "code": null, "e": 951, "s": 858, "text": "Returns:-The probability distribution at each point for a given mean and standard deviation." }, { "code": null, "e": 960, "s": 951, "text": "Approach" }, { "code": null, "e": 989, "s": 960, "text": "Create a sequence of numbers" }, { "code": null, "e": 1072, "s": 989, "text": "Get probability distribution at each point for a given mean and standard deviation" }, { "code": null, "e": 1110, "s": 1072, "text": "Plot data with appropriate attributes" }, { "code": null, "e": 1121, "s": 1110, "text": "Example 1:" }, { "code": null, "e": 1123, "s": 1121, "text": "R" }, { "code": "# sequence of numbers between -10 and 10 incrementing by 0.1.x <- seq(-12, 12, by = .1) # getting probability distribution for each pointy <- dnorm(x, mean = 5, sd = 1) # Plot graphplot(x,y)", "e": 1316, "s": 1123, "text": null }, { "code": null, "e": 1324, "s": 1316, "text": "Output:" }, { "code": null, "e": 1335, "s": 1324, "text": "Example 2:" }, { "code": null, "e": 1337, "s": 1335, "text": "R" }, { "code": "# sequence of numbers between -10 and 10 incrementing by 0.1.x <- seq(-5, 5, by = .5) # getting probability distributiony <- dnorm(x, mean = 1, sd = 1.5) # plot dataplot(x,y, col=\"red\")", "e": 1525, "s": 1337, "text": null }, { "code": null, "e": 1533, "s": 1525, "text": "Output:" }, { "code": null, "e": 1540, "s": 1533, "text": "Picked" }, { "code": null, "e": 1553, "s": 1540, "text": "R-Statistics" }, { "code": null, "e": 1564, "s": 1553, "text": "R Language" }, { "code": null, "e": 1662, "s": 1564, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1714, "s": 1662, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1772, "s": 1714, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1807, "s": 1772, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1845, "s": 1807, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1894, "s": 1845, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1911, "s": 1894, "text": "R - if statement" }, { "code": null, "e": 1948, "s": 1911, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1991, "s": 1948, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2028, "s": 1991, "text": "How to import an Excel File into R ?" } ]
Python | Canvas in Kivy using .kv file
04 Jul, 2022 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial – Learn Kivy with Examples. The Canvas is the root object used for drawing by a Widget. A kivy canvas is not the place where you paint. Each Widget in Kivy already has a Canvas by default. When you create a widget, you can create all the instructions needed for drawing. If self is your current widget. The instructions Color and Rectangle are automatically added to the canvas object and will be used when the window is drawn. To use Canvas you must have to import: from kivy.graphics import Rectangle, Color Basic Approach - -> import kivy -> import kivy App -> import widget -> import Canvas i.e.: from kivy.graphics import Rectangle, Color -> set minimum version(optional) -> Extend the Widget class -> Create the App Class -> create the .kv file: -> create the canvas -> Add action/callback if needed -> return a Widget -> Run an instance of the class Implementation of the Approach: 1) Creating A simple canvas: main.py file Python3 # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # A Widget is the base building block# of GUI interfaces in Kivy.# It provides a Canvas that# can be used to draw on screen.from kivy.uix.widget import Widget # From graphics module we are importing# Rectangle and Color as they are# basic building of canvas.from kivy.graphics import Rectangle, Color # class in which we are creating the canvasclass CanvasWidget(Widget): pass # Create the App Classclass CanvasApp(App): def build(self): return CanvasWidget() # run the AppCanvasApp().run() Kivy looks for a Kv file with the same name as your App class in lowercase, minus “App” if it ends with ‘App’ e.g: CanvasApp –> canvas.kv canvas.kv file: Python3 # .kv file of canvas <CanvasWidget@Widget> # creating canvas canvas: Color: rgba: 0, 0, 1, 1 # Blue # size and position of Canvas Rectangle: pos: self.pos size: self.size Output: Now, How can we change the color of canvas by any action so below is an example in which clicking the color of the screen changes. main.py file: Python3 # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # From graphics module we are importing# Rectangle and Color as they are# basic building of canvas.from kivy.graphics import Rectangle, Color # The ButtonBehavior mixin class provides Button behavior.from kivy.uix.button import ButtonBehavior # The Label widget is for rendering text.from kivy.uix.label import Label # class in which we are creating the canvasclass CanvasWidget(ButtonBehavior, Label): pass # Create the App Classclass CanvasApp(App): def build(self): return CanvasWidget() # run the AppCanvasApp().run() .kv file: Python3 # .kv file of canvas <CanvasWidget> # Creating Canvas canvas: # Color is blue if button is pressed, # otherwise color is red Color: rgb: (1, 0, 0, 1) if self.state == 'normal' else (0, 0, 1, 1) # Rounded rectangle canvas RoundedRectangle: size: self.size pos: self.pos # Play with these if you want smooth corners for your button radius: 100, 100, 100, 100 # Print the text when touched or button pressed on_release: print("I have been clicked") Output: Note: Kivy drawing instructions are not automatically relative to the position or size of the widget. Therefore you need to consider these factors when drawing. In order to make your drawing instructions relative to the widget, the instructions need either to be declared in the KvLang or bound to pos and size changes. germanshephered48 gopikumarkaushik9065 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 287, "s": 52, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications." }, { "code": null, "e": 329, "s": 287, "text": "Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 768, "s": 329, "text": "The Canvas is the root object used for drawing by a Widget. A kivy canvas is not the place where you paint. Each Widget in Kivy already has a Canvas by default. When you create a widget, you can create all the instructions needed for drawing. If self is your current widget. The instructions Color and Rectangle are automatically added to the canvas object and will be used when the window is drawn. To use Canvas you must have to import:" }, { "code": null, "e": 811, "s": 768, "text": "from kivy.graphics import Rectangle, Color" }, { "code": null, "e": 1172, "s": 811, "text": "Basic Approach -\n-> import kivy\n-> import kivy App\n-> import widget\n-> import Canvas i.e.:\n from kivy.graphics import Rectangle, Color\n-> set minimum version(optional)\n-> Extend the Widget class\n-> Create the App Class\n-> create the .kv file:\n -> create the canvas\n -> Add action/callback if needed\n-> return a Widget\n-> Run an instance of the class" }, { "code": null, "e": 1247, "s": 1172, "text": "Implementation of the Approach: 1) Creating A simple canvas: main.py file " }, { "code": null, "e": 1255, "s": 1247, "text": "Python3" }, { "code": "# import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # A Widget is the base building block# of GUI interfaces in Kivy.# It provides a Canvas that# can be used to draw on screen.from kivy.uix.widget import Widget # From graphics module we are importing# Rectangle and Color as they are# basic building of canvas.from kivy.graphics import Rectangle, Color # class in which we are creating the canvasclass CanvasWidget(Widget): pass # Create the App Classclass CanvasApp(App): def build(self): return CanvasWidget() # run the AppCanvasApp().run()", "e": 2048, "s": 1255, "text": null }, { "code": null, "e": 2186, "s": 2048, "text": "Kivy looks for a Kv file with the same name as your App class in lowercase, minus “App” if it ends with ‘App’ e.g: CanvasApp –> canvas.kv" }, { "code": null, "e": 2202, "s": 2186, "text": "canvas.kv file:" }, { "code": null, "e": 2210, "s": 2202, "text": "Python3" }, { "code": "# .kv file of canvas <CanvasWidget@Widget> # creating canvas canvas: Color: rgba: 0, 0, 1, 1 # Blue # size and position of Canvas Rectangle: pos: self.pos size: self.size", "e": 2446, "s": 2210, "text": null }, { "code": null, "e": 2454, "s": 2446, "text": "Output:" }, { "code": null, "e": 2588, "s": 2457, "text": "Now, How can we change the color of canvas by any action so below is an example in which clicking the color of the screen changes." }, { "code": null, "e": 2603, "s": 2588, "text": "main.py file: " }, { "code": null, "e": 2611, "s": 2603, "text": "Python3" }, { "code": "# import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # From graphics module we are importing# Rectangle and Color as they are# basic building of canvas.from kivy.graphics import Rectangle, Color # The ButtonBehavior mixin class provides Button behavior.from kivy.uix.button import ButtonBehavior # The Label widget is for rendering text.from kivy.uix.label import Label # class in which we are creating the canvasclass CanvasWidget(ButtonBehavior, Label): pass # Create the App Classclass CanvasApp(App): def build(self): return CanvasWidget() # run the AppCanvasApp().run()", "e": 3434, "s": 2611, "text": null }, { "code": null, "e": 3445, "s": 3434, "text": ".kv file: " }, { "code": null, "e": 3453, "s": 3445, "text": "Python3" }, { "code": "# .kv file of canvas <CanvasWidget> # Creating Canvas canvas: # Color is blue if button is pressed, # otherwise color is red Color: rgb: (1, 0, 0, 1) if self.state == 'normal' else (0, 0, 1, 1) # Rounded rectangle canvas RoundedRectangle: size: self.size pos: self.pos # Play with these if you want smooth corners for your button radius: 100, 100, 100, 100 # Print the text when touched or button pressed on_release: print(\"I have been clicked\")", "e": 4041, "s": 3453, "text": null }, { "code": null, "e": 4052, "s": 4041, "text": "Output: " }, { "code": null, "e": 4372, "s": 4052, "text": "Note: Kivy drawing instructions are not automatically relative to the position or size of the widget. Therefore you need to consider these factors when drawing. In order to make your drawing instructions relative to the widget, the instructions need either to be declared in the KvLang or bound to pos and size changes." }, { "code": null, "e": 4390, "s": 4372, "text": "germanshephered48" }, { "code": null, "e": 4411, "s": 4390, "text": "gopikumarkaushik9065" }, { "code": null, "e": 4422, "s": 4411, "text": "Python-gui" }, { "code": null, "e": 4434, "s": 4422, "text": "Python-kivy" }, { "code": null, "e": 4441, "s": 4434, "text": "Python" } ]
Finding the k smallest values of a NumPy array
02 Sep, 2020 In this article, let us see how to find the k number of the smallest values from a NumPy array. Examples: Input: [1,3,5,2,4,6] k = 3 Output: [1,2,3] Method 1: Using np.sort() . Approach: Create a NumPy array.Determine the value of k.Sort the array in ascending order using the sort() method.Print the first k values of the sorted array. Create a NumPy array. Determine the value of k. Sort the array in ascending order using the sort() method. Print the first k values of the sorted array. Python3 # importing the modulesimport numpy as np # creating the array arr = np.array([23, 12, 1, 3, 4, 5, 6])print("The Original Array Content")print(arr) # value of kk = 4 # sorting the arrayarr1 = np.sort(arr) # k smallest number of arrayprint(k, "smallest elements of the array")print(arr1[:k]) Output: The Original Array Content [23 12 1 3 4 5 6] 4 smallest elements of the array [1 3 4 5] Method 2: Using np.argpartition() Approach: Create a NumPy array.Determine the value of k.Get the indexes of the smallest k elements using the argpartition() method.Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array. Create a NumPy array. Determine the value of k. Get the indexes of the smallest k elements using the argpartition() method. Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array. Python3 # importing the moduleimport numpy as np # creating the array arr = np.array([23, 12, 1, 3, 4, 5, 6])print("The Original Array Content")print(arr) # value of kk = 4 # using np.argpartition()result = np.argpartition(arr, k) # k smallest number of arrayprint(k, "smallest elements of the array")print(arr[result[:k]]) Output: The Original Array Content [23 12 1 3 4 5 6] 4 smallest elements of the array [4 3 1 5] Python numpy-Sorting Searching Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 124, "s": 28, "text": "In this article, let us see how to find the k number of the smallest values from a NumPy array." }, { "code": null, "e": 134, "s": 124, "text": "Examples:" }, { "code": null, "e": 181, "s": 134, "text": "Input: [1,3,5,2,4,6] \nk = 3\n\nOutput: [1,2,3] \n" }, { "code": null, "e": 210, "s": 181, "text": "Method 1: Using np.sort() . " }, { "code": null, "e": 220, "s": 210, "text": "Approach:" }, { "code": null, "e": 370, "s": 220, "text": "Create a NumPy array.Determine the value of k.Sort the array in ascending order using the sort() method.Print the first k values of the sorted array." }, { "code": null, "e": 392, "s": 370, "text": "Create a NumPy array." }, { "code": null, "e": 418, "s": 392, "text": "Determine the value of k." }, { "code": null, "e": 477, "s": 418, "text": "Sort the array in ascending order using the sort() method." }, { "code": null, "e": 523, "s": 477, "text": "Print the first k values of the sorted array." }, { "code": null, "e": 531, "s": 523, "text": "Python3" }, { "code": "# importing the modulesimport numpy as np # creating the array arr = np.array([23, 12, 1, 3, 4, 5, 6])print(\"The Original Array Content\")print(arr) # value of kk = 4 # sorting the arrayarr1 = np.sort(arr) # k smallest number of arrayprint(k, \"smallest elements of the array\")print(arr1[:k])", "e": 826, "s": 531, "text": null }, { "code": null, "e": 834, "s": 826, "text": "Output:" }, { "code": null, "e": 928, "s": 834, "text": "The Original Array Content\n[23 12 1 3 4 5 6]\n4 smallest elements of the array\n[1 3 4 5]\n" }, { "code": null, "e": 963, "s": 928, "text": "Method 2: Using np.argpartition() " }, { "code": null, "e": 973, "s": 963, "text": "Approach:" }, { "code": null, "e": 1228, "s": 973, "text": "Create a NumPy array.Determine the value of k.Get the indexes of the smallest k elements using the argpartition() method.Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array." }, { "code": null, "e": 1250, "s": 1228, "text": "Create a NumPy array." }, { "code": null, "e": 1276, "s": 1250, "text": "Determine the value of k." }, { "code": null, "e": 1352, "s": 1276, "text": "Get the indexes of the smallest k elements using the argpartition() method." }, { "code": null, "e": 1486, "s": 1352, "text": "Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array." }, { "code": null, "e": 1494, "s": 1486, "text": "Python3" }, { "code": "# importing the moduleimport numpy as np # creating the array arr = np.array([23, 12, 1, 3, 4, 5, 6])print(\"The Original Array Content\")print(arr) # value of kk = 4 # using np.argpartition()result = np.argpartition(arr, k) # k smallest number of arrayprint(k, \"smallest elements of the array\")print(arr[result[:k]])", "e": 1814, "s": 1494, "text": null }, { "code": null, "e": 1822, "s": 1814, "text": "Output:" }, { "code": null, "e": 1916, "s": 1822, "text": "The Original Array Content\n[23 12 1 3 4 5 6]\n4 smallest elements of the array\n[4 3 1 5]\n" }, { "code": null, "e": 1947, "s": 1916, "text": "Python numpy-Sorting Searching" }, { "code": null, "e": 1960, "s": 1947, "text": "Python-numpy" }, { "code": null, "e": 1967, "s": 1960, "text": "Python" }, { "code": null, "e": 2065, "s": 1967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2107, "s": 2065, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2129, "s": 2107, "text": "Enumerate() in Python" }, { "code": null, "e": 2164, "s": 2129, "text": "Read a file line by line in Python" }, { "code": null, "e": 2190, "s": 2164, "text": "Python String | replace()" }, { "code": null, "e": 2222, "s": 2190, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2251, "s": 2222, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2278, "s": 2251, "text": "Python Classes and Objects" }, { "code": null, "e": 2308, "s": 2278, "text": "Iterate over a list in Python" }, { "code": null, "e": 2344, "s": 2308, "text": "Convert integer to string in Python" } ]
Smallest subarray with all occurrences of a most frequent element
11 May, 2022 Given an array, A. Let x be an element in the array. x has the maximum frequency in the array. Find the smallest subsegment of the array which also has x as the maximum frequency element.Examples: Input : arr[] = {4, 1, 1, 2, 2, 1, 3, 3} Output : 1, 1, 2, 2, 1 The most frequent element is 1. The smallest subarray that has all occurrences of it is 1 1 2 2 1 Input : A[] = {1, 2, 2, 3, 1} Output : 2, 2 Note that there are two elements that appear two times, 1 and 2. The smallest window for 1 is whole array and smallest window for 2 is {2, 2}. Since window for 2 is smaller, this is our output. Approach: Observe that if X is the maximum repeated element of our subsegment then the subsegment should look like this [X, ....., X], cause if the subsegment end or begins with another element we can delete it which does not alter our answer. To solve this problem, let us store for every distinct element in the array three values, index of the first occurrence of the element and the index of the last occurrence the element and the frequency of the element. And at every step for a maximum repeated element minimize the size of our subsegment. C++ Java Python3 C# Javascript // Java implementation to find smallest// subarray with all occurrences of// a most frequent elementimport java.io.*;import java.util.*;class GfG { static void smallestSubsegment(int a[], int n) { // To store left most occurrence of elements HashMap<Integer, Integer> left= new HashMap<Integer, Integer>(); // To store counts of elements HashMap<Integer, Integer> count= new HashMap<Integer, Integer>(); // To store maximum frequency int mx = 0; // To store length and starting index of // smallest result window int mn = -1, strindex = -1; for (int i = 0; i < n; i++) { int x = a[i]; // First occurrence of an element, // store the index if (count.get(x) == null) { left.put(x, i) ; count.put(x, 1); } // increase the frequency of elements else count.put(x, count.get(x) + 1); // Find maximum repeated element and // store its last occurrence and first // occurrence if (count.get(x) > mx) { mx = count.get(x); // length of subsegment mn = i - left.get(x) + 1; strindex = left.get(x); } // select subsegment of smallest size else if ((count.get(x) == mx) && (i - left.get(x) + 1 < mn)) { mn = i - left.get(x) + 1; strindex = left.get(x); } } // Print the subsegment with all occurrences of // a most frequent element for (int i = strindex; i < strindex + mn; i++) System.out.print(a[i] + " "); } // Driver program public static void main (String[] args) { int A[] = { 1, 2, 2, 2, 1 }; int n = A.length; smallestSubsegment(A, n); }} // This code is contributed by Gitanjali. # Python3 implementation to find smallest# subarray with all occurrences of# a most frequent elementdef smallestSubsegment(a, n): # To store left most occurrence of elements left = dict() # To store counts of elements count = dict() # To store maximum frequency mx = 0 # To store length and starting index of # smallest result window mn, strindex = 0, 0 for i in range(n): x = a[i] # First occurrence of an element, # store the index if (x not in count.keys()): left[x] = i count[x] = 1 # increase the frequency of elements else: count[x] += 1 # Find maximum repeated element and # store its last occurrence and first # occurrence if (count[x] > mx): mx = count[x] mn = i - left[x] + 1 # length of subsegment strindex = left[x] # select subsegment of smallest size elif (count[x] == mx and i - left[x] + 1 < mn): mn = i - left[x] + 1 strindex = left[x] # Print the subsegment with all occurrences of # a most frequent element for i in range(strindex, strindex + mn): print(a[i], end = " ") # Driver codeA = [1, 2, 2, 2, 1]n = len(A)smallestSubsegment(A, n) # This code is contributed by Mohit Kumar // C# implementation to find smallest// subarray with all occurrences of// a most frequent elementusing System;using System.Collections.Generic; class GfG{ static void smallestSubsegment(int []a, int n) { // To store left most occurrence of elements Dictionary<int, int> left = new Dictionary<int, int>(); // To store counts of elements Dictionary<int, int> count = new Dictionary<int, int>(); // To store maximum frequency int mx = 0; // To store length and starting index of // smallest result window int mn = -1, strindex = -1; for (int i = 0; i < n; i++) { int x = a[i]; // First occurrence of an element, // store the index if (!count.ContainsKey(x)) { left.Add(x, i) ; count.Add(x, 1); } // increase the frequency of elements else count[x] = count[x] + 1; // Find maximum repeated element and // store its last occurrence and first // occurrence if (count[x] > mx) { mx = count[x]; // length of subsegment mn = i - left[x] + 1; strindex = left[x]; } // select subsegment of smallest size else if ((count[x] == mx) && (i - left[x] + 1 < mn)) { mn = i - left[x] + 1; strindex = left[x]; } } // Print the subsegment with all occurrences of // a most frequent element for (int i = strindex; i < strindex + mn; i++) Console.Write(a[i] + " "); } // Driver code public static void Main (String[] args) { int []A = { 1, 2, 2, 2, 1 }; int n = A.Length; smallestSubsegment(A, n); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation to find smallest// subarray with all occurrences of// a most frequent element function smallestSubsegment(a,n) { // To store left most occurrence of elements let left= new Map(); // To store counts of elements let count= new Map(); // To store maximum frequency let mx = 0; // To store length and starting index of // smallest result window let mn = -1, strindex = -1; for (let i = 0; i < n; i++) { let x = a[i]; // First occurrence of an element, // store the index if (count.get(x) == null) { left.set(x, i) ; count.set(x, 1); } // increase the frequency of elements else count.set(x, count.get(x) + 1); // Find maximum repeated element and // store its last occurrence and first // occurrence if (count.get(x) > mx) { mx = count.get(x); // length of subsegment mn = i - left.get(x) + 1; strindex = left.get(x); } // select subsegment of smallest size else if ((count.get(x) == mx) && (i - left.get(x) + 1 < mn)) { mn = i - left.get(x) + 1; strindex = left.get(x); } } // Print the subsegment with all occurrences of // a most frequent element for (let i = strindex; i < strindex + mn; i++) document.write(a[i] + " "); } // Driver program let A=[1, 2, 2, 2, 1]; let n = A.length; smallestSubsegment(A, n); // This code is contributed by unknown2108 </script> Output: 2 2 2 Time Complexity: O(n) mohit kumar 29 nidhi_biet princiraj1992 unknown2108 simmytarika5 Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2022" }, { "code": null, "e": 253, "s": 54, "text": "Given an array, A. Let x be an element in the array. x has the maximum frequency in the array. Find the smallest subsegment of the array which also has x as the maximum frequency element.Examples: " }, { "code": null, "e": 659, "s": 253, "text": "Input : arr[] = {4, 1, 1, 2, 2, 1, 3, 3} \nOutput : 1, 1, 2, 2, 1\nThe most frequent element is 1. The smallest\nsubarray that has all occurrences of it is\n1 1 2 2 1\n\nInput : A[] = {1, 2, 2, 3, 1}\nOutput : 2, 2\nNote that there are two elements that appear\ntwo times, 1 and 2. The smallest window for\n1 is whole array and smallest window for 2 is\n{2, 2}. Since window for 2 is smaller, this is\nour output." }, { "code": null, "e": 1211, "s": 661, "text": "Approach: Observe that if X is the maximum repeated element of our subsegment then the subsegment should look like this [X, ....., X], cause if the subsegment end or begins with another element we can delete it which does not alter our answer. To solve this problem, let us store for every distinct element in the array three values, index of the first occurrence of the element and the index of the last occurrence the element and the frequency of the element. And at every step for a maximum repeated element minimize the size of our subsegment. " }, { "code": null, "e": 1215, "s": 1211, "text": "C++" }, { "code": null, "e": 1220, "s": 1215, "text": "Java" }, { "code": null, "e": 1228, "s": 1220, "text": "Python3" }, { "code": null, "e": 1231, "s": 1228, "text": "C#" }, { "code": null, "e": 1242, "s": 1231, "text": "Javascript" }, { "code": "// Java implementation to find smallest// subarray with all occurrences of// a most frequent elementimport java.io.*;import java.util.*;class GfG { static void smallestSubsegment(int a[], int n) { // To store left most occurrence of elements HashMap<Integer, Integer> left= new HashMap<Integer, Integer>(); // To store counts of elements HashMap<Integer, Integer> count= new HashMap<Integer, Integer>(); // To store maximum frequency int mx = 0; // To store length and starting index of // smallest result window int mn = -1, strindex = -1; for (int i = 0; i < n; i++) { int x = a[i]; // First occurrence of an element, // store the index if (count.get(x) == null) { left.put(x, i) ; count.put(x, 1); } // increase the frequency of elements else count.put(x, count.get(x) + 1); // Find maximum repeated element and // store its last occurrence and first // occurrence if (count.get(x) > mx) { mx = count.get(x); // length of subsegment mn = i - left.get(x) + 1; strindex = left.get(x); } // select subsegment of smallest size else if ((count.get(x) == mx) && (i - left.get(x) + 1 < mn)) { mn = i - left.get(x) + 1; strindex = left.get(x); } } // Print the subsegment with all occurrences of // a most frequent element for (int i = strindex; i < strindex + mn; i++) System.out.print(a[i] + \" \"); } // Driver program public static void main (String[] args) { int A[] = { 1, 2, 2, 2, 1 }; int n = A.length; smallestSubsegment(A, n); }} // This code is contributed by Gitanjali.", "e": 3304, "s": 1242, "text": null }, { "code": "# Python3 implementation to find smallest# subarray with all occurrences of# a most frequent elementdef smallestSubsegment(a, n): # To store left most occurrence of elements left = dict() # To store counts of elements count = dict() # To store maximum frequency mx = 0 # To store length and starting index of # smallest result window mn, strindex = 0, 0 for i in range(n): x = a[i] # First occurrence of an element, # store the index if (x not in count.keys()): left[x] = i count[x] = 1 # increase the frequency of elements else: count[x] += 1 # Find maximum repeated element and # store its last occurrence and first # occurrence if (count[x] > mx): mx = count[x] mn = i - left[x] + 1 # length of subsegment strindex = left[x] # select subsegment of smallest size elif (count[x] == mx and i - left[x] + 1 < mn): mn = i - left[x] + 1 strindex = left[x] # Print the subsegment with all occurrences of # a most frequent element for i in range(strindex, strindex + mn): print(a[i], end = \" \") # Driver codeA = [1, 2, 2, 2, 1]n = len(A)smallestSubsegment(A, n) # This code is contributed by Mohit Kumar", "e": 4661, "s": 3304, "text": null }, { "code": "// C# implementation to find smallest// subarray with all occurrences of// a most frequent elementusing System;using System.Collections.Generic; class GfG{ static void smallestSubsegment(int []a, int n) { // To store left most occurrence of elements Dictionary<int, int> left = new Dictionary<int, int>(); // To store counts of elements Dictionary<int, int> count = new Dictionary<int, int>(); // To store maximum frequency int mx = 0; // To store length and starting index of // smallest result window int mn = -1, strindex = -1; for (int i = 0; i < n; i++) { int x = a[i]; // First occurrence of an element, // store the index if (!count.ContainsKey(x)) { left.Add(x, i) ; count.Add(x, 1); } // increase the frequency of elements else count[x] = count[x] + 1; // Find maximum repeated element and // store its last occurrence and first // occurrence if (count[x] > mx) { mx = count[x]; // length of subsegment mn = i - left[x] + 1; strindex = left[x]; } // select subsegment of smallest size else if ((count[x] == mx) && (i - left[x] + 1 < mn)) { mn = i - left[x] + 1; strindex = left[x]; } } // Print the subsegment with all occurrences of // a most frequent element for (int i = strindex; i < strindex + mn; i++) Console.Write(a[i] + \" \"); } // Driver code public static void Main (String[] args) { int []A = { 1, 2, 2, 2, 1 }; int n = A.Length; smallestSubsegment(A, n); }} // This code is contributed by PrinciRaj1992", "e": 6672, "s": 4661, "text": null }, { "code": "<script> // JavaScript implementation to find smallest// subarray with all occurrences of// a most frequent element function smallestSubsegment(a,n) { // To store left most occurrence of elements let left= new Map(); // To store counts of elements let count= new Map(); // To store maximum frequency let mx = 0; // To store length and starting index of // smallest result window let mn = -1, strindex = -1; for (let i = 0; i < n; i++) { let x = a[i]; // First occurrence of an element, // store the index if (count.get(x) == null) { left.set(x, i) ; count.set(x, 1); } // increase the frequency of elements else count.set(x, count.get(x) + 1); // Find maximum repeated element and // store its last occurrence and first // occurrence if (count.get(x) > mx) { mx = count.get(x); // length of subsegment mn = i - left.get(x) + 1; strindex = left.get(x); } // select subsegment of smallest size else if ((count.get(x) == mx) && (i - left.get(x) + 1 < mn)) { mn = i - left.get(x) + 1; strindex = left.get(x); } } // Print the subsegment with all occurrences of // a most frequent element for (let i = strindex; i < strindex + mn; i++) document.write(a[i] + \" \"); } // Driver program let A=[1, 2, 2, 2, 1]; let n = A.length; smallestSubsegment(A, n); // This code is contributed by unknown2108 </script>", "e": 8559, "s": 6672, "text": null }, { "code": null, "e": 8569, "s": 8559, "text": "Output: " }, { "code": null, "e": 8576, "s": 8569, "text": "2 2 2 " }, { "code": null, "e": 8599, "s": 8576, "text": "Time Complexity: O(n) " }, { "code": null, "e": 8614, "s": 8599, "text": "mohit kumar 29" }, { "code": null, "e": 8625, "s": 8614, "text": "nidhi_biet" }, { "code": null, "e": 8639, "s": 8625, "text": "princiraj1992" }, { "code": null, "e": 8651, "s": 8639, "text": "unknown2108" }, { "code": null, "e": 8664, "s": 8651, "text": "simmytarika5" }, { "code": null, "e": 8671, "s": 8664, "text": "Arrays" }, { "code": null, "e": 8676, "s": 8671, "text": "Hash" }, { "code": null, "e": 8683, "s": 8676, "text": "Arrays" }, { "code": null, "e": 8688, "s": 8683, "text": "Hash" } ]
Map.entries( ) In JavaScript
31 May, 2022 What is a map in JavaScript? Map is a data structure in JavaScript which allows storing of [key, value] pairs where any value can be either used as a key or value. The keys and values in the map collection may be of any type and if a value is added to the map collection using a key that already exists in the collection, then the new value replaces the old value. The iteration of elements in a map object is done in the insertion order and a “for...” loop returns an array of all [key, value] pairs for each iteration. Differences between Objects and Maps in JavaScript Both of these data structures are similar in many ways such as both store values using keys, allow retrieval of those values using keys, deletion of keys and verify whether a key holds any value or not. However, there are quite significant differences between Objects and Maps in JavaScript which make the usage of maps a better and more preferable option in many cases. The keys used in maps can be any type of values such as functions, objects etc whereas the keys in objects are limited to symbols and strings. The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually. A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterative data type and can be directly iterated whereas iterating an object requires obtaining its keys in a specific manner. Map.entries() Method in JavaScript The Map.entries() method in JavaScript is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be passed and returns an iterator object of the map. Applications: Whenever we want to get all the [key, value] pairs of each element of a map using an iterator object, we use the Map.entries() method. Syntax: mapObj.entries() Parameters Used: It does not require any parameters to be passed. Return Value: The Map.entries() method returns the [key, value] pairs of all the elements of a map in the order of their insertion. Examples of the above function are provided below. Example: Input : var myMap = new Map(); myMap.set(0, 'geeksforgeeks'); myMap.set(1, 'is an online portal'); myMap.set(2, 'for geeks'); var iterator_obj=myMap.entries(); document.write(iterator_obj.next().value,"<br>"); document.write(iterator_obj.next().value,"<br>"); document.write(iterator_obj.next().value,"<br>"); Output : Array [0, "geeksforgeeks"] Array [1, "is an online portal"] Array [2, "for geeks"] Explanation: In this example, a map object “myMap” has been created with a three [key, value] pairs and an iterator object “iterator_obj” method is created which uses Map.entries() method to return the [key, value] pairs of all the elements of a map in the order of their insertion. Code 1: javascript <script> // creating a map object var myMap = new Map(); // Adding [key, value] pair to the mapmyMap.set(0, 'geeksforgeeks');myMap.set(1, 'is an online portal');myMap.set(2, 'for geeks'); // creating an iterator object using Map.entries() methodvar iterator_obj = myMap.entries(); // displaying the [key, value] pairs of all the elements of the mapdocument.write(iterator_obj.next().value,"</br>");document.write(iterator_obj.next().value,"</br>");document.write(iterator_obj.next().value,"</br>"); </script> Output: Array [0, "geeksforgeeks"] Array [1, "is an online portal"] Array [2, "for geeks"] Code 2: javascript <script> // creating a map object var myMap = new Map(); // Adding [key, value] pair to the mapmyMap.set(0, 'Maps');myMap.set(1, 'in JavaScript'); // creating an iterator object using Map.entries() methodvar iterator_obj = myMap.entries(); // displaying the [key, value] pairs of all the elements of the mapdocument.write(iterator_obj.next().value,"</br>");document.write(iterator_obj.next().value,"</br>"); </script> Output: Array [0, "Maps"] Array [1, "in JavaScript"] Exceptions: If the variable is not of the Map type then the Map.entries() operation throws a TypeError. If the “iterator_obj.next().value” is used more number of times as compared to [key, value] pairs of a map, the Map.entries() function returns undefined for all those cases. Supported Browsers: Google Chrome 38 and above Edge 12 and above Firefox 20 and above Opera 25 and above Safari 8 and above Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries kumargaurav97520 javascript-functions javascript-map JavaScript Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 57, "s": 28, "text": "What is a map in JavaScript?" }, { "code": null, "e": 192, "s": 57, "text": "Map is a data structure in JavaScript which allows storing of [key, value] pairs where any value can be either used as a key or value." }, { "code": null, "e": 393, "s": 192, "text": "The keys and values in the map collection may be of any type and if a value is added to the map collection using a key that already exists in the collection, then the new value replaces the old value." }, { "code": null, "e": 549, "s": 393, "text": "The iteration of elements in a map object is done in the insertion order and a “for...” loop returns an array of all [key, value] pairs for each iteration." }, { "code": null, "e": 971, "s": 549, "text": "Differences between Objects and Maps in JavaScript Both of these data structures are similar in many ways such as both store values using keys, allow retrieval of those values using keys, deletion of keys and verify whether a key holds any value or not. However, there are quite significant differences between Objects and Maps in JavaScript which make the usage of maps a better and more preferable option in many cases." }, { "code": null, "e": 1114, "s": 971, "text": "The keys used in maps can be any type of values such as functions, objects etc whereas the keys in objects are limited to symbols and strings." }, { "code": null, "e": 1251, "s": 1114, "text": "The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually." }, { "code": null, "e": 1516, "s": 1251, "text": "A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterative data type and can be directly iterated whereas iterating an object requires obtaining its keys in a specific manner." }, { "code": null, "e": 1909, "s": 1516, "text": "Map.entries() Method in JavaScript The Map.entries() method in JavaScript is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be passed and returns an iterator object of the map. " }, { "code": null, "e": 2059, "s": 1909, "text": "Applications: Whenever we want to get all the [key, value] pairs of each element of a map using an iterator object, we use the Map.entries() method. " }, { "code": null, "e": 2067, "s": 2059, "text": "Syntax:" }, { "code": null, "e": 2084, "s": 2067, "text": "mapObj.entries()" }, { "code": null, "e": 2102, "s": 2084, "text": "Parameters Used: " }, { "code": null, "e": 2151, "s": 2102, "text": "It does not require any parameters to be passed." }, { "code": null, "e": 2166, "s": 2151, "text": "Return Value: " }, { "code": null, "e": 2284, "s": 2166, "text": "The Map.entries() method returns the [key, value] pairs of all the elements of a map in the order of their insertion." }, { "code": null, "e": 2344, "s": 2284, "text": "Examples of the above function are provided below. Example:" }, { "code": null, "e": 2822, "s": 2344, "text": "Input : var myMap = new Map();\n myMap.set(0, 'geeksforgeeks');\n myMap.set(1, 'is an online portal');\n myMap.set(2, 'for geeks');\n var iterator_obj=myMap.entries();\n document.write(iterator_obj.next().value,\"<br>\");\n document.write(iterator_obj.next().value,\"<br>\");\n document.write(iterator_obj.next().value,\"<br>\");\n\n\nOutput : Array [0, \"geeksforgeeks\"]\n Array [1, \"is an online portal\"]\n Array [2, \"for geeks\"]" }, { "code": null, "e": 3106, "s": 2822, "text": "Explanation: In this example, a map object “myMap” has been created with a three [key, value] pairs and an iterator object “iterator_obj” method is created which uses Map.entries() method to return the [key, value] pairs of all the elements of a map in the order of their insertion. " }, { "code": null, "e": 3115, "s": 3106, "text": "Code 1: " }, { "code": null, "e": 3126, "s": 3115, "text": "javascript" }, { "code": "<script> // creating a map object var myMap = new Map(); // Adding [key, value] pair to the mapmyMap.set(0, 'geeksforgeeks');myMap.set(1, 'is an online portal');myMap.set(2, 'for geeks'); // creating an iterator object using Map.entries() methodvar iterator_obj = myMap.entries(); // displaying the [key, value] pairs of all the elements of the mapdocument.write(iterator_obj.next().value,\"</br>\");document.write(iterator_obj.next().value,\"</br>\");document.write(iterator_obj.next().value,\"</br>\"); </script> ", "e": 3660, "s": 3126, "text": null }, { "code": null, "e": 3668, "s": 3660, "text": "Output:" }, { "code": null, "e": 3766, "s": 3668, "text": " Array [0, \"geeksforgeeks\"]\n Array [1, \"is an online portal\"]\n Array [2, \"for geeks\"]" }, { "code": null, "e": 3775, "s": 3766, "text": "Code 2: " }, { "code": null, "e": 3786, "s": 3775, "text": "javascript" }, { "code": "<script> // creating a map object var myMap = new Map(); // Adding [key, value] pair to the mapmyMap.set(0, 'Maps');myMap.set(1, 'in JavaScript'); // creating an iterator object using Map.entries() methodvar iterator_obj = myMap.entries(); // displaying the [key, value] pairs of all the elements of the mapdocument.write(iterator_obj.next().value,\"</br>\");document.write(iterator_obj.next().value,\"</br>\"); </script> ", "e": 4229, "s": 3786, "text": null }, { "code": null, "e": 4237, "s": 4229, "text": "Output:" }, { "code": null, "e": 4292, "s": 4237, "text": " Array [0, \"Maps\"]\n Array [1, \"in JavaScript\"]" }, { "code": null, "e": 4304, "s": 4292, "text": "Exceptions:" }, { "code": null, "e": 4396, "s": 4304, "text": "If the variable is not of the Map type then the Map.entries() operation throws a TypeError." }, { "code": null, "e": 4570, "s": 4396, "text": "If the “iterator_obj.next().value” is used more number of times as compared to [key, value] pairs of a map, the Map.entries() function returns undefined for all those cases." }, { "code": null, "e": 4590, "s": 4570, "text": "Supported Browsers:" }, { "code": null, "e": 4617, "s": 4590, "text": "Google Chrome 38 and above" }, { "code": null, "e": 4635, "s": 4617, "text": "Edge 12 and above" }, { "code": null, "e": 4656, "s": 4635, "text": "Firefox 20 and above" }, { "code": null, "e": 4675, "s": 4656, "text": "Opera 25 and above" }, { "code": null, "e": 4694, "s": 4675, "text": "Safari 8 and above" }, { "code": null, "e": 4798, "s": 4694, "text": "Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries" }, { "code": null, "e": 4815, "s": 4798, "text": "kumargaurav97520" }, { "code": null, "e": 4836, "s": 4815, "text": "javascript-functions" }, { "code": null, "e": 4851, "s": 4836, "text": "javascript-map" }, { "code": null, "e": 4862, "s": 4851, "text": "JavaScript" }, { "code": null, "e": 4867, "s": 4862, "text": "Misc" }, { "code": null, "e": 4872, "s": 4867, "text": "Misc" }, { "code": null, "e": 4877, "s": 4872, "text": "Misc" } ]
How to use close() and quit() method in Selenium Python ?
06 Mar, 2020 While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.dispose method that successively closes all the browser windows and ends the WebDriver session graciously. Syntax : driver.close() driver.quit() Argument : Both methods takes no argument Action performed :close() method closes the current window.quit() method quits the driver instance, closing every associated window, which is opened. # importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver = webdriver.Chrome() # URL of websiteurl = "https://www.geeksforgeeks.org/" # Opening the websitedriver.get(url) # Closes the current windowdriver.close() Output : The webpage will loaded then closes due to close() method. Code for quit() method: # importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver = webdriver.Chrome() # URL of websiteurl = "https://www.geeksforgeeks.org/" # Opening the websitedriver.get(url) # All windows related to driver instance will quitdriver.quit() Output : The webpage will be loaded then window get quit due to quit() method. Python-selenium Python 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": "\n06 Mar, 2020" }, { "code": null, "e": 437, "s": 28, "text": "While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.dispose method that successively closes all the browser windows and ends the WebDriver session graciously." }, { "code": null, "e": 446, "s": 437, "text": "Syntax :" }, { "code": null, "e": 476, "s": 446, "text": "driver.close()\ndriver.quit()\n" }, { "code": null, "e": 487, "s": 476, "text": "Argument :" }, { "code": null, "e": 518, "s": 487, "text": "Both methods takes no argument" }, { "code": null, "e": 668, "s": 518, "text": "Action performed :close() method closes the current window.quit() method quits the driver instance, closing every associated window, which is opened." }, { "code": "# importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver = webdriver.Chrome() # URL of websiteurl = \"https://www.geeksforgeeks.org/\" # Opening the websitedriver.get(url) # Closes the current windowdriver.close()", "e": 927, "s": 668, "text": null }, { "code": null, "e": 995, "s": 927, "text": "Output : The webpage will loaded then closes due to close() method." }, { "code": null, "e": 1019, "s": 995, "text": "Code for quit() method:" }, { "code": "# importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver = webdriver.Chrome() # URL of websiteurl = \"https://www.geeksforgeeks.org/\" # Opening the websitedriver.get(url) # All windows related to driver instance will quitdriver.quit()", "e": 1300, "s": 1019, "text": null }, { "code": null, "e": 1379, "s": 1300, "text": "Output : The webpage will be loaded then window get quit due to quit() method." }, { "code": null, "e": 1395, "s": 1379, "text": "Python-selenium" }, { "code": null, "e": 1402, "s": 1395, "text": "Python" }, { "code": null, "e": 1419, "s": 1402, "text": "Web Technologies" } ]
TensorFlow - Exporting
Here, we will focus on MetaGraph formation in TensorFlow. This will help us understand export module in TensorFlow. The MetaGraph contains the basic information, which is required to train, perform evaluation, or run inference on a previously trained graph. Following is the code snippet for the same − def export_meta_graph(filename = None, collection_list = None, as_text = False): """this code writes `MetaGraphDef` to save_path/filename. Arguments: filename: Optional meta_graph filename including the path. collection_list: List of string keys to collect. as_text: If `True`, writes the meta_graph as an ASCII proto. Returns: A `MetaGraphDef` proto. """ One of the typical usage model for the same is mentioned below − # Build the model ... with tf.Session() as sess: # Use the model ... # Export the model to /tmp/my-model.meta. meta_graph_def = tf.train.export_meta_graph(filename = '/tmp/my-model.meta')
[ { "code": null, "e": 2707, "s": 2449, "text": "Here, we will focus on MetaGraph formation in TensorFlow. This will help us understand export module in TensorFlow. The MetaGraph contains the basic information, which is required to train, perform evaluation, or run inference on a previously trained graph." }, { "code": null, "e": 2752, "s": 2707, "text": "Following is the code snippet for the same −" }, { "code": null, "e": 3150, "s": 2752, "text": "def export_meta_graph(filename = None, collection_list = None, as_text = False): \n \"\"\"this code writes `MetaGraphDef` to save_path/filename. \n \n Arguments: \n filename: Optional meta_graph filename including the path. collection_list: \n List of string keys to collect. as_text: If `True`, \n writes the meta_graph as an ASCII proto. \n \n Returns: \n A `MetaGraphDef` proto. \"\"\"" }, { "code": null, "e": 3215, "s": 3150, "text": "One of the typical usage model for the same is mentioned below −" } ]
TypeScript - Variables
A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. TypeScript variables must follow the JavaScript naming rules − Variable names can contain alphabets and numeric digits. Variable names can contain alphabets and numeric digits. They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Variable names cannot begin with a digit. Variable names cannot begin with a digit. A variable must be declared before it is used. Use the var keyword to declare variables. The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. When you declare a variable, you have four options − Declare its type and value in one statement. Declare its type and value in one statement. Declare its type but no value. In this case, the variable will be set to undefined. Declare its type but no value. In this case, the variable will be set to undefined. Declare its value but no type. The variable type will be set to the data type of the assigned value. Declare its value but no type. The variable type will be set to the data type of the assigned value. Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined. Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined. The following table illustrates the valid syntax for variable declaration as discussed above − var name:string = ”mary” The variable stores a value of type string var name:string; The variable is a string variable. The variable’s value is set to undefined by default var name = ”mary” The variable’s type is inferred from the data type of the value. Here, the variable is of the type string var name; The variable’s data type is any. Its value is set to undefined by default. var name:string = "John"; var score1:number = 50; var score2:number = 42.50 var sum = score1 + score2 console.log("name"+name) console.log("first score: "+score1) console.log("second score: "+score2) console.log("sum of the scores: "+sum) On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var name = "John"; var score1 = 50; var score2 = 42.50; var sum = score1 + score2; console.log("name" + name); console.log("first score: " + score1); console.log("second score : " + score2); console.log("sum of the scores: " + sum); The output of the above program is given below − name:John first score:50 second score:42.50 sum of the scores:92.50 The TypeScript compiler will generate errors, if we attempt to assign a value to a variable that is not of the same type. Hence, TypeScript follows Strong Typing. The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same. This is why the following code will result in a compilation error − var num:number = "hello" // will result in a compilation error TypeScript allows changing a variable from one type to another. TypeScript refers to this process as Type Assertion. The syntax is to put the target type between < > symbols and place it in front of the variable or expression. The following example explains this concept − var str = '1' var str2:number = <number> <any> str //str is now of type number console.log(typeof(str2)) If you hover the mouse pointer over the type assertion statement in Visual Studio Code, it displays the change in the variable’s data type. Basically it allows the assertion from type S to T succeed if either S is a subtype of T or T is a subtype of S. The reason why it's not called "type casting" is that casting generally implies some sort of runtime support while, “type assertions” are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed. On compiling, it will generate following JavaScript code. "use strict"; var str = '1'; var str2 = str; //str is now of type number console.log(typeof (str2)); It will produce the following output − string Given the fact that, Typescript is strongly typed, this feature is optional. TypeScript also encourages dynamic typing of variables. This means that, TypeScript encourages declaring a variable without a type. In such cases, the compiler will determine the type of the variable on the basis of the value assigned to it. TypeScript will find the first usage of the variable within the code, determine the type to which it has been initially set and then assume the same type for this variable in the rest of your code block. The same is explained in the following code snippet − var num = 2; // data type inferred as number console.log("value of num "+num); num = "12"; console.log(num); In the above code snippet − The code declares a variable and sets its value to 2. Note that the variable declaration doesn’t specify the data type. Hence, the program uses inferred typing to determine the data type of the variable, i.e., it assigns the type of the first value that the variable is set to. In this case, num is set to the type number. The code declares a variable and sets its value to 2. Note that the variable declaration doesn’t specify the data type. Hence, the program uses inferred typing to determine the data type of the variable, i.e., it assigns the type of the first value that the variable is set to. In this case, num is set to the type number. When the code tries to set the variable’s value to string. The compiler throws an error as the variable’s type is already set to number. When the code tries to set the variable’s value to string. The compiler throws an error as the variable’s type is already set to number. It will produce the following output − error TS2011: Cannot convert 'string' to 'number'. The scope of a variable specifies where the variable is defined. The availability of a variable within a program is determined by its scope. TypeScript variables can be of the following scopes − Global Scope − Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code. Global Scope − Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code. Class Scope − These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name. Class Scope − These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name. Local Scope − Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared. Local Scope − Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared. The following example illustrates variable scopes in TypeScript. var global_num = 12 //global variable class Numbers { num_val = 13; //class variable static sval = 10; //static field storeNum():void { var local_num = 14; //local variable } } console.log("Global num: "+global_num) console.log(Numbers.sval) //static variable var obj = new Numbers(); console.log("Global num: "+obj.num_val) On transpiling, the following JavaScript code is generated − var global_num = 12; //global variable var Numbers = (function () { function Numbers() { this.num_val = 13; //class variable } Numbers.prototype.storeNum = function () { var local_num = 14; //local variable }; Numbers.sval = 10; //static field return Numbers; }()); console.log("Global num: " + global_num); console.log(Numbers.sval); //static variable var obj = new Numbers(); console.log("Global num: " + obj.num_val); It will produce the following output − Global num: 12 10 Global num: 13 If you try accessing the local variable outside the method, it results in a compilation error. error TS2095: Could not find symbol 'local_num'.
[ { "code": null, "e": 2389, "s": 2182, "text": "A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. TypeScript variables must follow the JavaScript naming rules −" }, { "code": null, "e": 2446, "s": 2389, "text": "Variable names can contain alphabets and numeric digits." }, { "code": null, "e": 2503, "s": 2446, "text": "Variable names can contain alphabets and numeric digits." }, { "code": null, "e": 2605, "s": 2503, "text": "They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign." }, { "code": null, "e": 2707, "s": 2605, "text": "They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign." }, { "code": null, "e": 2749, "s": 2707, "text": "Variable names cannot begin with a digit." }, { "code": null, "e": 2791, "s": 2749, "text": "Variable names cannot begin with a digit." }, { "code": null, "e": 2880, "s": 2791, "text": "A variable must be declared before it is used. Use the var keyword to declare variables." }, { "code": null, "e": 3077, "s": 2880, "text": "The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable." }, { "code": null, "e": 3130, "s": 3077, "text": "When you declare a variable, you have four options −" }, { "code": null, "e": 3175, "s": 3130, "text": "Declare its type and value in one statement." }, { "code": null, "e": 3220, "s": 3175, "text": "Declare its type and value in one statement." }, { "code": null, "e": 3304, "s": 3220, "text": "Declare its type but no value. In this case, the variable will be set to undefined." }, { "code": null, "e": 3388, "s": 3304, "text": "Declare its type but no value. In this case, the variable will be set to undefined." }, { "code": null, "e": 3489, "s": 3388, "text": "Declare its value but no type. The variable type will be set to the data type of the assigned value." }, { "code": null, "e": 3590, "s": 3489, "text": "Declare its value but no type. The variable type will be set to the data type of the assigned value." }, { "code": null, "e": 3716, "s": 3590, "text": "Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined." }, { "code": null, "e": 3842, "s": 3716, "text": "Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined." }, { "code": null, "e": 3937, "s": 3842, "text": "The following table illustrates the valid syntax for variable declaration as discussed above −" }, { "code": null, "e": 3962, "s": 3937, "text": "var name:string = ”mary”" }, { "code": null, "e": 4005, "s": 3962, "text": "The variable stores a value of type string" }, { "code": null, "e": 4022, "s": 4005, "text": "var name:string;" }, { "code": null, "e": 4109, "s": 4022, "text": "The variable is a string variable. The variable’s value is set to undefined by default" }, { "code": null, "e": 4127, "s": 4109, "text": "var name = ”mary”" }, { "code": null, "e": 4233, "s": 4127, "text": "The variable’s type is inferred from the data type of the value. Here, the variable is of the type string" }, { "code": null, "e": 4243, "s": 4233, "text": "var name;" }, { "code": null, "e": 4318, "s": 4243, "text": "The variable’s data type is any. Its value is set to undefined by default." }, { "code": null, "e": 4563, "s": 4318, "text": "var name:string = \"John\"; \nvar score1:number = 50;\nvar score2:number = 42.50\nvar sum = score1 + score2 \nconsole.log(\"name\"+name) \nconsole.log(\"first score: \"+score1) \nconsole.log(\"second score: \"+score2) \nconsole.log(\"sum of the scores: \"+sum)\n" }, { "code": null, "e": 4621, "s": 4563, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 4888, "s": 4621, "text": "//Generated by typescript 1.8.10\nvar name = \"John\";\nvar score1 = 50;\nvar score2 = 42.50;\nvar sum = score1 + score2;\nconsole.log(\"name\" + name);\nconsole.log(\"first score: \" + score1);\nconsole.log(\"second score : \" + score2);\nconsole.log(\"sum of the scores: \" + sum);\n" }, { "code": null, "e": 4937, "s": 4888, "text": "The output of the above program is given below −" }, { "code": null, "e": 5009, "s": 4937, "text": "name:John \nfirst score:50 \nsecond score:42.50 \nsum of the scores:92.50\n" }, { "code": null, "e": 5358, "s": 5009, "text": "The TypeScript compiler will generate errors, if we attempt to assign a value to a variable that is not of the same type. Hence, TypeScript follows Strong Typing. The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same. This is why the following code will result in a compilation error −" }, { "code": null, "e": 5426, "s": 5358, "text": "var num:number = \"hello\" // will result in a compilation error\n" }, { "code": null, "e": 5699, "s": 5426, "text": "TypeScript allows changing a variable from one type to another. TypeScript refers to this process as Type Assertion. The syntax is to put the target type between < > symbols and place it in front of the variable or expression. The following example explains this concept −" }, { "code": null, "e": 5809, "s": 5699, "text": "var str = '1' \nvar str2:number = <number> <any> str //str is now of type number \nconsole.log(typeof(str2))\n" }, { "code": null, "e": 6062, "s": 5809, "text": "If you hover the mouse pointer over the type assertion statement in Visual Studio Code, it displays the change in the variable’s data type. Basically it allows the assertion from type S to T succeed if either S is a subtype of T or T is a subtype of S." }, { "code": null, "e": 6325, "s": 6062, "text": "The reason why it's not called \"type casting\" is that casting generally implies some sort of runtime support while, “type assertions” are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed." }, { "code": null, "e": 6383, "s": 6325, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 6486, "s": 6383, "text": "\"use strict\";\nvar str = '1';\nvar str2 = str; //str is now of type number \nconsole.log(typeof (str2));\n" }, { "code": null, "e": 6525, "s": 6486, "text": "It will produce the following output −" }, { "code": null, "e": 6533, "s": 6525, "text": "string\n" }, { "code": null, "e": 7056, "s": 6533, "text": "Given the fact that, Typescript is strongly typed, this feature is optional. TypeScript also encourages dynamic typing of variables. This means that, TypeScript encourages declaring a variable without a type. In such cases, the compiler will determine the type of the variable on the basis of the value assigned to it. TypeScript will find the first usage of the variable within the code, determine the type to which it has been initially set and then assume the same type for this variable in the rest of your code block." }, { "code": null, "e": 7110, "s": 7056, "text": "The same is explained in the following code snippet −" }, { "code": null, "e": 7226, "s": 7110, "text": "var num = 2; // data type inferred as number \nconsole.log(\"value of num \"+num); \nnum = \"12\";\nconsole.log(num);\n" }, { "code": null, "e": 7254, "s": 7226, "text": "In the above code snippet −" }, { "code": null, "e": 7577, "s": 7254, "text": "The code declares a variable and sets its value to 2. Note that the variable declaration doesn’t specify the data type. Hence, the program uses inferred typing to determine the data type of the variable, i.e., it assigns the type of the first value that the variable is set to. In this case, num is set to the type number." }, { "code": null, "e": 7900, "s": 7577, "text": "The code declares a variable and sets its value to 2. Note that the variable declaration doesn’t specify the data type. Hence, the program uses inferred typing to determine the data type of the variable, i.e., it assigns the type of the first value that the variable is set to. In this case, num is set to the type number." }, { "code": null, "e": 8037, "s": 7900, "text": "When the code tries to set the variable’s value to string. The compiler throws an error as the variable’s type is already set to number." }, { "code": null, "e": 8174, "s": 8037, "text": "When the code tries to set the variable’s value to string. The compiler throws an error as the variable’s type is already set to number." }, { "code": null, "e": 8213, "s": 8174, "text": "It will produce the following output −" }, { "code": null, "e": 8265, "s": 8213, "text": "error TS2011: Cannot convert 'string' to 'number'.\n" }, { "code": null, "e": 8460, "s": 8265, "text": "The scope of a variable specifies where the variable is defined. The availability of a variable within a program is determined by its scope. TypeScript variables can be of the following scopes −" }, { "code": null, "e": 8605, "s": 8460, "text": "Global Scope − Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code." }, { "code": null, "e": 8750, "s": 8605, "text": "Global Scope − Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code." }, { "code": null, "e": 9027, "s": 8750, "text": "Class Scope − These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name." }, { "code": null, "e": 9304, "s": 9027, "text": "Class Scope − These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name." }, { "code": null, "e": 9499, "s": 9304, "text": "Local Scope − Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared." }, { "code": null, "e": 9694, "s": 9499, "text": "Local Scope − Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared." }, { "code": null, "e": 9759, "s": 9694, "text": "The following example illustrates variable scopes in TypeScript." }, { "code": null, "e": 10155, "s": 9759, "text": "var global_num = 12 //global variable \nclass Numbers { \n num_val = 13; //class variable \n static sval = 10; //static field \n \n storeNum():void { \n var local_num = 14; //local variable \n } \n} \nconsole.log(\"Global num: \"+global_num) \nconsole.log(Numbers.sval) //static variable \nvar obj = new Numbers(); \nconsole.log(\"Global num: \"+obj.num_val) \n" }, { "code": null, "e": 10216, "s": 10155, "text": "On transpiling, the following JavaScript code is generated −" }, { "code": null, "e": 10722, "s": 10216, "text": "var global_num = 12; //global variable \nvar Numbers = (function () {\n function Numbers() {\n this.num_val = 13; //class variable \n }\n Numbers.prototype.storeNum = function () {\n var local_num = 14; //local variable \n };\n Numbers.sval = 10; //static field \n return Numbers;\n}());\n\nconsole.log(\"Global num: \" + global_num);\nconsole.log(Numbers.sval); //static variable \n\nvar obj = new Numbers();\nconsole.log(\"Global num: \" + obj.num_val);\n" }, { "code": null, "e": 10761, "s": 10722, "text": "It will produce the following output −" }, { "code": null, "e": 10795, "s": 10761, "text": "Global num: 12\n10\nGlobal num: 13\n" }, { "code": null, "e": 10890, "s": 10795, "text": "If you try accessing the local variable outside the method, it results in a compilation error." } ]
Java.lang.StackTraceElement class in Java
03 Sep, 2021 An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. This class describes single stack frame, which is an individual element of a stack trace when an exception occur. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represent the execution point of which the stack trace was generated. Each stack frame represents an execution point, which includes such things as the name of the method, the name of file and the source code line number. An array of StackTraceElement is returned by getStackTrace()method of the Throwable class. Constructor: Creates a stack trace element representing the specified execution point. StackTraceElement(String declaringClass, String methodName, String fileName, int lineNumber) Parameters: declaringClass – the fully qualified name of the class containing the execution point represented by the stack trace element. methodName – the name of the method containing the execution point represented by the stack trace element. fileName – the name of the file containing the execution point represented by the stack trace element, or null if this information is unavailable lineNumber – the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable. A value of -2 indicates that the method containing the execution point is a native method. Throws: NullPointerException – if declaringClass or methodName is null. Methods: 1. boolean equals(ob): Returns try if the invoking StackTraceElement is as the one passed in ob. Otherwise it returns false. Syntax: public boolean equals(ob) Returns: true if the specified object is another StackTraceElement instance representing the same execution point as this instance. Exception: NA Java // Java code illustrating equals() methodimport java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { StackTraceElement st1 = new StackTraceElement("foo", "fuction1", "StackTrace.java", 1); StackTraceElement st2 = new StackTraceElement("bar", "function2", "StackTrace.java", 1); Object ob = st1.getFileName(); // checking whether file names are same or not System.out.println(st2.getFileName().equals(ob)); }} Output: true 2. String getClassName(): Returns the class name of the execution point described by the invoking StackTraceElement. Syntax: public String getClassName(). Returns: the fully qualified name of the Class containing the execution point represented by this stack trace element. Exception: NA. Java // Java code illustrating getClassName() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println("Class name of each thread involved:"); for(int i = 0; i<2; i++) { System.out.println(Thread.currentThread().getStackTrace()[I]. getClassName()); } }} Output: Class name of each thread involved: java.lang.Thread StackTraceElementDemo 3. String getFileName(): Returns the file name of the execution point described by the invoking StackTraceElement. Syntax: public String getFileName(). Returns: the name of the file containing the execution point represented by this stack trace element, or null if this information is unavailable. Exception: NA. Java // Java code illustrating getFileName() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println("file name: "); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getFileName()); }} Output: file name: Thread.java StackTraceElementDemo.java 4. int getLineNumber(): Returns the source-code line number of the execution point described by the invoking StackTraceElement. In some situation the line number will not be available, in which case a negative value is returned. Syntax: public int getLineNumber(). Returns: the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable. Exception: NA. Java // Java code illustrating getLineNumber() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println("line number: "); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getLineNumber()); }} Output: line number: 1556 10 5. String getMethodName(): Returns the method name of the execution point described by the invoking StackTraceElement. Syntax: public String getMethodName(). Returns: the name of the method containing the execution point represented by this stack trace element. Exception: NA. Java // Java code illustrating getMethodName() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println("method name: "); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getMethodName()); }} Output: method name: getStackTrace main 6. int hashCode(): Returns the hash code of the invoking StackTraceElement. Syntax: public int hashCode(). Returns: a hash code value for this object. Exception: NA. Java // Java code illustrating hashCode() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println("hash code: "); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. hashCode()); }} Output: hash code: -1225537245 -1314176653 7. boolean isNativeMethod(): Returns true if the invoking StackTraceElement describes a native method. Otherwise returns false. Syntax: public boolean isNativeMethod(). Returns: true if the method containing the execution point represented by this stack trace element is a native method. Exception: NA. Java // Java code illustrating isNativeMethod() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. isNativeMethod()); }} Output: false false 8. String toString(): Returns the String equivalent of the invoking sequence. Syntax: public String toString(). Returns: a string representation of the object. Exception: NA. Java // Java code illustrating toString() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println("String equivalent: "); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. toString()); }} Output: String equivalent: java.lang.Thread.getStackTrace StackTraceElementDemo.main This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gulshankumarar231 Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Sep, 2021" }, { "code": null, "e": 342, "s": 28, "text": "An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. " }, { "code": null, "e": 456, "s": 342, "text": "This class describes single stack frame, which is an individual element of a stack trace when an exception occur." }, { "code": null, "e": 547, "s": 456, "text": "All stack frames except for the one at the top of the stack represent a method invocation." }, { "code": null, "e": 651, "s": 547, "text": "The frame at the top of the stack represent the execution point of which the stack trace was generated." }, { "code": null, "e": 803, "s": 651, "text": "Each stack frame represents an execution point, which includes such things as the name of the method, the name of file and the source code line number." }, { "code": null, "e": 894, "s": 803, "text": "An array of StackTraceElement is returned by getStackTrace()method of the Throwable class." }, { "code": null, "e": 981, "s": 894, "text": "Constructor: Creates a stack trace element representing the specified execution point." }, { "code": null, "e": 1075, "s": 981, "text": "StackTraceElement(String declaringClass, \nString methodName, String fileName, int lineNumber)" }, { "code": null, "e": 1088, "s": 1075, "text": "Parameters: " }, { "code": null, "e": 1214, "s": 1088, "text": "declaringClass – the fully qualified name of the class containing the execution point represented by the stack trace element." }, { "code": null, "e": 1321, "s": 1214, "text": "methodName – the name of the method containing the execution point represented by the stack trace element." }, { "code": null, "e": 1467, "s": 1321, "text": "fileName – the name of the file containing the execution point represented by the stack trace element, or null if this information is unavailable" }, { "code": null, "e": 1735, "s": 1467, "text": "lineNumber – the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable. A value of -2 indicates that the method containing the execution point is a native method." }, { "code": null, "e": 1807, "s": 1735, "text": "Throws: NullPointerException – if declaringClass or methodName is null." }, { "code": null, "e": 1817, "s": 1807, "text": "Methods: " }, { "code": null, "e": 1942, "s": 1817, "text": "1. boolean equals(ob): Returns try if the invoking StackTraceElement is as the one passed in ob. Otherwise it returns false." }, { "code": null, "e": 2124, "s": 1942, "text": "Syntax: public boolean equals(ob)\nReturns: true if the specified object is \nanother StackTraceElement instance representing the same execution \npoint as this instance.\nException: NA" }, { "code": null, "e": 2129, "s": 2124, "text": "Java" }, { "code": "// Java code illustrating equals() methodimport java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { StackTraceElement st1 = new StackTraceElement(\"foo\", \"fuction1\", \"StackTrace.java\", 1); StackTraceElement st2 = new StackTraceElement(\"bar\", \"function2\", \"StackTrace.java\", 1); Object ob = st1.getFileName(); // checking whether file names are same or not System.out.println(st2.getFileName().equals(ob)); }}", "e": 2764, "s": 2129, "text": null }, { "code": null, "e": 2772, "s": 2764, "text": "Output:" }, { "code": null, "e": 2777, "s": 2772, "text": "true" }, { "code": null, "e": 2894, "s": 2777, "text": "2. String getClassName(): Returns the class name of the execution point described by the invoking StackTraceElement." }, { "code": null, "e": 3066, "s": 2894, "text": "Syntax: public String getClassName().\nReturns: the fully qualified name of the Class\ncontaining the execution point represented by this stack trace element.\nException: NA." }, { "code": null, "e": 3071, "s": 3066, "text": "Java" }, { "code": "// Java code illustrating getClassName() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println(\"Class name of each thread involved:\"); for(int i = 0; i<2; i++) { System.out.println(Thread.currentThread().getStackTrace()[I]. getClassName()); } }}", "e": 3484, "s": 3071, "text": null }, { "code": null, "e": 3492, "s": 3484, "text": "Output:" }, { "code": null, "e": 3567, "s": 3492, "text": "Class name of each thread involved:\njava.lang.Thread\nStackTraceElementDemo" }, { "code": null, "e": 3682, "s": 3567, "text": "3. String getFileName(): Returns the file name of the execution point described by the invoking StackTraceElement." }, { "code": null, "e": 3881, "s": 3682, "text": "Syntax: public String getFileName().\nReturns: the name of the file containing \nthe execution point represented by this stack trace element,\nor null if this information is unavailable.\nException: NA." }, { "code": null, "e": 3886, "s": 3881, "text": "Java" }, { "code": "// Java code illustrating getFileName() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println(\"file name: \"); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getFileName()); }}", "e": 4237, "s": 3886, "text": null }, { "code": null, "e": 4245, "s": 4237, "text": "Output:" }, { "code": null, "e": 4296, "s": 4245, "text": "file name: \nThread.java\nStackTraceElementDemo.java" }, { "code": null, "e": 4525, "s": 4296, "text": "4. int getLineNumber(): Returns the source-code line number of the execution point described by the invoking StackTraceElement. In some situation the line number will not be available, in which case a negative value is returned." }, { "code": null, "e": 4752, "s": 4525, "text": "Syntax: public int getLineNumber().\nReturns: the line number of the source line \ncontaining the execution point represented by this stack \ntrace element, or a negative number if this information is \nunavailable.\nException: NA." }, { "code": null, "e": 4757, "s": 4752, "text": "Java" }, { "code": "// Java code illustrating getLineNumber() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println(\"line number: \"); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getLineNumber()); }}", "e": 5114, "s": 4757, "text": null }, { "code": null, "e": 5122, "s": 5114, "text": "Output:" }, { "code": null, "e": 5144, "s": 5122, "text": "line number: \n1556\n10" }, { "code": null, "e": 5263, "s": 5144, "text": "5. String getMethodName(): Returns the method name of the execution point described by the invoking StackTraceElement." }, { "code": null, "e": 5422, "s": 5263, "text": "Syntax: public String getMethodName().\nReturns: the name of the method containing the \nexecution point represented by this stack trace element.\nException: NA." }, { "code": null, "e": 5427, "s": 5422, "text": "Java" }, { "code": "// Java code illustrating getMethodName() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println(\"method name: \"); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. getMethodName()); }}", "e": 5784, "s": 5427, "text": null }, { "code": null, "e": 5792, "s": 5784, "text": "Output:" }, { "code": null, "e": 5825, "s": 5792, "text": "method name: \ngetStackTrace\nmain" }, { "code": null, "e": 5901, "s": 5825, "text": "6. int hashCode(): Returns the hash code of the invoking StackTraceElement." }, { "code": null, "e": 5991, "s": 5901, "text": "Syntax: public int hashCode().\nReturns: a hash code value for this object.\nException: NA." }, { "code": null, "e": 5996, "s": 5991, "text": "Java" }, { "code": "// Java code illustrating hashCode() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println(\"hash code: \"); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. hashCode()); }}", "e": 6341, "s": 5996, "text": null }, { "code": null, "e": 6349, "s": 6341, "text": "Output:" }, { "code": null, "e": 6385, "s": 6349, "text": "hash code: \n-1225537245\n-1314176653" }, { "code": null, "e": 6513, "s": 6385, "text": "7. boolean isNativeMethod(): Returns true if the invoking StackTraceElement describes a native method. Otherwise returns false." }, { "code": null, "e": 6689, "s": 6513, "text": "Syntax: public boolean isNativeMethod().\nReturns: true if the method containing the execution \npoint represented by this stack trace element is a native method.\nException: NA." }, { "code": null, "e": 6694, "s": 6689, "text": "Java" }, { "code": "// Java code illustrating isNativeMethod() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. isNativeMethod()); }}", "e": 7016, "s": 6694, "text": null }, { "code": null, "e": 7024, "s": 7016, "text": "Output:" }, { "code": null, "e": 7036, "s": 7024, "text": "false\nfalse" }, { "code": null, "e": 7114, "s": 7036, "text": "8. String toString(): Returns the String equivalent of the invoking sequence." }, { "code": null, "e": 7211, "s": 7114, "text": "Syntax: public String toString().\nReturns: a string representation of the object.\nException: NA." }, { "code": null, "e": 7216, "s": 7211, "text": "Java" }, { "code": "// Java code illustrating toString() method.import java.lang.*;import java.io.*;import java.util.*;public class StackTraceElementDemo{ public static void main(String[] arg) { System.out.println(\"String equivalent: \"); for(int i = 0; i<2; i++) System.out.println(Thread.currentThread().getStackTrace()[i]. toString()); }}", "e": 7569, "s": 7216, "text": null }, { "code": null, "e": 7577, "s": 7569, "text": "Output:" }, { "code": null, "e": 7655, "s": 7577, "text": "String equivalent: \njava.lang.Thread.getStackTrace\nStackTraceElementDemo.main" }, { "code": null, "e": 8078, "s": 7655, "text": "This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8096, "s": 8078, "text": "gulshankumarar231" }, { "code": null, "e": 8114, "s": 8096, "text": "Java-lang package" }, { "code": null, "e": 8119, "s": 8114, "text": "Java" }, { "code": null, "e": 8124, "s": 8119, "text": "Java" } ]
Creating an Server-Client Application using the DatagramPacket and DatagramSocket classes
20 Nov, 2021 To create an application that uses UDP to establish the connection between a client and server, we need to perform the following steps: Create a server program Create a client program Execute the client and server program Let’s perform the steps in the following subsections: Creating the Server Program Let’s create the server class, named UDPServerEx which takes messages from a user and sends the messages (datagrams) to the clients. Listing 1 shows the code of the UDPServerEx.java file: Filename: UDPServerEx.java Java // A server that sends messages to the client import java.net.*; class UDPServerEx { public static DatagramSocket mySocket; public static byte myBuffer[] = new byte[2000]; public static void serverMethod() throws Exception { int position = 0; while (true) { int charData = System.in.read(); switch (charData) { case -1: System.out.println( "The execution of " + "the server has been terminated"); return; case '\r': break; case '\n': mySocket.send( new DatagramPacket( myBuffer, position, InetAddress.getLocalHost(), 777)); position = 0; break; default: myBuffer[position++] = (byte)charData; } } } public static void main(String args[]) throws Exception { System.out.println("Please enter some text here"); mySocket = new DatagramSocket(888); serverMethod(); }} To compile the UDPServerEx.java file: D:\UDPExample>javac UDPServerEx.java Note: The path may vary according to where you save file. Creating the ClientProgram Let’s create a client class, named UDPClient, which accepts the messages sent from the server, UDPServerEx class. The client then displays the messages received in the Command Prompt. Listing 2 shows the code of the UDPClient.java file: Filename: UDPClient.java Java // UDPClient that receives and// displays messages sent from the server import java.net.*;class UDPClient { public static DatagramSocket mySocket; public static byte myBuffer[] = new byte[2000]; public static void clientMethod() throws Exception { while (true) { DatagramPacket dataPacket = new DatagramPacket(myBuffer, myBuffer.length); mySocket.receive(dataPacket); System.out.println("Message Received :"); System.out.println( new String( dataPacket.getData(), 0, dataPacket.getLength())); } } public static void main(String args[]) throws Exception { System.out.println( "You need to press CTRL+C" + " in order to quit."); mySocket = new DatagramSocket(777); clientMethod(); }} Use the following command to compile the UDPClient.java file: D:\UDPExample>javac UDPClient.java Output Note: To execute the UDPServerEx and UDPClient classes, run the UDPServerEx.java and UDPClient.java in two separate Command Prompt windows. Remember, the UDPServerEx class is executed before the UDPClient class. Figure 1 shows the output of the UDP Server java and UDPClient.java files: Showing the Output of the UDPServerEx and UDPClient Classes surindertarika1234 sweetyty clintra Java-Networking Java Java Programs 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 Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2021" }, { "code": null, "e": 164, "s": 28, "text": "To create an application that uses UDP to establish the connection between a client and server, we need to perform the following steps:" }, { "code": null, "e": 188, "s": 164, "text": "Create a server program" }, { "code": null, "e": 212, "s": 188, "text": "Create a client program" }, { "code": null, "e": 250, "s": 212, "text": "Execute the client and server program" }, { "code": null, "e": 304, "s": 250, "text": "Let’s perform the steps in the following subsections:" }, { "code": null, "e": 333, "s": 304, "text": "Creating the Server Program " }, { "code": null, "e": 522, "s": 333, "text": "Let’s create the server class, named UDPServerEx which takes messages from a user and sends the messages (datagrams) to the clients. Listing 1 shows the code of the UDPServerEx.java file: " }, { "code": null, "e": 549, "s": 522, "text": "Filename: UDPServerEx.java" }, { "code": null, "e": 554, "s": 549, "text": "Java" }, { "code": "// A server that sends messages to the client import java.net.*; class UDPServerEx { public static DatagramSocket mySocket; public static byte myBuffer[] = new byte[2000]; public static void serverMethod() throws Exception { int position = 0; while (true) { int charData = System.in.read(); switch (charData) { case -1: System.out.println( \"The execution of \" + \"the server has been terminated\"); return; case '\\r': break; case '\\n': mySocket.send( new DatagramPacket( myBuffer, position, InetAddress.getLocalHost(), 777)); position = 0; break; default: myBuffer[position++] = (byte)charData; } } } public static void main(String args[]) throws Exception { System.out.println(\"Please enter some text here\"); mySocket = new DatagramSocket(888); serverMethod(); }}", "e": 1735, "s": 554, "text": null }, { "code": null, "e": 1774, "s": 1735, "text": "To compile the UDPServerEx.java file: " }, { "code": null, "e": 1811, "s": 1774, "text": "D:\\UDPExample>javac UDPServerEx.java" }, { "code": null, "e": 1869, "s": 1811, "text": "Note: The path may vary according to where you save file." }, { "code": null, "e": 1897, "s": 1869, "text": "Creating the ClientProgram " }, { "code": null, "e": 2135, "s": 1897, "text": "Let’s create a client class, named UDPClient, which accepts the messages sent from the server, UDPServerEx class. The client then displays the messages received in the Command Prompt. Listing 2 shows the code of the UDPClient.java file: " }, { "code": null, "e": 2161, "s": 2135, "text": "Filename: UDPClient.java " }, { "code": null, "e": 2166, "s": 2161, "text": "Java" }, { "code": "// UDPClient that receives and// displays messages sent from the server import java.net.*;class UDPClient { public static DatagramSocket mySocket; public static byte myBuffer[] = new byte[2000]; public static void clientMethod() throws Exception { while (true) { DatagramPacket dataPacket = new DatagramPacket(myBuffer, myBuffer.length); mySocket.receive(dataPacket); System.out.println(\"Message Received :\"); System.out.println( new String( dataPacket.getData(), 0, dataPacket.getLength())); } } public static void main(String args[]) throws Exception { System.out.println( \"You need to press CTRL+C\" + \" in order to quit.\"); mySocket = new DatagramSocket(777); clientMethod(); }}", "e": 3098, "s": 2166, "text": null }, { "code": null, "e": 3161, "s": 3098, "text": "Use the following command to compile the UDPClient.java file: " }, { "code": null, "e": 3196, "s": 3161, "text": "D:\\UDPExample>javac UDPClient.java" }, { "code": null, "e": 3204, "s": 3196, "text": "Output " }, { "code": null, "e": 3491, "s": 3204, "text": "Note: To execute the UDPServerEx and UDPClient classes, run the UDPServerEx.java and UDPClient.java in two separate Command Prompt windows. Remember, the UDPServerEx class is executed before the UDPClient class. Figure 1 shows the output of the UDP Server java and UDPClient.java files:" }, { "code": null, "e": 3551, "s": 3491, "text": "Showing the Output of the UDPServerEx and UDPClient Classes" }, { "code": null, "e": 3572, "s": 3553, "text": "surindertarika1234" }, { "code": null, "e": 3581, "s": 3572, "text": "sweetyty" }, { "code": null, "e": 3589, "s": 3581, "text": "clintra" }, { "code": null, "e": 3605, "s": 3589, "text": "Java-Networking" }, { "code": null, "e": 3610, "s": 3605, "text": "Java" }, { "code": null, "e": 3624, "s": 3610, "text": "Java Programs" }, { "code": null, "e": 3629, "s": 3624, "text": "Java" }, { "code": null, "e": 3727, "s": 3629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3742, "s": 3727, "text": "Stream In Java" }, { "code": null, "e": 3763, "s": 3742, "text": "Introduction to Java" }, { "code": null, "e": 3784, "s": 3763, "text": "Constructors in Java" }, { "code": null, "e": 3803, "s": 3784, "text": "Exceptions in Java" }, { "code": null, "e": 3820, "s": 3803, "text": "Generics in Java" }, { "code": null, "e": 3846, "s": 3820, "text": "Java Programming Examples" }, { "code": null, "e": 3880, "s": 3846, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3927, "s": 3880, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3965, "s": 3927, "text": "Factory method design pattern in Java" } ]
Hill Cipher
21 Jul, 2021 Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is represented by a number modulo 26. Often the simple scheme A = 0, B = 1, ..., Z = 25 is used, but this is not an essential feature of the cipher. To encrypt a message, each block of n letters (considered as an n-component vector) is multiplied by an invertible n × n matrix, against modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.The matrix used for encryption is the cipher key, and it should be chosen randomly from the set of invertible n × n matrices (modulo 26).Examples: Input : Plaintext: ACT Key: GYBNQKURP Output : Ciphertext: POH Input : Plaintext: GFG Key: HILLMAGIC Output : Ciphertext: SWK Encryption We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be written as the nxn matrix: The message ‘ACT’ is written as vector: The enciphered vector is given as: which corresponds to ciphertext of ‘POH’ Decryption To decrypt the message, we turn the ciphertext back into a vector, then simply multiply by the inverse matrix of the key matrix (IFKVIVVMI in letters).The inverse of the matrix used in the previous example is: For the previous Ciphertext ‘POH’: which gives us back ‘ACT’. Assume that all the alphabets are in upper case. Below is the implementation of the above idea for n=3. C++ Java Python3 C# Javascript // C++ code to implement Hill Cipher#include <iostream>using namespace std; // Following function generates the// key matrix for the key stringvoid getKeyMatrix(string key, int keyMatrix[][3]){ int k = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { keyMatrix[i][j] = (key[k]) % 65; k++; } }} // Following function encrypts the messagevoid encrypt(int cipherMatrix[][1], int keyMatrix[][3], int messageVector[][1]){ int x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i][j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j]; } cipherMatrix[i][j] = cipherMatrix[i][j] % 26; } }} // Function to implement Hill Ciphervoid HillCipher(string message, string key){ // Get key matrix from the key string int keyMatrix[3][3]; getKeyMatrix(key, keyMatrix); int messageVector[3][1]; // Generate vector for the message for (int i = 0; i < 3; i++) messageVector[i][0] = (message[i]) % 65; int cipherMatrix[3][1]; // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); string CipherText; // Generate the encrypted text from // the encrypted vector for (int i = 0; i < 3; i++) CipherText += cipherMatrix[i][0] + 65; // Finally print the ciphertext cout << " Ciphertext:" << CipherText;} // Driver function for above codeint main(){ // Get the message to be encrypted string message = "ACT"; // Get the key string key = "GYBNQKURP"; HillCipher(message, key); return 0;} // Java code to implement Hill Cipherclass GFG{ // Following function generates the// key matrix for the key stringstatic void getKeyMatrix(String key, int keyMatrix[][]){ int k = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { keyMatrix[i][j] = (key.charAt(k)) % 65; k++; } }} // Following function encrypts the messagestatic void encrypt(int cipherMatrix[][], int keyMatrix[][], int messageVector[][]){ int x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i][j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j]; } cipherMatrix[i][j] = cipherMatrix[i][j] % 26; } }} // Function to implement Hill Cipherstatic void HillCipher(String message, String key){ // Get key matrix from the key string int [][]keyMatrix = new int[3][3]; getKeyMatrix(key, keyMatrix); int [][]messageVector = new int[3][1]; // Generate vector for the message for (int i = 0; i < 3; i++) messageVector[i][0] = (message.charAt(i)) % 65; int [][]cipherMatrix = new int[3][1]; // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); String CipherText=""; // Generate the encrypted text from // the encrypted vector for (int i = 0; i < 3; i++) CipherText += (char)(cipherMatrix[i][0] + 65); // Finally print the ciphertext System.out.print(" Ciphertext:" + CipherText);} // Driver codepublic static void main(String[] args){ // Get the message to be encrypted String message = "ACT"; // Get the key String key = "GYBNQKURP"; HillCipher(message, key); }} // This code has been contributed by 29AjayKumar # Python3 code to implement Hill Cipher keyMatrix = [[0] * 3 for i in range(3)] # Generate vector for the messagemessageVector = [[0] for i in range(3)] # Generate vector for the ciphercipherMatrix = [[0] for i in range(3)] # Following function generates the# key matrix for the key stringdef getKeyMatrix(key): k = 0 for i in range(3): for j in range(3): keyMatrix[i][j] = ord(key[k]) % 65 k += 1 # Following function encrypts the messagedef encrypt(messageVector): for i in range(3): for j in range(1): cipherMatrix[i][j] = 0 for x in range(3): cipherMatrix[i][j] += (keyMatrix[i][x] * messageVector[x][j]) cipherMatrix[i][j] = cipherMatrix[i][j] % 26 def HillCipher(message, key): # Get key matrix from the key string getKeyMatrix(key) # Generate vector for the message for i in range(3): messageVector[i][0] = ord(message[i]) % 65 # Following function generates # the encrypted vector encrypt(messageVector) # Generate the encrypted text # from the encrypted vector CipherText = [] for i in range(3): CipherText.append(chr(cipherMatrix[i][0] + 65)) # Finally print the ciphertext print("Ciphertext: ", "".join(CipherText)) # Driver Codedef main(): # Get the message to # be encrypted message = "ACT" # Get the key key = "GYBNQKURP" HillCipher(message, key) if __name__ == "__main__": main() # This code is contributed# by Pratik Somwanshi // C# code to implement Hill Cipherusing System; class GFG{ // Following function generates the// key matrix for the key stringstatic void getKeyMatrix(String key, int [,]keyMatrix){ int k = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { keyMatrix[i, j] = (key[k]) % 65; k++; } }} // Following function encrypts the messagestatic void encrypt(int [,]cipherMatrix, int [,]keyMatrix, int [,]messageVector){ int x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i, j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i, j] += keyMatrix[i, x] * messageVector[x, j]; } cipherMatrix[i, j] = cipherMatrix[i, j] % 26; } }} // Function to implement Hill Cipherstatic void HillCipher(String message, String key){ // Get key matrix from the key string int [,]keyMatrix = new int[3, 3]; getKeyMatrix(key, keyMatrix); int [,]messageVector = new int[3, 1]; // Generate vector for the message for (int i = 0; i < 3; i++) messageVector[i, 0] = (message[i]) % 65; int [,]cipherMatrix = new int[3, 1]; // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); String CipherText = ""; // Generate the encrypted text from // the encrypted vector for (int i = 0; i < 3; i++) CipherText += (char)(cipherMatrix[i, 0] + 65); // Finally print the ciphertext Console.Write("Ciphertext: " + CipherText);} // Driver codepublic static void Main(String[] args){ // Get the message to be encrypted String message = "ACT"; // Get the key String key = "GYBNQKURP"; HillCipher(message, key);}} // This code is contributed by Rajput-Ji <script>// Javascript code to implement Hill Cipher // Following function generates the// key matrix for the key stringfunction getKeyMatrix(key,keyMatrix){ let k = 0; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { keyMatrix[i][j] = (key[k]).charCodeAt(0) % 65; k++; } }} // Following function encrypts the messagefunction encrypt(cipherMatrix,keyMatrix,messageVector){ let x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i][j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j]; } cipherMatrix[i][j] = cipherMatrix[i][j] % 26; } }} // Function to implement Hill Cipherfunction HillCipher(message, key){ // Get key matrix from the key string let keyMatrix = new Array(3); for(let i=0;i<3;i++) { keyMatrix[i]=new Array(3); for(let j=0;j<3;j++) keyMatrix[i][j]=0; } getKeyMatrix(key, keyMatrix); let messageVector = new Array(3); for(let i=0;i<3;i++) { messageVector[i]=new Array(1); messageVector[i][0]=0; } // Generate vector for the message for (let i = 0; i < 3; i++) messageVector[i][0] = (message[i]).charCodeAt(0) % 65; let cipherMatrix = new Array(3); for(let i=0;i<3;i++) { cipherMatrix[i]=new Array(1); cipherMatrix[i][0]=0; } // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); let CipherText=""; // Generate the encrypted text from // the encrypted vector for (let i = 0; i < 3; i++) CipherText += String.fromCharCode(cipherMatrix[i][0] + 65); // Finally print the ciphertext document.write(" Ciphertext: " + CipherText);} // Driver code// Get the message to be encryptedlet message = "ACT"; // Get the keylet key = "GYBNQKURP"; HillCipher(message, key); // This code is contributed by rag2127</script> Output: Ciphertext: POH In a similar way you can write the code for decrypting the encrypted message by following the steps explained above. Reference: https://en.wikipedia.org/wiki/Hill_cipher PratikSomwanshi 29AjayKumar Rajput-Ji Akanksha_Rai rag2127 cryptography secure-coding Strings Technical Scripter Strings cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Length of the longest substring without repeating characters Convert string to char array in C++ Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Reverse words in a given string What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Reverse string in Python (6 different ways) Remove duplicates from a given string Array of Strings in C++ - 5 Different Ways to Create
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jul, 2021" }, { "code": null, "e": 682, "s": 52, "text": "Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is represented by a number modulo 26. Often the simple scheme A = 0, B = 1, ..., Z = 25 is used, but this is not an essential feature of the cipher. To encrypt a message, each block of n letters (considered as an n-component vector) is multiplied by an invertible n × n matrix, against modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.The matrix used for encryption is the cipher key, and it should be chosen randomly from the set of invertible n × n matrices (modulo 26).Examples: " }, { "code": null, "e": 755, "s": 682, "text": "Input : Plaintext: ACT\n Key: GYBNQKURP\nOutput : Ciphertext: POH" }, { "code": null, "e": 831, "s": 757, "text": "Input : Plaintext: GFG\n Key: HILLMAGIC \nOutput : Ciphertext: SWK" }, { "code": null, "e": 844, "s": 833, "text": "Encryption" }, { "code": null, "e": 952, "s": 844, "text": "We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be written as the nxn matrix: " }, { "code": null, "e": 994, "s": 952, "text": "The message ‘ACT’ is written as vector: " }, { "code": null, "e": 1031, "s": 994, "text": "The enciphered vector is given as: " }, { "code": null, "e": 1074, "s": 1031, "text": "which corresponds to ciphertext of ‘POH’ " }, { "code": null, "e": 1085, "s": 1074, "text": "Decryption" }, { "code": null, "e": 1297, "s": 1085, "text": "To decrypt the message, we turn the ciphertext back into a vector, then simply multiply by the inverse matrix of the key matrix (IFKVIVVMI in letters).The inverse of the matrix used in the previous example is: " }, { "code": null, "e": 1334, "s": 1297, "text": "For the previous Ciphertext ‘POH’: " }, { "code": null, "e": 1467, "s": 1334, "text": "which gives us back ‘ACT’. Assume that all the alphabets are in upper case. Below is the implementation of the above idea for n=3. " }, { "code": null, "e": 1471, "s": 1467, "text": "C++" }, { "code": null, "e": 1476, "s": 1471, "text": "Java" }, { "code": null, "e": 1484, "s": 1476, "text": "Python3" }, { "code": null, "e": 1487, "s": 1484, "text": "C#" }, { "code": null, "e": 1498, "s": 1487, "text": "Javascript" }, { "code": "// C++ code to implement Hill Cipher#include <iostream>using namespace std; // Following function generates the// key matrix for the key stringvoid getKeyMatrix(string key, int keyMatrix[][3]){ int k = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { keyMatrix[i][j] = (key[k]) % 65; k++; } }} // Following function encrypts the messagevoid encrypt(int cipherMatrix[][1], int keyMatrix[][3], int messageVector[][1]){ int x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i][j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j]; } cipherMatrix[i][j] = cipherMatrix[i][j] % 26; } }} // Function to implement Hill Ciphervoid HillCipher(string message, string key){ // Get key matrix from the key string int keyMatrix[3][3]; getKeyMatrix(key, keyMatrix); int messageVector[3][1]; // Generate vector for the message for (int i = 0; i < 3; i++) messageVector[i][0] = (message[i]) % 65; int cipherMatrix[3][1]; // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); string CipherText; // Generate the encrypted text from // the encrypted vector for (int i = 0; i < 3; i++) CipherText += cipherMatrix[i][0] + 65; // Finally print the ciphertext cout << \" Ciphertext:\" << CipherText;} // Driver function for above codeint main(){ // Get the message to be encrypted string message = \"ACT\"; // Get the key string key = \"GYBNQKURP\"; HillCipher(message, key); return 0;}", "e": 3298, "s": 1498, "text": null }, { "code": "// Java code to implement Hill Cipherclass GFG{ // Following function generates the// key matrix for the key stringstatic void getKeyMatrix(String key, int keyMatrix[][]){ int k = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { keyMatrix[i][j] = (key.charAt(k)) % 65; k++; } }} // Following function encrypts the messagestatic void encrypt(int cipherMatrix[][], int keyMatrix[][], int messageVector[][]){ int x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i][j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j]; } cipherMatrix[i][j] = cipherMatrix[i][j] % 26; } }} // Function to implement Hill Cipherstatic void HillCipher(String message, String key){ // Get key matrix from the key string int [][]keyMatrix = new int[3][3]; getKeyMatrix(key, keyMatrix); int [][]messageVector = new int[3][1]; // Generate vector for the message for (int i = 0; i < 3; i++) messageVector[i][0] = (message.charAt(i)) % 65; int [][]cipherMatrix = new int[3][1]; // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); String CipherText=\"\"; // Generate the encrypted text from // the encrypted vector for (int i = 0; i < 3; i++) CipherText += (char)(cipherMatrix[i][0] + 65); // Finally print the ciphertext System.out.print(\" Ciphertext:\" + CipherText);} // Driver codepublic static void main(String[] args){ // Get the message to be encrypted String message = \"ACT\"; // Get the key String key = \"GYBNQKURP\"; HillCipher(message, key); }} // This code has been contributed by 29AjayKumar", "e": 5206, "s": 3298, "text": null }, { "code": "# Python3 code to implement Hill Cipher keyMatrix = [[0] * 3 for i in range(3)] # Generate vector for the messagemessageVector = [[0] for i in range(3)] # Generate vector for the ciphercipherMatrix = [[0] for i in range(3)] # Following function generates the# key matrix for the key stringdef getKeyMatrix(key): k = 0 for i in range(3): for j in range(3): keyMatrix[i][j] = ord(key[k]) % 65 k += 1 # Following function encrypts the messagedef encrypt(messageVector): for i in range(3): for j in range(1): cipherMatrix[i][j] = 0 for x in range(3): cipherMatrix[i][j] += (keyMatrix[i][x] * messageVector[x][j]) cipherMatrix[i][j] = cipherMatrix[i][j] % 26 def HillCipher(message, key): # Get key matrix from the key string getKeyMatrix(key) # Generate vector for the message for i in range(3): messageVector[i][0] = ord(message[i]) % 65 # Following function generates # the encrypted vector encrypt(messageVector) # Generate the encrypted text # from the encrypted vector CipherText = [] for i in range(3): CipherText.append(chr(cipherMatrix[i][0] + 65)) # Finally print the ciphertext print(\"Ciphertext: \", \"\".join(CipherText)) # Driver Codedef main(): # Get the message to # be encrypted message = \"ACT\" # Get the key key = \"GYBNQKURP\" HillCipher(message, key) if __name__ == \"__main__\": main() # This code is contributed# by Pratik Somwanshi", "e": 6762, "s": 5206, "text": null }, { "code": "// C# code to implement Hill Cipherusing System; class GFG{ // Following function generates the// key matrix for the key stringstatic void getKeyMatrix(String key, int [,]keyMatrix){ int k = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { keyMatrix[i, j] = (key[k]) % 65; k++; } }} // Following function encrypts the messagestatic void encrypt(int [,]cipherMatrix, int [,]keyMatrix, int [,]messageVector){ int x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i, j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i, j] += keyMatrix[i, x] * messageVector[x, j]; } cipherMatrix[i, j] = cipherMatrix[i, j] % 26; } }} // Function to implement Hill Cipherstatic void HillCipher(String message, String key){ // Get key matrix from the key string int [,]keyMatrix = new int[3, 3]; getKeyMatrix(key, keyMatrix); int [,]messageVector = new int[3, 1]; // Generate vector for the message for (int i = 0; i < 3; i++) messageVector[i, 0] = (message[i]) % 65; int [,]cipherMatrix = new int[3, 1]; // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); String CipherText = \"\"; // Generate the encrypted text from // the encrypted vector for (int i = 0; i < 3; i++) CipherText += (char)(cipherMatrix[i, 0] + 65); // Finally print the ciphertext Console.Write(\"Ciphertext: \" + CipherText);} // Driver codepublic static void Main(String[] args){ // Get the message to be encrypted String message = \"ACT\"; // Get the key String key = \"GYBNQKURP\"; HillCipher(message, key);}} // This code is contributed by Rajput-Ji", "e": 8711, "s": 6762, "text": null }, { "code": "<script>// Javascript code to implement Hill Cipher // Following function generates the// key matrix for the key stringfunction getKeyMatrix(key,keyMatrix){ let k = 0; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { keyMatrix[i][j] = (key[k]).charCodeAt(0) % 65; k++; } }} // Following function encrypts the messagefunction encrypt(cipherMatrix,keyMatrix,messageVector){ let x, i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 1; j++) { cipherMatrix[i][j] = 0; for (x = 0; x < 3; x++) { cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j]; } cipherMatrix[i][j] = cipherMatrix[i][j] % 26; } }} // Function to implement Hill Cipherfunction HillCipher(message, key){ // Get key matrix from the key string let keyMatrix = new Array(3); for(let i=0;i<3;i++) { keyMatrix[i]=new Array(3); for(let j=0;j<3;j++) keyMatrix[i][j]=0; } getKeyMatrix(key, keyMatrix); let messageVector = new Array(3); for(let i=0;i<3;i++) { messageVector[i]=new Array(1); messageVector[i][0]=0; } // Generate vector for the message for (let i = 0; i < 3; i++) messageVector[i][0] = (message[i]).charCodeAt(0) % 65; let cipherMatrix = new Array(3); for(let i=0;i<3;i++) { cipherMatrix[i]=new Array(1); cipherMatrix[i][0]=0; } // Following function generates // the encrypted vector encrypt(cipherMatrix, keyMatrix, messageVector); let CipherText=\"\"; // Generate the encrypted text from // the encrypted vector for (let i = 0; i < 3; i++) CipherText += String.fromCharCode(cipherMatrix[i][0] + 65); // Finally print the ciphertext document.write(\" Ciphertext: \" + CipherText);} // Driver code// Get the message to be encryptedlet message = \"ACT\"; // Get the keylet key = \"GYBNQKURP\"; HillCipher(message, key); // This code is contributed by rag2127</script>", "e": 10819, "s": 8711, "text": null }, { "code": null, "e": 10829, "s": 10819, "text": "Output: " }, { "code": null, "e": 10845, "s": 10829, "text": "Ciphertext: POH" }, { "code": null, "e": 11016, "s": 10845, "text": "In a similar way you can write the code for decrypting the encrypted message by following the steps explained above. Reference: https://en.wikipedia.org/wiki/Hill_cipher " }, { "code": null, "e": 11032, "s": 11016, "text": "PratikSomwanshi" }, { "code": null, "e": 11044, "s": 11032, "text": "29AjayKumar" }, { "code": null, "e": 11054, "s": 11044, "text": "Rajput-Ji" }, { "code": null, "e": 11067, "s": 11054, "text": "Akanksha_Rai" }, { "code": null, "e": 11075, "s": 11067, "text": "rag2127" }, { "code": null, "e": 11088, "s": 11075, "text": "cryptography" }, { "code": null, "e": 11102, "s": 11088, "text": "secure-coding" }, { "code": null, "e": 11110, "s": 11102, "text": "Strings" }, { "code": null, "e": 11129, "s": 11110, "text": "Technical Scripter" }, { "code": null, "e": 11137, "s": 11129, "text": "Strings" }, { "code": null, "e": 11150, "s": 11137, "text": "cryptography" }, { "code": null, "e": 11248, "s": 11150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11309, "s": 11248, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 11345, "s": 11309, "text": "Convert string to char array in C++" }, { "code": null, "e": 11397, "s": 11345, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 11442, "s": 11397, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 11474, "s": 11442, "text": "Reverse words in a given string" }, { "code": null, "e": 11538, "s": 11474, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11583, "s": 11538, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 11627, "s": 11583, "text": "Reverse string in Python (6 different ways)" }, { "code": null, "e": 11665, "s": 11627, "text": "Remove duplicates from a given string" } ]
Print characters and their frequencies in order of occurrence in C++
This problem, We are given a string of lowercase characters. and we have to find the frequencies of each character that occurs in the string. the below example when explaining more about the problem. Input : “jskdk” Output : j 1 s 1 k 2 d 1 Explanation − In the String, the characters j, s, d occur once and k occurs twice. Hence, the output printed gives the above result. Now let's create a logic to solve this problem. As stated we have to find the frequency of occurrence of each character in the string. One logical way is to traverse the string and count the frequency of occurrence of a character and store it in an array and then print the character along with their frequency of occurrence. Step 1 : Create an array of size 26 that stores the frequency of characters in the string. Step 2 : print all the characters along with their frequency of occurrence from the array. Now, let’s create a program to find the solution to this problem, Live Demo #include <bits/stdc++.h> using namespace std; int main(){ string str = "tutorialspoint"; int n = str.size(); int frequency[26]; memset(frequency, 0, sizeof(frequency)); for (int i = 0; i < n; i++) frequency[str[i] - 'a']++; for (int i = 0; i < n; i++) { if (frequency[str[i] - 'a'] != 0) { cout<<str[i]<<"\t"<<frequency[str[i] - 'a']<<"\n"; frequency[str[i] - 'a'] = 0; } } return 0; } t 3 u 1 o 2 r 1 i 2 a 1 l 1 s 1 p 1 n 1
[ { "code": null, "e": 1262, "s": 1062, "text": "This problem, We are given a string of lowercase characters. and we have to find the frequencies of each character that occurs in the string. the below example when explaining more about the problem." }, { "code": null, "e": 1303, "s": 1262, "text": "Input : “jskdk”\nOutput :\nj 1\ns 1\nk 2\nd 1" }, { "code": null, "e": 1436, "s": 1303, "text": "Explanation − In the String, the characters j, s, d occur once and k occurs twice. Hence, the output printed gives the above result." }, { "code": null, "e": 1762, "s": 1436, "text": "Now let's create a logic to solve this problem. As stated we have to find the frequency of occurrence of each character in the string. One logical way is to traverse the string and count the frequency of occurrence of a character and store it in an array and then print the character along with their frequency of occurrence." }, { "code": null, "e": 1944, "s": 1762, "text": "Step 1 : Create an array of size 26 that stores the frequency of characters in the string.\nStep 2 : print all the characters along with their frequency of occurrence from the array." }, { "code": null, "e": 2010, "s": 1944, "text": "Now, let’s create a program to find the solution to this problem," }, { "code": null, "e": 2021, "s": 2010, "text": " Live Demo" }, { "code": null, "e": 2467, "s": 2021, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n string str = \"tutorialspoint\";\n int n = str.size();\n int frequency[26];\n memset(frequency, 0, sizeof(frequency));\n for (int i = 0; i < n; i++)\n frequency[str[i] - 'a']++;\n for (int i = 0; i < n; i++) {\n if (frequency[str[i] - 'a'] != 0) {\n cout<<str[i]<<\"\\t\"<<frequency[str[i] - 'a']<<\"\\n\";\n frequency[str[i] - 'a'] = 0;\n }\n }\n return 0;\n}" }, { "code": null, "e": 2507, "s": 2467, "text": "t 3\nu 1\no 2\nr 1\ni 2\na 1\nl 1\ns 1\np 1\nn 1" } ]
How to Delete Tkinter Text Box's Contents?
Tkinter provides many functions and modules through which we can create fully featured applications with buttons, dialogue boxes, widgets, and many more. To create a text widget, we can use the tkinter entry widget function which is basically a constructor and it takes the window or frame of the tkinter. Further, we can delete the content of this text widget using the built-in method delete(first, last=None) which basically takes a range within the textbox. In this example, we will create a Delete Button which basically deletes all the contents from the given text box. from tkinter import * win= Tk() win.geometry("600x300") label= Label(win, text= "Write something ??", font= ('Helvetica', 25)) label.pack(pady=20) #Create a Text Widget text= Text(win, height=10) text.pack() def delete(): text.delete("1.0","end") #Create a Delete Button to remove the Text from the text-widget b1= Button(win, text= "Delete",command= delete) b1.pack(pady=10) win.mainloop() Running the above code will create a text widget and a delete button which can be used to delete the contents written in the text box. Type something inside the textbox, and then, click the “Delete” button. It will erase the content inside the textbox.
[ { "code": null, "e": 1216, "s": 1062, "text": "Tkinter provides many functions and modules through which we can create fully\nfeatured applications with buttons, dialogue boxes, widgets, and many more." }, { "code": null, "e": 1524, "s": 1216, "text": "To create a text widget, we can use the tkinter entry widget function which is basically a constructor and it takes the window or frame of the tkinter. Further, we can delete the content of this text widget using the built-in method delete(first,\nlast=None) which basically takes a range within the textbox." }, { "code": null, "e": 1638, "s": 1524, "text": "In this example, we will create a Delete Button which basically deletes all the\ncontents from the given text box." }, { "code": null, "e": 2038, "s": 1638, "text": "from tkinter import *\n\nwin= Tk()\nwin.geometry(\"600x300\")\n\nlabel= Label(win, text= \"Write something ??\", font= ('Helvetica', 25))\nlabel.pack(pady=20)\n\n#Create a Text Widget\ntext= Text(win, height=10)\ntext.pack()\n\ndef delete():\n text.delete(\"1.0\",\"end\")\n\n#Create a Delete Button to remove the Text from the text-widget\n\nb1= Button(win, text= \"Delete\",command= delete)\nb1.pack(pady=10)\nwin.mainloop()" }, { "code": null, "e": 2173, "s": 2038, "text": "Running the above code will create a text widget and a delete button which can be\nused to delete the contents written in the text box." }, { "code": null, "e": 2291, "s": 2173, "text": "Type something inside the textbox, and then, click the “Delete” button. It will erase\nthe content inside the textbox." } ]
Colab on steroids: free GPU instances with SSH access and Visual Studio Code Server | Towards Data Science
As most of you already know, Google Research offers free instances of Jupyter Notebook environment, with GPU and TPU, that runs entirely in the cloud. The platform is called Colaboratory (“Colab” for short) and it is a great resource when you want to perform quick experiments or prototype new machine learning models because no setup is required: all you need is a browser! However, a simple Jupyter Notebook interface could be quite limiting when things get tough: we could need to have a SSH session! Let’s do it! Sign up for free on ngrok and get an Authtoken from the authentication setting on the left. Inside a notebook cell in Colab copy and paste the code below, insert your token from ngrok and run the cell. # Install useful stuff! apt install --yes ssh screen nano htop ranger git > /dev/null# SSH setting! echo "root:carbonara" | chpasswd! echo "PasswordAuthentication yes" > /etc/ssh/sshd_config! echo "PermitUserEnvironment yes" >> /etc/ssh/sshd_config! echo "PermitRootLogin yes" >> /etc/ssh/sshd_config! service ssh restart > /dev/null# Download ngrok! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip! unzip -qq -n ngrok-stable-linux-amd64.zip# Run ngrokauthtoken = "PUT_YOUR_TOKEN_HERE"get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')! sleep 3# Get the address for SSHimport requestsfrom re import subr = requests.get('http://localhost:4040/api/tunnels')str_ssh = r.json()['tunnels'][0]['public_url']str_ssh = sub("tcp://", "", str_ssh)str_ssh = sub(":", " -p ", str_ssh)str_ssh = "ssh root@" + str_sshprint(str_ssh) As output, you should receive something like (the address and the port could be different): ssh root@0.tcp.ngrok.io -p 14407 Copy and paste it in your preferred terminal emulator, insert carbonara when a password is required and enjoy your SSH session! Of course, you can change the password with whatever you want! Not used to Linux command line? Check this post: Basic Linux Console Commands Every Data Scientist Should Know. SSH is fine but having a complete code editor directly in your browser is better! Let’s see now how to install Visual Studio Code in Colab instance. Firstly, we need to mount our Google Drive. # Mount Google Drive and make some folders for vscodefrom google.colab import drivedrive.mount('/googledrive')! mkdir -p /googledrive/My\ Drive/colabdrive! mkdir -p /googledrive/My\ Drive/colabdrive/root/.local/share/code-server! ln -s /googledrive/My\ Drive/colabdrive /! ln -s /googledrive/My\ Drive/colabdrive/root/.local/share/code-server /root/.local/share/ You will be prompted to authorize the access by inserting a token generated on a second page. Now, let’s download, install and run the server version of Visual Studio Code. ! curl -fsSL https://code-server.dev/install.sh | sh > /dev/null! code-server --bind-addr 127.0.0.1:9999 --auth none & Let’s start another SSH session with port forwarding (substitute the ngrok address and port with yours): ssh -L 9999:localhost:9999 root@0.tcp.ngrok.io -p 14407 then open your browser at http://127.0.0.1:9999 Since we have mounted Google Drive before, settings, extensions of Visual Studio Code and project files (if saved under /colabdrive) will persist through sessions. Enjoy Visual Studio Code in Colab! https://gist.github.com/yashkumaratri/204755a85977586cebbb58dc971496da https://stackoverflow.com/questions/48459804/how-can-i-ssh-to-google-colaboratory-vm https://medium.com/@meet_patel/how-to-ssh-into-google-colab-and-run-scripts-from-terminal-instead-of-jupyter-notebook-3931f2674258 Contacts: LinkedIn | Twitter
[ { "code": null, "e": 547, "s": 172, "text": "As most of you already know, Google Research offers free instances of Jupyter Notebook environment, with GPU and TPU, that runs entirely in the cloud. The platform is called Colaboratory (“Colab” for short) and it is a great resource when you want to perform quick experiments or prototype new machine learning models because no setup is required: all you need is a browser!" }, { "code": null, "e": 689, "s": 547, "text": "However, a simple Jupyter Notebook interface could be quite limiting when things get tough: we could need to have a SSH session! Let’s do it!" }, { "code": null, "e": 781, "s": 689, "text": "Sign up for free on ngrok and get an Authtoken from the authentication setting on the left." }, { "code": null, "e": 891, "s": 781, "text": "Inside a notebook cell in Colab copy and paste the code below, insert your token from ngrok and run the cell." }, { "code": null, "e": 1768, "s": 891, "text": "# Install useful stuff! apt install --yes ssh screen nano htop ranger git > /dev/null# SSH setting! echo \"root:carbonara\" | chpasswd! echo \"PasswordAuthentication yes\" > /etc/ssh/sshd_config! echo \"PermitUserEnvironment yes\" >> /etc/ssh/sshd_config! echo \"PermitRootLogin yes\" >> /etc/ssh/sshd_config! service ssh restart > /dev/null# Download ngrok! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip! unzip -qq -n ngrok-stable-linux-amd64.zip# Run ngrokauthtoken = \"PUT_YOUR_TOKEN_HERE\"get_ipython().system_raw('./ngrok authtoken $authtoken && ./ngrok tcp 22 &')! sleep 3# Get the address for SSHimport requestsfrom re import subr = requests.get('http://localhost:4040/api/tunnels')str_ssh = r.json()['tunnels'][0]['public_url']str_ssh = sub(\"tcp://\", \"\", str_ssh)str_ssh = sub(\":\", \" -p \", str_ssh)str_ssh = \"ssh root@\" + str_sshprint(str_ssh)" }, { "code": null, "e": 1860, "s": 1768, "text": "As output, you should receive something like (the address and the port could be different):" }, { "code": null, "e": 1893, "s": 1860, "text": "ssh root@0.tcp.ngrok.io -p 14407" }, { "code": null, "e": 2084, "s": 1893, "text": "Copy and paste it in your preferred terminal emulator, insert carbonara when a password is required and enjoy your SSH session! Of course, you can change the password with whatever you want!" }, { "code": null, "e": 2196, "s": 2084, "text": "Not used to Linux command line? Check this post: Basic Linux Console Commands Every Data Scientist Should Know." }, { "code": null, "e": 2345, "s": 2196, "text": "SSH is fine but having a complete code editor directly in your browser is better! Let’s see now how to install Visual Studio Code in Colab instance." }, { "code": null, "e": 2389, "s": 2345, "text": "Firstly, we need to mount our Google Drive." }, { "code": null, "e": 2752, "s": 2389, "text": "# Mount Google Drive and make some folders for vscodefrom google.colab import drivedrive.mount('/googledrive')! mkdir -p /googledrive/My\\ Drive/colabdrive! mkdir -p /googledrive/My\\ Drive/colabdrive/root/.local/share/code-server! ln -s /googledrive/My\\ Drive/colabdrive /! ln -s /googledrive/My\\ Drive/colabdrive/root/.local/share/code-server /root/.local/share/" }, { "code": null, "e": 2846, "s": 2752, "text": "You will be prompted to authorize the access by inserting a token generated on a second page." }, { "code": null, "e": 2925, "s": 2846, "text": "Now, let’s download, install and run the server version of Visual Studio Code." }, { "code": null, "e": 3044, "s": 2925, "text": "! curl -fsSL https://code-server.dev/install.sh | sh > /dev/null! code-server --bind-addr 127.0.0.1:9999 --auth none &" }, { "code": null, "e": 3149, "s": 3044, "text": "Let’s start another SSH session with port forwarding (substitute the ngrok address and port with yours):" }, { "code": null, "e": 3205, "s": 3149, "text": "ssh -L 9999:localhost:9999 root@0.tcp.ngrok.io -p 14407" }, { "code": null, "e": 3253, "s": 3205, "text": "then open your browser at http://127.0.0.1:9999" }, { "code": null, "e": 3417, "s": 3253, "text": "Since we have mounted Google Drive before, settings, extensions of Visual Studio Code and project files (if saved under /colabdrive) will persist through sessions." }, { "code": null, "e": 3452, "s": 3417, "text": "Enjoy Visual Studio Code in Colab!" }, { "code": null, "e": 3523, "s": 3452, "text": "https://gist.github.com/yashkumaratri/204755a85977586cebbb58dc971496da" }, { "code": null, "e": 3608, "s": 3523, "text": "https://stackoverflow.com/questions/48459804/how-can-i-ssh-to-google-colaboratory-vm" }, { "code": null, "e": 3739, "s": 3608, "text": "https://medium.com/@meet_patel/how-to-ssh-into-google-colab-and-run-scripts-from-terminal-instead-of-jupyter-notebook-3931f2674258" } ]
Bitwise ORs of Subarrays in C++
Suppose we have an array A of non-negative integers. For every (contiguous) subarray say B = [A[i], A[i+1], ..., A[j]] (with i <= j), we will do the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j]. We have to find the number of possible results. (Results that occur more than once are only counted once in the final answer.) So if the input is like [1,1,2], then the result will be 3 as subarrays are [1], [1], [2], [1,1], [1,2], [1,1,2], then the results will be 1,1,2,1,3,3, then there are three distinct results. To solve this, we will follow these steps − Create two sets ret and curr2 Create two sets ret and curr2 for i in range 0 to size of arraymake a set curr1, insert A[i] into itfor each element e in curr2 −insert (e OR A[i]) into curr1for each element e curr1insert e in retcurr2 := curr1 for i in range 0 to size of array make a set curr1, insert A[i] into it make a set curr1, insert A[i] into it for each element e in curr2 −insert (e OR A[i]) into curr1 for each element e in curr2 − insert (e OR A[i]) into curr1 insert (e OR A[i]) into curr1 for each element e curr1insert e in ret for each element e curr1 insert e in ret insert e in ret curr2 := curr1 curr2 := curr1 return size of ret return size of ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int subarrayBitwiseORs(vector<int>& A) { unordered_set <int> ret; unordered_set <int> curr2; for(int i = 0; i < A.size(); i++){ unordered_set <int> curr1; curr1.insert(A[i]); unordered_set<int>::iterator it = curr2.begin(); while(it != curr2.end()){ curr1.insert(*it | A[i]); it++; } it = curr1.begin(); while(it != curr1.end()){ ret.insert(*it); it++; } curr2 = curr1; } return ret.size(); } }; main(){ vector<int> v = {1,1,2}; Solution ob; cout << (ob.subarrayBitwiseORs(v)); } [1,1,2] 3
[ { "code": null, "e": 1422, "s": 1062, "text": "Suppose we have an array A of non-negative integers. For every (contiguous) subarray say B = [A[i], A[i+1], ..., A[j]] (with i <= j), we will do the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j]. We have to find the number of possible results. (Results that occur more than once are only counted once in the final answer.)" }, { "code": null, "e": 1613, "s": 1422, "text": "So if the input is like [1,1,2], then the result will be 3 as subarrays are [1], [1], [2], [1,1], [1,2], [1,1,2], then the results will be 1,1,2,1,3,3, then there are three distinct results." }, { "code": null, "e": 1657, "s": 1613, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1687, "s": 1657, "text": "Create two sets ret and curr2" }, { "code": null, "e": 1717, "s": 1687, "text": "Create two sets ret and curr2" }, { "code": null, "e": 1899, "s": 1717, "text": "for i in range 0 to size of arraymake a set curr1, insert A[i] into itfor each element e in curr2 −insert (e OR A[i]) into curr1for each element e curr1insert e in retcurr2 := curr1" }, { "code": null, "e": 1933, "s": 1899, "text": "for i in range 0 to size of array" }, { "code": null, "e": 1971, "s": 1933, "text": "make a set curr1, insert A[i] into it" }, { "code": null, "e": 2009, "s": 1971, "text": "make a set curr1, insert A[i] into it" }, { "code": null, "e": 2068, "s": 2009, "text": "for each element e in curr2 −insert (e OR A[i]) into curr1" }, { "code": null, "e": 2098, "s": 2068, "text": "for each element e in curr2 −" }, { "code": null, "e": 2128, "s": 2098, "text": "insert (e OR A[i]) into curr1" }, { "code": null, "e": 2158, "s": 2128, "text": "insert (e OR A[i]) into curr1" }, { "code": null, "e": 2198, "s": 2158, "text": "for each element e curr1insert e in ret" }, { "code": null, "e": 2223, "s": 2198, "text": "for each element e curr1" }, { "code": null, "e": 2239, "s": 2223, "text": "insert e in ret" }, { "code": null, "e": 2255, "s": 2239, "text": "insert e in ret" }, { "code": null, "e": 2270, "s": 2255, "text": "curr2 := curr1" }, { "code": null, "e": 2285, "s": 2270, "text": "curr2 := curr1" }, { "code": null, "e": 2304, "s": 2285, "text": "return size of ret" }, { "code": null, "e": 2323, "s": 2304, "text": "return size of ret" }, { "code": null, "e": 2393, "s": 2323, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2404, "s": 2393, "text": " Live Demo" }, { "code": null, "e": 3132, "s": 2404, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int subarrayBitwiseORs(vector<int>& A) {\n unordered_set <int> ret;\n unordered_set <int> curr2;\n for(int i = 0; i < A.size(); i++){\n unordered_set <int> curr1;\n curr1.insert(A[i]);\n unordered_set<int>::iterator it = curr2.begin();\n while(it != curr2.end()){\n curr1.insert(*it | A[i]);\n it++;\n }\n it = curr1.begin();\n while(it != curr1.end()){\n ret.insert(*it);\n it++;\n }\n curr2 = curr1;\n }\n return ret.size();\n }\n};\nmain(){\n vector<int> v = {1,1,2};\n Solution ob;\n cout << (ob.subarrayBitwiseORs(v));\n}" }, { "code": null, "e": 3140, "s": 3132, "text": "[1,1,2]" }, { "code": null, "e": 3142, "s": 3140, "text": "3" } ]
Python - Sum only specific rows of a Pandas Dataframe
To sum only specific rows, use the loc() method. Mention the beginning and end row index using the : operator. Using loc(), you can also set the columns to be included. We can display the result in a new column. At first, let us create a DataFrame. We have Product records in it, including the Opening and Closing Stock − dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) Sum of some rows i.e. 1st two rows. Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock. We are displaying result in a new column “Sum_Result” − dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,["Opening_Stock" , "Closing_Stock"]].sum(axis = 1) Following is the complete code − import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...\n",dataFrame # sum of some rows # Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock # displaying result in a new column Sum_Result dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,["Opening_Stock" , "Closing_Stock"]].sum(axis = 1) print"\nSumming some rows...\n",dataFrame This will produce the following output − DataFrame... Closing_Stock Opening_Stock Product 0 200 300 SmartTV 1 500 700 ChromeCast 2 1000 1200 Speaker 3 900 1500 Earphone Summing some rows... Closing_Stock Opening_Stock Product Sum_Result 0 200 300 SmartTV 500.0 1 500 700 ChromeCast 1200.0 2 1000 1200 Speaker NaN 3 900 1500 Earphone NaN
[ { "code": null, "e": 1274, "s": 1062, "text": "To sum only specific rows, use the loc() method. Mention the beginning and end row index using the : operator. Using loc(), you can also set the columns to be included. We can display the result in a new column." }, { "code": null, "e": 1384, "s": 1274, "text": "At first, let us create a DataFrame. We have Product records in it, including the Opening and Closing Stock −" }, { "code": null, "e": 1553, "s": 1384, "text": "dataFrame = pd.DataFrame({\"Product\": [\"SmartTV\", \"ChromeCast\", \"Speaker\", \"Earphone\"], \"Opening_Stock\": [300, 700, 1200, 1500], \"Closing_Stock\": [200, 500, 1000, 900]})" }, { "code": null, "e": 1724, "s": 1553, "text": "Sum of some rows i.e. 1st two rows. Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock. We are displaying result in a new column “Sum_Result” −" }, { "code": null, "e": 1821, "s": 1724, "text": "dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,[\"Opening_Stock\" , \"Closing_Stock\"]].sum(axis = 1)" }, { "code": null, "e": 1854, "s": 1821, "text": "Following is the complete code −" }, { "code": null, "e": 2363, "s": 1854, "text": "import pandas as pd\n\ndataFrame = pd.DataFrame({\"Product\": [\"SmartTV\", \"ChromeCast\", \"Speaker\", \"Earphone\"], \"Opening_Stock\": [300, 700, 1200, 1500], \"Closing_Stock\": [200, 500, 1000, 900]})\n\nprint\"DataFrame...\\n\",dataFrame\n\n# sum of some rows\n# Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock\n# displaying result in a new column Sum_Result\ndataFrame['Sum_Result'] = dataFrame.loc[0 : 1,[\"Opening_Stock\" , \"Closing_Stock\"]].sum(axis = 1)\nprint\"\\nSumming some rows...\\n\",dataFrame" }, { "code": null, "e": 2404, "s": 2363, "text": "This will produce the following output −" }, { "code": null, "e": 2934, "s": 2404, "text": "DataFrame...\n Closing_Stock Opening_Stock Product\n0 200 300 SmartTV\n1 500 700 ChromeCast\n2 1000 1200 Speaker\n3 900 1500 Earphone\n\nSumming some rows...\n Closing_Stock Opening_Stock Product Sum_Result\n0 200 300 SmartTV 500.0\n1 500 700 ChromeCast 1200.0\n2 1000 1200 Speaker NaN\n3 900 1500 Earphone NaN" } ]
Calculate range of data types using C++
In C++ we have different datatypes like int, char, double etc. In this section we will see how to get the size of them programmatically. We can get the size of datatypes in byte, so we can simply multiply them into 8 to get the values in bits. Now we know that if the number of bits are n, then the minimum range will be – 2^(n-1), and maximum range will be 2^(n-1) – 1 for signed numbers. For unsigned numbers it will be 2^n – 1 as there are no negative numbers. #include <iostream> #include <cmath> #define SIZE(x) sizeof(x) * 8 //Get the size in bits using namespace std; void getRange(string type, int n) { if(type.compare("SIGNED") == 0) { //for signed numbers calculate lower and upper limit int min = pow(2, n - 1); int max = pow(2, n - 1) - 1; cout << "Range from " << (-1) * min << " to " << max <<endl; }else{ //for signed numbers calculate limit from 0 int range = pow(2, n )-1; cout << "Range from 0 to " << range << endl; } } int main() { cout << "For Signed int: "; getRange("SIGNED", SIZE(int)); cout << "For Signed float: "; getRange("SIGNED", SIZE(float)); cout << "For Unsigned int: "; getRange("UNSIGNED", SIZE(unsigned int)); cout << "For Unsigned short: "; getRange("UNSIGNED", SIZE(unsigned short int)); cout << "For Signed char: "; getRange("SIGNED", SIZE(char)); } For Signed int: Range from -2147483648 to 2147483647 For Signed float: Range from -2147483648 to 2147483647 For Unsigned int: Range from 0 to -2147483648 For Unsigned short: Range from 0 to 65535 For Signed char: Range from -128 to 127
[ { "code": null, "e": 1199, "s": 1062, "text": "In C++ we have different datatypes like int, char, double etc. In this section we will see how to get the size of them programmatically." }, { "code": null, "e": 1526, "s": 1199, "text": "We can get the size of datatypes in byte, so we can simply multiply them into 8 to get the values in bits. Now we know that if the number of bits are n, then the minimum range will be – 2^(n-1), and maximum range will be 2^(n-1) – 1 for signed numbers. For unsigned numbers it will be 2^n – 1 as there are no negative numbers." }, { "code": null, "e": 2420, "s": 1526, "text": "#include <iostream>\n#include <cmath>\n#define SIZE(x) sizeof(x) * 8 //Get the size in bits\nusing namespace std;\nvoid getRange(string type, int n) {\n if(type.compare(\"SIGNED\") == 0) { //for signed numbers calculate lower and upper limit\n int min = pow(2, n - 1);\n int max = pow(2, n - 1) - 1;\n cout << \"Range from \" << (-1) * min << \" to \" << max <<endl;\n }else{ //for signed numbers calculate limit from 0\n int range = pow(2, n )-1;\n cout << \"Range from 0 to \" << range << endl;\n }\n}\nint main() {\n cout << \"For Signed int: \";\n getRange(\"SIGNED\", SIZE(int));\n cout << \"For Signed float: \";\n getRange(\"SIGNED\", SIZE(float));\n cout << \"For Unsigned int: \";\n getRange(\"UNSIGNED\", SIZE(unsigned int));\n cout << \"For Unsigned short: \";\n getRange(\"UNSIGNED\", SIZE(unsigned short int));\n cout << \"For Signed char: \";\n getRange(\"SIGNED\", SIZE(char));\n}" }, { "code": null, "e": 2656, "s": 2420, "text": "For Signed int: Range from -2147483648 to 2147483647\nFor Signed float: Range from -2147483648 to 2147483647\nFor Unsigned int: Range from 0 to -2147483648\nFor Unsigned short: Range from 0 to 65535\nFor Signed char: Range from -128 to 127" } ]
Deep Face Recognition
11 Jun, 2021 DeepFace is the facial recognition system used by Facebook for tagging images. It was proposed by researchers at Facebook AI Research (FAIR) at the 2014 IEEE Computer Vision and Pattern Recognition Conference (CVPR). In modern face recognition there are 4 steps: DetectAlignRepresentClassify Detect Align Represent Classify This approach focuses on alignment and representation of facial images. We will discuss these two part in detail. Alignment: The goal of this alignment part is to generate frontal face from the input image that may contain faces from different pose and angles. The method proposed in this paper used 3D frontalization of faces based on the fiducial (face feature points) to extract the frontal face. The whole alignment process is done in the following steps: Given an input image, we first identify the face using six fiducial points. These six fiducial points are 2 eyes, tip of the nose and 3 points on the lips. These feature points are used to detect faces in the image. 6-fiducial points In this step we generate the 2D-face image cropped from the original image using 6 fiducial points. 2D-cropped face In the third step, we apply the 67 fiducial point map with their corresponding Delauney Triangulation on the 2D-aligned cropped image. This step is done in order to align the out of plane rotations. In this step, we also generate a 3D-model using a generic 2D to 3D model generator and plot 67 fiducial points on that manually. 67 fiducial points with Delaunay triangulation 3D shape generated from the align 2D-crop image Visibility map of 2D shape in 3D (darker triangles are less visible as compared to lifgt triangles) Then we try to establish a relation between 2D and 3D using given relation Here to improve this transformation, we need to minimize the loss on which can be calculated by the following relation: where, and ∑ *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty is a covariance matrix and dimensions of (67 x 2) x (67 x 2), X3d *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty is (67 x 2) x 8 and *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty [Tex]\overrightarrow{P} [/Tex] has dimensions of (2 x 4). We are using Cholesky descomposition to convert that loss function into ordinary least square. Here to improve this transformation, we need to minimize the loss on which can be calculated by the following relation: where, and ∑ *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty is a covariance matrix and dimensions of (67 x 2) x (67 x 2), X3d *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty is (67 x 2) x 8 and *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty [Tex]\overrightarrow{P} [/Tex] has dimensions of (2 x 4). We are using Cholesky descomposition to convert that loss function into ordinary least square. 67 ficudial point mapping on 2D-3D affine face. The final stage is frontalization of alignment. But before achieving frontalization we add the residual component to x-y coordinates of 3D warp because it reduces corruption in 3D-warp. Finally, frontalization is achieved by doing piece-wise affine on Delauney triangulation that we generated on 67-fiducial points. final frontalization Representation and Classification Architecture: DeepFace is trained for multi-class face recognition i.e. to classify the images of multiple peoples based on their identities. It takes input into a 3D-aligned RGB image of 152*152. This image is then passed the Convolution layer with 32 filters and size 11*11*3 and a 3*3 max-pooling layer with the stride of 2. This is followed by another convolution layer of 16 filters and size 9*9*16. The purpose of these layers to extract low-level features from the image edges and textures. The next three layers are locally connected layers, a type of fully connected layer that has different types of filters in a different feature map. This helps in improving the model because different regions of the face have different discrimination ability so it is better to have different types of feature maps to distinguish these facial regions. DeepFace full architecture The last two layers of the model are fully connected layers. These layers help in establishing a correlation between two distant parts of the face. Example: Position and shape of eyes and position and shape of the mouth. The output of the second last fully connected layer is used as a face representation and the output of the last layer is the softmax layer K classes for the classification of the face. The total number of parameters in this network is 120 million approximately with most of them (~95%) comes from the final fully connected layers. The interesting property of this network is the feature map/vector generated during the training of this model amazingly sparse. For Example, 75% of the values in topmost layers is 0. This may be because of this network uses ReLU activation function in every convolution network which is essentially max(0, x). This network also uses Drop-out Regularization which also contributed to sparsity. However, Dropout is only applied to the first fully connected layer. In the final stages of this network, we also normalize the feature to be between 0 and 1. This also reduces the effect of illumination changes across. We also perform an L2-regularization after this normalization. Verification Metric: We need to define some metric that measures whether two input images belong to the same class or not. There are two methods: supervised and unsupervised with supervised having better accuracy than unsupervised. It is intuitive because while training on particular target dataset one is able to improve the accuracy by fine-tuning the model according to it. For Example, Labeled Faces in the Wild (LFW) dataset has 75% of faces are male, training on LFW may introduce some bias and add some generalization which is not suitable while testing on other face recognition datasets. However, training using a small dataset may reduce generalization when used on other datasets. In these cases, the unsupervised similarity metric is better. This paper uses the inner product of two feature vectors generated from representation architecture for unsupervised similarity. This paper also uses two supervised verification metrics. These are The Weighted *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty [Tex]\chi ^{2} [/Tex]distance : The Weighted similarity is defined as : where are face representation vector and is weight we can learn using linear SVM. *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty [Tex]\chi ^{2} [/Tex]distance : The Weighted similarity is defined as : where are face representation vector and is weight we can learn using linear SVM. Siamese Network: Siamese network is a very common approach and used to predict whether two faces belong to the same class or not. It calculates the Siamese distance between two face representations if the distance is within tolerance then if the distance is under the tolerance level then it predicts two faces belong to the same class else not. Siamese distance is defined as Training and Results DeepFace is trained and experimented on the following three datasets SFC dataset: This is the dataset generated by Facebook itself. It contains nearly 4.4 million images of 4030 peoples each having 800 to 1200 face images. For the testing purpose, they take 5% most recent images from each class. The model is trained using a standard feed-forward network with SGD with momentum = 0.9, batch size = 128 and the learning rate is the same for all the layer i.e 0.01. The model is trained on three subsets of dataset 1.5k people (1.5 M images), 3k people (3.3 M images) and 4k people (4.4 M images). The classification error rate on these subsets are 7%, 7.2% and 8.7% respectively. LFW dataset: It is one of the most popular datasets in the domain of face recognition. It contains more than 13000 web images of more than 5700 celebrities. The performance is measured using three methods:Restricted method in which the the pair of images provided to model and the goal is to identify whether the image is same or not same.Unrestricted method in which more images than a single pair is accessible to training.Unsupervised method in which the model has not been trained on LFW dataset. Restricted method in which the the pair of images provided to model and the goal is to identify whether the image is same or not same.Unrestricted method in which more images than a single pair is accessible to training.Unsupervised method in which the model has not been trained on LFW dataset. Restricted method in which the the pair of images provided to model and the goal is to identify whether the image is same or not same. Unrestricted method in which more images than a single pair is accessible to training. Unsupervised method in which the model has not been trained on LFW dataset. The results are as follows: Here, DeepFace-ensamble represents combination of different DeepFace-single model that uses different verification metrics we discussed above.As we can conclude that DeepFace-ensemble reach maximum accuracy of 97.35% accuracy which is very close to the human level 97.53% YTF dataset: It contains 3425 videos of 1595 celebrities (a subset of celebrities from LFW). These videos are divided into 5000 video pairs of 10 splits and used to evaluate performance on video level face verification. The results on YTF dataset is as follows: Results on YTF Notice, because of motion blur and other factors the image quality of video datasets is generally worse than images dataset. However, 91.4% is still the state-of-the-art accuracy at that time and reduces the error rate by more than 50%. In terms of testing time, DeepFace takes 0.33 seconds when tested on a single-core 2.2GHz Intel processor. This includes 0.05 seconds taken on alignment and 0.18 seconds on feature extraction. Conclusion: At the time of its publication, It was one of the best face recognition model now of course models such as Google-FaceNet and other models which provide accuracy up to 99.6% on LFW dataset. The main problem the DeepFace has been able to solve is to build a model that is invariant to light effect, pose, facial expression, etc. and that’s why it is used in most of the Facebook’s face recognition tasks. The novel approach to use 3D alignment also contributed to the increase in the accuracy of the model. Reference: DeepFace paper sooda367 Image-Processing Neural Network Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI Intuition of Adam Optimizer
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jun, 2021" }, { "code": null, "e": 272, "s": 54, "text": "DeepFace is the facial recognition system used by Facebook for tagging images. It was proposed by researchers at Facebook AI Research (FAIR) at the 2014 IEEE Computer Vision and Pattern Recognition Conference (CVPR). " }, { "code": null, "e": 319, "s": 272, "text": "In modern face recognition there are 4 steps: " }, { "code": null, "e": 348, "s": 319, "text": "DetectAlignRepresentClassify" }, { "code": null, "e": 355, "s": 348, "text": "Detect" }, { "code": null, "e": 361, "s": 355, "text": "Align" }, { "code": null, "e": 371, "s": 361, "text": "Represent" }, { "code": null, "e": 380, "s": 371, "text": "Classify" }, { "code": null, "e": 495, "s": 380, "text": "This approach focuses on alignment and representation of facial images. We will discuss these two part in detail. " }, { "code": null, "e": 842, "s": 495, "text": "Alignment: The goal of this alignment part is to generate frontal face from the input image that may contain faces from different pose and angles. The method proposed in this paper used 3D frontalization of faces based on the fiducial (face feature points) to extract the frontal face. The whole alignment process is done in the following steps: " }, { "code": null, "e": 1059, "s": 842, "text": "Given an input image, we first identify the face using six fiducial points. These six fiducial points are 2 eyes, tip of the nose and 3 points on the lips. These feature points are used to detect faces in the image. " }, { "code": null, "e": 1077, "s": 1059, "text": "6-fiducial points" }, { "code": null, "e": 1178, "s": 1077, "text": "In this step we generate the 2D-face image cropped from the original image using 6 fiducial points. " }, { "code": null, "e": 1194, "s": 1178, "text": "2D-cropped face" }, { "code": null, "e": 1523, "s": 1194, "text": "In the third step, we apply the 67 fiducial point map with their corresponding Delauney Triangulation on the 2D-aligned cropped image. This step is done in order to align the out of plane rotations. In this step, we also generate a 3D-model using a generic 2D to 3D model generator and plot 67 fiducial points on that manually. " }, { "code": null, "e": 1570, "s": 1523, "text": "67 fiducial points with Delaunay triangulation" }, { "code": null, "e": 1620, "s": 1572, "text": "3D shape generated from the align 2D-crop image" }, { "code": null, "e": 1722, "s": 1622, "text": "Visibility map of 2D shape in 3D (darker triangles are less visible as compared to lifgt triangles)" }, { "code": null, "e": 2477, "s": 1722, "text": "Then we try to establish a relation between 2D and 3D using given relation Here to improve this transformation, we need to minimize the loss on which can be calculated by the following relation: where, and ∑ *** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\nis a covariance matrix and dimensions of (67 x 2) x (67 x 2), X3d *** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\nis (67 x 2) x 8 and *** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n[Tex]\\overrightarrow{P} [/Tex] has dimensions of (2 x 4). We are using Cholesky descomposition to convert that loss function into ordinary least square. " }, { "code": null, "e": 2598, "s": 2477, "text": "Here to improve this transformation, we need to minimize the loss on which can be calculated by the following relation: " }, { "code": null, "e": 2606, "s": 2598, "text": "where, " }, { "code": null, "e": 2613, "s": 2606, "text": "and ∑ " }, { "code": null, "e": 2716, "s": 2613, "text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n" }, { "code": null, "e": 2783, "s": 2716, "text": "is a covariance matrix and dimensions of (67 x 2) x (67 x 2), X3d " }, { "code": null, "e": 2886, "s": 2783, "text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n" }, { "code": null, "e": 2907, "s": 2886, "text": "is (67 x 2) x 8 and " }, { "code": null, "e": 3010, "s": 2907, "text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n" }, { "code": null, "e": 3165, "s": 3010, "text": "[Tex]\\overrightarrow{P} [/Tex] has dimensions of (2 x 4). We are using Cholesky descomposition to convert that loss function into ordinary least square. " }, { "code": null, "e": 3213, "s": 3165, "text": "67 ficudial point mapping on 2D-3D affine face." }, { "code": null, "e": 3530, "s": 3213, "text": "The final stage is frontalization of alignment. But before achieving frontalization we add the residual component to x-y coordinates of 3D warp because it reduces corruption in 3D-warp. Finally, frontalization is achieved by doing piece-wise affine on Delauney triangulation that we generated on 67-fiducial points. " }, { "code": null, "e": 3551, "s": 3530, "text": "final frontalization" }, { "code": null, "e": 4084, "s": 3551, "text": "Representation and Classification Architecture: DeepFace is trained for multi-class face recognition i.e. to classify the images of multiple peoples based on their identities. It takes input into a 3D-aligned RGB image of 152*152. This image is then passed the Convolution layer with 32 filters and size 11*11*3 and a 3*3 max-pooling layer with the stride of 2. This is followed by another convolution layer of 16 filters and size 9*9*16. The purpose of these layers to extract low-level features from the image edges and textures. " }, { "code": null, "e": 4436, "s": 4084, "text": "The next three layers are locally connected layers, a type of fully connected layer that has different types of filters in a different feature map. This helps in improving the model because different regions of the face have different discrimination ability so it is better to have different types of feature maps to distinguish these facial regions. " }, { "code": null, "e": 4463, "s": 4436, "text": "DeepFace full architecture" }, { "code": null, "e": 5693, "s": 4463, "text": "The last two layers of the model are fully connected layers. These layers help in establishing a correlation between two distant parts of the face. Example: Position and shape of eyes and position and shape of the mouth. The output of the second last fully connected layer is used as a face representation and the output of the last layer is the softmax layer K classes for the classification of the face. The total number of parameters in this network is 120 million approximately with most of them (~95%) comes from the final fully connected layers. The interesting property of this network is the feature map/vector generated during the training of this model amazingly sparse. For Example, 75% of the values in topmost layers is 0. This may be because of this network uses ReLU activation function in every convolution network which is essentially max(0, x). This network also uses Drop-out Regularization which also contributed to sparsity. However, Dropout is only applied to the first fully connected layer. In the final stages of this network, we also normalize the feature to be between 0 and 1. This also reduces the effect of illumination changes across. We also perform an L2-regularization after this normalization. " }, { "code": null, "e": 6646, "s": 5693, "text": "Verification Metric: We need to define some metric that measures whether two input images belong to the same class or not. There are two methods: supervised and unsupervised with supervised having better accuracy than unsupervised. It is intuitive because while training on particular target dataset one is able to improve the accuracy by fine-tuning the model according to it. For Example, Labeled Faces in the Wild (LFW) dataset has 75% of faces are male, training on LFW may introduce some bias and add some generalization which is not suitable while testing on other face recognition datasets. However, training using a small dataset may reduce generalization when used on other datasets. In these cases, the unsupervised similarity metric is better. This paper uses the inner product of two feature vectors generated from representation architecture for unsupervised similarity. This paper also uses two supervised verification metrics. These are " }, { "code": null, "e": 6918, "s": 6646, "text": "The Weighted *** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n[Tex]\\chi ^{2} [/Tex]distance : The Weighted similarity is defined as : where are face representation vector and is weight we can learn using linear SVM. " }, { "code": null, "e": 7021, "s": 6918, "text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n" }, { "code": null, "e": 7095, "s": 7021, "text": "[Tex]\\chi ^{2} [/Tex]distance : The Weighted similarity is defined as : " }, { "code": null, "e": 7179, "s": 7095, "text": "where are face representation vector and is weight we can learn using linear SVM. " }, { "code": null, "e": 7558, "s": 7179, "text": "Siamese Network: Siamese network is a very common approach and used to predict whether two faces belong to the same class or not. It calculates the Siamese distance between two face representations if the distance is within tolerance then if the distance is under the tolerance level then it predicts two faces belong to the same class else not. Siamese distance is defined as " }, { "code": null, "e": 7651, "s": 7560, "text": "Training and Results DeepFace is trained and experimented on the following three datasets " }, { "code": null, "e": 8264, "s": 7651, "text": "SFC dataset: This is the dataset generated by Facebook itself. It contains nearly 4.4 million images of 4030 peoples each having 800 to 1200 face images. For the testing purpose, they take 5% most recent images from each class. The model is trained using a standard feed-forward network with SGD with momentum = 0.9, batch size = 128 and the learning rate is the same for all the layer i.e 0.01. The model is trained on three subsets of dataset 1.5k people (1.5 M images), 3k people (3.3 M images) and 4k people (4.4 M images). The classification error rate on these subsets are 7%, 7.2% and 8.7% respectively. " }, { "code": null, "e": 8765, "s": 8264, "text": "LFW dataset: It is one of the most popular datasets in the domain of face recognition. It contains more than 13000 web images of more than 5700 celebrities. The performance is measured using three methods:Restricted method in which the the pair of images provided to model and the goal is to identify whether the image is same or not same.Unrestricted method in which more images than a single pair is accessible to training.Unsupervised method in which the model has not been trained on LFW dataset." }, { "code": null, "e": 9061, "s": 8765, "text": "Restricted method in which the the pair of images provided to model and the goal is to identify whether the image is same or not same.Unrestricted method in which more images than a single pair is accessible to training.Unsupervised method in which the model has not been trained on LFW dataset." }, { "code": null, "e": 9196, "s": 9061, "text": "Restricted method in which the the pair of images provided to model and the goal is to identify whether the image is same or not same." }, { "code": null, "e": 9283, "s": 9196, "text": "Unrestricted method in which more images than a single pair is accessible to training." }, { "code": null, "e": 9359, "s": 9283, "text": "Unsupervised method in which the model has not been trained on LFW dataset." }, { "code": null, "e": 9387, "s": 9359, "text": "The results are as follows:" }, { "code": null, "e": 9659, "s": 9387, "text": "Here, DeepFace-ensamble represents combination of different DeepFace-single model that uses different verification metrics we discussed above.As we can conclude that DeepFace-ensemble reach maximum accuracy of 97.35% accuracy which is very close to the human level 97.53%" }, { "code": null, "e": 9922, "s": 9659, "text": "YTF dataset: It contains 3425 videos of 1595 celebrities (a subset of celebrities from LFW). These videos are divided into 5000 video pairs of 10 splits and used to evaluate performance on video level face verification. The results on YTF dataset is as follows: " }, { "code": null, "e": 9937, "s": 9922, "text": "Results on YTF" }, { "code": null, "e": 10175, "s": 9937, "text": "Notice, because of motion blur and other factors the image quality of video datasets is generally worse than images dataset. However, 91.4% is still the state-of-the-art accuracy at that time and reduces the error rate by more than 50%. " }, { "code": null, "e": 10368, "s": 10175, "text": "In terms of testing time, DeepFace takes 0.33 seconds when tested on a single-core 2.2GHz Intel processor. This includes 0.05 seconds taken on alignment and 0.18 seconds on feature extraction." }, { "code": null, "e": 10887, "s": 10368, "text": "Conclusion: At the time of its publication, It was one of the best face recognition model now of course models such as Google-FaceNet and other models which provide accuracy up to 99.6% on LFW dataset. The main problem the DeepFace has been able to solve is to build a model that is invariant to light effect, pose, facial expression, etc. and that’s why it is used in most of the Facebook’s face recognition tasks. The novel approach to use 3D alignment also contributed to the increase in the accuracy of the model. " }, { "code": null, "e": 10899, "s": 10887, "text": "Reference: " }, { "code": null, "e": 10914, "s": 10899, "text": "DeepFace paper" }, { "code": null, "e": 10925, "s": 10916, "text": "sooda367" }, { "code": null, "e": 10942, "s": 10925, "text": "Image-Processing" }, { "code": null, "e": 10957, "s": 10942, "text": "Neural Network" }, { "code": null, "e": 10974, "s": 10957, "text": "Machine Learning" }, { "code": null, "e": 10991, "s": 10974, "text": "Machine Learning" }, { "code": null, "e": 11089, "s": 10991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11130, "s": 11089, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 11163, "s": 11130, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 11199, "s": 11163, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 11223, "s": 11199, "text": "Markov Decision Process" }, { "code": null, "e": 11274, "s": 11223, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 11307, "s": 11274, "text": "Normalization vs Standardization" }, { "code": null, "e": 11347, "s": 11307, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 11388, "s": 11347, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 11416, "s": 11388, "text": "Types of Environments in AI" } ]
Node.js fs.readFile() Method
12 Oct, 2021 The fs.readFile() method is an inbuilt method which is used to read the file. This method read the entire file into buffer. To load the fs module we use require() method. For example: var fs = require(‘fs’); Syntax: fs.readFile( filename, encoding, callback_function ) Parameters: The method accept three parameters as mentioned above and described below: filename: It holds the name of the file to read or the entire path if stored at other location. encoding: It holds the encoding of file. Its default value is ‘utf8’. callback_function: It is a callback function that is called after reading of file. It takes two parameters:err: If any error occurred.data: Contents of the file. err: If any error occurred. data: Contents of the file. Return Value: It returns the contents/data stored in file or error if any.Below examples illustrate the fs.readFile() method in Node.js:Example 1: javaScript // Node.js program to demonstrate// the fs.readFile() method // Include fs modulevar fs = require('fs'); // Use fs.readFile() method to read the filefs.readFile('Demo.txt', 'utf8', function(err, data){ // Display the file content console.log(data);}); console.log('readFile called'); Output: readFile called undefined Explanation: The output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘readFile called’ statement is printed then the contents of the file are printed.Example 2: javascript // Node.js program to demonstrate// the fs.readFile() method // Include fs modulevar fs = require('fs'); // Use fs.readFile() method to read the filefs.readFile('demo.txt', (err, data) => { console.log(data); }) Output: undefined Reference: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback simmytarika5 surindertarika1234 Node.js-fs-module Picked Node.js 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": "\n12 Oct, 2021" }, { "code": null, "e": 237, "s": 28, "text": "The fs.readFile() method is an inbuilt method which is used to read the file. This method read the entire file into buffer. To load the fs module we use require() method. For example: var fs = require(‘fs’); " }, { "code": null, "e": 247, "s": 237, "text": "Syntax: " }, { "code": null, "e": 300, "s": 247, "text": "fs.readFile( filename, encoding, callback_function )" }, { "code": null, "e": 389, "s": 300, "text": "Parameters: The method accept three parameters as mentioned above and described below: " }, { "code": null, "e": 485, "s": 389, "text": "filename: It holds the name of the file to read or the entire path if stored at other location." }, { "code": null, "e": 555, "s": 485, "text": "encoding: It holds the encoding of file. Its default value is ‘utf8’." }, { "code": null, "e": 717, "s": 555, "text": "callback_function: It is a callback function that is called after reading of file. It takes two parameters:err: If any error occurred.data: Contents of the file." }, { "code": null, "e": 745, "s": 717, "text": "err: If any error occurred." }, { "code": null, "e": 773, "s": 745, "text": "data: Contents of the file." }, { "code": null, "e": 922, "s": 773, "text": "Return Value: It returns the contents/data stored in file or error if any.Below examples illustrate the fs.readFile() method in Node.js:Example 1: " }, { "code": null, "e": 933, "s": 922, "text": "javaScript" }, { "code": "// Node.js program to demonstrate// the fs.readFile() method // Include fs modulevar fs = require('fs'); // Use fs.readFile() method to read the filefs.readFile('Demo.txt', 'utf8', function(err, data){ // Display the file content console.log(data);}); console.log('readFile called');", "e": 1232, "s": 933, "text": null }, { "code": null, "e": 1241, "s": 1232, "text": "Output: " }, { "code": null, "e": 1267, "s": 1241, "text": "readFile called\nundefined" }, { "code": null, "e": 1559, "s": 1267, "text": "Explanation: The output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘readFile called’ statement is printed then the contents of the file are printed.Example 2: " }, { "code": null, "e": 1570, "s": 1559, "text": "javascript" }, { "code": "// Node.js program to demonstrate// the fs.readFile() method // Include fs modulevar fs = require('fs'); // Use fs.readFile() method to read the filefs.readFile('demo.txt', (err, data) => { console.log(data); })", "e": 1787, "s": 1570, "text": null }, { "code": null, "e": 1796, "s": 1787, "text": "Output: " }, { "code": null, "e": 1806, "s": 1796, "text": "undefined" }, { "code": null, "e": 1886, "s": 1806, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback " }, { "code": null, "e": 1899, "s": 1886, "text": "simmytarika5" }, { "code": null, "e": 1918, "s": 1899, "text": "surindertarika1234" }, { "code": null, "e": 1936, "s": 1918, "text": "Node.js-fs-module" }, { "code": null, "e": 1943, "s": 1936, "text": "Picked" }, { "code": null, "e": 1951, "s": 1943, "text": "Node.js" }, { "code": null, "e": 1968, "s": 1951, "text": "Web Technologies" } ]
Different Ways to Prevent Method Overriding in Java
10 Aug, 2021 Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows: Methods: Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method Using a static method Using private access modifier Using default access modifier Using the final keyword method Method 1: Using a static method This is the first way of preventing method overriding in the child class. If you make any method static then it becomes a class method and not an object method and hence it is not allowed to be overridden as they are resolved at compilation time and overridden methods are resolved at runtime. Java // Java Program to Prevent Method Overriding// using a static method // Importing java input output classesimport java.io.*; // Class 1// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object og Base class Base base = new Child(); // Printing message from base class as // its static methods have static binding // Hence even if the object is of Child class // message printed is from base class base.hello(); }} // Class 2// Parent classclass Base { // hello() method of parent class public static void hello() { // Print and display the message if // hello() method of parent class is called System.out.println("Hello from base class"); }} // Class 3// Child classclass Child extends Base { // Overriding the existing method - hello() // @Override // hello() method of child class public static void hello() { // Print and display the message if // hello() method of child class is called System.out.println("Hello from child class"); }} Hello from base class Method 2 Using private access modifier Making any method private reduces the scope of that method to class only which means absolutely no one outside the class can reference that method. Example Java // Java Program to Prevent Method Overriding// using a private method specifier // Importing input output classesimport java.io.*; // Class 1// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of Child class Child child = new Child(); // Calling hello() method in main() child.hello(); }} // Class 2// Helper class 1// Child Classclass Child extends Base { //@Override // hello() method of child class public void hello() { // Print statement when hello() method of // child class is called System.out.println("Hello from child class"); }} // Class 3// Helper class 2// Parent Classclass Base { // hello() method of parent class private void hello() { // Print statement when hello() method of // child class is called System.out.println("Hello from base class"); }} Hello from child class Method 3 Using default access modifier This can only be used when the method overriding is allowed within the same package but not outside the package. Default modifier allows the method to be visible only within the package so any child class outside the same package can never override it. Example Java // Java Program to Prevent Method Overriding// using a private method specifier // Importing input output classesimport java.io.*; // Class 1// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of base class Base base = new Child(); // Calling hello() method using Base class object base.hello(); }} // Class 2// Parent classclass Base { // hello() method of parent class private void hello() { // Print statement when hello() method of // child class is called System.out.println("Hello from base class"); }} // Class 3// Child classclass Child extends Base { // Overriding existing method // @Override // Hello method of child class void hello() { // Print statement when hello() method // of child class is called System.out.println("Hello from child class"); }} Output: Method 4: Using the final keyword method The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior. Java // Java Program to Prevent Method Overriding// using a final keyword method // Importing input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of Child class Child child = new Child(); // Calling hello() method using Child class object child.hello(); }} // Class 2// Child classclass Child extends Base { // Overriding // @Override // Method of child class public void hello() { // Print statement for Child class System.out.println("Hello from child class"); }} // Class 3// Base classclass Base { // Method of parent class public final void hello() { // Print statement for Base(parent) class System.out.println("Hello from base class"); }} Output: RajSuvariya prabormukherjee java-inheritance Java-Object Oriented Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Aug, 2021" }, { "code": null, "e": 206, "s": 28, "text": "Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows:" }, { "code": null, "e": 215, "s": 206, "text": "Methods:" }, { "code": null, "e": 325, "s": 215, "text": "Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method" }, { "code": null, "e": 347, "s": 325, "text": "Using a static method" }, { "code": null, "e": 377, "s": 347, "text": "Using private access modifier" }, { "code": null, "e": 407, "s": 377, "text": "Using default access modifier" }, { "code": null, "e": 438, "s": 407, "text": "Using the final keyword method" }, { "code": null, "e": 470, "s": 438, "text": "Method 1: Using a static method" }, { "code": null, "e": 764, "s": 470, "text": "This is the first way of preventing method overriding in the child class. If you make any method static then it becomes a class method and not an object method and hence it is not allowed to be overridden as they are resolved at compilation time and overridden methods are resolved at runtime." }, { "code": null, "e": 769, "s": 764, "text": "Java" }, { "code": "// Java Program to Prevent Method Overriding// using a static method // Importing java input output classesimport java.io.*; // Class 1// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object og Base class Base base = new Child(); // Printing message from base class as // its static methods have static binding // Hence even if the object is of Child class // message printed is from base class base.hello(); }} // Class 2// Parent classclass Base { // hello() method of parent class public static void hello() { // Print and display the message if // hello() method of parent class is called System.out.println(\"Hello from base class\"); }} // Class 3// Child classclass Child extends Base { // Overriding the existing method - hello() // @Override // hello() method of child class public static void hello() { // Print and display the message if // hello() method of child class is called System.out.println(\"Hello from child class\"); }}", "e": 1902, "s": 769, "text": null }, { "code": null, "e": 1924, "s": 1902, "text": "Hello from base class" }, { "code": null, "e": 2111, "s": 1924, "text": "Method 2 Using private access modifier Making any method private reduces the scope of that method to class only which means absolutely no one outside the class can reference that method." }, { "code": null, "e": 2119, "s": 2111, "text": "Example" }, { "code": null, "e": 2124, "s": 2119, "text": "Java" }, { "code": "// Java Program to Prevent Method Overriding// using a private method specifier // Importing input output classesimport java.io.*; // Class 1// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of Child class Child child = new Child(); // Calling hello() method in main() child.hello(); }} // Class 2// Helper class 1// Child Classclass Child extends Base { //@Override // hello() method of child class public void hello() { // Print statement when hello() method of // child class is called System.out.println(\"Hello from child class\"); }} // Class 3// Helper class 2// Parent Classclass Base { // hello() method of parent class private void hello() { // Print statement when hello() method of // child class is called System.out.println(\"Hello from base class\"); }}", "e": 3071, "s": 2124, "text": null }, { "code": null, "e": 3094, "s": 3071, "text": "Hello from child class" }, { "code": null, "e": 3133, "s": 3094, "text": "Method 3 Using default access modifier" }, { "code": null, "e": 3387, "s": 3133, "text": "This can only be used when the method overriding is allowed within the same package but not outside the package. Default modifier allows the method to be visible only within the package so any child class outside the same package can never override it. " }, { "code": null, "e": 3396, "s": 3387, "text": "Example " }, { "code": null, "e": 3401, "s": 3396, "text": "Java" }, { "code": "// Java Program to Prevent Method Overriding// using a private method specifier // Importing input output classesimport java.io.*; // Class 1// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of base class Base base = new Child(); // Calling hello() method using Base class object base.hello(); }} // Class 2// Parent classclass Base { // hello() method of parent class private void hello() { // Print statement when hello() method of // child class is called System.out.println(\"Hello from base class\"); }} // Class 3// Child classclass Child extends Base { // Overriding existing method // @Override // Hello method of child class void hello() { // Print statement when hello() method // of child class is called System.out.println(\"Hello from child class\"); }}", "e": 4344, "s": 3401, "text": null }, { "code": null, "e": 4352, "s": 4344, "text": "Output:" }, { "code": null, "e": 4394, "s": 4352, "text": " Method 4: Using the final keyword method" }, { "code": null, "e": 4656, "s": 4394, "text": "The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior." }, { "code": null, "e": 4661, "s": 4656, "text": "Java" }, { "code": "// Java Program to Prevent Method Overriding// using a final keyword method // Importing input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of Child class Child child = new Child(); // Calling hello() method using Child class object child.hello(); }} // Class 2// Child classclass Child extends Base { // Overriding // @Override // Method of child class public void hello() { // Print statement for Child class System.out.println(\"Hello from child class\"); }} // Class 3// Base classclass Base { // Method of parent class public final void hello() { // Print statement for Base(parent) class System.out.println(\"Hello from base class\"); }}", "e": 5493, "s": 4661, "text": null }, { "code": null, "e": 5501, "s": 5493, "text": "Output:" }, { "code": null, "e": 5513, "s": 5501, "text": "RajSuvariya" }, { "code": null, "e": 5529, "s": 5513, "text": "prabormukherjee" }, { "code": null, "e": 5546, "s": 5529, "text": "java-inheritance" }, { "code": null, "e": 5567, "s": 5546, "text": "Java-Object Oriented" }, { "code": null, "e": 5574, "s": 5567, "text": "Picked" }, { "code": null, "e": 5579, "s": 5574, "text": "Java" }, { "code": null, "e": 5584, "s": 5579, "text": "Java" } ]
Sum of Fibonacci Numbers
22 Nov, 2021 Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i’th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... Examples : Input : n = 3 Output : 4 Explanation : 0 + 1 + 1 + 2 = 4 Input : n = 4 Output : 7 Explanation : 0 + 1 + 1 + 2 + 3 = 7 Method 1 (O(n)) Brute Force approach is pretty straight forward, find all the Fibonacci numbers till f(n) and then add them up. C++ Java Python3 C# PHP Javascript // C++ Program to find sum of Fibonacci numbers#include<bits/stdc++.h>using namespace std; // Computes value of first fibonacci numbersint calculateSum(int n){ if (n <= 0) return 0; int fibo[n+1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = fibo[0] + fibo[1]; // Add remaining terms for (int i=2; i<=n; i++) { fibo[i] = fibo[i-1]+fibo[i-2]; sum += fibo[i]; } return sum;} // Driver program to test above functionint main(){ int n = 4; cout << "Sum of Fibonacci numbers is : " << calculateSum(n) << endl; return 0;} // Java Program to find// sum of Fibonacci numbers import java.io.*; class GFG { // Computes value of first // fibonacci numbers static int calculateSum(int n) { if (n <= 0) return 0; int fibo[]=new int[n+1]; fibo[0] = 0; fibo[1] = 1; // Initialize result int sum = fibo[0] + fibo[1]; // Add remaining terms for (int i=2; i<=n; i++) { fibo[i] = fibo[i-1]+fibo[i-2]; sum += fibo[i]; } return sum; } // Driver program to test above function public static void main(String args[]) { int n = 4; System.out.println("Sum of Fibonacci" + " numbers is : "+ calculateSum(n)); }} // This code is contributed by Nikita tiwari. # Python 3 Program to find# sum of Fibonacci numbers # Computes value of first# fibonacci numbersdef calculateSum(n) : if (n <= 0) : return 0 fibo =[0] * (n+1) fibo[1] = 1 # Initialize result sm = fibo[0] + fibo[1] # Add remaining terms for i in range(2,n+1) : fibo[i] = fibo[i-1] + fibo[i-2] sm = sm + fibo[i] return sm # Driver program to test# above functionn = 4print("Sum of Fibonacci numbers is : " , calculateSum(n)) # This code is contributed# by Nikita tiwari. // C# Program to find// sum of Fibonacci numbersusing System; class GFG{ // Computes value of first // fibonacci numbers static int calculateSum(int n) { if (n <= 0) return 0; int []fibo = new int[n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result int sum = fibo[0] + fibo[1]; // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += fibo[i]; } return sum; } // Driver Code static void Main() { int n = 4; Console.WriteLine( "Sum of Fibonacci" + " numbers is : "+ calculateSum(n)); }} // This code is contributed by Anuj_67 <?php// PHP Program to find sum// of Fibonacci numbers // Computes value of first// fibonacci numbersfunction calculateSum($n){ if ($n <= 0) return 0; $fibo[0] = 0; $fibo[1] = 1; // Initialize result $sum = $fibo[0] + $fibo[1]; // Add remaining terms for($i = 2; $i <= $n; $i++) { $fibo[$i] = $fibo[$i - 1] + $fibo[$i - 2]; $sum += $fibo[$i]; } return $sum;} // Driver Code $n = 4; echo "Sum of Fibonacci numbers is : ", calculateSum($n),"\n"; // This code is contributed by aj_36?> <script>// Javascript Program to find sum// of Fibonacci numbers // Computes value of first// fibonacci numbersfunction calculateSum(n){ let fibo = []; if (n <= 0) return 0; fibo[0] = 0; fibo[1] = 1; // Initialize result let sum = fibo[0] + fibo[1]; // Add remaining terms for(let i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += fibo[i]; } return sum;} // Driver Code let n = 4; document.write(`Sum of Fibonacci numbers is : ${calculateSum(n)} <br>`); // This code is contributed by _saurabh_jaiswal</script> Output : Sum of Fibonacci numbers is : 7 Method 2 (O(Log n)) The idea is to find relationship between the sum of Fibonacci numbers and n’th Fibonacci number.F(i) refers to the i’th Fibonacci number. S(i) refers to sum of Fibonacci numbers till F(i), We can rewrite the relation F(n+1) = F(n) + F(n-1) as below F(n-1) = F(n+1) - F(n) Similarly, F(n-2) = F(n) - F(n-1) . . . . . . . . . F(0) = F(2) - F(1) ------------------------------- Adding all the equations, on left side, we have F(0) + F(1) + ... F(n-1) which is S(n-1).Therefore, S(n-1) = F(n+1) – F(1) S(n-1) = F(n+1) – 1 S(n) = F(n+2) – 1 —-(1)In order to find S(n), simply calculate the (n+2)’th Fibonacci number and subtract 1 from the result.F(n) can be evaluated in O(log n) time using either method 5 or method 6 in this article (Refer to methods 5 and 6).Below is the implementation based on method 6 of this C++ Java Python3 C# PHP Javascript // C++ Program to find sum of Fibonacci numbers in// O(Log n) time.#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint f[MAX] = {0}; // Returns n'th Fibonacci number using table f[]int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1)? (n+1)/2 : n/2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n];} // Computes value of first Fibonacci numbersint calculateSum(int n){ return fib(n+2) - 1;} // Driver program to test above functionint main(){ int n = 4; cout << "Sum of Fibonacci numbers is : " << calculateSum(n) << endl; return 0;} // Java Program to find sum of Fibonacci numbers in// O(Log n) time.import java.util.*; class GFG{static int MAX = 1000; // Create an array for memoizationstatic int []f = new int[MAX]; // Returns n'th Fibonacci number using table f[]static int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]>0) return f[n]; int k = ((n & 1)>0)? (n+1)/2 : n/2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1)>0? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n];} // Computes value of first Fibonacci numbersstatic int calculateSum(int n){ return fib(n+2) - 1;} // Driver program to test above functionpublic static void main(String[] args){ int n = 4; System.out.print("Sum of Fibonacci numbers is : " + calculateSum(n) +"\n");}} // This code is contributed by gauravrajput1 # Python 3 Program to find sum of# Fibonacci numbers in O(Log n) time. MAX = 1000 # Create an array for memoizationf = [0] * MAX # Returns n'th Fibonacci number# using table f[]def fib(n): n = int(n) # Base cases if (n == 0): return 0 if (n == 1 or n == 2): return (1) # If fib(n) is already computed if (f[n] == True): return f[n] k = (n+1)/2 if (n & 1) else n/2 # Applying above formula [Note value n&1 # is 1 if n is odd, else 0]. f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1)) if (n & 1) else (2 * fib(k-1) + fib(k)) * fib(k) return f[n] # Computes value of first Fibonacci numbersdef calculateSum(n): return fib(n+2) - 1 # Driver program to test above functionn = 4print("Sum of Fibonacci numbers is :", calculateSum(n)) # This code is contributed by# Smitha Dinesh Semwal // C# Program to find sum// of Fibonacci numbers in// O(Log n) time.using System; class GFG { static int MAX = 1000; // Create an array for memoization static int []f = new int[MAX]; // Returns n'th Fibonacci // number using table f[] static int fib(int n) { for(int i = 0;i < MAX;i++) f[i] = 0; //Arrays.fill(f, 0); // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is // already computed if (f[n] == 1) return f[n]; int k; if((n & 1) == 1) k = (n + 1) / 2 ; else k = n / 2; // Applying above formula // [Note value n&1 is 1 // if n is odd, else 0]. if((n & 1) == 1) f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)); else f[n] = (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of first // Fibonacci numbers static int calculateSum(int n) { return fib(n + 2) - 1; } // Driver Code public static void Main() { int n = 4; Console.Write( "Sum of Fibonacci numbers is : " + calculateSum(n)); }} // This code is contributed by nitin mittal. <?php// PHP Program to find sum of Fibonacci// numbers in O(Log n) time.$MAX = 1000; // Create an array for memoization$f = array_fill(0, $MAX, 0); // Returns n'th Fibonacci number// using table f[]function fib($n){ global $f; // Base cases if ($n == 0) return 0; if ($n == 1 || $n == 2) return ($f[$n] = 1); // If fib(n) is already computed if ($f[$n]) return $f[$n]; $k = ($n & 1) ? ($n + 1) / 2 : $n / 2; // Applying above formula [Note value n&1 // is 1 if n is odd, else 0]. $f[$n] = ($n & 1) ? (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) : (2 * fib($k - 1) + fib($k)) * fib($k); return $f[$n];} // Computes value of first Fibonacci numbersfunction calculateSum($n){ return fib($n + 2) - 1;} // Driver Code$n = 4;print("Sum of Fibonacci numbers is : " . calculateSum($n)); // This code is contributed by mits?> <script>// javascript Program to find sum of Fibonacci numbers in// O(Log n) time. var MAX = 1000; // Create an array for memoization var f = Array(MAX).fill(0); // Returns n'th Fibonacci number using table f function fib(n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n] > 0) return f[n]; var k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) > 0 ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of first Fibonacci numbers function calculateSum(n) { return fib(n + 2) - 1; } // Driver program to test above function var n = 4; document.write("Sum of Fibonacci numbers is : " + calculateSum(n) + "\n"); // This code is contributed by gauravrajput1</script> Output : Sum of Fibonacci numbers is : 7 This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t nitin mittal vt_m Mithun Kumar _saurabh_jaiswal GauravRajput1 Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end Modulo 10^9+7 (1000000007) Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Modulo Operator (%) in C/C++ with Examples Program for Decimal to Binary Conversion Program for factorial of a number
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Nov, 2021" }, { "code": null, "e": 248, "s": 54, "text": "Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i’th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... Examples : " }, { "code": null, "e": 373, "s": 248, "text": "Input : n = 3\nOutput : 4\nExplanation : 0 + 1 + 1 + 2 = 4\n\nInput : n = 4\nOutput : 7\nExplanation : 0 + 1 + 1 + 2 + 3 = 7" }, { "code": null, "e": 506, "s": 375, "text": " Method 1 (O(n)) Brute Force approach is pretty straight forward, find all the Fibonacci numbers till f(n) and then add them up. " }, { "code": null, "e": 510, "s": 506, "text": "C++" }, { "code": null, "e": 515, "s": 510, "text": "Java" }, { "code": null, "e": 523, "s": 515, "text": "Python3" }, { "code": null, "e": 526, "s": 523, "text": "C#" }, { "code": null, "e": 530, "s": 526, "text": "PHP" }, { "code": null, "e": 541, "s": 530, "text": "Javascript" }, { "code": "// C++ Program to find sum of Fibonacci numbers#include<bits/stdc++.h>using namespace std; // Computes value of first fibonacci numbersint calculateSum(int n){ if (n <= 0) return 0; int fibo[n+1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = fibo[0] + fibo[1]; // Add remaining terms for (int i=2; i<=n; i++) { fibo[i] = fibo[i-1]+fibo[i-2]; sum += fibo[i]; } return sum;} // Driver program to test above functionint main(){ int n = 4; cout << \"Sum of Fibonacci numbers is : \" << calculateSum(n) << endl; return 0;}", "e": 1140, "s": 541, "text": null }, { "code": "// Java Program to find// sum of Fibonacci numbers import java.io.*; class GFG { // Computes value of first // fibonacci numbers static int calculateSum(int n) { if (n <= 0) return 0; int fibo[]=new int[n+1]; fibo[0] = 0; fibo[1] = 1; // Initialize result int sum = fibo[0] + fibo[1]; // Add remaining terms for (int i=2; i<=n; i++) { fibo[i] = fibo[i-1]+fibo[i-2]; sum += fibo[i]; } return sum; } // Driver program to test above function public static void main(String args[]) { int n = 4; System.out.println(\"Sum of Fibonacci\" + \" numbers is : \"+ calculateSum(n)); }} // This code is contributed by Nikita tiwari.", "e": 1941, "s": 1140, "text": null }, { "code": "# Python 3 Program to find# sum of Fibonacci numbers # Computes value of first# fibonacci numbersdef calculateSum(n) : if (n <= 0) : return 0 fibo =[0] * (n+1) fibo[1] = 1 # Initialize result sm = fibo[0] + fibo[1] # Add remaining terms for i in range(2,n+1) : fibo[i] = fibo[i-1] + fibo[i-2] sm = sm + fibo[i] return sm # Driver program to test# above functionn = 4print(\"Sum of Fibonacci numbers is : \" , calculateSum(n)) # This code is contributed# by Nikita tiwari.", "e": 2478, "s": 1941, "text": null }, { "code": "// C# Program to find// sum of Fibonacci numbersusing System; class GFG{ // Computes value of first // fibonacci numbers static int calculateSum(int n) { if (n <= 0) return 0; int []fibo = new int[n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result int sum = fibo[0] + fibo[1]; // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += fibo[i]; } return sum; } // Driver Code static void Main() { int n = 4; Console.WriteLine( \"Sum of Fibonacci\" + \" numbers is : \"+ calculateSum(n)); }} // This code is contributed by Anuj_67", "e": 3275, "s": 2478, "text": null }, { "code": "<?php// PHP Program to find sum// of Fibonacci numbers // Computes value of first// fibonacci numbersfunction calculateSum($n){ if ($n <= 0) return 0; $fibo[0] = 0; $fibo[1] = 1; // Initialize result $sum = $fibo[0] + $fibo[1]; // Add remaining terms for($i = 2; $i <= $n; $i++) { $fibo[$i] = $fibo[$i - 1] + $fibo[$i - 2]; $sum += $fibo[$i]; } return $sum;} // Driver Code $n = 4; echo \"Sum of Fibonacci numbers is : \", calculateSum($n),\"\\n\"; // This code is contributed by aj_36?>", "e": 3847, "s": 3275, "text": null }, { "code": "<script>// Javascript Program to find sum// of Fibonacci numbers // Computes value of first// fibonacci numbersfunction calculateSum(n){ let fibo = []; if (n <= 0) return 0; fibo[0] = 0; fibo[1] = 1; // Initialize result let sum = fibo[0] + fibo[1]; // Add remaining terms for(let i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += fibo[i]; } return sum;} // Driver Code let n = 4; document.write(`Sum of Fibonacci numbers is : ${calculateSum(n)} <br>`); // This code is contributed by _saurabh_jaiswal</script>", "e": 4464, "s": 3847, "text": null }, { "code": null, "e": 4475, "s": 4464, "text": "Output : " }, { "code": null, "e": 4507, "s": 4475, "text": "Sum of Fibonacci numbers is : 7" }, { "code": null, "e": 4719, "s": 4507, "text": " Method 2 (O(Log n)) The idea is to find relationship between the sum of Fibonacci numbers and n’th Fibonacci number.F(i) refers to the i’th Fibonacci number. S(i) refers to sum of Fibonacci numbers till F(i), " }, { "code": null, "e": 4988, "s": 4719, "text": "We can rewrite the relation F(n+1) = F(n) + F(n-1) as below\nF(n-1) = F(n+1) - F(n)\n\nSimilarly,\nF(n-2) = F(n) - F(n-1)\n. . .\n. . .\n. . .\nF(0) = F(2) - F(1)\n-------------------------------" }, { "code": null, "e": 5427, "s": 4988, "text": "Adding all the equations, on left side, we have F(0) + F(1) + ... F(n-1) which is S(n-1).Therefore, S(n-1) = F(n+1) – F(1) S(n-1) = F(n+1) – 1 S(n) = F(n+2) – 1 —-(1)In order to find S(n), simply calculate the (n+2)’th Fibonacci number and subtract 1 from the result.F(n) can be evaluated in O(log n) time using either method 5 or method 6 in this article (Refer to methods 5 and 6).Below is the implementation based on method 6 of this " }, { "code": null, "e": 5431, "s": 5427, "text": "C++" }, { "code": null, "e": 5436, "s": 5431, "text": "Java" }, { "code": null, "e": 5444, "s": 5436, "text": "Python3" }, { "code": null, "e": 5447, "s": 5444, "text": "C#" }, { "code": null, "e": 5451, "s": 5447, "text": "PHP" }, { "code": null, "e": 5462, "s": 5451, "text": "Javascript" }, { "code": "// C++ Program to find sum of Fibonacci numbers in// O(Log n) time.#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint f[MAX] = {0}; // Returns n'th Fibonacci number using table f[]int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1)? (n+1)/2 : n/2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n];} // Computes value of first Fibonacci numbersint calculateSum(int n){ return fib(n+2) - 1;} // Driver program to test above functionint main(){ int n = 4; cout << \"Sum of Fibonacci numbers is : \" << calculateSum(n) << endl; return 0;}", "e": 6365, "s": 5462, "text": null }, { "code": "// Java Program to find sum of Fibonacci numbers in// O(Log n) time.import java.util.*; class GFG{static int MAX = 1000; // Create an array for memoizationstatic int []f = new int[MAX]; // Returns n'th Fibonacci number using table f[]static int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]>0) return f[n]; int k = ((n & 1)>0)? (n+1)/2 : n/2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1)>0? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n];} // Computes value of first Fibonacci numbersstatic int calculateSum(int n){ return fib(n+2) - 1;} // Driver program to test above functionpublic static void main(String[] args){ int n = 4; System.out.print(\"Sum of Fibonacci numbers is : \" + calculateSum(n) +\"\\n\");}} // This code is contributed by gauravrajput1", "e": 7358, "s": 6365, "text": null }, { "code": "# Python 3 Program to find sum of# Fibonacci numbers in O(Log n) time. MAX = 1000 # Create an array for memoizationf = [0] * MAX # Returns n'th Fibonacci number# using table f[]def fib(n): n = int(n) # Base cases if (n == 0): return 0 if (n == 1 or n == 2): return (1) # If fib(n) is already computed if (f[n] == True): return f[n] k = (n+1)/2 if (n & 1) else n/2 # Applying above formula [Note value n&1 # is 1 if n is odd, else 0]. f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1)) if (n & 1) else (2 * fib(k-1) + fib(k)) * fib(k) return f[n] # Computes value of first Fibonacci numbersdef calculateSum(n): return fib(n+2) - 1 # Driver program to test above functionn = 4print(\"Sum of Fibonacci numbers is :\", calculateSum(n)) # This code is contributed by# Smitha Dinesh Semwal", "e": 8203, "s": 7358, "text": null }, { "code": "// C# Program to find sum// of Fibonacci numbers in// O(Log n) time.using System; class GFG { static int MAX = 1000; // Create an array for memoization static int []f = new int[MAX]; // Returns n'th Fibonacci // number using table f[] static int fib(int n) { for(int i = 0;i < MAX;i++) f[i] = 0; //Arrays.fill(f, 0); // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is // already computed if (f[n] == 1) return f[n]; int k; if((n & 1) == 1) k = (n + 1) / 2 ; else k = n / 2; // Applying above formula // [Note value n&1 is 1 // if n is odd, else 0]. if((n & 1) == 1) f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)); else f[n] = (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of first // Fibonacci numbers static int calculateSum(int n) { return fib(n + 2) - 1; } // Driver Code public static void Main() { int n = 4; Console.Write( \"Sum of Fibonacci numbers is : \" + calculateSum(n)); }} // This code is contributed by nitin mittal.", "e": 9637, "s": 8203, "text": null }, { "code": "<?php// PHP Program to find sum of Fibonacci// numbers in O(Log n) time.$MAX = 1000; // Create an array for memoization$f = array_fill(0, $MAX, 0); // Returns n'th Fibonacci number// using table f[]function fib($n){ global $f; // Base cases if ($n == 0) return 0; if ($n == 1 || $n == 2) return ($f[$n] = 1); // If fib(n) is already computed if ($f[$n]) return $f[$n]; $k = ($n & 1) ? ($n + 1) / 2 : $n / 2; // Applying above formula [Note value n&1 // is 1 if n is odd, else 0]. $f[$n] = ($n & 1) ? (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) : (2 * fib($k - 1) + fib($k)) * fib($k); return $f[$n];} // Computes value of first Fibonacci numbersfunction calculateSum($n){ return fib($n + 2) - 1;} // Driver Code$n = 4;print(\"Sum of Fibonacci numbers is : \" . calculateSum($n)); // This code is contributed by mits?>", "e": 10573, "s": 9637, "text": null }, { "code": "<script>// javascript Program to find sum of Fibonacci numbers in// O(Log n) time. var MAX = 1000; // Create an array for memoization var f = Array(MAX).fill(0); // Returns n'th Fibonacci number using table f function fib(n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n] > 0) return f[n]; var k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) > 0 ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of first Fibonacci numbers function calculateSum(n) { return fib(n + 2) - 1; } // Driver program to test above function var n = 4; document.write(\"Sum of Fibonacci numbers is : \" + calculateSum(n) + \"\\n\"); // This code is contributed by gauravrajput1</script>", "e": 11614, "s": 10573, "text": null }, { "code": null, "e": 11625, "s": 11614, "text": "Output : " }, { "code": null, "e": 11657, "s": 11625, "text": "Sum of Fibonacci numbers is : 7" }, { "code": null, "e": 12050, "s": 11657, "text": "This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 12056, "s": 12050, "text": "jit_t" }, { "code": null, "e": 12069, "s": 12056, "text": "nitin mittal" }, { "code": null, "e": 12074, "s": 12069, "text": "vt_m" }, { "code": null, "e": 12087, "s": 12074, "text": "Mithun Kumar" }, { "code": null, "e": 12104, "s": 12087, "text": "_saurabh_jaiswal" }, { "code": null, "e": 12118, "s": 12104, "text": "GauravRajput1" }, { "code": null, "e": 12128, "s": 12118, "text": "Fibonacci" }, { "code": null, "e": 12141, "s": 12128, "text": "Mathematical" }, { "code": null, "e": 12154, "s": 12141, "text": "Mathematical" }, { "code": null, "e": 12164, "s": 12154, "text": "Fibonacci" }, { "code": null, "e": 12262, "s": 12164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12286, "s": 12262, "text": "Merge two sorted arrays" }, { "code": null, "e": 12307, "s": 12286, "text": "Operators in C / C++" }, { "code": null, "e": 12321, "s": 12307, "text": "Prime Numbers" }, { "code": null, "e": 12358, "s": 12321, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 12385, "s": 12358, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 12417, "s": 12385, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 12460, "s": 12417, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 12503, "s": 12460, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 12544, "s": 12503, "text": "Program for Decimal to Binary Conversion" } ]
Maximum Path Sum in a Binary Tree
02 Jul, 2021 Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.Example: Input: Root of below tree 1 / \ 2 3 Output: 6 See below diagram for another example. 1+2+3 For each node there can be four ways that the max path goes through the node: 1. Node only 2. Max path through Left Child + Node 3. Max path through Right Child + Node 4. Max path through Left Child + Node + Max path through Right ChildThe idea is to keep trace of four paths and pick up the max one in the end. An important thing to note is, root of every subtree need to return maximum path sum such that at most one child of root is involved. This is needed for parent function call. In below code, this sum is stored in ‘max_single’ and returned by the recursive function. C++ Java Python C# Javascript // C/C++ program to find maximum path sum in Binary Tree#include<bits/stdc++.h>using namespace std; // A binary tree nodestruct Node{ int data; struct Node* left, *right;}; // A utility function to allocate a new nodestruct Node* newNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return (newNode);} // This function returns overall maximum path sum in 'res'// And returns max path sum going through root.int findMaxUtil(Node* root, int &res){ //Base Case if (root == NULL) return 0; // l and r store maximum path sum going through left and // right child of root respectively int l = findMaxUtil(root->left,res); int r = findMaxUtil(root->right,res); // Max path for parent call of root. This path must // include at-most one child of root int max_single = max(max(l, r) + root->data, root->data); // Max Top represents the sum when the Node under // consideration is the root of the maxsum path and no // ancestors of root are there in max sum path int max_top = max(max_single, l + r + root->data); res = max(res, max_top); // Store the Maximum Result. return max_single;} // Returns maximum path sum in tree with given rootint findMaxSum(Node *root){ // Initialize result int res = INT_MIN; // Compute and return result findMaxUtil(root, res); return res;} // Driver programint main(void){ struct Node *root = newNode(10); root->left = newNode(2); root->right = newNode(10); root->left->left = newNode(20); root->left->right = newNode(1); root->right->right = newNode(-25); root->right->right->left = newNode(3); root->right->right->right = newNode(4); cout << "Max path sum is " << findMaxSum(root); return 0;} // Java program to find maximum path sum in Binary Tree /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.class Res { public int val;} class BinaryTree { // Root of the Binary Tree Node root; // This function returns overall maximum path sum in 'res' // And returns max path sum going through root. int findMaxUtil(Node node, Res res) { // Base Case if (node == null) return 0; // l and r store maximum path sum going through left and // right child of root respectively int l = findMaxUtil(node.left, res); int r = findMaxUtil(node.right, res); // Max path for parent call of root. This path must // include at-most one child of root int max_single = Math.max(Math.max(l, r) + node.data, node.data); // Max Top represents the sum when the Node under // consideration is the root of the maxsum path and no // ancestors of root are there in max sum path int max_top = Math.max(max_single, l + r + node.data); // Store the Maximum Result. res.val = Math.max(res.val, max_top); return max_single; } int findMaxSum() { return findMaxSum(root); } // Returns maximum path sum in tree with given root int findMaxSum(Node node) { // Initialize result // int res2 = Integer.MIN_VALUE; Res res = new Res(); res.val = Integer.MIN_VALUE; // Compute and return result findMaxUtil(node, res); return res.val; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(1); tree.root.right.right = new Node(-25); tree.root.right.right.left = new Node(3); tree.root.right.right.right = new Node(4); System.out.println("maximum path sum is : " + tree.findMaxSum()); }} # Python program to find maximum path sum in Binary Tree # A Binary Tree Nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # This function returns overall maximum path sum in 'res'# And returns max path sum going through rootdef findMaxUtil(root): # Base Case if root is None: return 0 # l and r store maximum path sum going through left # and right child of root respectively l = findMaxUtil(root.left) r = findMaxUtil(root.right) # Max path for parent call of root. This path # must include at most one child of root max_single = max(max(l, r) + root.data, root.data) # Max top represents the sum when the node under # consideration is the root of the maxSum path and # no ancestor of root are there in max sum path max_top = max(max_single, l+r+ root.data) # Static variable to store the changes # Store the maximum result findMaxUtil.res = max(findMaxUtil.res, max_top) return max_single # Return maximum path sum in tree with given rootdef findMaxSum(root): # Initialize result findMaxUtil.res = float("-inf") # Compute and return result findMaxUtil(root) return findMaxUtil.res # Driver programroot = Node(10)root.left = Node(2)root.right = Node(10);root.left.left = Node(20);root.left.right = Node(1);root.right.right = Node(-25);root.right.right.left = Node(3);root.right.right.right = Node(4);print "Max path sum is " ,findMaxSum(root); # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to find maximum// path sum in Binary Treeusing System; /* Class containing left andright child of currentnode and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // An object of Res is passed// around so that the same value// can be used by multiple recursive calls.class Res{ public int val;} public class BinaryTree{ // Root of the Binary Tree Node root; // This function returns overall // maximum path sum in 'res' And // returns max path sum going through root. int findMaxUtil(Node node, Res res) { // Base Case if (node == null) return 0; // l and r store maximum path // sum going through left and // right child of root respectively int l = findMaxUtil(node.left, res); int r = findMaxUtil(node.right, res); // Max path for parent call of root. // This path must include // at-most one child of root int max_single = Math.Max(Math.Max(l, r) + node.data, node.data); // Max Top represents the sum // when the Node under // consideration is the root // of the maxsum path and no // ancestors of root are there // in max sum path int max_top = Math.Max(max_single, l + r + node.data); // Store the Maximum Result. res.val = Math.Max(res.val, max_top); return max_single; } int findMaxSum() { return findMaxSum(root); } // Returns maximum path // sum in tree with given root int findMaxSum(Node node) { // Initialize result // int res2 = int.MinValue; Res res = new Res(); res.val = int.MinValue; // Compute and return result findMaxUtil(node, res); return res.val; } /* Driver code */ public static void Main(String []args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(1); tree.root.right.right = new Node(-25); tree.root.right.right.left = new Node(3); tree.root.right.right.right = new Node(4); Console.WriteLine("maximum path sum is : " + tree.findMaxSum()); }} // This code is contributed Rajput-Ji. <script> // JavaScript program to find maximum // path sum in Binary Tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let val; // Root of the Binary Tree let root; // This function returns overall maximum path sum in 'res' // And returns max path sum going through root. function findMaxUtil(node) { // Base Case if (node == null) return 0; // l and r store maximum path sum going through left and // right child of root respectively let l = findMaxUtil(node.left); let r = findMaxUtil(node.right); // Max path for parent call of root. This path must // include at-most one child of root let max_single = Math.max(Math.max(l, r) + node.data, node.data); // Max Top represents the sum when the Node under // consideration is the root of the maxsum path and no // ancestors of root are there in max sum path let max_top = Math.max(max_single, l + r + node.data); // Store the Maximum Result. val = Math.max(val, max_top); return max_single; } function findMaxsum() { return findMaxSum(root); } // Returns maximum path sum in tree with given root function findMaxSum(node) { // Initialize result // int res2 = Integer.MIN_VALUE; val = Number.MIN_VALUE; // Compute and return result findMaxUtil(node); return val; } root = new Node(10); root.left = new Node(2); root.right = new Node(10); root.left.left = new Node(20); root.left.right = new Node(1); root.right.right = new Node(-25); root.right.right.left = new Node(3); root.right.right.right = new Node(4); document.write("Max path sum is : " + findMaxsum()); </script> Output: Max path sum is 42 Time Complexity: O(n) where n is number of nodes in Binary Tree. Maximum Path Sum in a Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum Path Sum in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:10•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cSnETAcziS0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Anmol Varshney (FB Profile: https://www.facebook.com/anmolvarshney695). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Rajput-Ji simmytarika5 suresh07 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Print Right View of a Binary Tree Inorder Tree Traversal without Recursion BFS vs DFS for Binary Tree Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Introduction to Data Structures A program to check if a binary tree is BST or not Introduction to Tree Data Structure Decision Tree Iterative Preorder Traversal
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jul, 2021" }, { "code": null, "e": 161, "s": 52, "text": "Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.Example: " }, { "code": null, "e": 273, "s": 161, "text": "Input: Root of below tree\n 1\n / \\\n 2 3\nOutput: 6\n\nSee below diagram for another example.\n1+2+3" }, { "code": null, "e": 855, "s": 277, "text": "For each node there can be four ways that the max path goes through the node: 1. Node only 2. Max path through Left Child + Node 3. Max path through Right Child + Node 4. Max path through Left Child + Node + Max path through Right ChildThe idea is to keep trace of four paths and pick up the max one in the end. An important thing to note is, root of every subtree need to return maximum path sum such that at most one child of root is involved. This is needed for parent function call. In below code, this sum is stored in ‘max_single’ and returned by the recursive function. " }, { "code": null, "e": 859, "s": 855, "text": "C++" }, { "code": null, "e": 864, "s": 859, "text": "Java" }, { "code": null, "e": 871, "s": 864, "text": "Python" }, { "code": null, "e": 874, "s": 871, "text": "C#" }, { "code": null, "e": 885, "s": 874, "text": "Javascript" }, { "code": "// C/C++ program to find maximum path sum in Binary Tree#include<bits/stdc++.h>using namespace std; // A binary tree nodestruct Node{ int data; struct Node* left, *right;}; // A utility function to allocate a new nodestruct Node* newNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return (newNode);} // This function returns overall maximum path sum in 'res'// And returns max path sum going through root.int findMaxUtil(Node* root, int &res){ //Base Case if (root == NULL) return 0; // l and r store maximum path sum going through left and // right child of root respectively int l = findMaxUtil(root->left,res); int r = findMaxUtil(root->right,res); // Max path for parent call of root. This path must // include at-most one child of root int max_single = max(max(l, r) + root->data, root->data); // Max Top represents the sum when the Node under // consideration is the root of the maxsum path and no // ancestors of root are there in max sum path int max_top = max(max_single, l + r + root->data); res = max(res, max_top); // Store the Maximum Result. return max_single;} // Returns maximum path sum in tree with given rootint findMaxSum(Node *root){ // Initialize result int res = INT_MIN; // Compute and return result findMaxUtil(root, res); return res;} // Driver programint main(void){ struct Node *root = newNode(10); root->left = newNode(2); root->right = newNode(10); root->left->left = newNode(20); root->left->right = newNode(1); root->right->right = newNode(-25); root->right->right->left = newNode(3); root->right->right->right = newNode(4); cout << \"Max path sum is \" << findMaxSum(root); return 0;}", "e": 2701, "s": 885, "text": null }, { "code": "// Java program to find maximum path sum in Binary Tree /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.class Res { public int val;} class BinaryTree { // Root of the Binary Tree Node root; // This function returns overall maximum path sum in 'res' // And returns max path sum going through root. int findMaxUtil(Node node, Res res) { // Base Case if (node == null) return 0; // l and r store maximum path sum going through left and // right child of root respectively int l = findMaxUtil(node.left, res); int r = findMaxUtil(node.right, res); // Max path for parent call of root. This path must // include at-most one child of root int max_single = Math.max(Math.max(l, r) + node.data, node.data); // Max Top represents the sum when the Node under // consideration is the root of the maxsum path and no // ancestors of root are there in max sum path int max_top = Math.max(max_single, l + r + node.data); // Store the Maximum Result. res.val = Math.max(res.val, max_top); return max_single; } int findMaxSum() { return findMaxSum(root); } // Returns maximum path sum in tree with given root int findMaxSum(Node node) { // Initialize result // int res2 = Integer.MIN_VALUE; Res res = new Res(); res.val = Integer.MIN_VALUE; // Compute and return result findMaxUtil(node, res); return res.val; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(1); tree.root.right.right = new Node(-25); tree.root.right.right.left = new Node(3); tree.root.right.right.right = new Node(4); System.out.println(\"maximum path sum is : \" + tree.findMaxSum()); }}", "e": 5098, "s": 2701, "text": null }, { "code": "# Python program to find maximum path sum in Binary Tree # A Binary Tree Nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # This function returns overall maximum path sum in 'res'# And returns max path sum going through rootdef findMaxUtil(root): # Base Case if root is None: return 0 # l and r store maximum path sum going through left # and right child of root respectively l = findMaxUtil(root.left) r = findMaxUtil(root.right) # Max path for parent call of root. This path # must include at most one child of root max_single = max(max(l, r) + root.data, root.data) # Max top represents the sum when the node under # consideration is the root of the maxSum path and # no ancestor of root are there in max sum path max_top = max(max_single, l+r+ root.data) # Static variable to store the changes # Store the maximum result findMaxUtil.res = max(findMaxUtil.res, max_top) return max_single # Return maximum path sum in tree with given rootdef findMaxSum(root): # Initialize result findMaxUtil.res = float(\"-inf\") # Compute and return result findMaxUtil(root) return findMaxUtil.res # Driver programroot = Node(10)root.left = Node(2)root.right = Node(10);root.left.left = Node(20);root.left.right = Node(1);root.right.right = Node(-25);root.right.right.left = Node(3);root.right.right.right = Node(4);print \"Max path sum is \" ,findMaxSum(root); # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 6725, "s": 5098, "text": null }, { "code": "// C# program to find maximum// path sum in Binary Treeusing System; /* Class containing left andright child of currentnode and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // An object of Res is passed// around so that the same value// can be used by multiple recursive calls.class Res{ public int val;} public class BinaryTree{ // Root of the Binary Tree Node root; // This function returns overall // maximum path sum in 'res' And // returns max path sum going through root. int findMaxUtil(Node node, Res res) { // Base Case if (node == null) return 0; // l and r store maximum path // sum going through left and // right child of root respectively int l = findMaxUtil(node.left, res); int r = findMaxUtil(node.right, res); // Max path for parent call of root. // This path must include // at-most one child of root int max_single = Math.Max(Math.Max(l, r) + node.data, node.data); // Max Top represents the sum // when the Node under // consideration is the root // of the maxsum path and no // ancestors of root are there // in max sum path int max_top = Math.Max(max_single, l + r + node.data); // Store the Maximum Result. res.val = Math.Max(res.val, max_top); return max_single; } int findMaxSum() { return findMaxSum(root); } // Returns maximum path // sum in tree with given root int findMaxSum(Node node) { // Initialize result // int res2 = int.MinValue; Res res = new Res(); res.val = int.MinValue; // Compute and return result findMaxUtil(node, res); return res.val; } /* Driver code */ public static void Main(String []args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(2); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(1); tree.root.right.right = new Node(-25); tree.root.right.right.left = new Node(3); tree.root.right.right.right = new Node(4); Console.WriteLine(\"maximum path sum is : \" + tree.findMaxSum()); }} // This code is contributed Rajput-Ji.", "e": 9252, "s": 6725, "text": null }, { "code": "<script> // JavaScript program to find maximum // path sum in Binary Tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let val; // Root of the Binary Tree let root; // This function returns overall maximum path sum in 'res' // And returns max path sum going through root. function findMaxUtil(node) { // Base Case if (node == null) return 0; // l and r store maximum path sum going through left and // right child of root respectively let l = findMaxUtil(node.left); let r = findMaxUtil(node.right); // Max path for parent call of root. This path must // include at-most one child of root let max_single = Math.max(Math.max(l, r) + node.data, node.data); // Max Top represents the sum when the Node under // consideration is the root of the maxsum path and no // ancestors of root are there in max sum path let max_top = Math.max(max_single, l + r + node.data); // Store the Maximum Result. val = Math.max(val, max_top); return max_single; } function findMaxsum() { return findMaxSum(root); } // Returns maximum path sum in tree with given root function findMaxSum(node) { // Initialize result // int res2 = Integer.MIN_VALUE; val = Number.MIN_VALUE; // Compute and return result findMaxUtil(node); return val; } root = new Node(10); root.left = new Node(2); root.right = new Node(10); root.left.left = new Node(20); root.left.right = new Node(1); root.right.right = new Node(-25); root.right.right.left = new Node(3); root.right.right.right = new Node(4); document.write(\"Max path sum is : \" + findMaxsum()); </script>", "e": 11198, "s": 9252, "text": null }, { "code": null, "e": 11206, "s": 11198, "text": "Output:" }, { "code": null, "e": 11225, "s": 11206, "text": "Max path sum is 42" }, { "code": null, "e": 11291, "s": 11225, "text": "Time Complexity: O(n) where n is number of nodes in Binary Tree. " }, { "code": null, "e": 12175, "s": 11291, "text": "Maximum Path Sum in a Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum Path Sum in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:10•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cSnETAcziS0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 12403, "s": 12175, "text": "This article is contributed by Anmol Varshney (FB Profile: https://www.facebook.com/anmolvarshney695). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 12413, "s": 12403, "text": "Rajput-Ji" }, { "code": null, "e": 12426, "s": 12413, "text": "simmytarika5" }, { "code": null, "e": 12435, "s": 12426, "text": "suresh07" }, { "code": null, "e": 12440, "s": 12435, "text": "Tree" }, { "code": null, "e": 12445, "s": 12440, "text": "Tree" }, { "code": null, "e": 12543, "s": 12445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12577, "s": 12543, "text": "Print Right View of a Binary Tree" }, { "code": null, "e": 12618, "s": 12577, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 12645, "s": 12618, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 12688, "s": 12645, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 12721, "s": 12688, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 12753, "s": 12721, "text": "Introduction to Data Structures" }, { "code": null, "e": 12803, "s": 12753, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 12839, "s": 12803, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 12853, "s": 12839, "text": "Decision Tree" } ]
Python – Itertools.Permutations()
11 Jul, 2022 Itertool is a module provided by Python for creating iterators for efficient looping. It also provides various features or functions that work with iterators to produce complex iterators and help us to solve problems easily and efficiently in terms of time as well as memory. Itertools module provides us various ways to manipulate the sequence that we are traversing through. Different types of iterators provided by this module are: Infinite Iterators Iterators terminating on the shortest input sequence Combinatoric Iterators Note: For more information, refer to Python Itertools Itertools.permutation() function falls under the Combinatoric Generators. The recursive generators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators. As understood by the word “Permutation” it refers to all the possible combinations in which a set or string can be ordered or arranged. Similarly here itertool.permutations() method provides us with all the possible arrangements that can be there for an iterator and all elements are assumed to be unique on the basis of there position and not by there value or category. All these permutations are provided in lexicographical order. The function itertool.permutations() takes an iterator and ‘r’ (length of permutation needed) as input and assumes ‘r’ as default length of iterator if not mentioned and returns all possible permutations of length ‘r’ each. Syntax: Permutations(iterator, r) Example 1:- Python3 from itertools import permutations a = "GeEK" # no length entered so default length# taken as 4(the length of string GeEK)p = permutations(a) # Print the obtained permutationsfor j in list(p): print(j) Output :- ('G', 'e', 'E', 'K') ('G', 'e', 'K', 'E') ('G', 'E', 'e', 'K') ('G', 'E', 'K', 'e') ('G', 'K', 'e', 'E') ('G', 'K', 'E', 'e') ('e', 'G', 'E', 'K') ('e', 'G', 'K', 'E') ('e', 'E', 'G', 'K') ('e', 'E', 'K', 'G') ('e', 'K', 'G', 'E') ('e', 'K', 'E', 'G') ('E', 'G', 'e', 'K') ('E', 'G', 'K', 'e') ('E', 'e', 'G', 'K') ('E', 'e', 'K', 'G') ('E', 'K', 'G', 'e') ('E', 'K', 'e', 'G') ('K', 'G', 'e', 'E') ('K', 'G', 'E', 'e') ('K', 'e', 'G', 'E') ('K', 'e', 'E', 'G') ('K', 'E', 'G', 'e') ('K', 'E', 'e', 'G') Time Complexity: O(n!) where n is the size of the string.Auxiliary Space: O(n*n!) Example 2:- Python3 from itertools import permutations print ("All the permutations of the given list is:")print (list(permutations([1, 'geeks'], 2)))print() print ("All the permutations of the given string is:")print (list(permutations('AB')))print() print ("All the permutations of the given container is:")print(list(permutations(range(3), 2))) Output:- All the permutations of the given list is: [(1, 'geeks'), ('geeks', 1)] All the permutations of the given string is: [('A', 'B'), ('B', 'A')] All the permutations of the given container is: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] pushpeshrajdx01 Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jul, 2022" }, { "code": null, "e": 488, "s": 53, "text": "Itertool is a module provided by Python for creating iterators for efficient looping. It also provides various features or functions that work with iterators to produce complex iterators and help us to solve problems easily and efficiently in terms of time as well as memory. Itertools module provides us various ways to manipulate the sequence that we are traversing through. Different types of iterators provided by this module are:" }, { "code": null, "e": 507, "s": 488, "text": "Infinite Iterators" }, { "code": null, "e": 560, "s": 507, "text": "Iterators terminating on the shortest input sequence" }, { "code": null, "e": 583, "s": 560, "text": "Combinatoric Iterators" }, { "code": null, "e": 637, "s": 583, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 1547, "s": 637, "text": "Itertools.permutation() function falls under the Combinatoric Generators. The recursive generators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators. As understood by the word “Permutation” it refers to all the possible combinations in which a set or string can be ordered or arranged. Similarly here itertool.permutations() method provides us with all the possible arrangements that can be there for an iterator and all elements are assumed to be unique on the basis of there position and not by there value or category. All these permutations are provided in lexicographical order. The function itertool.permutations() takes an iterator and ‘r’ (length of permutation needed) as input and assumes ‘r’ as default length of iterator if not mentioned and returns all possible permutations of length ‘r’ each. Syntax:" }, { "code": null, "e": 1573, "s": 1547, "text": "Permutations(iterator, r)" }, { "code": null, "e": 1586, "s": 1573, "text": "Example 1:- " }, { "code": null, "e": 1594, "s": 1586, "text": "Python3" }, { "code": "from itertools import permutations a = \"GeEK\" # no length entered so default length# taken as 4(the length of string GeEK)p = permutations(a) # Print the obtained permutationsfor j in list(p): print(j)", "e": 1798, "s": 1594, "text": null }, { "code": null, "e": 1808, "s": 1798, "text": "Output :-" }, { "code": null, "e": 2312, "s": 1808, "text": "('G', 'e', 'E', 'K')\n('G', 'e', 'K', 'E')\n('G', 'E', 'e', 'K')\n('G', 'E', 'K', 'e')\n('G', 'K', 'e', 'E')\n('G', 'K', 'E', 'e')\n('e', 'G', 'E', 'K')\n('e', 'G', 'K', 'E')\n('e', 'E', 'G', 'K')\n('e', 'E', 'K', 'G')\n('e', 'K', 'G', 'E')\n('e', 'K', 'E', 'G')\n('E', 'G', 'e', 'K')\n('E', 'G', 'K', 'e')\n('E', 'e', 'G', 'K')\n('E', 'e', 'K', 'G')\n('E', 'K', 'G', 'e')\n('E', 'K', 'e', 'G')\n('K', 'G', 'e', 'E')\n('K', 'G', 'E', 'e')\n('K', 'e', 'G', 'E')\n('K', 'e', 'E', 'G')\n('K', 'E', 'G', 'e')\n('K', 'E', 'e', 'G')" }, { "code": null, "e": 2395, "s": 2312, "text": "Time Complexity: O(n!) where n is the size of the string.Auxiliary Space: O(n*n!) " }, { "code": null, "e": 2408, "s": 2395, "text": "Example 2:- " }, { "code": null, "e": 2416, "s": 2408, "text": "Python3" }, { "code": "from itertools import permutations print (\"All the permutations of the given list is:\")print (list(permutations([1, 'geeks'], 2)))print() print (\"All the permutations of the given string is:\")print (list(permutations('AB')))print() print (\"All the permutations of the given container is:\")print(list(permutations(range(3), 2)))", "e": 2748, "s": 2416, "text": null }, { "code": null, "e": 2757, "s": 2748, "text": "Output:-" }, { "code": null, "e": 2998, "s": 2757, "text": "All the permutations of the given list is:\n[(1, 'geeks'), ('geeks', 1)]\n\nAll the permutations of the given string is:\n[('A', 'B'), ('B', 'A')]\n\nAll the permutations of the given container is:\n[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]" }, { "code": null, "e": 3014, "s": 2998, "text": "pushpeshrajdx01" }, { "code": null, "e": 3031, "s": 3014, "text": "Python-itertools" }, { "code": null, "e": 3038, "s": 3031, "text": "Python" } ]
Sum of product of all elements of sub-arrays of size k
03 Jan, 2022 Given an array and a number k, the task is to calculate the sum of the product of all elements of subarrays of size k.Examples : Input : arr[] = {1, 2, 3, 4, 5, 6} k = 3 Output : 210 Consider all subarrays of size k 1*2*3 = 6 2*3*4 = 24 3*4*5 = 60 4*5*6 = 120 6 + 24 + 60 + 120 = 210 Input : arr[] = {1, -2, 3, -4, 5, 6} k = 2 Output : -10 Consider all subarrays of size k 1*-2 = -2 -2*3 = -6 3*-4 = -12 -4*5 = -20 5*6 = 30 -2 + -6 + -12 + -20+ 30 = -10 A Naive approach is to generate all subarrays of size k and do the sum of product of all elements of subarrays. C++ Java Python3 C# Javascript // C++ program to find the sum of// product of all subarrays#include <iostream>using namespace std; // Function to calculate the sum of productint calcSOP(int arr[], int n, int k){ // Initialize sum = 0 int sum = 0; // Consider every subarray of size k for (int i = 0; i <= n - k; i++) { int prod = 1; // Calculate product of all elements // of current subarray for (int j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all the products sum += prod; } // Return sum return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << calcSOP(arr, n, k); return 0;} // Java program to find the sum of// product of all subarrays class GFG { // Method to calculate the sum of product static int calcSOP(int arr[], int n, int k) { // Initialize sum = 0 int sum = 0; // Consider every subarray of size k for (int i = 0; i <= n - k; i++) { int prod = 1; // Calculate product of all elements // of current subarray for (int j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all the products sum += prod; } // Return sum return sum; } // Driver method public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6 }; int k = 3; System.out.println(calcSOP(arr, arr.length, k)); }} # python program to find the sum of# product of all subarrays # Function to calculate the sum of productdef calcSOP(arr, n, k): # Initialize sum = 0 sum = 0 # Consider every subarray of size k for i in range(0, (n-k)+1): prod = 1 # Calculate product of all elements # of current subarray for j in range(i, k+i): prod = int(prod * arr[j]) # Store sum of all the products sum = sum + prod # Return sum return sum #Driver codearr = [ 1, 2, 3, 4, 5, 6 ]n = len(arr)k = 3print(calcSOP(arr, n, k)) # This code is contributed by Sam007 // C# program to find the sum of// product of all subarraysusing System; public class GFG { // Method to calculate the sum of product static int calcSOP(int[] arr, int n, int k) { // Initialize sum = 0 int sum = 0; // Consider every subarray of size k for (int i = 0; i <= n - k; i++) { int prod = 1; // Calculate product of all elements // of current subarray for (int j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all the products sum += prod; } // Return sum return sum; } // Driver method public static void Main() { int[] arr = {1, 2, 3, 4, 5, 6}; int k = 3; Console.WriteLine(calcSOP(arr, arr.Length, k)); }} // This code is contributed by Sam007 PHP <?php // PHP program to find the sum of // product of all subarrays // Function to calculate // the sum of product function calcSOP($arr, $n, $k) { // Initialize sum = 0 $sum = 0; // Consider every subarray // of size k for ($i = 0; $i <= $n - $k; $i++) { $prod = 1; // Calculate product of all // elements of current subarray for ($j = $i; $j < $k + $i; $j++) $prod *= $arr[$j]; // Store sum of all // the products $sum += $prod; } // Return sum return $sum; } // Driver code $arr = array( 1, 2, 3, 4, 5, 6 ); $n = count($arr); $k = 3; echo calcSOP($arr, $n, $k); // This code is contributed by Sam007 ?> <script>// Javascript program to find the sum of// product of all subarrays // Function to calculate// the sum of productfunction calcSOP(arr, n, k) { // Initialize sum = 0 let sum = 0; // Consider every subarray // of size k for (let i = 0; i <= n - k; i++) { let prod = 1; // Calculate product of all // elements of current subarray for (let j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all // the products sum += prod; } // Return sum return sum;} // Driver codelet arr = new Array(1, 2, 3, 4, 5, 6);let n = arr.length;let k = 3; document.write(calcSOP(arr, n, k)); // This code is contributed by gfgking</script> Output: 210 Time Complexity: O(nk)An Efficient Method is to use the concept of Sliding Window.1- Consider first subarray/window of size k, do the product of elements and add to the total_sum. for (i=0; i < k; i++) prod = prod * arr[i]; 2- Now, By Using sliding window concept, remove first element of window from the product and add next element to the window. i.e. for (i =k ; i < n; i++) { // Removing first element from product prod = prod / arr[i-k]; // Adding current element to the product prod = prod * arr[i]; sum += prod; } 3- Return sum C++ Java Python3 C# PHP Javascript // C++ program to find the sum of// product of all subarrays#include <iostream>using namespace std; // Method to calculate the sum of product int calcSOP(int arr[], int n, int k) { // Initialize sum = 0 and prod = 1 int sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (int i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (int i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (prod / arr[i - k]) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << calcSOP(arr, n, k); return 0;} // This code is contributed by avijitmondal1998. // Java program to find the sum of// product of all subarrays class GFG { // Method to calculate the sum of product static int calcSOP(int arr[], int n, int k) { // Initialize sum = 0 and prod = 1 int sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (int i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (int i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (prod / arr[i - k]) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver method public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6 }; int k = 3; System.out.println(calcSOP(arr, arr.length, k)); }} # Python3 program to find the sum of# product of all subarrays # Function to calculate the sum of productdef calcSOP(arr, n, k): # Initialize sum = 0 and prod = 1 sum = 0 prod = 1 # Consider first subarray of size k # Store the products of elements for i in range(k): prod *= arr[i] # Add the product to the sum sum += prod # Consider every subarray of size k # Remove first element and add current # element to the window for i in range(k, n, 1): # Divide by the first element of # previous subarray/ window and # product with the current element prod = (prod / arr[i - k]) * arr[i] # Add current product to the sum sum += prod # Return sum return int(sum) # Drivers codearr = [1, 2, 3, 4, 5, 6]n = len(arr)k = 3 print(calcSOP(arr, n, k)) # This code is contributed 29AjayKumar // C# program to find the sum of// product of all subarraysusing System; public class GFG { // Method to calculate the sum of product static int calcSOP(int[] arr, int n, int k) { // Initialize sum = 0 and prod = 1 int sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (int i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (int i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (prod / arr[i - k]) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver method public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6 }; int k = 3; // Function calling Console.WriteLine(calcSOP(arr, arr.Length, k)); }} // This code is contributed by Sam007 <?php // php program to find the sum of// product of all subarrays // Function to calculate the sum of productfunction calcSOP($arr, $n, $k){ // Initialize sum = 0 and prod = 1 $sum = 0; $prod = 1; // Consider first subarray of size k // Store the products of elements for ($i = 0; $i < $k; $i++) $prod *= $arr[$i]; // Add the product to the sum $sum += $prod; // Consider every subarray of size k // Remove first element and add current // element to the window for ($i = $k; $i < $n; $i++) { // Divide by the first element // of previous subarray/ window // and product with the current element $prod = ($prod / $arr[$i - $k]) * $arr[$i]; // Add current product to the sum $sum += $prod; } // Return sum return $sum;} // Drivers code $arr = array( 1, 2, 3, 4, 5, 6 ); $n = count($arr); $k = 3; echo calcSOP($arr, $n, $k); // This code is contributed by Sam007?> <script> // JavaScript program for the above approach function calcSOP(arr,n,k) { // Initialize sum = 0 and prod = 1 let sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (let i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (let i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (Math.floor(prod / arr[i - k])) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver method let arr= [1, 2, 3, 4, 5, 6 ]; let k = 3; document.write(calcSOP(arr, arr.length, k)); // This code is contributed by Potta Lokesh </script> Output: 210 Time Complexity: O(n)This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 29AjayKumar nidhi_biet gfgking lokeshpotta20 avijitmondal1998 sliding-window Arrays sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) K'th Smallest/Largest Element in Unsorted Array | Set 1 Python | Using 2D arrays/lists the right way Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jan, 2022" }, { "code": null, "e": 183, "s": 52, "text": "Given an array and a number k, the task is to calculate the sum of the product of all elements of subarrays of size k.Examples : " }, { "code": null, "e": 542, "s": 183, "text": "Input : arr[] = {1, 2, 3, 4, 5, 6} \n k = 3\nOutput : 210\nConsider all subarrays of size k\n1*2*3 = 6\n2*3*4 = 24\n3*4*5 = 60\n4*5*6 = 120\n6 + 24 + 60 + 120 = 210\n\nInput : arr[] = {1, -2, 3, -4, 5, 6} \n k = 2\nOutput : -10\nConsider all subarrays of size k\n1*-2 = -2\n-2*3 = -6\n3*-4 = -12\n-4*5 = -20\n5*6 = 30\n-2 + -6 + -12 + -20+ 30 = -10" }, { "code": null, "e": 659, "s": 544, "text": "A Naive approach is to generate all subarrays of size k and do the sum of product of all elements of subarrays. " }, { "code": null, "e": 663, "s": 659, "text": "C++" }, { "code": null, "e": 668, "s": 663, "text": "Java" }, { "code": null, "e": 676, "s": 668, "text": "Python3" }, { "code": null, "e": 679, "s": 676, "text": "C#" }, { "code": null, "e": 690, "s": 679, "text": "Javascript" }, { "code": "// C++ program to find the sum of// product of all subarrays#include <iostream>using namespace std; // Function to calculate the sum of productint calcSOP(int arr[], int n, int k){ // Initialize sum = 0 int sum = 0; // Consider every subarray of size k for (int i = 0; i <= n - k; i++) { int prod = 1; // Calculate product of all elements // of current subarray for (int j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all the products sum += prod; } // Return sum return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << calcSOP(arr, n, k); return 0;}", "e": 1418, "s": 690, "text": null }, { "code": "// Java program to find the sum of// product of all subarrays class GFG { // Method to calculate the sum of product static int calcSOP(int arr[], int n, int k) { // Initialize sum = 0 int sum = 0; // Consider every subarray of size k for (int i = 0; i <= n - k; i++) { int prod = 1; // Calculate product of all elements // of current subarray for (int j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all the products sum += prod; } // Return sum return sum; } // Driver method public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6 }; int k = 3; System.out.println(calcSOP(arr, arr.length, k)); }}", "e": 2221, "s": 1418, "text": null }, { "code": "# python program to find the sum of# product of all subarrays # Function to calculate the sum of productdef calcSOP(arr, n, k): # Initialize sum = 0 sum = 0 # Consider every subarray of size k for i in range(0, (n-k)+1): prod = 1 # Calculate product of all elements # of current subarray for j in range(i, k+i): prod = int(prod * arr[j]) # Store sum of all the products sum = sum + prod # Return sum return sum #Driver codearr = [ 1, 2, 3, 4, 5, 6 ]n = len(arr)k = 3print(calcSOP(arr, n, k)) # This code is contributed by Sam007", "e": 2842, "s": 2221, "text": null }, { "code": "// C# program to find the sum of// product of all subarraysusing System; public class GFG { // Method to calculate the sum of product static int calcSOP(int[] arr, int n, int k) { // Initialize sum = 0 int sum = 0; // Consider every subarray of size k for (int i = 0; i <= n - k; i++) { int prod = 1; // Calculate product of all elements // of current subarray for (int j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all the products sum += prod; } // Return sum return sum; } // Driver method public static void Main() { int[] arr = {1, 2, 3, 4, 5, 6}; int k = 3; Console.WriteLine(calcSOP(arr, arr.Length, k)); }} // This code is contributed by Sam007", "e": 3690, "s": 2842, "text": null }, { "code": null, "e": 3695, "s": 3690, "text": "PHP " }, { "code": null, "e": 4453, "s": 3695, "text": "\n<?php\n// PHP program to find the sum of\n// product of all subarrays\n\n// Function to calculate\n// the sum of product\nfunction calcSOP($arr, $n, $k)\n{\n \n // Initialize sum = 0\n $sum = 0;\n\n // Consider every subarray \n // of size k\n for ($i = 0; $i <= $n - $k; $i++)\n {\n $prod = 1;\n\n // Calculate product of all \n // elements of current subarray\n for ($j = $i; $j < $k + $i; $j++)\n $prod *= $arr[$j];\n\n // Store sum of all \n // the products\n $sum += $prod;\n }\n\n // Return sum\n return $sum;\n}\n\n // Driver code\n $arr = array( 1, 2, 3, 4, 5, 6 );\n $n = count($arr);\n $k = 3;\n\n echo calcSOP($arr, $n, $k);\n \n// This code is contributed by Sam007\n?>\n\n\n" }, { "code": "<script>// Javascript program to find the sum of// product of all subarrays // Function to calculate// the sum of productfunction calcSOP(arr, n, k) { // Initialize sum = 0 let sum = 0; // Consider every subarray // of size k for (let i = 0; i <= n - k; i++) { let prod = 1; // Calculate product of all // elements of current subarray for (let j = i; j < k + i; j++) prod *= arr[j]; // Store sum of all // the products sum += prod; } // Return sum return sum;} // Driver codelet arr = new Array(1, 2, 3, 4, 5, 6);let n = arr.length;let k = 3; document.write(calcSOP(arr, n, k)); // This code is contributed by gfgking</script>", "e": 5169, "s": 4453, "text": null }, { "code": null, "e": 5179, "s": 5169, "text": "Output: " }, { "code": null, "e": 5183, "s": 5179, "text": "210" }, { "code": null, "e": 5365, "s": 5183, "text": "Time Complexity: O(nk)An Efficient Method is to use the concept of Sliding Window.1- Consider first subarray/window of size k, do the product of elements and add to the total_sum. " }, { "code": null, "e": 5417, "s": 5365, "text": " for (i=0; i < k; i++)\n prod = prod * arr[i];" }, { "code": null, "e": 5549, "s": 5417, "text": "2- Now, By Using sliding window concept, remove first element of window from the product and add next element to the window. i.e. " }, { "code": null, "e": 5750, "s": 5549, "text": "for (i =k ; i < n; i++)\n {\n // Removing first element from product \n prod = prod / arr[i-k]; \n\n // Adding current element to the product\n prod = prod * arr[i]; \n sum += prod;\n }" }, { "code": null, "e": 5766, "s": 5750, "text": "3- Return sum " }, { "code": null, "e": 5770, "s": 5766, "text": "C++" }, { "code": null, "e": 5775, "s": 5770, "text": "Java" }, { "code": null, "e": 5783, "s": 5775, "text": "Python3" }, { "code": null, "e": 5786, "s": 5783, "text": "C#" }, { "code": null, "e": 5790, "s": 5786, "text": "PHP" }, { "code": null, "e": 5801, "s": 5790, "text": "Javascript" }, { "code": "// C++ program to find the sum of// product of all subarrays#include <iostream>using namespace std; // Method to calculate the sum of product int calcSOP(int arr[], int n, int k) { // Initialize sum = 0 and prod = 1 int sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (int i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (int i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (prod / arr[i - k]) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << calcSOP(arr, n, k); return 0;} // This code is contributed by avijitmondal1998.", "e": 6955, "s": 5801, "text": null }, { "code": "// Java program to find the sum of// product of all subarrays class GFG { // Method to calculate the sum of product static int calcSOP(int arr[], int n, int k) { // Initialize sum = 0 and prod = 1 int sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (int i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (int i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (prod / arr[i - k]) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver method public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6 }; int k = 3; System.out.println(calcSOP(arr, arr.length, k)); }}", "e": 8065, "s": 6955, "text": null }, { "code": "# Python3 program to find the sum of# product of all subarrays # Function to calculate the sum of productdef calcSOP(arr, n, k): # Initialize sum = 0 and prod = 1 sum = 0 prod = 1 # Consider first subarray of size k # Store the products of elements for i in range(k): prod *= arr[i] # Add the product to the sum sum += prod # Consider every subarray of size k # Remove first element and add current # element to the window for i in range(k, n, 1): # Divide by the first element of # previous subarray/ window and # product with the current element prod = (prod / arr[i - k]) * arr[i] # Add current product to the sum sum += prod # Return sum return int(sum) # Drivers codearr = [1, 2, 3, 4, 5, 6]n = len(arr)k = 3 print(calcSOP(arr, n, k)) # This code is contributed 29AjayKumar", "e": 8955, "s": 8065, "text": null }, { "code": "// C# program to find the sum of// product of all subarraysusing System; public class GFG { // Method to calculate the sum of product static int calcSOP(int[] arr, int n, int k) { // Initialize sum = 0 and prod = 1 int sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (int i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (int i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (prod / arr[i - k]) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver method public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6 }; int k = 3; // Function calling Console.WriteLine(calcSOP(arr, arr.Length, k)); }} // This code is contributed by Sam007", "e": 10147, "s": 8955, "text": null }, { "code": "<?php // php program to find the sum of// product of all subarrays // Function to calculate the sum of productfunction calcSOP($arr, $n, $k){ // Initialize sum = 0 and prod = 1 $sum = 0; $prod = 1; // Consider first subarray of size k // Store the products of elements for ($i = 0; $i < $k; $i++) $prod *= $arr[$i]; // Add the product to the sum $sum += $prod; // Consider every subarray of size k // Remove first element and add current // element to the window for ($i = $k; $i < $n; $i++) { // Divide by the first element // of previous subarray/ window // and product with the current element $prod = ($prod / $arr[$i - $k]) * $arr[$i]; // Add current product to the sum $sum += $prod; } // Return sum return $sum;} // Drivers code $arr = array( 1, 2, 3, 4, 5, 6 ); $n = count($arr); $k = 3; echo calcSOP($arr, $n, $k); // This code is contributed by Sam007?>", "e": 11133, "s": 10147, "text": null }, { "code": "<script> // JavaScript program for the above approach function calcSOP(arr,n,k) { // Initialize sum = 0 and prod = 1 let sum = 0, prod = 1; // Consider first subarray of size k // Store the products of elements for (let i = 0; i < k; i++) prod *= arr[i]; // Add the product to the sum sum += prod; // Consider every subarray of size k // Remove first element and add current // element to the window for (let i = k; i < n; i++) { // Divide by the first element // of previous subarray/ window // and product with the current element prod = (Math.floor(prod / arr[i - k])) * arr[i]; // Add current product to the sum sum += prod; } // Return sum return sum; } // Driver method let arr= [1, 2, 3, 4, 5, 6 ]; let k = 3; document.write(calcSOP(arr, arr.length, k)); // This code is contributed by Potta Lokesh </script>", "e": 12185, "s": 11133, "text": null }, { "code": null, "e": 12195, "s": 12185, "text": "Output: " }, { "code": null, "e": 12199, "s": 12195, "text": "210" }, { "code": null, "e": 12642, "s": 12199, "text": "Time Complexity: O(n)This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12649, "s": 12642, "text": "Sam007" }, { "code": null, "e": 12661, "s": 12649, "text": "29AjayKumar" }, { "code": null, "e": 12672, "s": 12661, "text": "nidhi_biet" }, { "code": null, "e": 12680, "s": 12672, "text": "gfgking" }, { "code": null, "e": 12694, "s": 12680, "text": "lokeshpotta20" }, { "code": null, "e": 12711, "s": 12694, "text": "avijitmondal1998" }, { "code": null, "e": 12726, "s": 12711, "text": "sliding-window" }, { "code": null, "e": 12733, "s": 12726, "text": "Arrays" }, { "code": null, "e": 12748, "s": 12733, "text": "sliding-window" }, { "code": null, "e": 12755, "s": 12748, "text": "Arrays" }, { "code": null, "e": 12853, "s": 12755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12921, "s": 12853, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 12965, "s": 12921, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 12997, "s": 12965, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 13045, "s": 12997, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 13059, "s": 13045, "text": "Linear Search" }, { "code": null, "e": 13082, "s": 13059, "text": "Introduction to Arrays" }, { "code": null, "e": 13167, "s": 13082, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 13223, "s": 13167, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 13268, "s": 13223, "text": "Python | Using 2D arrays/lists the right way" } ]
Python | Pandas Series.iloc
28 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.iloc attribute enables purely integer-location based indexing for selection by position over the given Series object. Syntax:Series.iloc Parameter : None Returns : Series Example #1: Use Series.iloc attribute to perform indexing over the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr) Output : Now we will use Series.iloc attribute to perform indexing over the given Series object. # slice the object element in the # passed rangesr.iloc[0:2] Output : As we can see in the output, the Series.iloc attribute has returned a series object containing the sliced element from the original Series object. Example #2 : Use Series.iloc attribute to perform indexing over the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr) Output : Now we will use Series.iloc attribute to perform indexing over the given Series object. # slice the object element in the # passed rangesr.iloc[1:3] Output :As we can see in the output, the Series.iloc attribute has returned a series object containing the sliced element from the original Series object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python 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 Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 499, "s": 242, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 631, "s": 499, "text": "Pandas Series.iloc attribute enables purely integer-location based indexing for selection by position over the given Series object." }, { "code": null, "e": 650, "s": 631, "text": "Syntax:Series.iloc" }, { "code": null, "e": 667, "s": 650, "text": "Parameter : None" }, { "code": null, "e": 684, "s": 667, "text": "Returns : Series" }, { "code": null, "e": 772, "s": 684, "text": "Example #1: Use Series.iloc attribute to perform indexing over the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)", "e": 1012, "s": 772, "text": null }, { "code": null, "e": 1021, "s": 1012, "text": "Output :" }, { "code": null, "e": 1109, "s": 1021, "text": "Now we will use Series.iloc attribute to perform indexing over the given Series object." }, { "code": "# slice the object element in the # passed rangesr.iloc[0:2]", "e": 1170, "s": 1109, "text": null }, { "code": null, "e": 1179, "s": 1170, "text": "Output :" }, { "code": null, "e": 1415, "s": 1179, "text": "As we can see in the output, the Series.iloc attribute has returned a series object containing the sliced element from the original Series object. Example #2 : Use Series.iloc attribute to perform indexing over the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)", "e": 1654, "s": 1415, "text": null }, { "code": null, "e": 1663, "s": 1654, "text": "Output :" }, { "code": null, "e": 1751, "s": 1663, "text": "Now we will use Series.iloc attribute to perform indexing over the given Series object." }, { "code": "# slice the object element in the # passed rangesr.iloc[1:3]", "e": 1812, "s": 1751, "text": null }, { "code": null, "e": 1967, "s": 1812, "text": "Output :As we can see in the output, the Series.iloc attribute has returned a series object containing the sliced element from the original Series object." }, { "code": null, "e": 1988, "s": 1967, "text": "Python pandas-series" }, { "code": null, "e": 2017, "s": 1988, "text": "Python pandas-series-methods" }, { "code": null, "e": 2031, "s": 2017, "text": "Python-pandas" }, { "code": null, "e": 2038, "s": 2031, "text": "Python" }, { "code": null, "e": 2136, "s": 2038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2154, "s": 2136, "text": "Python Dictionary" }, { "code": null, "e": 2196, "s": 2154, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2218, "s": 2196, "text": "Enumerate() in Python" }, { "code": null, "e": 2253, "s": 2218, "text": "Read a file line by line in Python" }, { "code": null, "e": 2285, "s": 2253, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2314, "s": 2285, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2344, "s": 2314, "text": "Iterate over a list in Python" }, { "code": null, "e": 2371, "s": 2344, "text": "Python Classes and Objects" }, { "code": null, "e": 2407, "s": 2371, "text": "Convert integer to string in Python" } ]
How to Pass Video Using Intent Between Activities in Android?
23 Dec, 2021 In android, An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. In this article, we will learn that how we can pass Video using Intent between two activities and then play that video in the second activity. Here is a sample video of what we are going to build in this application. Note that we are going to implement this application using Java language. Step 1: Create a New Project Open a new project. We will be working on Empty Activity with language as Java. Leave all other options unchanged. You can change the name of the project at your convenience. There will be two default files named activity_main.xml and MainActivity.java. If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2: Adding storage permission Follow the path app > manifests > AndroidManifest.xml and paste the following piece of code in it. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> Step 3: Working on XML files 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: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"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bt_select" android:text="Select Video" android:layout_centerInParent="true" /> </RelativeLayout> Follow the path app > right click > new > activity > Empty Activity > name it as “MainActvity2”. Navigate to the app > res > layout > activity_main2.xml and add the below code to that file. Below is the code for the activity_main2.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.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=".MainActivity2"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:fitsSystemWindows="true"> <VideoView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/video_view"/> </RelativeLayout> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Working on java files 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 package com.example.videointent; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Initialize variables Button btSelect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Assign variable btSelect=findViewById(R.id.bt_select); btSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Check condition if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // When permission is not granted // Request permission ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE} ,1); } else { // When permission is granted // Create method selectVideo(); } } }); } private void selectVideo() { // Initialize intent Intent intent=new Intent(Intent.ACTION_PICK); // set type intent.setType("video/*"); // start activity result startActivityForResult(Intent.createChooser(intent,"Select Video"),100); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // Check condition if(requestCode==1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // When permission is granted // Call method selectVideo(); } else { // When permission is denied // Display toast Toast.makeText(getApplicationContext() ,"Permission denied",Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Check condition if(requestCode==100 && resultCode==RESULT_OK && data!=null) { // When result code is okay // Initialize uri Uri uri=data.getData(); // Initialize intent Intent intent=new Intent(this,MainActivity2.class); // Put extra intent.putExtra("uri",uri.toString()); // Start activity startActivity(intent); } }} Go to the MainActivity2.java file and refer to the following code. Below is the code for the MainActivity2.java file. Comments are added inside the code to understand the code in more detail. Java package com.example.videointent; import androidx.appcompat.app.AppCompatActivity; import android.net.Uri;import android.os.Bundle;import android.widget.VideoView; public class MainActivity2 extends AppCompatActivity { // Initialize variables VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // Assign variables videoView=findViewById(R.id.video_view); // Get data from main activity Bundle bundle=getIntent().getExtras(); // Check condition if(bundle!=null) { // When bundle not equal to null // Initialize uri Uri uri=Uri.parse(bundle.getString("uri")); // Set video uri videoView.setVideoURI(uri); // Start video videoView.start(); } }} Here is the final output of our application. Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 372, "s": 28, "text": "In android, An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed." }, { "code": null, "e": 663, "s": 372, "text": "In this article, we will learn that how we can pass Video using Intent between two activities and then play that video in the second activity. Here is a sample video of what we are going to build in this application. Note that we are going to implement this application using Java language." }, { "code": null, "e": 692, "s": 663, "text": "Step 1: Create a New Project" }, { "code": null, "e": 712, "s": 692, "text": "Open a new project." }, { "code": null, "e": 807, "s": 712, "text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged." }, { "code": null, "e": 867, "s": 807, "text": "You can change the name of the project at your convenience." }, { "code": null, "e": 946, "s": 867, "text": "There will be two default files named activity_main.xml and MainActivity.java." }, { "code": null, "e": 1086, "s": 946, "text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? " }, { "code": null, "e": 1120, "s": 1086, "text": "Step 2: Adding storage permission" }, { "code": null, "e": 1219, "s": 1120, "text": "Follow the path app > manifests > AndroidManifest.xml and paste the following piece of code in it." }, { "code": null, "e": 1294, "s": 1219, "text": "<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>" }, { "code": null, "e": 1323, "s": 1294, "text": "Step 3: Working on XML files" }, { "code": null, "e": 1465, "s": 1323, "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": 1469, "s": 1465, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/bt_select\" android:text=\"Select Video\" android:layout_centerInParent=\"true\" /> </RelativeLayout>", "e": 2039, "s": 1469, "text": null }, { "code": null, "e": 2280, "s": 2039, "text": "Follow the path app > right click > new > activity > Empty Activity > name it as “MainActvity2”. Navigate to the app > res > layout > activity_main2.xml and add the below code to that file. Below is the code for the activity_main2.xml file." }, { "code": null, "e": 2284, "s": 2280, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.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=\".MainActivity2\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:clipToPadding=\"false\" android:fitsSystemWindows=\"true\"> <VideoView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/video_view\"/> </RelativeLayout> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3075, "s": 2284, "text": null }, { "code": null, "e": 3105, "s": 3075, "text": "Step 4: Working on java files" }, { "code": null, "e": 3295, "s": 3105, "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": 3300, "s": 3295, "text": "Java" }, { "code": "package com.example.videointent; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Initialize variables Button btSelect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Assign variable btSelect=findViewById(R.id.bt_select); btSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Check condition if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // When permission is not granted // Request permission ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE} ,1); } else { // When permission is granted // Create method selectVideo(); } } }); } private void selectVideo() { // Initialize intent Intent intent=new Intent(Intent.ACTION_PICK); // set type intent.setType(\"video/*\"); // start activity result startActivityForResult(Intent.createChooser(intent,\"Select Video\"),100); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // Check condition if(requestCode==1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // When permission is granted // Call method selectVideo(); } else { // When permission is denied // Display toast Toast.makeText(getApplicationContext() ,\"Permission denied\",Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Check condition if(requestCode==100 && resultCode==RESULT_OK && data!=null) { // When result code is okay // Initialize uri Uri uri=data.getData(); // Initialize intent Intent intent=new Intent(this,MainActivity2.class); // Put extra intent.putExtra(\"uri\",uri.toString()); // Start activity startActivity(intent); } }}", "e": 6484, "s": 3300, "text": null }, { "code": null, "e": 6676, "s": 6484, "text": "Go to the MainActivity2.java file and refer to the following code. Below is the code for the MainActivity2.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 6681, "s": 6676, "text": "Java" }, { "code": "package com.example.videointent; import androidx.appcompat.app.AppCompatActivity; import android.net.Uri;import android.os.Bundle;import android.widget.VideoView; public class MainActivity2 extends AppCompatActivity { // Initialize variables VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // Assign variables videoView=findViewById(R.id.video_view); // Get data from main activity Bundle bundle=getIntent().getExtras(); // Check condition if(bundle!=null) { // When bundle not equal to null // Initialize uri Uri uri=Uri.parse(bundle.getString(\"uri\")); // Set video uri videoView.setVideoURI(uri); // Start video videoView.start(); } }}", "e": 7605, "s": 6681, "text": null }, { "code": null, "e": 7650, "s": 7605, "text": "Here is the final output of our application." }, { "code": null, "e": 7658, "s": 7650, "text": "Output:" }, { "code": null, "e": 7666, "s": 7658, "text": "Android" }, { "code": null, "e": 7671, "s": 7666, "text": "Java" }, { "code": null, "e": 7676, "s": 7671, "text": "Java" }, { "code": null, "e": 7684, "s": 7676, "text": "Android" }, { "code": null, "e": 7782, "s": 7684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7851, "s": 7782, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 7883, "s": 7851, "text": "Android SDK and it's Components" }, { "code": null, "e": 7932, "s": 7883, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 7971, "s": 7932, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8013, "s": 7971, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8028, "s": 8013, "text": "Arrays in Java" }, { "code": null, "e": 8072, "s": 8028, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8108, "s": 8072, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8159, "s": 8108, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
PyQt5 QSpinBox – Setting Maximum value
06 May, 2020 In this article we will see how we can set the maximum value i.e upper bound of the spin box, by default when we create a spin box it ranges from 0 to 99 i.e its maximum value is 99 although we can change this. In order to do this we will use spin_box.setMaximum method Syntax : spin_box.setMaximum(n) Argument : It takes integer as argument Return : None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 100, 40) # setting maximum value self.spin.setMaximum(5) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2020" }, { "code": null, "e": 239, "s": 28, "text": "In this article we will see how we can set the maximum value i.e upper bound of the spin box, by default when we create a spin box it ranges from 0 to 99 i.e its maximum value is 99 although we can change this." }, { "code": null, "e": 298, "s": 239, "text": "In order to do this we will use spin_box.setMaximum method" }, { "code": null, "e": 330, "s": 298, "text": "Syntax : spin_box.setMaximum(n)" }, { "code": null, "e": 370, "s": 330, "text": "Argument : It takes integer as argument" }, { "code": null, "e": 384, "s": 370, "text": "Return : None" }, { "code": null, "e": 412, "s": 384, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 100, 40) # setting maximum value self.spin.setMaximum(5) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec())", "e": 1305, "s": 412, "text": null }, { "code": null, "e": 1314, "s": 1305, "text": "Output :" }, { "code": null, "e": 1334, "s": 1314, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 1345, "s": 1334, "text": "Python-gui" }, { "code": null, "e": 1357, "s": 1345, "text": "Python-PyQt" }, { "code": null, "e": 1364, "s": 1357, "text": "Python" } ]
Matplotlib.figure.Figure.gca() in Python
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The gca() method figure module of matplotlib library is used to get the current axes. Syntax: gca(self, **kwargs) Parameters: This method does not accept any parameters. Returns: This method returns the current axes. Below examples illustrate the matplotlib.figure.Figure.gca() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspecfrom mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all')arr = np.arange(100).reshape((10, 10))fig = plt.figure(figsize =(4, 4)) im = plt.imshow(arr, interpolation ="none", cmap ="plasma") divider = make_axes_locatable(fig.gca())cax = divider.append_axes("left", "15 %", pad ="30 %") plt.colorbar(im, cax = cax) fig.suptitle('matplotlib.figure.Figure.gca()\ function Example', fontweight ="bold") plt.show() Output: Example 2: #Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np ang = 3radi = 8radii = np.linspace(0.25, 0.95, radi) res = np.linspace(0, 4 * np.pi, ang)res = np.repeat(res[..., np.newaxis], radi, axis=1)res[:, 1::2] += np.pi / ang x = (radii*np.cos(2*res)).flatten()y = (radii*np.sin(2*res)).flatten() triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < 0.25) trifinder = triang.get_trifinder() fig = plt.figure()plt.triplot(triang, 'go-')polygon = Polygon([[0, 0], [0, 0]], facecolor='r') def update_polygon(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(np.column_stack([xs, ys])) def motion_notify(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) update_polygon(tri) fig.suptitle('matplotlib.figure.Figure.gca()\ function Example\n\n Potion number : %i' % tri, fontweight="bold") event.canvas.draw() update_polygon(-1)fig.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify) plt.show() Output: Matplotlib figure-class 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 Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 425, "s": 339, "text": "The gca() method figure module of matplotlib library is used to get the current axes." }, { "code": null, "e": 453, "s": 425, "text": "Syntax: gca(self, **kwargs)" }, { "code": null, "e": 509, "s": 453, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 556, "s": 509, "text": "Returns: This method returns the current axes." }, { "code": null, "e": 648, "s": 556, "text": "Below examples illustrate the matplotlib.figure.Figure.gca() function in matplotlib.figure:" }, { "code": null, "e": 659, "s": 648, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.gridspec as gridspecfrom mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all')arr = np.arange(100).reshape((10, 10))fig = plt.figure(figsize =(4, 4)) im = plt.imshow(arr, interpolation =\"none\", cmap =\"plasma\") divider = make_axes_locatable(fig.gca())cax = divider.append_axes(\"left\", \"15 %\", pad =\"30 %\") plt.colorbar(im, cax = cax) fig.suptitle('matplotlib.figure.Figure.gca()\\ function Example', fontweight =\"bold\") plt.show()", "e": 1302, "s": 659, "text": null }, { "code": null, "e": 1310, "s": 1302, "text": "Output:" }, { "code": null, "e": 1321, "s": 1310, "text": "Example 2:" }, { "code": "#Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np ang = 3radi = 8radii = np.linspace(0.25, 0.95, radi) res = np.linspace(0, 4 * np.pi, ang)res = np.repeat(res[..., np.newaxis], radi, axis=1)res[:, 1::2] += np.pi / ang x = (radii*np.cos(2*res)).flatten()y = (radii*np.sin(2*res)).flatten() triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < 0.25) trifinder = triang.get_trifinder() fig = plt.figure()plt.triplot(triang, 'go-')polygon = Polygon([[0, 0], [0, 0]], facecolor='r') def update_polygon(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(np.column_stack([xs, ys])) def motion_notify(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) update_polygon(tri) fig.suptitle('matplotlib.figure.Figure.gca()\\ function Example\\n\\n Potion number : %i' % tri, fontweight=\"bold\") event.canvas.draw() update_polygon(-1)fig.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify) plt.show()", "e": 2779, "s": 1321, "text": null }, { "code": null, "e": 2787, "s": 2779, "text": "Output:" }, { "code": null, "e": 2811, "s": 2787, "text": "Matplotlib figure-class" }, { "code": null, "e": 2829, "s": 2811, "text": "Python-matplotlib" }, { "code": null, "e": 2836, "s": 2829, "text": "Python" }, { "code": null, "e": 2934, "s": 2836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2952, "s": 2934, "text": "Python Dictionary" }, { "code": null, "e": 2994, "s": 2952, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3016, "s": 2994, "text": "Enumerate() in Python" }, { "code": null, "e": 3051, "s": 3016, "text": "Read a file line by line in Python" }, { "code": null, "e": 3077, "s": 3051, "text": "Python String | replace()" }, { "code": null, "e": 3109, "s": 3077, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3138, "s": 3109, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3165, "s": 3138, "text": "Python Classes and Objects" }, { "code": null, "e": 3195, "s": 3165, "text": "Iterate over a list in Python" } ]
Java String getChars() with examples
04 Feb, 2022 The java string getChars() method copies characters from the given string into the destination character array.Syntax: public void getChars(int srhStartIndex, int srhEndIndex, char[] destArray, int destStartIndex) Parameters: srhStartIndex : Index of the first character in the string to copy. srhEndIndex : Index after the last character in the string to copy. destArray : Destination array where chars will get copied. destStartIndex : Index in the array starting from where the chars will be pushed into the array. Return: It does not return any value. Exception: StringIndexOutOfBoundsException – If srhStartIndex, srhEndIndex are not in proper range.Example : To show working of getChars() method java // Java program to demonstrate// working of getChars() method class Gfg1 { public static void main(String args[]) { String str = "Welcome! to GeeksforGeeks"; char[] destArray = new char[20]; try { str.getChars(12, 25, destArray, 0); System.out.println(destArray); } catch (Exception ex) { System.out.println(ex); } }} Output: GeeksforGeeks java // Java program to demonstrate// exception condition in// working of getChars() method class Gfg2 { public static void main(String args[]) { String str = "Welcome! to GeeksforGeeks"; char[] destArray = new char[20]; try { // Starting index 0 and ending index 24 str.getChars(12, 26, destArray, 0); System.out.println(destArray); } catch (Exception ex) { System.out.println(ex); } }} Output: java.lang.StringIndexOutOfBoundsException: String index out of range: 26 gulshankumarar231 Java-Functions Java-lang package Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Feb, 2022" }, { "code": null, "e": 174, "s": 53, "text": "The java string getChars() method copies characters from the given string into the destination character array.Syntax: " }, { "code": null, "e": 635, "s": 174, "text": "public void getChars(int srhStartIndex, \nint srhEndIndex, char[] destArray, int destStartIndex) \nParameters:\nsrhStartIndex : Index of the first character in the string to copy. \nsrhEndIndex : Index after the last character in the string to copy.\ndestArray : Destination array where chars will get copied.\ndestStartIndex : Index in the array starting from where the chars\n will be pushed into the array.\nReturn: It does not return any value." }, { "code": null, "e": 783, "s": 635, "text": "Exception: StringIndexOutOfBoundsException – If srhStartIndex, srhEndIndex are not in proper range.Example : To show working of getChars() method " }, { "code": null, "e": 788, "s": 783, "text": "java" }, { "code": "// Java program to demonstrate// working of getChars() method class Gfg1 { public static void main(String args[]) { String str = \"Welcome! to GeeksforGeeks\"; char[] destArray = new char[20]; try { str.getChars(12, 25, destArray, 0); System.out.println(destArray); } catch (Exception ex) { System.out.println(ex); } }}", "e": 1191, "s": 788, "text": null }, { "code": null, "e": 1201, "s": 1191, "text": "Output: " }, { "code": null, "e": 1215, "s": 1201, "text": "GeeksforGeeks" }, { "code": null, "e": 1222, "s": 1217, "text": "java" }, { "code": "// Java program to demonstrate// exception condition in// working of getChars() method class Gfg2 { public static void main(String args[]) { String str = \"Welcome! to GeeksforGeeks\"; char[] destArray = new char[20]; try { // Starting index 0 and ending index 24 str.getChars(12, 26, destArray, 0); System.out.println(destArray); } catch (Exception ex) { System.out.println(ex); } }}", "e": 1701, "s": 1222, "text": null }, { "code": null, "e": 1711, "s": 1701, "text": "Output: " }, { "code": null, "e": 1784, "s": 1711, "text": "java.lang.StringIndexOutOfBoundsException: String index out of range: 26" }, { "code": null, "e": 1804, "s": 1786, "text": "gulshankumarar231" }, { "code": null, "e": 1819, "s": 1804, "text": "Java-Functions" }, { "code": null, "e": 1837, "s": 1819, "text": "Java-lang package" }, { "code": null, "e": 1850, "s": 1837, "text": "Java-Strings" }, { "code": null, "e": 1855, "s": 1850, "text": "Java" }, { "code": null, "e": 1868, "s": 1855, "text": "Java-Strings" }, { "code": null, "e": 1873, "s": 1868, "text": "Java" }, { "code": null, "e": 1971, "s": 1873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1990, "s": 1971, "text": "Interfaces in Java" }, { "code": null, "e": 2008, "s": 1990, "text": "ArrayList in Java" }, { "code": null, "e": 2023, "s": 2008, "text": "Stream In Java" }, { "code": null, "e": 2043, "s": 2023, "text": "Collections in Java" }, { "code": null, "e": 2075, "s": 2043, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2099, "s": 2075, "text": "Singleton Class in Java" }, { "code": null, "e": 2119, "s": 2099, "text": "Stack Class in Java" }, { "code": null, "e": 2131, "s": 2119, "text": "Set in Java" }, { "code": null, "e": 2152, "s": 2131, "text": "Introduction to Java" } ]
Java Program for Binary Search (Recursive and Iterative)
13 Jun, 2022 So as we all know binary search is one of the searching algorithms that is most frequently applied while dealing with data structures where the eccentric goal is not to traverse the whole array. Here array must be sorted as we check the middle element and ignore the half of the array which is of no use as per the number system. We basically ignore half of the elements just after one comparison. So do we keep on iterating till the element is found or land upon a conclusion that element is not present n the array. Algorithms: Compare x with the middle element.If x matches with the middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.Else (x is smaller) recur for the left half. Compare x with the middle element. If x matches with the middle element, we return the mid index. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half. Else (x is smaller) recur for the left half. Example 1 Java // Java Program to Illustrate// Iterative Binary Search // Main class// BinarySearchclass GFG { // Method 1 // Returns index of x // if it is present in arr[], // else return -1 int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; // Checking element in whole array while (l <= r) { int m = l + (r - l) / 2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, // element is on left side // so ignore right half else r = m - 1; } // If we reach here, // element is not present return -1; } // Method 2 // Main driver method public static void main(String args[]) { GFG ob = new GFG(); // Input array int arr[] = { 2, 3, 4, 10, 40 }; // Length of array int n = arr.length; // Element to be checked if present or not int x = 10; // Calling the method 1 and // storing result int result = ob.binarySearch(arr, x); // Element present if (result == -1) // Print statement System.out.println("Element not present"); // Element not present else // Print statement System.out.println("Element found at index " + result); }} Element found at index 3 Time Complexity: O(log n) Auxiliary Space: O(1) Example 2 Java // Java Program to Illustrate Recursive Binary Search // Importing required classesimport java.util.*; // Main classclass GFG { // Method 1 // Recursive binary search // Returns index of x if it is present // in arr[l..r], else return -1 int binarySearch(int arr[], int l, int r, int x) { // Restrict the boundary of right index // and the left index to prevent // overflow of indices if (r >= l && l <= arr.length - 1) { int mid = l + (r - l) / 2; // If the element is present // at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can // only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in // array return -1; } // Method 2 // Main driver method public static void main(String args[]) { // Creating object of above class GFG ob = new GFG(); // Custom input array int arr[] = { 2, 3, 4, 10, 40 }; // Length of array int n = arr.length; // Custom element to be checked // whether present or not int x = 10; // Calling above method int result = ob.binarySearch(arr, 0, n - 1, x); // Element present if (result == -1) // Print statement System.out.println("Element not present"); // Element not present else // Print statement System.out.println("Element found at index " + result); }} Element found at index 3 Time Complexity: O(log n) Auxiliary Space: O(1) naveenrao aryandaftari7 anikakapoor nnr223442 RishabhPrabhu chandramauliguptach Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Iterate through List in Java Java program to count the occurrence of each character in a string using Hashmap How to Iterate HashMap in Java? Remove first and last character of a string in Java Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to find largest element in an array
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 572, "s": 54, "text": "So as we all know binary search is one of the searching algorithms that is most frequently applied while dealing with data structures where the eccentric goal is not to traverse the whole array. Here array must be sorted as we check the middle element and ignore the half of the array which is of no use as per the number system. We basically ignore half of the elements just after one comparison. So do we keep on iterating till the element is found or land upon a conclusion that element is not present n the array." }, { "code": null, "e": 584, "s": 572, "text": "Algorithms:" }, { "code": null, "e": 869, "s": 584, "text": "Compare x with the middle element.If x matches with the middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.Else (x is smaller) recur for the left half." }, { "code": null, "e": 904, "s": 869, "text": "Compare x with the middle element." }, { "code": null, "e": 967, "s": 904, "text": "If x matches with the middle element, we return the mid index." }, { "code": null, "e": 1112, "s": 967, "text": "Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half." }, { "code": null, "e": 1157, "s": 1112, "text": "Else (x is smaller) recur for the left half." }, { "code": null, "e": 1168, "s": 1157, "text": "Example 1 " }, { "code": null, "e": 1173, "s": 1168, "text": "Java" }, { "code": "// Java Program to Illustrate// Iterative Binary Search // Main class// BinarySearchclass GFG { // Method 1 // Returns index of x // if it is present in arr[], // else return -1 int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; // Checking element in whole array while (l <= r) { int m = l + (r - l) / 2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, // element is on left side // so ignore right half else r = m - 1; } // If we reach here, // element is not present return -1; } // Method 2 // Main driver method public static void main(String args[]) { GFG ob = new GFG(); // Input array int arr[] = { 2, 3, 4, 10, 40 }; // Length of array int n = arr.length; // Element to be checked if present or not int x = 10; // Calling the method 1 and // storing result int result = ob.binarySearch(arr, x); // Element present if (result == -1) // Print statement System.out.println(\"Element not present\"); // Element not present else // Print statement System.out.println(\"Element found at index \" + result); }}", "e": 2707, "s": 1173, "text": null }, { "code": null, "e": 2732, "s": 2707, "text": "Element found at index 3" }, { "code": null, "e": 2758, "s": 2732, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 2781, "s": 2758, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 2792, "s": 2781, "text": "Example 2 " }, { "code": null, "e": 2797, "s": 2792, "text": "Java" }, { "code": "// Java Program to Illustrate Recursive Binary Search // Importing required classesimport java.util.*; // Main classclass GFG { // Method 1 // Recursive binary search // Returns index of x if it is present // in arr[l..r], else return -1 int binarySearch(int arr[], int l, int r, int x) { // Restrict the boundary of right index // and the left index to prevent // overflow of indices if (r >= l && l <= arr.length - 1) { int mid = l + (r - l) / 2; // If the element is present // at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can // only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in // array return -1; } // Method 2 // Main driver method public static void main(String args[]) { // Creating object of above class GFG ob = new GFG(); // Custom input array int arr[] = { 2, 3, 4, 10, 40 }; // Length of array int n = arr.length; // Custom element to be checked // whether present or not int x = 10; // Calling above method int result = ob.binarySearch(arr, 0, n - 1, x); // Element present if (result == -1) // Print statement System.out.println(\"Element not present\"); // Element not present else // Print statement System.out.println(\"Element found at index \" + result); }}", "e": 4643, "s": 2797, "text": null }, { "code": null, "e": 4668, "s": 4643, "text": "Element found at index 3" }, { "code": null, "e": 4694, "s": 4668, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 4717, "s": 4694, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 4727, "s": 4717, "text": "naveenrao" }, { "code": null, "e": 4741, "s": 4727, "text": "aryandaftari7" }, { "code": null, "e": 4753, "s": 4741, "text": "anikakapoor" }, { "code": null, "e": 4763, "s": 4753, "text": "nnr223442" }, { "code": null, "e": 4777, "s": 4763, "text": "RishabhPrabhu" }, { "code": null, "e": 4797, "s": 4777, "text": "chandramauliguptach" }, { "code": null, "e": 4811, "s": 4797, "text": "Java Programs" }, { "code": null, "e": 4909, "s": 4811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4947, "s": 4909, "text": "Factory method design pattern in Java" }, { "code": null, "e": 5004, "s": 4947, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 5033, "s": 5004, "text": "Iterate through List in Java" }, { "code": null, "e": 5114, "s": 5033, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 5146, "s": 5114, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 5198, "s": 5146, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 5246, "s": 5198, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 5285, "s": 5246, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 5336, "s": 5285, "text": "How to Get Elements By Index from HashSet in Java?" } ]
Sliding Window protocols Summary With Questions
03 May, 2022 Prerequisites – Stop & Wait, Go Back N, Selective Repeat Before starting with the questions a quick recap for all the protocols. Stop and wait – Sender window size (Ws) = 1Receiver window size (Wr) = 1Sequence Number ≥ 1 + 1Uses independent acknowledgementDiscards out of order packetsPacket Loss ? Retransmit packet after time outAcknowledgement loss ? Resends packet after time outEfficiency = 1/(1+2a) where a = Tp / Tt Sender window size (Ws) = 1 Receiver window size (Wr) = 1 Sequence Number ≥ 1 + 1 Uses independent acknowledgement Discards out of order packets Packet Loss ? Retransmit packet after time out Acknowledgement loss ? Resends packet after time out Efficiency = 1/(1+2a) where a = Tp / Tt Go Back N – Sender window size Ws = NReceiver window size Wr = 1Sequence number ≥ N + 1Can use both cumulative or independent acknowledgement depends on acknowledge timerDiscards out of order packetsPacket Loss ? Track back N size from the last packet within the window limit to the lost packet and retransmit themAcknowledgement loss ? If not received before timeout the entire window N size is resendEfficiency = N/(1+2a) where a = Tp / Tt Sender window size Ws = N Receiver window size Wr = 1 Sequence number ≥ N + 1 Can use both cumulative or independent acknowledgement depends on acknowledge timer Discards out of order packets Packet Loss ? Track back N size from the last packet within the window limit to the lost packet and retransmit them Acknowledgement loss ? If not received before timeout the entire window N size is resend Efficiency = N/(1+2a) where a = Tp / Tt Selective Repeat – Sender window size Ws = NReceiver window size Wr = NSequence Number ≥ N + NUses only independent acknowledgementCan Accept out of order packetsPacket Loss ? Resend only the lost packet after timeoutAcknowledgement loss ? Resend if not receive before timeoutEfficiency = N/(1+2a) where a = Tp / Tt Sender window size Ws = N Receiver window size Wr = N Sequence Number ≥ N + N Uses only independent acknowledgement Can Accept out of order packets Packet Loss ? Resend only the lost packet after timeout Acknowledgement loss ? Resend if not receive before timeout Efficiency = N/(1+2a) where a = Tp / Tt Example-1. In Stop and wait protocol every 4th packet is lost and we need to send total 10 packets so how many transmission it took to send all the packets? Explanation – 1 2 3 4 5 6 7 8 9 10 (Initially) ^ 1 2 3 4 4 5 6 7 8 9 10 (Packet no. 4 retransmitted) ^ 1 2 3 4 4 5 6 7 7 8 9 10 (Packet no. 10 retransmitted) ^ 1 2 3 4 4 5 6 7 7 8 9 10 10 (Result) So, we retransmitted packet number 4, 7, 10 Total count = 13 Example-2. In S&W protocol if Error probability is p and no. of packets to send is ‘n’. How many packets we have to send ? Explanation – Total retransmissions = n*p0+ n*p1+ n*p2 + n*p3 + n*p4 + ... = n(1 + p + p2 + p3 + p4 + ...) = n*(1 / (1-p)) using infinite GP sum formula Example-3. In GBN sender Window size = 10 and Tp = 49.5ms & Tt = 1ms. What is the Efficiency of the protocol and Throughput given Bandwidth = 1000 bps? Explanation – Efficiency = N/(1+2a), N = 10 (given), a = Tp/Tt = 49.5 Efficiency = 10/(1 + 2 * 49.5) = 10/100 = 0.1 or 10% Throughput = Efficiency * Bandwidth = 0.1 * 1000 = 100 Example-4. In GB3 if every 5th packet is lost & we need to send 10 packets so how many retransmissions are required ? Explanation – 1 2 3 4 5 6 7 | 8 9 10 ^ $ (packet no. 5 lost) 1 2 3 4 5 6 7 5 6 7 8 9 | 10 * ^ $ 1 2 3 4 5 6 7 5 6 7 8 9 7 8 9 10 * ^ $ 1 2 3 4 5 6 7 5 6 7 8 9 7 8 9 10 9 10 (count starts from * till ^) (from ^ to $ retransmission is done) Note – From the Last packet is window size to lost pocket we resend the entire window. Total no. of transmissions = 18 Example-5. In SR Ws = 5 and we are sending 10 packets where every 5th packet is lost find number of retransmissions? Explanation – 1 2 3 4 5 6 7 8 9 10 ^ 1 2 3 4 5 5 6 7 8 9 10 ^ 1 2 3 4 5 5 6 7 8 9 9 10 We see here there is no role of Window size in SR only the lost packet is resent. Total transmissions = 12 Example-6. If there is K bits sequence no. define require sender window size and receiver window size for S&W, GBN & SR? Explanation – Given, K bits, For S&W Ws = 1 and Wr = 1 For GBN, Ws = 2K-1 and Wr = 1 For SR, Ws = 2K-1 and Wr = 2(K-1) ayushgangwar vaibhavsinghtanwar3 rkbhola5 divyanshkhetan Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Introduction of Operating System - Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n03 May, 2022" }, { "code": null, "e": 111, "s": 54, "text": "Prerequisites – Stop & Wait, Go Back N, Selective Repeat" }, { "code": null, "e": 199, "s": 111, "text": "Before starting with the questions a quick recap for all the protocols. Stop and wait –" }, { "code": null, "e": 477, "s": 199, "text": "Sender window size (Ws) = 1Receiver window size (Wr) = 1Sequence Number ≥ 1 + 1Uses independent acknowledgementDiscards out of order packetsPacket Loss ? Retransmit packet after time outAcknowledgement loss ? Resends packet after time outEfficiency = 1/(1+2a) where a = Tp / Tt" }, { "code": null, "e": 505, "s": 477, "text": "Sender window size (Ws) = 1" }, { "code": null, "e": 535, "s": 505, "text": "Receiver window size (Wr) = 1" }, { "code": null, "e": 559, "s": 535, "text": "Sequence Number ≥ 1 + 1" }, { "code": null, "e": 592, "s": 559, "text": "Uses independent acknowledgement" }, { "code": null, "e": 622, "s": 592, "text": "Discards out of order packets" }, { "code": null, "e": 669, "s": 622, "text": "Packet Loss ? Retransmit packet after time out" }, { "code": null, "e": 722, "s": 669, "text": "Acknowledgement loss ? Resends packet after time out" }, { "code": null, "e": 762, "s": 722, "text": "Efficiency = 1/(1+2a) where a = Tp / Tt" }, { "code": null, "e": 774, "s": 762, "text": "Go Back N –" }, { "code": null, "e": 1204, "s": 774, "text": "Sender window size Ws = NReceiver window size Wr = 1Sequence number ≥ N + 1Can use both cumulative or independent acknowledgement depends on acknowledge timerDiscards out of order packetsPacket Loss ? Track back N size from the last packet within the window limit to the lost packet and retransmit themAcknowledgement loss ? If not received before timeout the entire window N size is resendEfficiency = N/(1+2a) where a = Tp / Tt" }, { "code": null, "e": 1230, "s": 1204, "text": "Sender window size Ws = N" }, { "code": null, "e": 1258, "s": 1230, "text": "Receiver window size Wr = 1" }, { "code": null, "e": 1282, "s": 1258, "text": "Sequence number ≥ N + 1" }, { "code": null, "e": 1366, "s": 1282, "text": "Can use both cumulative or independent acknowledgement depends on acknowledge timer" }, { "code": null, "e": 1396, "s": 1366, "text": "Discards out of order packets" }, { "code": null, "e": 1512, "s": 1396, "text": "Packet Loss ? Track back N size from the last packet within the window limit to the lost packet and retransmit them" }, { "code": null, "e": 1601, "s": 1512, "text": "Acknowledgement loss ? If not received before timeout the entire window N size is resend" }, { "code": null, "e": 1641, "s": 1601, "text": "Efficiency = N/(1+2a) where a = Tp / Tt" }, { "code": null, "e": 1660, "s": 1641, "text": "Selective Repeat –" }, { "code": null, "e": 1957, "s": 1660, "text": "Sender window size Ws = NReceiver window size Wr = NSequence Number ≥ N + NUses only independent acknowledgementCan Accept out of order packetsPacket Loss ? Resend only the lost packet after timeoutAcknowledgement loss ? Resend if not receive before timeoutEfficiency = N/(1+2a) where a = Tp / Tt" }, { "code": null, "e": 1983, "s": 1957, "text": "Sender window size Ws = N" }, { "code": null, "e": 2011, "s": 1983, "text": "Receiver window size Wr = N" }, { "code": null, "e": 2035, "s": 2011, "text": "Sequence Number ≥ N + N" }, { "code": null, "e": 2073, "s": 2035, "text": "Uses only independent acknowledgement" }, { "code": null, "e": 2105, "s": 2073, "text": "Can Accept out of order packets" }, { "code": null, "e": 2161, "s": 2105, "text": "Packet Loss ? Resend only the lost packet after timeout" }, { "code": null, "e": 2221, "s": 2161, "text": "Acknowledgement loss ? Resend if not receive before timeout" }, { "code": null, "e": 2261, "s": 2221, "text": "Efficiency = N/(1+2a) where a = Tp / Tt" }, { "code": null, "e": 2418, "s": 2261, "text": "Example-1. In Stop and wait protocol every 4th packet is lost and we need to send total 10 packets so how many transmission it took to send all the packets?" }, { "code": null, "e": 2432, "s": 2418, "text": "Explanation –" }, { "code": null, "e": 2659, "s": 2432, "text": "1 2 3 4 5 6 7 8 9 10 (Initially)\n ^\n1 2 3 4 4 5 6 7 8 9 10 (Packet no. 4 retransmitted) \n ^\n1 2 3 4 4 5 6 7 7 8 9 10 (Packet no. 10 retransmitted)\n ^\n1 2 3 4 4 5 6 7 7 8 9 10 10 (Result)" }, { "code": null, "e": 2720, "s": 2659, "text": "So, we retransmitted packet number 4, 7, 10 Total count = 13" }, { "code": null, "e": 2843, "s": 2720, "text": "Example-2. In S&W protocol if Error probability is p and no. of packets to send is ‘n’. How many packets we have to send ?" }, { "code": null, "e": 2996, "s": 2843, "text": "Explanation – Total retransmissions = n*p0+ n*p1+ n*p2 + n*p3 + n*p4 + ... = n(1 + p + p2 + p3 + p4 + ...) = n*(1 / (1-p)) using infinite GP sum formula" }, { "code": null, "e": 3148, "s": 2996, "text": "Example-3. In GBN sender Window size = 10 and Tp = 49.5ms & Tt = 1ms. What is the Efficiency of the protocol and Throughput given Bandwidth = 1000 bps?" }, { "code": null, "e": 3326, "s": 3148, "text": "Explanation – Efficiency = N/(1+2a), N = 10 (given), a = Tp/Tt = 49.5 Efficiency = 10/(1 + 2 * 49.5) = 10/100 = 0.1 or 10% Throughput = Efficiency * Bandwidth = 0.1 * 1000 = 100" }, { "code": null, "e": 3444, "s": 3326, "text": "Example-4. In GB3 if every 5th packet is lost & we need to send 10 packets so how many retransmissions are required ?" }, { "code": null, "e": 3458, "s": 3444, "text": "Explanation –" }, { "code": null, "e": 3758, "s": 3458, "text": "1 2 3 4 5 6 7 | 8 9 10 \n ^ $ (packet no. 5 lost)\n1 2 3 4 5 6 7 5 6 7 8 9 | 10\n * ^ $ \n1 2 3 4 5 6 7 5 6 7 8 9 7 8 9 10\n * ^ $\n1 2 3 4 5 6 7 5 6 7 8 9 7 8 9 10 9 10 (count starts from * till ^)\n(from ^ to $ retransmission is done)" }, { "code": null, "e": 3877, "s": 3758, "text": "Note – From the Last packet is window size to lost pocket we resend the entire window. Total no. of transmissions = 18" }, { "code": null, "e": 3994, "s": 3877, "text": "Example-5. In SR Ws = 5 and we are sending 10 packets where every 5th packet is lost find number of retransmissions?" }, { "code": null, "e": 4008, "s": 3994, "text": "Explanation –" }, { "code": null, "e": 4107, "s": 4008, "text": "1 2 3 4 5 6 7 8 9 10\n ^\n1 2 3 4 5 5 6 7 8 9 10\n ^\n1 2 3 4 5 5 6 7 8 9 9 10" }, { "code": null, "e": 4214, "s": 4107, "text": "We see here there is no role of Window size in SR only the lost packet is resent. Total transmissions = 12" }, { "code": null, "e": 4454, "s": 4214, "text": "Example-6. If there is K bits sequence no. define require sender window size and receiver window size for S&W, GBN & SR? Explanation – Given, K bits, For S&W Ws = 1 and Wr = 1 For GBN, Ws = 2K-1 and Wr = 1 For SR, Ws = 2K-1 and Wr = 2(K-1)" }, { "code": null, "e": 4467, "s": 4454, "text": "ayushgangwar" }, { "code": null, "e": 4487, "s": 4467, "text": "vaibhavsinghtanwar3" }, { "code": null, "e": 4496, "s": 4487, "text": "rkbhola5" }, { "code": null, "e": 4511, "s": 4496, "text": "divyanshkhetan" }, { "code": null, "e": 4529, "s": 4511, "text": "Computer Networks" }, { "code": null, "e": 4537, "s": 4529, "text": "GATE CS" }, { "code": null, "e": 4555, "s": 4537, "text": "Computer Networks" }, { "code": null, "e": 4653, "s": 4555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4683, "s": 4653, "text": "GSM in Wireless Communication" }, { "code": null, "e": 4712, "s": 4683, "text": "Socket Programming in Python" }, { "code": null, "e": 4746, "s": 4712, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 4772, "s": 4746, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 4802, "s": 4772, "text": "Wireless Application Protocol" }, { "code": null, "e": 4826, "s": 4802, "text": "ACID Properties in DBMS" }, { "code": null, "e": 4853, "s": 4826, "text": "Types of Operating Systems" }, { "code": null, "e": 4874, "s": 4853, "text": "Normal Forms in DBMS" }, { "code": null, "e": 4923, "s": 4874, "text": "Page Replacement Algorithms in Operating Systems" } ]
Mathematical functions in MySQL
07 Aug, 2019 SQL stands for ‘Structured Query Language’. As the name already suggests, the data is stored in the form of rows and columns, in a structured format. Using the SQL language, we can store, retrieve, and manipulate the data stored in the MySQL database. Sometimes, the database table contains thousands of entries. For example, a table containing the salary information of thousands of its employees. Now suppose, the company’s manager wants to calculate the average salary of the employees, or wants to calculate the total amount of money he is spending on paying the salary to his employees. It will be very hectic for him to manually do the job as it will be very much time and energy consuming. Thus, there are some mathematical functions in MySQL that can be used in such cases. For the sake of convenience, we will consider the table_name as ’employees’ and the ‘column_name’ containing information about the salaries of the employees as ‘salary’ for this whole article. In this article, we will be looking at 5 such functions: 1. COUNT() 2. AVG() 3. SUM() 4. MIN() 5. MAX() Let’s have a look at each of them, one by one. COUNT() Function:The COUNT() function returns the number of rows that match specified criteria.For example, the manager wants to find the number of employees whose salary is greater than or equals to Rs.40, 000 per month. Using COUNT() function, he can create a general MySQL query to fetch the required data.SELECT COUNT(salary) FROM employees WHERE salary >= 40000;This will fetch the information of all of his employees whose salary either equals to 40, 000 or is greater than that.AVG() Function:The AVG() function will help the manager in determining the average salary of all of his employees.The output will be returned in the form of int.SELECT AVG(salary) FROM employees;SUM() Function:The SUM() function returns the total sum of a numeric column.This will help the manager in finding the total amount of money he is spending in giving away the salaries of his employees.SELECT SUM(Price) FROM Products;MAX() Function:As the name already suggests, the MAX() function returns the largest value of the selected column. This means that the manager can use this function to find the employee that is drawing the maximum salary in his company.The working code of the function will be;SELECT MAX(column_name) FROM table_name;MIN() Function:The MIN() function returns the smallest value of the selected column. This function can be to find the information about the employee that is drawing the minimum salary from the company.The working code of this function will be;SELECT MIN(column_name) FROM table_name; COUNT() Function:The COUNT() function returns the number of rows that match specified criteria.For example, the manager wants to find the number of employees whose salary is greater than or equals to Rs.40, 000 per month. Using COUNT() function, he can create a general MySQL query to fetch the required data.SELECT COUNT(salary) FROM employees WHERE salary >= 40000;This will fetch the information of all of his employees whose salary either equals to 40, 000 or is greater than that. SELECT COUNT(salary) FROM employees WHERE salary >= 40000; This will fetch the information of all of his employees whose salary either equals to 40, 000 or is greater than that. AVG() Function:The AVG() function will help the manager in determining the average salary of all of his employees.The output will be returned in the form of int.SELECT AVG(salary) FROM employees; SELECT AVG(salary) FROM employees; SUM() Function:The SUM() function returns the total sum of a numeric column.This will help the manager in finding the total amount of money he is spending in giving away the salaries of his employees.SELECT SUM(Price) FROM Products; SELECT SUM(Price) FROM Products; MAX() Function:As the name already suggests, the MAX() function returns the largest value of the selected column. This means that the manager can use this function to find the employee that is drawing the maximum salary in his company.The working code of the function will be;SELECT MAX(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; MIN() Function:The MIN() function returns the smallest value of the selected column. This function can be to find the information about the employee that is drawing the minimum salary from the company.The working code of this function will be;SELECT MIN(column_name) FROM table_name; SELECT MIN(column_name) FROM table_name; decoder_111 mysql SQLmysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Aug, 2019" }, { "code": null, "e": 280, "s": 28, "text": "SQL stands for ‘Structured Query Language’. As the name already suggests, the data is stored in the form of rows and columns, in a structured format. Using the SQL language, we can store, retrieve, and manipulate the data stored in the MySQL database." }, { "code": null, "e": 810, "s": 280, "text": "Sometimes, the database table contains thousands of entries. For example, a table containing the salary information of thousands of its employees. Now suppose, the company’s manager wants to calculate the average salary of the employees, or wants to calculate the total amount of money he is spending on paying the salary to his employees. It will be very hectic for him to manually do the job as it will be very much time and energy consuming. Thus, there are some mathematical functions in MySQL that can be used in such cases." }, { "code": null, "e": 1003, "s": 810, "text": "For the sake of convenience, we will consider the table_name as ’employees’ and the ‘column_name’ containing information about the salaries of the employees as ‘salary’ for this whole article." }, { "code": null, "e": 1060, "s": 1003, "text": "In this article, we will be looking at 5 such functions:" }, { "code": null, "e": 1108, "s": 1060, "text": "1. COUNT()\n2. AVG()\n3. SUM()\n4. MIN()\n5. MAX() " }, { "code": null, "e": 1155, "s": 1108, "text": "Let’s have a look at each of them, one by one." }, { "code": null, "e": 2667, "s": 1155, "text": "COUNT() Function:The COUNT() function returns the number of rows that match specified criteria.For example, the manager wants to find the number of employees whose salary is greater than or equals to Rs.40, 000 per month. Using COUNT() function, he can create a general MySQL query to fetch the required data.SELECT COUNT(salary)\nFROM employees\nWHERE salary >= 40000;This will fetch the information of all of his employees whose salary either equals to 40, 000 or is greater than that.AVG() Function:The AVG() function will help the manager in determining the average salary of all of his employees.The output will be returned in the form of int.SELECT AVG(salary)\nFROM employees;SUM() Function:The SUM() function returns the total sum of a numeric column.This will help the manager in finding the total amount of money he is spending in giving away the salaries of his employees.SELECT SUM(Price)\nFROM Products;MAX() Function:As the name already suggests, the MAX() function returns the largest value of the selected column. This means that the manager can use this function to find the employee that is drawing the maximum salary in his company.The working code of the function will be;SELECT MAX(column_name)\nFROM table_name;MIN() Function:The MIN() function returns the smallest value of the selected column. This function can be to find the information about the employee that is drawing the minimum salary from the company.The working code of this function will be;SELECT MIN(column_name)\nFROM table_name;" }, { "code": null, "e": 3153, "s": 2667, "text": "COUNT() Function:The COUNT() function returns the number of rows that match specified criteria.For example, the manager wants to find the number of employees whose salary is greater than or equals to Rs.40, 000 per month. Using COUNT() function, he can create a general MySQL query to fetch the required data.SELECT COUNT(salary)\nFROM employees\nWHERE salary >= 40000;This will fetch the information of all of his employees whose salary either equals to 40, 000 or is greater than that." }, { "code": null, "e": 3212, "s": 3153, "text": "SELECT COUNT(salary)\nFROM employees\nWHERE salary >= 40000;" }, { "code": null, "e": 3331, "s": 3212, "text": "This will fetch the information of all of his employees whose salary either equals to 40, 000 or is greater than that." }, { "code": null, "e": 3527, "s": 3331, "text": "AVG() Function:The AVG() function will help the manager in determining the average salary of all of his employees.The output will be returned in the form of int.SELECT AVG(salary)\nFROM employees;" }, { "code": null, "e": 3562, "s": 3527, "text": "SELECT AVG(salary)\nFROM employees;" }, { "code": null, "e": 3795, "s": 3562, "text": "SUM() Function:The SUM() function returns the total sum of a numeric column.This will help the manager in finding the total amount of money he is spending in giving away the salaries of his employees.SELECT SUM(Price)\nFROM Products;" }, { "code": null, "e": 3828, "s": 3795, "text": "SELECT SUM(Price)\nFROM Products;" }, { "code": null, "e": 4145, "s": 3828, "text": "MAX() Function:As the name already suggests, the MAX() function returns the largest value of the selected column. This means that the manager can use this function to find the employee that is drawing the maximum salary in his company.The working code of the function will be;SELECT MAX(column_name)\nFROM table_name;" }, { "code": null, "e": 4186, "s": 4145, "text": "SELECT MAX(column_name)\nFROM table_name;" }, { "code": null, "e": 4470, "s": 4186, "text": "MIN() Function:The MIN() function returns the smallest value of the selected column. This function can be to find the information about the employee that is drawing the minimum salary from the company.The working code of this function will be;SELECT MIN(column_name)\nFROM table_name;" }, { "code": null, "e": 4511, "s": 4470, "text": "SELECT MIN(column_name)\nFROM table_name;" }, { "code": null, "e": 4523, "s": 4511, "text": "decoder_111" }, { "code": null, "e": 4529, "s": 4523, "text": "mysql" }, { "code": null, "e": 4538, "s": 4529, "text": "SQLmysql" }, { "code": null, "e": 4542, "s": 4538, "text": "SQL" }, { "code": null, "e": 4546, "s": 4542, "text": "SQL" } ]
Program to Convert a Vector to List in Java
11 Dec, 2018 Given a Vector, the task is to Convert Vector to List in Java Examples: Input: Vector: [1, 2, 3, 4, 5] Output: List: [1, 2, 3, 4, 5] Input : Vector = [a, b, c, d, e, f] Output : List = [a, b, c, d, e, f] Using Collections.list() methodSyntax:List list = Collections.list(vec.elements()); Approach:Get the VectorConvert into list using Collections.list(vector.elements()) method, which returns a List of objects.Print the ListBelow is the implementation of the above approach:// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add("1"); vec.add("2"); vec.add("3"); vec.add("4"); vec.add("5"); // print Vector elements System.out.println("Vector: " + vec); // Convert Vector to List List<String> list = Collections.list(vec.elements()); // print List Elements System.out.println("List:" + list); }}Output:Vector: [1, 2, 3, 4, 5] List:[1, 2, 3, 4, 5] Syntax: List list = Collections.list(vec.elements()); Approach: Get the VectorConvert into list using Collections.list(vector.elements()) method, which returns a List of objects.Print the List Get the Vector Convert into list using Collections.list(vector.elements()) method, which returns a List of objects. Print the List Below is the implementation of the above approach: // Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add("1"); vec.add("2"); vec.add("3"); vec.add("4"); vec.add("5"); // print Vector elements System.out.println("Vector: " + vec); // Convert Vector to List List<String> list = Collections.list(vec.elements()); // print List Elements System.out.println("List:" + list); }} Vector: [1, 2, 3, 4, 5] List:[1, 2, 3, 4, 5] Using Collection.unmodifiableList()Syntax:List list = Collections.unmodifiableList(vector); Approach:Get the VectorConvert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects.Print the ListBelow is the implementation of the above approach:// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add("1"); vec.add("2"); vec.add("3"); vec.add("4"); vec.add("5"); // print Vector elements System.out.println("Vector: " + vec); // Convert Vector to List List<String> list = Collections.unmodifiableList(vec); // print List Elements System.out.println("List:" + list); }}Output:Vector: [1, 2, 3, 4, 5] List:[1, 2, 3, 4, 5] Syntax: List list = Collections.unmodifiableList(vector); Approach: Get the VectorConvert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects.Print the List Get the Vector Convert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects. Print the List Below is the implementation of the above approach: // Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add("1"); vec.add("2"); vec.add("3"); vec.add("4"); vec.add("5"); // print Vector elements System.out.println("Vector: " + vec); // Convert Vector to List List<String> list = Collections.unmodifiableList(vec); // print List Elements System.out.println("List:" + list); }} Vector: [1, 2, 3, 4, 5] List:[1, 2, 3, 4, 5] Using constructorSyntax:List list = new ArrayList(vector); Approach:Get the VectorCreate a List from the Vector by passing the vector as the parameter.Print the ListBelow is the implementation of the above approach:// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add("1"); vec.add("2"); vec.add("3"); vec.add("4"); vec.add("5"); // print Vector elements System.out.println("Vector: " + vec); // Convert Vector to List List<String> list = new ArrayList<String>(vec); // print List Elements System.out.println("List:" + list); }}Output:Vector: [1, 2, 3, 4, 5] List:[1, 2, 3, 4, 5] Syntax: List list = new ArrayList(vector); Approach: Get the VectorCreate a List from the Vector by passing the vector as the parameter.Print the List Get the Vector Create a List from the Vector by passing the vector as the parameter. Print the List Below is the implementation of the above approach: // Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add("1"); vec.add("2"); vec.add("3"); vec.add("4"); vec.add("5"); // print Vector elements System.out.println("Vector: " + vec); // Convert Vector to List List<String> list = new ArrayList<String>(vec); // print List Elements System.out.println("List:" + list); }} Vector: [1, 2, 3, 4, 5] List:[1, 2, 3, 4, 5] java-list Java-List-Programs Java-Vector Technical Scripter 2018 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 90, "s": 28, "text": "Given a Vector, the task is to Convert Vector to List in Java" }, { "code": null, "e": 100, "s": 90, "text": "Examples:" }, { "code": null, "e": 235, "s": 100, "text": "Input: Vector: [1, 2, 3, 4, 5]\nOutput: List: [1, 2, 3, 4, 5]\n\nInput : Vector = [a, b, c, d, e, f]\nOutput : List = [a, b, c, d, e, f]\n" }, { "code": null, "e": 1195, "s": 235, "text": "Using Collections.list() methodSyntax:List list = Collections.list(vec.elements());\nApproach:Get the VectorConvert into list using Collections.list(vector.elements()) method, which returns a List of objects.Print the ListBelow is the implementation of the above approach:// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add(\"1\"); vec.add(\"2\"); vec.add(\"3\"); vec.add(\"4\"); vec.add(\"5\"); // print Vector elements System.out.println(\"Vector: \" + vec); // Convert Vector to List List<String> list = Collections.list(vec.elements()); // print List Elements System.out.println(\"List:\" + list); }}Output:Vector: [1, 2, 3, 4, 5]\nList:[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 1203, "s": 1195, "text": "Syntax:" }, { "code": null, "e": 1250, "s": 1203, "text": "List list = Collections.list(vec.elements());\n" }, { "code": null, "e": 1260, "s": 1250, "text": "Approach:" }, { "code": null, "e": 1389, "s": 1260, "text": "Get the VectorConvert into list using Collections.list(vector.elements()) method, which returns a List of objects.Print the List" }, { "code": null, "e": 1404, "s": 1389, "text": "Get the Vector" }, { "code": null, "e": 1505, "s": 1404, "text": "Convert into list using Collections.list(vector.elements()) method, which returns a List of objects." }, { "code": null, "e": 1520, "s": 1505, "text": "Print the List" }, { "code": null, "e": 1571, "s": 1520, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add(\"1\"); vec.add(\"2\"); vec.add(\"3\"); vec.add(\"4\"); vec.add(\"5\"); // print Vector elements System.out.println(\"Vector: \" + vec); // Convert Vector to List List<String> list = Collections.list(vec.elements()); // print List Elements System.out.println(\"List:\" + list); }}", "e": 2208, "s": 1571, "text": null }, { "code": null, "e": 2254, "s": 2208, "text": "Vector: [1, 2, 3, 4, 5]\nList:[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 3235, "s": 2254, "text": "Using Collection.unmodifiableList()Syntax:List list = Collections.unmodifiableList(vector);\nApproach:Get the VectorConvert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects.Print the ListBelow is the implementation of the above approach:// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add(\"1\"); vec.add(\"2\"); vec.add(\"3\"); vec.add(\"4\"); vec.add(\"5\"); // print Vector elements System.out.println(\"Vector: \" + vec); // Convert Vector to List List<String> list = Collections.unmodifiableList(vec); // print List Elements System.out.println(\"List:\" + list); }}Output:Vector: [1, 2, 3, 4, 5]\nList:[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 3243, "s": 3235, "text": "Syntax:" }, { "code": null, "e": 3294, "s": 3243, "text": "List list = Collections.unmodifiableList(vector);\n" }, { "code": null, "e": 3304, "s": 3294, "text": "Approach:" }, { "code": null, "e": 3445, "s": 3304, "text": "Get the VectorConvert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects.Print the List" }, { "code": null, "e": 3460, "s": 3445, "text": "Get the Vector" }, { "code": null, "e": 3573, "s": 3460, "text": "Convert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects." }, { "code": null, "e": 3588, "s": 3573, "text": "Print the List" }, { "code": null, "e": 3639, "s": 3588, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add(\"1\"); vec.add(\"2\"); vec.add(\"3\"); vec.add(\"4\"); vec.add(\"5\"); // print Vector elements System.out.println(\"Vector: \" + vec); // Convert Vector to List List<String> list = Collections.unmodifiableList(vec); // print List Elements System.out.println(\"List:\" + list); }}", "e": 4277, "s": 3639, "text": null }, { "code": null, "e": 4323, "s": 4277, "text": "Vector: [1, 2, 3, 4, 5]\nList:[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 5221, "s": 4323, "text": "Using constructorSyntax:List list = new ArrayList(vector);\nApproach:Get the VectorCreate a List from the Vector by passing the vector as the parameter.Print the ListBelow is the implementation of the above approach:// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add(\"1\"); vec.add(\"2\"); vec.add(\"3\"); vec.add(\"4\"); vec.add(\"5\"); // print Vector elements System.out.println(\"Vector: \" + vec); // Convert Vector to List List<String> list = new ArrayList<String>(vec); // print List Elements System.out.println(\"List:\" + list); }}Output:Vector: [1, 2, 3, 4, 5]\nList:[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 5229, "s": 5221, "text": "Syntax:" }, { "code": null, "e": 5265, "s": 5229, "text": "List list = new ArrayList(vector);\n" }, { "code": null, "e": 5275, "s": 5265, "text": "Approach:" }, { "code": null, "e": 5373, "s": 5275, "text": "Get the VectorCreate a List from the Vector by passing the vector as the parameter.Print the List" }, { "code": null, "e": 5388, "s": 5373, "text": "Get the Vector" }, { "code": null, "e": 5458, "s": 5388, "text": "Create a List from the Vector by passing the vector as the parameter." }, { "code": null, "e": 5473, "s": 5458, "text": "Print the List" }, { "code": null, "e": 5524, "s": 5473, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to// convert vector to List import java.util.*; public class GFG { public static void main(String[] args) { // Create a Vector of String elements Vector<String> vec = new Vector<String>(); // Adding values of Vector vec.add(\"1\"); vec.add(\"2\"); vec.add(\"3\"); vec.add(\"4\"); vec.add(\"5\"); // print Vector elements System.out.println(\"Vector: \" + vec); // Convert Vector to List List<String> list = new ArrayList<String>(vec); // print List Elements System.out.println(\"List:\" + list); }}", "e": 6155, "s": 5524, "text": null }, { "code": null, "e": 6201, "s": 6155, "text": "Vector: [1, 2, 3, 4, 5]\nList:[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 6211, "s": 6201, "text": "java-list" }, { "code": null, "e": 6230, "s": 6211, "text": "Java-List-Programs" }, { "code": null, "e": 6242, "s": 6230, "text": "Java-Vector" }, { "code": null, "e": 6266, "s": 6242, "text": "Technical Scripter 2018" }, { "code": null, "e": 6271, "s": 6266, "text": "Java" }, { "code": null, "e": 6285, "s": 6271, "text": "Java Programs" }, { "code": null, "e": 6304, "s": 6285, "text": "Technical Scripter" }, { "code": null, "e": 6309, "s": 6304, "text": "Java" }, { "code": null, "e": 6407, "s": 6309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6458, "s": 6407, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6489, "s": 6458, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6508, "s": 6489, "text": "Interfaces in Java" }, { "code": null, "e": 6538, "s": 6508, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6553, "s": 6538, "text": "Stream In Java" }, { "code": null, "e": 6581, "s": 6553, "text": "Initializing a List in Java" }, { "code": null, "e": 6607, "s": 6581, "text": "Java Programming Examples" }, { "code": null, "e": 6651, "s": 6607, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 6685, "s": 6651, "text": "Convert Double to Integer in Java" } ]
Routes and Navigator in Flutter
13 Jun, 2022 Flutter is an open-source mobile app SDK created by Google. Flutter uses Dart language for creating mobile apps, that follow object-oriented concepts. Flutter has a very good reach among mobile app developers because of its striking features like cross-platform development, hot reload, hot restart, eye-catching UI, etc. In flutter, from text to padding, everything is a widget. Everything in Flutter is a widget. Route: Apps are the new trend. The number of apps available in the play Store nowadays is quite a lot. The apps display their content in a full-screen container called pages or screens. In flutter, the pages or screens are called Routes. In android, these pages/screens are referred to as Activity and in iOS, it is referred to as ViewController. But, in a flutter, routes are referred to as Widgets. In Flutter, a Page / Screen is called a Route. Creating routes: A route can be written in the form of a “Class” in Dart using object-oriented concepts. Each route can be written as a separate class and has its own contents and UI. Now let’s create two routes, each having unique App Bars and Raised Buttons. The code is as follows: Dart class HomeRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( child: Text('Click Me!'), onPressed: () { /* Contains the code that helps us navigate to the second route. */ }, ), ), ); }} class SecondRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Click Me Page"), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( onPressed: () { /* Contains the code that helps us navigate to first route. */ }, child: Text('Home!'), ), ), ); }} Navigator: As the name suggests, Navigator is a widget that helps us to navigate between the routes. The navigator follows stack method when dealing with the routes. Based on the actions made by the user, the routes are stacked one over the other and when pressed back, it goes to the most recently visited route. Navigator is a widget that follows a stack discipline. Defining Home: While navigating, the first thing that we need to do is to define or initialize the “home page”. The home page can be any route according to our needs. The home usually will be placed at the bottom of the navigator stack. Now let’s see how to initialize our HomeRoute() as our home page: Dart void main() { runApp(MaterialApp( home: HomeRoute(), ));} Navigating to a Page: Since we have defined our Home, all the remaining is to navigate from home to another route of the app. For that the navigator widget has a method called Navigator.push(). This method pushes the route on top of the home, thereby displaying the second route. The code for pushing a route into the stack is as follows: Dart // Within the `HomeRoute` widget onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); }), Navigating Back to Home: Now we have arrived at our destination, but how do we go back home? For that, the navigator has a method called Navigator.pop(). This helps us to remove the present route from the stack so that we go back to our home route. This can be done as follows: Dart // Within the SecondRoute widgetonPressed: () { Navigator.pop(context);} Example: So, this is how we can navigate between two pages in an app. The whole code for the above flutter app is as follows: Dart import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp( home: HomeRoute(), ));} class HomeRoute extends StatelessWidget { const HomeRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( child: const Text('Click Me!'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); }), ), ); }} class SecondRoute extends StatelessWidget { const SecondRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(""Click Me Page""), backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('Home!'), ), ), ); }} Output: ankit_kumar_ Flutter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 467, "s": 52, "text": "Flutter is an open-source mobile app SDK created by Google. Flutter uses Dart language for creating mobile apps, that follow object-oriented concepts. Flutter has a very good reach among mobile app developers because of its striking features like cross-platform development, hot reload, hot restart, eye-catching UI, etc. In flutter, from text to padding, everything is a widget. Everything in Flutter is a widget." }, { "code": null, "e": 915, "s": 467, "text": "Route: Apps are the new trend. The number of apps available in the play Store nowadays is quite a lot. The apps display their content in a full-screen container called pages or screens. In flutter, the pages or screens are called Routes. In android, these pages/screens are referred to as Activity and in iOS, it is referred to as ViewController. But, in a flutter, routes are referred to as Widgets. In Flutter, a Page / Screen is called a Route." }, { "code": null, "e": 1099, "s": 915, "text": "Creating routes: A route can be written in the form of a “Class” in Dart using object-oriented concepts. Each route can be written as a separate class and has its own contents and UI." }, { "code": null, "e": 1200, "s": 1099, "text": "Now let’s create two routes, each having unique App Bars and Raised Buttons. The code is as follows:" }, { "code": null, "e": 1205, "s": 1200, "text": "Dart" }, { "code": "class HomeRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( child: Text('Click Me!'), onPressed: () { /* Contains the code that helps us navigate to the second route. */ }, ), ), ); }} class SecondRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"Click Me Page\"), backgroundColor: Colors.green, ), body: Center( child: RaisedButton( onPressed: () { /* Contains the code that helps us navigate to first route. */ }, child: Text('Home!'), ), ), ); }}", "e": 2106, "s": 1205, "text": null }, { "code": null, "e": 2475, "s": 2106, "text": "Navigator: As the name suggests, Navigator is a widget that helps us to navigate between the routes. The navigator follows stack method when dealing with the routes. Based on the actions made by the user, the routes are stacked one over the other and when pressed back, it goes to the most recently visited route. Navigator is a widget that follows a stack discipline." }, { "code": null, "e": 2778, "s": 2475, "text": "Defining Home: While navigating, the first thing that we need to do is to define or initialize the “home page”. The home page can be any route according to our needs. The home usually will be placed at the bottom of the navigator stack. Now let’s see how to initialize our HomeRoute() as our home page:" }, { "code": null, "e": 2783, "s": 2778, "text": "Dart" }, { "code": "void main() { runApp(MaterialApp( home: HomeRoute(), ));}", "e": 2846, "s": 2783, "text": null }, { "code": null, "e": 3185, "s": 2846, "text": "Navigating to a Page: Since we have defined our Home, all the remaining is to navigate from home to another route of the app. For that the navigator widget has a method called Navigator.push(). This method pushes the route on top of the home, thereby displaying the second route. The code for pushing a route into the stack is as follows:" }, { "code": null, "e": 3190, "s": 3185, "text": "Dart" }, { "code": "// Within the `HomeRoute` widget onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); }),", "e": 3400, "s": 3190, "text": null }, { "code": null, "e": 3678, "s": 3400, "text": "Navigating Back to Home: Now we have arrived at our destination, but how do we go back home? For that, the navigator has a method called Navigator.pop(). This helps us to remove the present route from the stack so that we go back to our home route. This can be done as follows:" }, { "code": null, "e": 3683, "s": 3678, "text": "Dart" }, { "code": "// Within the SecondRoute widgetonPressed: () { Navigator.pop(context);}", "e": 3757, "s": 3683, "text": null }, { "code": null, "e": 3883, "s": 3757, "text": "Example: So, this is how we can navigate between two pages in an app. The whole code for the above flutter app is as follows:" }, { "code": null, "e": 3888, "s": 3883, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp( home: HomeRoute(), ));} class HomeRoute extends StatelessWidget { const HomeRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( child: const Text('Click Me!'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); }), ), ); }} class SecondRoute extends StatelessWidget { const SecondRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(\"\"Click Me Page\"\"), backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('Home!'), ), ), ); }}", "e": 5029, "s": 3888, "text": null }, { "code": null, "e": 5037, "s": 5029, "text": "Output:" }, { "code": null, "e": 5052, "s": 5039, "text": "ankit_kumar_" }, { "code": null, "e": 5060, "s": 5052, "text": "Flutter" }, { "code": null, "e": 5077, "s": 5060, "text": "Web Technologies" } ]
TimeZone getOffset() Method in Java with Examples
02 Jan, 2019 The getOffset() method of TimeZone class in Java is used to know the offset value of this TimeZone at a specific date from the UTC or the Universal Time Coordinated. Syntax: public int getOffset(long in_date) Parameters: The method accepts one parameter, in_date of long type that refers to the actual date represented in milli-seconds since 1st January 1970 at 00:00:00 GMT. Return Value: The method returns the ID of the TimeZone. Below programs illustrate the working of getOffset() Method of TimeZone:Example 1: // Java code to illustrate getOffset() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone offtime_zone = TimeZone.getTimeZone("Europe/Rome"); // Checking the offset for the systems date System.out.println("The Offset Value is:" + offtime_zone .getOffset(Calendar.ZONE_OFFSET)); }} The Offset Value is:3600000 Example 2: // Java code to illustrate getOffset() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone offtime_zone = TimeZone.getTimeZone("Pacific/Pago_Pago"); // Checking the offset for the systems date System.out.println("The Offset Value is:" + offtime_zone .getOffset(Calendar.ZONE_OFFSET)); }} The Offset Value is:-39600000 Reference: https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getOffset() Java - util package Java-Functions Java-TimeZone Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jan, 2019" }, { "code": null, "e": 194, "s": 28, "text": "The getOffset() method of TimeZone class in Java is used to know the offset value of this TimeZone at a specific date from the UTC or the Universal Time Coordinated." }, { "code": null, "e": 202, "s": 194, "text": "Syntax:" }, { "code": null, "e": 237, "s": 202, "text": "public int getOffset(long in_date)" }, { "code": null, "e": 404, "s": 237, "text": "Parameters: The method accepts one parameter, in_date of long type that refers to the actual date represented in milli-seconds since 1st January 1970 at 00:00:00 GMT." }, { "code": null, "e": 461, "s": 404, "text": "Return Value: The method returns the ID of the TimeZone." }, { "code": null, "e": 544, "s": 461, "text": "Below programs illustrate the working of getOffset() Method of TimeZone:Example 1:" }, { "code": "// Java code to illustrate getOffset() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone offtime_zone = TimeZone.getTimeZone(\"Europe/Rome\"); // Checking the offset for the systems date System.out.println(\"The Offset Value is:\" + offtime_zone .getOffset(Calendar.ZONE_OFFSET)); }}", "e": 1014, "s": 544, "text": null }, { "code": null, "e": 1043, "s": 1014, "text": "The Offset Value is:3600000\n" }, { "code": null, "e": 1054, "s": 1043, "text": "Example 2:" }, { "code": "// Java code to illustrate getOffset() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating a TimeZone TimeZone offtime_zone = TimeZone.getTimeZone(\"Pacific/Pago_Pago\"); // Checking the offset for the systems date System.out.println(\"The Offset Value is:\" + offtime_zone .getOffset(Calendar.ZONE_OFFSET)); }}", "e": 1530, "s": 1054, "text": null }, { "code": null, "e": 1561, "s": 1530, "text": "The Offset Value is:-39600000\n" }, { "code": null, "e": 1650, "s": 1561, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getOffset()" }, { "code": null, "e": 1670, "s": 1650, "text": "Java - util package" }, { "code": null, "e": 1685, "s": 1670, "text": "Java-Functions" }, { "code": null, "e": 1699, "s": 1685, "text": "Java-TimeZone" }, { "code": null, "e": 1704, "s": 1699, "text": "Java" }, { "code": null, "e": 1709, "s": 1704, "text": "Java" } ]
All-Pairs Shortest Paths
The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the minimum distance from any node to all other nodes in the graph. At first the output matrix is same as given cost matrix of the graph. After that the output matrix will be updated with all vertices k as the intermediate vertex. The time complexity of this algorithm is O(V3), here V is the number of vertices in the graph. Input − The cost matrix of the graph. 0 3 6 ∞ ∞ ∞ ∞ 3 0 2 1 ∞ ∞ ∞ 6 2 0 1 4 2 ∞ ∞ 1 1 0 2 ∞ 4 ∞ ∞ 4 2 0 2 1 ∞ ∞ 2 ∞ 2 0 1 ∞ ∞ ∞ 4 1 1 0 Output − Matrix of all pair shortest path. 0 3 4 5 6 7 7 3 0 2 1 3 4 4 4 2 0 1 3 2 3 5 1 1 0 2 3 3 6 3 3 2 0 2 1 7 4 2 3 2 0 1 7 4 3 3 1 1 0 Input − The cost matrix of given Graph. Output − Matrix to for shortest path between any vertex to any vertex. Begin for k := 0 to n, do for i := 0 to n, do for j := 0 to n, do if cost[i,k] + cost[k,j] < cost[i,j], then cost[i,j] := cost[i,k] + cost[k,j] done done done display the current cost matrix End #include<iostream> #include<iomanip> #define NODE 7 #define INF 999 using namespace std; //Cost matrix of the graph int costMat[NODE][NODE] = { {0, 3, 6, INF, INF, INF, INF}, {3, 0, 2, 1, INF, INF, INF}, {6, 2, 0, 1, 4, 2, INF}, {INF, 1, 1, 0, 2, INF, 4}, {INF, INF, 4, 2, 0, 2, 1}, {INF, INF, 2, INF, 2, 0, 1}, {INF, INF, INF, 4, 1, 1, 0} }; void floydWarshal(){ int cost[NODE][NODE]; //defind to store shortest distance from any node to any node for(int i = 0; i<NODE; i++) for(int j = 0; j<NODE; j++) cost[i][j] = costMat[i][j]; //copy costMatrix to new matrix for(int k = 0; k<NODE; k++){ for(int i = 0; i<NODE; i++) for(int j = 0; j<NODE; j++) if(cost[i][k]+cost[k][j] < cost[i][j]) cost[i][j] = cost[i][k]+cost[k][j]; } cout << "The matrix:" << endl; for(int i = 0; i<NODE; i++){ for(int j = 0; j<NODE; j++) cout << setw(3) << cost[i][j]; cout << endl; } } int main(){ floydWarshal(); } The matrix: 0 3 5 4 6 7 7 3 0 2 1 3 4 4 5 2 0 1 3 2 3 4 1 1 0 2 3 3 6 3 3 2 0 2 1 7 4 2 3 2 0 1 7 4 3 3 1 1 0
[ { "code": null, "e": 1364, "s": 1062, "text": "The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the minimum distance from any node to all other nodes in the graph." }, { "code": null, "e": 1527, "s": 1364, "text": "At first the output matrix is same as given cost matrix of the graph. After that the output matrix will be updated with all vertices k as the intermediate vertex." }, { "code": null, "e": 1622, "s": 1527, "text": "The time complexity of this algorithm is O(V3), here V is the number of vertices in the graph." }, { "code": null, "e": 1660, "s": 1622, "text": "Input − The cost matrix of the graph." }, { "code": null, "e": 1758, "s": 1660, "text": "0 3 6 ∞ ∞ ∞ ∞\n3 0 2 1 ∞ ∞ ∞\n6 2 0 1 4 2 ∞\n∞ 1 1 0 2 ∞ 4\n∞ ∞ 4 2 0 2 1\n∞ ∞ 2 ∞ 2 0 1\n∞ ∞ ∞ 4 1 1 0" }, { "code": null, "e": 1801, "s": 1758, "text": "Output − Matrix of all pair shortest path." }, { "code": null, "e": 1899, "s": 1801, "text": "0 3 4 5 6 7 7\n3 0 2 1 3 4 4\n4 2 0 1 3 2 3\n5 1 1 0 2 3 3\n6 3 3 2 0 2 1\n7 4 2 3 2 0 1\n7 4 3 3 1 1 0" }, { "code": null, "e": 1939, "s": 1899, "text": "Input − The cost matrix of given Graph." }, { "code": null, "e": 2010, "s": 1939, "text": "Output − Matrix to for shortest path between any vertex to any vertex." }, { "code": null, "e": 2283, "s": 2010, "text": "Begin\n for k := 0 to n, do\n for i := 0 to n, do\n for j := 0 to n, do\n if cost[i,k] + cost[k,j] < cost[i,j], then\n cost[i,j] := cost[i,k] + cost[k,j]\n done\n done\n done\n display the current cost matrix\nEnd" }, { "code": null, "e": 3329, "s": 2283, "text": "#include<iostream>\n#include<iomanip>\n#define NODE 7\n#define INF 999\nusing namespace std;\n//Cost matrix of the graph\nint costMat[NODE][NODE] = {\n {0, 3, 6, INF, INF, INF, INF},\n {3, 0, 2, 1, INF, INF, INF},\n {6, 2, 0, 1, 4, 2, INF},\n {INF, 1, 1, 0, 2, INF, 4},\n {INF, INF, 4, 2, 0, 2, 1},\n {INF, INF, 2, INF, 2, 0, 1},\n {INF, INF, INF, 4, 1, 1, 0}\n};\nvoid floydWarshal(){\n int cost[NODE][NODE]; //defind to store shortest distance from any node to any node\n for(int i = 0; i<NODE; i++)\n for(int j = 0; j<NODE; j++)\n cost[i][j] = costMat[i][j]; //copy costMatrix to new matrix\n for(int k = 0; k<NODE; k++){\n for(int i = 0; i<NODE; i++)\n for(int j = 0; j<NODE; j++)\n if(cost[i][k]+cost[k][j] < cost[i][j])\n cost[i][j] = cost[i][k]+cost[k][j];\n }\n cout << \"The matrix:\" << endl;\n for(int i = 0; i<NODE; i++){\n for(int j = 0; j<NODE; j++)\n cout << setw(3) << cost[i][j];\n cout << endl;\n }\n}\nint main(){\n floydWarshal();\n}" }, { "code": null, "e": 3439, "s": 3329, "text": "The matrix:\n0 3 5 4 6 7 7\n3 0 2 1 3 4 4\n5 2 0 1 3 2 3\n4 1 1 0 2 3 3\n6 3 3 2 0 2 1\n7 4 2 3 2 0 1\n7 4 3 3 1 1 0" } ]
Java Program to Search the Contents of a Table in JDBC - GeeksforGeeks
27 Oct, 2021 In order to deal with JDBC standard 7 steps are supposed to be followed: Import the databaseLoad and register driversCreate a connectionCreate a statementExecute the queryProcess the resultsClose the connection Import the database Load and register drivers Create a connection Create a statement Execute the query Process the results Close the connection Procedure: Import the database-syntax for importing the sql database in java is- import java.sql.* ;Load and register drivers-syntax for registering drivers after the loading of driver class isforName(com.mysql.jdbc.xyz) ;Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named as “hotelman” and table names are “cuslogin” and “adminlogin”.Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating the class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.Searching content in a table, let’s suppose my “cuslogin” table has columns namely “id”, “name”, “email”, “password” and we want to search the customer whose id is 1.Initialize a string with the SQL query as follows Import the database-syntax for importing the sql database in java is- import java.sql.* ; Load and register drivers-syntax for registering drivers after the loading of driver class isforName(com.mysql.jdbc.xyz) ; Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named as “hotelman” and table names are “cuslogin” and “adminlogin”. Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating the class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java. Searching content in a table, let’s suppose my “cuslogin” table has columns namely “id”, “name”, “email”, “password” and we want to search the customer whose id is 1. Initialize a string with the SQL query as follows String sql="select * from cuslogin where id=1"; If we want to search for any id in general, then the SQL query becomes String sql="select * from cuslogin where id="+Integer.parseInt(textfield.getText()); The textfield is the area(in Jframe form) where the user types the id he wants to search in the “cuslogin” table. 4.1: Initialize the below objects of Connection class, PreparedStatement class, and ResultSet class(needed for JDBC) and connect with the database as follows Connection con = null; PreparedStatement p = null; ResultSet rs = null; con = connection.connectDB(); 4.2: Now, add the SQL query of step 3.1 inside prepareStatement and execute it as follows: p =con.prepareStatement(sql); rs =p.executeQuery(); 4.3: We check if rs.next() is not null, then we display the details of that particular customer present in “cuslogin” table 4.4: Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for searching the details of the customer whose id is 1, from table “cuslogin”. Note: both the file viz result.java and connection.java should be inside the same package, else the program won’t give desired output!! Implementation: Example 1 Connection class of JDBC by making an object to be invoked in main(App) java program below in 1B Java // Java program to search the contents of// a table in JDBC Connection class for JDBC// Connection class of JDBC // Importing required classesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class connectionDB { final String DB_URL = "jdbc:mysql://localhost:3306/testDB?useSSL=false"; // Database credentials // We need two parameters to access the database // Root and password // 1. Root final String USER = "root"; // 2. Password to fetch database final String PASS = "Imei@123"; // Connection class for our database connectivity public Connection connectDB() { // Initially setting NULL // to connection class object Connection con = null; // Try block to check exceptions try { // Loading DB(SQL) drivers Class.forName("com.mysql.cj.jdbc.Driver"); // Registering SQL drivers con = DriverManager.getConnection(DB_URL, USER, PASS); } // Catch block to handle database exceptions catch (SQLException e) { // Print the line number where exception occurs e.printStackTrace(); } // Catch block to handle exception // if class not found catch (ClassNotFoundException e) { // Function prints the line number // where exception occurs e.printStackTrace(); } // Returning Connection class object to // be used in (App/Main) GFG class return con; }} App/Main Class where the program is compiled and run calling the above connection class object Java // Java program to Search the// contents of a table in JDBC // Main Java program (App Class) of JDBC // Step 1: Importing database files// Importing SQL librariesimport java.sql.*; // Main class// It's connection class is shown abovepublic class GFG { // Main driver method public static void main(String[] args) { // Step 2: Establishing a connection connectionDB connection = new connectionDB(); // Assigning NULL to object of Connection class // as shown returned by above program Connection con = null; PreparedStatement p = null; ResultSet rs = null; // Step 3: Loading and registereding drivers // Loaded and registered in Connection class // shown in above program con = connection.connectDB(); // Try block to check exceptions try { // Step 4: Write a statement String sql = "select * from cuslogin where id=1"; // Step 5: Execute the query p = con.prepareStatement(sql); rs = p.executeQuery(); // Step 6: Process the results System.out.println( "id\t\tname\t\temail\t\tpassword"); // Condition check using next() method // Holds true till there is single element remaining // in the object if (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String password = rs.getString("password"); // Print and display name, emailID and password System.out.println(id + "\t\t" + name + "\t\t" + email + "\t\t" + password); } } // Catch block to handle exceptions catch (SQLException e) { // Print the exception System.out.println(e); } }} Output: Based on the values stored inside the “cuslogin” table. abhijithoyur simranarora5sos akshaysingh98088 prachisoda1234 JDBC Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24111, "s": 24083, "text": "\n27 Oct, 2021" }, { "code": null, "e": 24184, "s": 24111, "text": "In order to deal with JDBC standard 7 steps are supposed to be followed:" }, { "code": null, "e": 24322, "s": 24184, "text": "Import the databaseLoad and register driversCreate a connectionCreate a statementExecute the queryProcess the resultsClose the connection" }, { "code": null, "e": 24342, "s": 24322, "text": "Import the database" }, { "code": null, "e": 24368, "s": 24342, "text": "Load and register drivers" }, { "code": null, "e": 24388, "s": 24368, "text": "Create a connection" }, { "code": null, "e": 24407, "s": 24388, "text": "Create a statement" }, { "code": null, "e": 24425, "s": 24407, "text": "Execute the query" }, { "code": null, "e": 24445, "s": 24425, "text": "Process the results" }, { "code": null, "e": 24466, "s": 24445, "text": "Close the connection" }, { "code": null, "e": 24477, "s": 24466, "text": "Procedure:" }, { "code": null, "e": 25482, "s": 24477, "text": "Import the database-syntax for importing the sql database in java is- import java.sql.* ;Load and register drivers-syntax for registering drivers after the loading of driver class isforName(com.mysql.jdbc.xyz) ;Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named as “hotelman” and table names are “cuslogin” and “adminlogin”.Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating the class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.Searching content in a table, let’s suppose my “cuslogin” table has columns namely “id”, “name”, “email”, “password” and we want to search the customer whose id is 1.Initialize a string with the SQL query as follows" }, { "code": null, "e": 25575, "s": 25482, "text": "Import the database-syntax for importing the sql database in java is- import java.sql.* ;" }, { "code": null, "e": 25699, "s": 25575, "text": "Load and register drivers-syntax for registering drivers after the loading of driver class isforName(com.mysql.jdbc.xyz) ;" }, { "code": null, "e": 25983, "s": 25699, "text": "Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named as “hotelman” and table names are “cuslogin” and “adminlogin”." }, { "code": null, "e": 26275, "s": 25983, "text": "Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating the class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java." }, { "code": null, "e": 26442, "s": 26275, "text": "Searching content in a table, let’s suppose my “cuslogin” table has columns namely “id”, “name”, “email”, “password” and we want to search the customer whose id is 1." }, { "code": null, "e": 26492, "s": 26442, "text": "Initialize a string with the SQL query as follows" }, { "code": null, "e": 26540, "s": 26492, "text": "String sql=\"select * from cuslogin where id=1\";" }, { "code": null, "e": 26611, "s": 26540, "text": "If we want to search for any id in general, then the SQL query becomes" }, { "code": null, "e": 26696, "s": 26611, "text": "String sql=\"select * from cuslogin where id=\"+Integer.parseInt(textfield.getText());" }, { "code": null, "e": 26810, "s": 26696, "text": "The textfield is the area(in Jframe form) where the user types the id he wants to search in the “cuslogin” table." }, { "code": null, "e": 26969, "s": 26810, "text": "4.1: Initialize the below objects of Connection class, PreparedStatement class, and ResultSet class(needed for JDBC) and connect with the database as follows " }, { "code": null, "e": 27071, "s": 26969, "text": "Connection con = null;\nPreparedStatement p = null;\nResultSet rs = null;\ncon = connection.connectDB();" }, { "code": null, "e": 27162, "s": 27071, "text": "4.2: Now, add the SQL query of step 3.1 inside prepareStatement and execute it as follows:" }, { "code": null, "e": 27214, "s": 27162, "text": "p =con.prepareStatement(sql);\nrs =p.executeQuery();" }, { "code": null, "e": 27338, "s": 27214, "text": "4.3: We check if rs.next() is not null, then we display the details of that particular customer present in “cuslogin” table" }, { "code": null, "e": 27529, "s": 27338, "text": "4.4: Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for searching the details of the customer whose id is 1, from table “cuslogin”." }, { "code": null, "e": 27665, "s": 27529, "text": "Note: both the file viz result.java and connection.java should be inside the same package, else the program won’t give desired output!!" }, { "code": null, "e": 27682, "s": 27665, "text": "Implementation: " }, { "code": null, "e": 27692, "s": 27682, "text": "Example 1" }, { "code": null, "e": 27789, "s": 27692, "text": "Connection class of JDBC by making an object to be invoked in main(App) java program below in 1B" }, { "code": null, "e": 27794, "s": 27789, "text": "Java" }, { "code": "// Java program to search the contents of// a table in JDBC Connection class for JDBC// Connection class of JDBC // Importing required classesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class connectionDB { final String DB_URL = \"jdbc:mysql://localhost:3306/testDB?useSSL=false\"; // Database credentials // We need two parameters to access the database // Root and password // 1. Root final String USER = \"root\"; // 2. Password to fetch database final String PASS = \"Imei@123\"; // Connection class for our database connectivity public Connection connectDB() { // Initially setting NULL // to connection class object Connection con = null; // Try block to check exceptions try { // Loading DB(SQL) drivers Class.forName(\"com.mysql.cj.jdbc.Driver\"); // Registering SQL drivers con = DriverManager.getConnection(DB_URL, USER, PASS); } // Catch block to handle database exceptions catch (SQLException e) { // Print the line number where exception occurs e.printStackTrace(); } // Catch block to handle exception // if class not found catch (ClassNotFoundException e) { // Function prints the line number // where exception occurs e.printStackTrace(); } // Returning Connection class object to // be used in (App/Main) GFG class return con; }}", "e": 29404, "s": 27794, "text": null }, { "code": null, "e": 29505, "s": 29408, "text": " App/Main Class where the program is compiled and run calling the above connection class object " }, { "code": null, "e": 29512, "s": 29507, "text": "Java" }, { "code": "// Java program to Search the// contents of a table in JDBC // Main Java program (App Class) of JDBC // Step 1: Importing database files// Importing SQL librariesimport java.sql.*; // Main class// It's connection class is shown abovepublic class GFG { // Main driver method public static void main(String[] args) { // Step 2: Establishing a connection connectionDB connection = new connectionDB(); // Assigning NULL to object of Connection class // as shown returned by above program Connection con = null; PreparedStatement p = null; ResultSet rs = null; // Step 3: Loading and registereding drivers // Loaded and registered in Connection class // shown in above program con = connection.connectDB(); // Try block to check exceptions try { // Step 4: Write a statement String sql = \"select * from cuslogin where id=1\"; // Step 5: Execute the query p = con.prepareStatement(sql); rs = p.executeQuery(); // Step 6: Process the results System.out.println( \"id\\t\\tname\\t\\temail\\t\\tpassword\"); // Condition check using next() method // Holds true till there is single element remaining // in the object if (rs.next()) { int id = rs.getInt(\"id\"); String name = rs.getString(\"name\"); String email = rs.getString(\"email\"); String password = rs.getString(\"password\"); // Print and display name, emailID and password System.out.println(id + \"\\t\\t\" + name + \"\\t\\t\" + email + \"\\t\\t\" + password); } } // Catch block to handle exceptions catch (SQLException e) { // Print the exception System.out.println(e); } }}", "e": 31522, "s": 29512, "text": null }, { "code": null, "e": 31591, "s": 31526, "text": "Output: Based on the values stored inside the “cuslogin” table. " }, { "code": null, "e": 31608, "s": 31595, "text": "abhijithoyur" }, { "code": null, "e": 31624, "s": 31608, "text": "simranarora5sos" }, { "code": null, "e": 31641, "s": 31624, "text": "akshaysingh98088" }, { "code": null, "e": 31656, "s": 31641, "text": "prachisoda1234" }, { "code": null, "e": 31661, "s": 31656, "text": "JDBC" }, { "code": null, "e": 31668, "s": 31661, "text": "Picked" }, { "code": null, "e": 31692, "s": 31668, "text": "Technical Scripter 2020" }, { "code": null, "e": 31697, "s": 31692, "text": "Java" }, { "code": null, "e": 31711, "s": 31697, "text": "Java Programs" }, { "code": null, "e": 31730, "s": 31711, "text": "Technical Scripter" }, { "code": null, "e": 31735, "s": 31730, "text": "Java" }, { "code": null, "e": 31833, "s": 31735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31842, "s": 31833, "text": "Comments" }, { "code": null, "e": 31855, "s": 31842, "text": "Old Comments" }, { "code": null, "e": 31906, "s": 31855, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31936, "s": 31906, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31967, "s": 31936, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31986, "s": 31967, "text": "Interfaces in Java" }, { "code": null, "e": 32018, "s": 31986, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32062, "s": 32018, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 32090, "s": 32062, "text": "Initializing a List in Java" }, { "code": null, "e": 32116, "s": 32090, "text": "Java Programming Examples" }, { "code": null, "e": 32150, "s": 32116, "text": "Convert Double to Integer in Java" } ]
Automate your Data Management Discipline with Python | by Garrett Eichhorn | Towards Data Science
Anyone that interacts with data understands the importance of data quality. Whether you’re performing basic analysis in excel or forecasting sales trends with decision trees, poor data will always rear its ugly head and curtail your progress. It’s easy to place the onus on the overworked data steward and the gluttonous data consumer, but it’s ultimately the data professional’s burden to bear as the liaison between the two. So, how can you elevate the data management competency in your enterprise and advocate for more effective analysis? Automate your data quality metrics. Data quality metrics are defined in many ways, by many people. I like to use the 4 V’s and the 4 C’s to frame conversations about quality, because they’re easy to remember, market and visualize: Completeness — How much of the data that’s expected is there? Are the ‘important’ columns filled out? Consistency — Are data values the same across data sets? Conformity — Does the data comply with specified formats? Curiosity — Are stakeholders knowledgeable and/or engaged in the data management lifecycle? Volume — How much information is present? Velocity — What’s the frequency of incoming data? How often is the data processed and propagated? Variety — What types of data exist? Is the data structured, unstructured or semi-structured? Veracity — Is the data trustworthy? What are the inherent discrepancies? There are a few Python packages I use to quickly measure and socialize these concepts. Pandas has many built in methods to for investigating the data: I use .describe() with conditional formatting to find patterns. For a more robust report I use pandas-profiling, which is easily embedded in a Jupyter Notebook or saved to an HTML file. import pandas as pdimport pandas_profilingdf = read_csv("raw_data.csv")df.describe()profile = pandas_profiling.ProfileReport(df)profile.to_file("profile.html") Matplotlib and seaborn are great libraries for plotting data. I’ve recently been exploring plotly for creating quick, versatile and engaging visualizations that can be easily embedded in a website. Here’s a great guide on how to do just that. So far we’ve examined some trite theories to build a conceptual framework for socializing data quality, and have basic tools to visualize and present metrics. It’s time to automate! As data professionals, it’s critical that we educate and motivate the enterprise to manage data for effective analysis, by exposing dirty data and articulating data debt. Automation can solidify best-practice into discipline by sustaining transparency and accountability. I recently worked on a project that focused heavily on data ingestion to calculate profit margins for global products, grouped by franchise. The effort started as an executive order to better understand profitability, but quickly spiraled out of control. Like most enterprises with a global footprint, my client delivers strategic growth by purchasing companies that will minimize operating costs (like distributors) to streamline the supply chain. IT consolidation couldn’t quite catch up to the operating plan; previous efforts to calculate margin proved unsuccessful because of disparate ERP systems (more than 15 in total), discombobulated nomenclature, high steward turnover, etc. Data stewards from across the globe would send individual .csv files via email to the Business Intelligence team, to be merged manually with invoice sales data in an enterprise data warehouse. Pre-packaged reports were passed on to leadership with innumerable caveats, to be undermined by data stewards convinced other stakeholders were diluting the data. Data quality was so disorganized that visibility into basic margin analysis could not be reached, much less sustained. The burnt-out B.I group needed some help! Data completeness and conformity were creating major problems for the margin calculation: incomplete data would flood in from the stewards without structure and in many different formats. Velocity was inconsistent, flowing infrequently from various groups, where poor reputation dictated low veracity. Eventually, I would be contributing to the project by performing advanced analysis on margin calculations to interpret profitability and market share. But without effective data management for calculating profit margin to run through the data science pipeline, I had lots of opportunity to automate an effective pipeline and inform stakeholders on data quality. We collaborated with data stewards, owners and a governance council to identify only the relevant values needed for margin calculation, organized by function: product-to-product mappings, cost, unit of measure conversion, and additional attributes. The templates were replicated to fit each global franchise, so that a data steward was only responsible for maintaining their asset. In total, we would have more than 50 files! I built a SharePoint site to host the templates in Document Repositories, which is the SharePoint equivalent of a directory folder. I then created a simple python script to iterate through the “folders” to concatenate the files by function, adding additional columns like “Date Modified”, “Initial File Name”, and a “Completeness” metric that calculated how many columns were filled out relative to the total (by row). The more than 50 files reduced to 4, representing each of the functional data assets. In order to evangelize data quality concepts, I used pandas-profiling to build data quality reports by function and embed on the SharePoint site. The B.I team was tired of manually uploading flat files to the data warehouse. I employed pyODBC to establish a connection to the enterprise SQL Server, and loaded only the records that fulfilled an adequate “Completeness” score. import pyodbcconn = pyodbc.connect('Driver={SQL Server};' 'Server=<server>;' 'Database=<database>;' 'Trusted_Connection=yes;')cursor = conn.cursor()sql_query = "SELECT * FROM table_name"cursor.execute(sql_query)cursor.fetchall()sql_df = pd.read_sql(sql_query, conn) I can query the records once they’re loaded into the data warehouse and check for conformity by cross-referencing the data with information_schema and column constraints; if a column has a VARCHAR limit of 5 and the value has length equal to 10, the record won’t be loaded. I stored this “error log” on the SharePoint site for data stewards to reference as needed. Finally, we compute margin for the records loaded into the SQL Server and store the result in a plotly graph to provide immediate feedback on franchise performance. A beautiful, animated visualization describes expected records, provided records, loaded records, records with margin, and percentage of total revenue over time. Leaders can quickly view which data stewards are actively contributing quality data, which aren’t, and where the major discrepancies are occurring. The end result is a consolidated platform for consuming profit margins by franchise with data quality metrics updated in real-time, fed by an automated pipeline. Data professionals can focus on turning insights into action and less on “herding the cats”. Data management is terminally less sexy than analysis and advanced techniques, but is just as important. Poor data will distract you from insightful analysis and plague talented data professionals in your enterprise if managed improperly. Although oversimplified, the methodology outlined in this article articulates how people, process, data and technology can interact to produce an integral metric for the enterprise. By focusing on the fundamentals of the data management lifecycle before skipping to “the fun stuff”, the project team can quickly pivot from ingesting the data to understanding the data. In total, my contributions will save the enterprise more than 400 hours of manual work on an annual basis. Furthermore, we’ve contributed to a culture devoid of data management and helped coalesce data quality strategy along the way. Start automating your data management discipline!
[ { "code": null, "e": 751, "s": 172, "text": "Anyone that interacts with data understands the importance of data quality. Whether you’re performing basic analysis in excel or forecasting sales trends with decision trees, poor data will always rear its ugly head and curtail your progress. It’s easy to place the onus on the overworked data steward and the gluttonous data consumer, but it’s ultimately the data professional’s burden to bear as the liaison between the two. So, how can you elevate the data management competency in your enterprise and advocate for more effective analysis? Automate your data quality metrics." }, { "code": null, "e": 946, "s": 751, "text": "Data quality metrics are defined in many ways, by many people. I like to use the 4 V’s and the 4 C’s to frame conversations about quality, because they’re easy to remember, market and visualize:" }, { "code": null, "e": 1048, "s": 946, "text": "Completeness — How much of the data that’s expected is there? Are the ‘important’ columns filled out?" }, { "code": null, "e": 1105, "s": 1048, "text": "Consistency — Are data values the same across data sets?" }, { "code": null, "e": 1163, "s": 1105, "text": "Conformity — Does the data comply with specified formats?" }, { "code": null, "e": 1255, "s": 1163, "text": "Curiosity — Are stakeholders knowledgeable and/or engaged in the data management lifecycle?" }, { "code": null, "e": 1297, "s": 1255, "text": "Volume — How much information is present?" }, { "code": null, "e": 1395, "s": 1297, "text": "Velocity — What’s the frequency of incoming data? How often is the data processed and propagated?" }, { "code": null, "e": 1488, "s": 1395, "text": "Variety — What types of data exist? Is the data structured, unstructured or semi-structured?" }, { "code": null, "e": 1561, "s": 1488, "text": "Veracity — Is the data trustworthy? What are the inherent discrepancies?" }, { "code": null, "e": 1898, "s": 1561, "text": "There are a few Python packages I use to quickly measure and socialize these concepts. Pandas has many built in methods to for investigating the data: I use .describe() with conditional formatting to find patterns. For a more robust report I use pandas-profiling, which is easily embedded in a Jupyter Notebook or saved to an HTML file." }, { "code": null, "e": 2058, "s": 1898, "text": "import pandas as pdimport pandas_profilingdf = read_csv(\"raw_data.csv\")df.describe()profile = pandas_profiling.ProfileReport(df)profile.to_file(\"profile.html\")" }, { "code": null, "e": 2301, "s": 2058, "text": "Matplotlib and seaborn are great libraries for plotting data. I’ve recently been exploring plotly for creating quick, versatile and engaging visualizations that can be easily embedded in a website. Here’s a great guide on how to do just that." }, { "code": null, "e": 2755, "s": 2301, "text": "So far we’ve examined some trite theories to build a conceptual framework for socializing data quality, and have basic tools to visualize and present metrics. It’s time to automate! As data professionals, it’s critical that we educate and motivate the enterprise to manage data for effective analysis, by exposing dirty data and articulating data debt. Automation can solidify best-practice into discipline by sustaining transparency and accountability." }, { "code": null, "e": 3204, "s": 2755, "text": "I recently worked on a project that focused heavily on data ingestion to calculate profit margins for global products, grouped by franchise. The effort started as an executive order to better understand profitability, but quickly spiraled out of control. Like most enterprises with a global footprint, my client delivers strategic growth by purchasing companies that will minimize operating costs (like distributors) to streamline the supply chain." }, { "code": null, "e": 3441, "s": 3204, "text": "IT consolidation couldn’t quite catch up to the operating plan; previous efforts to calculate margin proved unsuccessful because of disparate ERP systems (more than 15 in total), discombobulated nomenclature, high steward turnover, etc." }, { "code": null, "e": 3958, "s": 3441, "text": "Data stewards from across the globe would send individual .csv files via email to the Business Intelligence team, to be merged manually with invoice sales data in an enterprise data warehouse. Pre-packaged reports were passed on to leadership with innumerable caveats, to be undermined by data stewards convinced other stakeholders were diluting the data. Data quality was so disorganized that visibility into basic margin analysis could not be reached, much less sustained. The burnt-out B.I group needed some help!" }, { "code": null, "e": 4260, "s": 3958, "text": "Data completeness and conformity were creating major problems for the margin calculation: incomplete data would flood in from the stewards without structure and in many different formats. Velocity was inconsistent, flowing infrequently from various groups, where poor reputation dictated low veracity." }, { "code": null, "e": 4622, "s": 4260, "text": "Eventually, I would be contributing to the project by performing advanced analysis on margin calculations to interpret profitability and market share. But without effective data management for calculating profit margin to run through the data science pipeline, I had lots of opportunity to automate an effective pipeline and inform stakeholders on data quality." }, { "code": null, "e": 5048, "s": 4622, "text": "We collaborated with data stewards, owners and a governance council to identify only the relevant values needed for margin calculation, organized by function: product-to-product mappings, cost, unit of measure conversion, and additional attributes. The templates were replicated to fit each global franchise, so that a data steward was only responsible for maintaining their asset. In total, we would have more than 50 files!" }, { "code": null, "e": 5699, "s": 5048, "text": "I built a SharePoint site to host the templates in Document Repositories, which is the SharePoint equivalent of a directory folder. I then created a simple python script to iterate through the “folders” to concatenate the files by function, adding additional columns like “Date Modified”, “Initial File Name”, and a “Completeness” metric that calculated how many columns were filled out relative to the total (by row). The more than 50 files reduced to 4, representing each of the functional data assets. In order to evangelize data quality concepts, I used pandas-profiling to build data quality reports by function and embed on the SharePoint site." }, { "code": null, "e": 5929, "s": 5699, "text": "The B.I team was tired of manually uploading flat files to the data warehouse. I employed pyODBC to establish a connection to the enterprise SQL Server, and loaded only the records that fulfilled an adequate “Completeness” score." }, { "code": null, "e": 6270, "s": 5929, "text": "import pyodbcconn = pyodbc.connect('Driver={SQL Server};' 'Server=<server>;' 'Database=<database>;' 'Trusted_Connection=yes;')cursor = conn.cursor()sql_query = \"SELECT * FROM table_name\"cursor.execute(sql_query)cursor.fetchall()sql_df = pd.read_sql(sql_query, conn)" }, { "code": null, "e": 6635, "s": 6270, "text": "I can query the records once they’re loaded into the data warehouse and check for conformity by cross-referencing the data with information_schema and column constraints; if a column has a VARCHAR limit of 5 and the value has length equal to 10, the record won’t be loaded. I stored this “error log” on the SharePoint site for data stewards to reference as needed." }, { "code": null, "e": 7365, "s": 6635, "text": "Finally, we compute margin for the records loaded into the SQL Server and store the result in a plotly graph to provide immediate feedback on franchise performance. A beautiful, animated visualization describes expected records, provided records, loaded records, records with margin, and percentage of total revenue over time. Leaders can quickly view which data stewards are actively contributing quality data, which aren’t, and where the major discrepancies are occurring. The end result is a consolidated platform for consuming profit margins by franchise with data quality metrics updated in real-time, fed by an automated pipeline. Data professionals can focus on turning insights into action and less on “herding the cats”." }, { "code": null, "e": 7973, "s": 7365, "text": "Data management is terminally less sexy than analysis and advanced techniques, but is just as important. Poor data will distract you from insightful analysis and plague talented data professionals in your enterprise if managed improperly. Although oversimplified, the methodology outlined in this article articulates how people, process, data and technology can interact to produce an integral metric for the enterprise. By focusing on the fundamentals of the data management lifecycle before skipping to “the fun stuff”, the project team can quickly pivot from ingesting the data to understanding the data." } ]
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. Print each fruit in a fruit list: The for loop does not require an indexing variable to set beforehand. Even strings are iterable objects, they contain a sequence of characters: Loop through the letters in the word "banana": With the break statement we can stop the loop before it has looped through all the items: Exit the loop when x is "banana": Exit the loop when x is "banana", but this time the break comes before the print: With the continue statement we can stop the current iteration of the loop, and continue with the next: Do not print banana: The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Using the range() function: Note that range(6) is not the values of 0 to 6, but the values 0 to 5. The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): Using the start parameter: The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): Increment the sequence with 3 (default is 1): The else keyword in a for loop specifies a block of code to be executed when the loop is finished: Print all numbers from 0 to 5, and print a message when the loop has ended: Note: The else block will NOT be executed if the loop is stopped by a break statement. Break the loop when x is 3, and see what happens with the else block: A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": Print each adjective for every fruit: for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. Loop through the items in the fruits list. fruits = ["apple", "banana", "cherry"] x fruits print(x) 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 118, "s": 0, "text": "A for loop is used for iterating over a sequence (that is either a list, a tuple, \na dictionary, a set, or a string)." }, { "code": null, "e": 282, "s": 118, "text": "This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages." }, { "code": null, "e": 382, "s": 282, "text": "With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc." }, { "code": null, "e": 416, "s": 382, "text": "Print each fruit in a fruit list:" }, { "code": null, "e": 486, "s": 416, "text": "The for loop does not require an indexing variable to set beforehand." }, { "code": null, "e": 560, "s": 486, "text": "Even strings are iterable objects, they contain a sequence of characters:" }, { "code": null, "e": 607, "s": 560, "text": "Loop through the letters in the word \"banana\":" }, { "code": null, "e": 698, "s": 607, "text": "With the break statement we can stop the \nloop before it has looped through all the items:" }, { "code": null, "e": 732, "s": 698, "text": "Exit the loop when x is \"banana\":" }, { "code": null, "e": 815, "s": 732, "text": "Exit the loop when x is \"banana\", \nbut this time the break comes before the print:" }, { "code": null, "e": 919, "s": 815, "text": "With the continue statement we can stop the \ncurrent iteration of the loop, and continue with the next:" }, { "code": null, "e": 940, "s": 919, "text": "Do not print banana:" }, { "code": null, "e": 1086, "s": 940, "text": "The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number." }, { "code": null, "e": 1114, "s": 1086, "text": "Using the range() function:" }, { "code": null, "e": 1185, "s": 1114, "text": "Note that range(6) is not the values of 0 to 6, but the values 0 to 5." }, { "code": null, "e": 1385, "s": 1185, "text": "The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which \nmeans values from 2 to 6 (but not including 6):" }, { "code": null, "e": 1412, "s": 1385, "text": "Using the start parameter:" }, { "code": null, "e": 1574, "s": 1412, "text": "The range() function defaults to increment the sequence by 1,\nhowever it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):" }, { "code": null, "e": 1620, "s": 1574, "text": "Increment the sequence with 3 (default is 1):" }, { "code": null, "e": 1720, "s": 1620, "text": "The else keyword in a\nfor loop specifies a block of code to be \nexecuted when the loop is finished:" }, { "code": null, "e": 1796, "s": 1720, "text": "Print all numbers from 0 to 5, and print a message when the loop has ended:" }, { "code": null, "e": 1883, "s": 1796, "text": "Note: The else block will NOT be executed if the loop is stopped by a break statement." }, { "code": null, "e": 1954, "s": 1883, "text": "Break the loop when x is 3, and see what happens with the \nelse block:" }, { "code": null, "e": 1993, "s": 1954, "text": "A nested loop is a loop inside a loop." }, { "code": null, "e": 2077, "s": 1993, "text": "The \"inner loop\" will be executed one time for each iteration of the \"outer \nloop\":" }, { "code": null, "e": 2115, "s": 2077, "text": "Print each adjective for every fruit:" }, { "code": null, "e": 2256, "s": 2115, "text": "for loops cannot be empty, but if you for \nsome reason have a for loop with no content, put in the pass statement to avoid getting an error." }, { "code": null, "e": 2299, "s": 2256, "text": "Loop through the items in the fruits list." }, { "code": null, "e": 2361, "s": 2299, "text": "fruits = [\"apple\", \"banana\", \"cherry\"]\n x fruits\n print(x)\n" }, { "code": null, "e": 2380, "s": 2361, "text": "Start the Exercise" }, { "code": null, "e": 2413, "s": 2380, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2455, "s": 2413, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2562, "s": 2455, "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": 2581, "s": 2562, "text": "help@w3schools.com" } ]
VBScript If..ElseIf..Else Statements
An If statement followed by one or more ElseIf Statements that consists of boolean expressions and then followed by a default else statement, which executes when all the condition becomes false. The syntax of an If-ElseIf-Else statement in VBScript is − If(boolean_expression) Then Statement 1 ..... ..... Statement n ElseIf (boolean_expression) Then Statement 1 ..... .... Statement n ElseIf (boolean_expression) Then Statement 1 ..... .... Statement n Else Statement 1 ..... .... Statement n End If <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim a a = -5 If a > 0 Then Document.write "a is a POSITIVE Number" ElseIf a < 0 Then Document.write "a is a NEGATIVE Number" Else Document.write "a is EQUAL than ZERO" End If </script> </body> </html> When the above code is executed, it produces the following result − a is a NEGATIVE Number 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2275, "s": 2080, "text": "An If statement followed by one or more ElseIf Statements that consists of boolean expressions and then followed by a default else statement, which executes when all the condition becomes false." }, { "code": null, "e": 2334, "s": 2275, "text": "The syntax of an If-ElseIf-Else statement in VBScript is −" }, { "code": null, "e": 2614, "s": 2334, "text": "If(boolean_expression) Then\n Statement 1\n\t.....\n\t.....\n Statement n\nElseIf (boolean_expression) Then\n Statement 1\n\t.....\n\t....\n Statement n\nElseIf (boolean_expression) Then\n Statement 1\n\t.....\n\t....\n Statement n\nElse\n Statement 1\n\t.....\n\t....\n Statement n\nEnd If\n" }, { "code": null, "e": 3010, "s": 2614, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim a \n a = -5\n\n If a > 0 Then\n Document.write \"a is a POSITIVE Number\"\n ElseIf a < 0 Then\n Document.write \"a is a NEGATIVE Number\"\n Else\n Document.write \"a is EQUAL than ZERO\"\n End If\n </script>\n </body>\n</html>" }, { "code": null, "e": 3078, "s": 3010, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3102, "s": 3078, "text": "a is a NEGATIVE Number\n" }, { "code": null, "e": 3135, "s": 3102, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 3152, "s": 3135, "text": " Frahaan Hussain" }, { "code": null, "e": 3159, "s": 3152, "text": " Print" }, { "code": null, "e": 3170, "s": 3159, "text": " Add Notes" } ]
How to create a dynamic 2D array inside a class in C++
Here it is a simple C++ program to create a dynamic 2D array inside a class to print the elements of the array. Begin Create a class Arr and declare size of array. Inside the class, initialize all the elements by using for loop. Print the all elements. End. Live Demo #include <iostream> #include <stdlib.h> using namespace std; const int M=7; class Arr { private: int A[M]; int size; public: Arr(int s, int v) { if(s>M) { cout<<endl<<"This is beyond maximum size"; exit(1); } size = s; for(int i=0;i<size;i++) A[i] = v; } int& operator[](int i) { if( (i<0) || (i >= size) ) { cout<<endl<<"Error: Array out of bound"; exit(1); } return A[i]; } }; int main() { int i=0; Arr a(7,0); for(i=0;i<7;i++) a[i] = i*10; cout<<"Array elements are:"<<endl; for(i=0;i<7;i++) { int val = a[i]; cout<<val<<endl; } return 0; } Array elements are: 0 10 20 30 40 50 60
[ { "code": null, "e": 1174, "s": 1062, "text": "Here it is a simple C++ program to create a dynamic 2D array inside a class to print the elements of the array." }, { "code": null, "e": 1329, "s": 1174, "text": "Begin\n Create a class Arr and declare size of array.\n Inside the class, initialize all the elements by using for loop.\n Print the all elements.\nEnd." }, { "code": null, "e": 1340, "s": 1329, "text": " Live Demo" }, { "code": null, "e": 2034, "s": 1340, "text": "#include <iostream>\n#include <stdlib.h>\nusing namespace std;\nconst int M=7;\nclass Arr {\n private:\n int A[M];\n int size;\n public:\n Arr(int s, int v) {\n if(s>M) {\n cout<<endl<<\"This is beyond maximum size\";\n exit(1);\n }\n size = s;\n for(int i=0;i<size;i++)\n A[i] = v;\n }\n int& operator[](int i) {\n if( (i<0) || (i >= size) ) {\n cout<<endl<<\"Error: Array out of bound\";\n exit(1);\n }\n return A[i];\n }\n};\nint main() {\n int i=0;\n Arr a(7,0);\n for(i=0;i<7;i++)\n a[i] = i*10;\n cout<<\"Array elements are:\"<<endl;\n for(i=0;i<7;i++) {\n int val = a[i];\n cout<<val<<endl;\n }\n return 0;\n}" }, { "code": null, "e": 2074, "s": 2034, "text": "Array elements are:\n0\n10\n20\n30\n40\n50\n60" } ]
PLSQL | SOUNDEX Function - GeeksforGeeks
27 Sep, 2019 The PLSQL SOUNDEX function is used for returning a phonetic representation of a string. The phonetic represents the way the string will sound. The PLSQL SOUNDEX function helps to compare words that are spelled differently, but sound alike in English. The SOUNDEX function accepts one parameter input_string which can be of any of the datatypes CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is the same datatype as char. Syntax: SOUNDEX( input_string ) Parameters Used: input_string – It is used to specify the string whose phonetic representation you want to know. Note: The value returned by the SOUNDEX function will always begin with the first letter of the input_string. The SOUNDEX function uses only the first 5 consonants to determine the NUMERIC portion of the return value, except if the first letter of string1 is a vowel. The SOUNDEX function is not a case-sensitive function. Supported Versions of Oracle/PLSQL: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: DECLARE Test_String string(25) := 'geeksforgeeks'; BEGIN dbms_output.put_line(SOUNDEX(Test_String)); END; Output: G216 Example-2: DECLARE Test_String string(25) := 'GEEKSFORGEEKS'; BEGIN dbms_output.put_line(SOUNDEX(Test_String)); END; Output: G216 Example-3: DECLARE Test_String string(25) := 'Hello'; BEGIN dbms_output.put_line(SOUNDEX(Test_String)); END; Output: H400 Example-4: DECLARE Test_String string(25) := 'Hello'; BEGIN dbms_output.put_line(SOUNDEX(Test_String)); END; Output: H400 Example-5: DECLARE Test_String string(25) := 'Hello User'; BEGIN dbms_output.put_line(SOUNDEX(Test_String)); END; Output: H426 shubham_singh SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL | Subquery
[ { "code": null, "e": 25237, "s": 25209, "text": "\n27 Sep, 2019" }, { "code": null, "e": 25488, "s": 25237, "text": "The PLSQL SOUNDEX function is used for returning a phonetic representation of a string. The phonetic represents the way the string will sound. The PLSQL SOUNDEX function helps to compare words that are spelled differently, but sound alike in English." }, { "code": null, "e": 25665, "s": 25488, "text": "The SOUNDEX function accepts one parameter input_string which can be of any of the datatypes CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is the same datatype as char." }, { "code": null, "e": 25673, "s": 25665, "text": "Syntax:" }, { "code": null, "e": 25697, "s": 25673, "text": "SOUNDEX( input_string )" }, { "code": null, "e": 25714, "s": 25697, "text": "Parameters Used:" }, { "code": null, "e": 25810, "s": 25714, "text": "input_string – It is used to specify the string whose phonetic representation you want to know." }, { "code": null, "e": 25816, "s": 25810, "text": "Note:" }, { "code": null, "e": 25920, "s": 25816, "text": "The value returned by the SOUNDEX function will always begin with the first letter of the input_string." }, { "code": null, "e": 26078, "s": 25920, "text": "The SOUNDEX function uses only the first 5 consonants to determine the NUMERIC portion of the return value, except if the first letter of string1 is a vowel." }, { "code": null, "e": 26133, "s": 26078, "text": "The SOUNDEX function is not a case-sensitive function." }, { "code": null, "e": 26169, "s": 26133, "text": "Supported Versions of Oracle/PLSQL:" }, { "code": null, "e": 26218, "s": 26169, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 26229, "s": 26218, "text": "Oracle 12c" }, { "code": null, "e": 26240, "s": 26229, "text": "Oracle 11g" }, { "code": null, "e": 26251, "s": 26240, "text": "Oracle 10g" }, { "code": null, "e": 26261, "s": 26251, "text": "Oracle 9i" }, { "code": null, "e": 26271, "s": 26261, "text": "Oracle 8i" }, { "code": null, "e": 26282, "s": 26271, "text": "Example-1:" }, { "code": null, "e": 26410, "s": 26282, "text": "DECLARE \n Test_String string(25) := 'geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(SOUNDEX(Test_String)); \n \nEND; " }, { "code": null, "e": 26418, "s": 26410, "text": "Output:" }, { "code": null, "e": 26424, "s": 26418, "text": "G216 " }, { "code": null, "e": 26435, "s": 26424, "text": "Example-2:" }, { "code": null, "e": 26560, "s": 26435, "text": "DECLARE \n Test_String string(25) := 'GEEKSFORGEEKS';\n \nBEGIN \n dbms_output.put_line(SOUNDEX(Test_String)); \n \nEND; " }, { "code": null, "e": 26568, "s": 26560, "text": "Output:" }, { "code": null, "e": 26574, "s": 26568, "text": "G216 " }, { "code": null, "e": 26585, "s": 26574, "text": "Example-3:" }, { "code": null, "e": 26702, "s": 26585, "text": "DECLARE \n Test_String string(25) := 'Hello';\n \nBEGIN \n dbms_output.put_line(SOUNDEX(Test_String)); \n \nEND; " }, { "code": null, "e": 26710, "s": 26702, "text": "Output:" }, { "code": null, "e": 26716, "s": 26710, "text": "H400 " }, { "code": null, "e": 26727, "s": 26716, "text": "Example-4:" }, { "code": null, "e": 26844, "s": 26727, "text": "DECLARE \n Test_String string(25) := 'Hello';\n \nBEGIN \n dbms_output.put_line(SOUNDEX(Test_String)); \n \nEND; " }, { "code": null, "e": 26852, "s": 26844, "text": "Output:" }, { "code": null, "e": 26858, "s": 26852, "text": "H400 " }, { "code": null, "e": 26869, "s": 26858, "text": "Example-5:" }, { "code": null, "e": 26991, "s": 26869, "text": "DECLARE \n Test_String string(25) := 'Hello User';\n \nBEGIN \n dbms_output.put_line(SOUNDEX(Test_String)); \n \nEND; " }, { "code": null, "e": 26999, "s": 26991, "text": "Output:" }, { "code": null, "e": 27005, "s": 26999, "text": "H426 " }, { "code": null, "e": 27019, "s": 27005, "text": "shubham_singh" }, { "code": null, "e": 27030, "s": 27019, "text": "SQL-PL/SQL" }, { "code": null, "e": 27034, "s": 27030, "text": "SQL" }, { "code": null, "e": 27038, "s": 27034, "text": "SQL" }, { "code": null, "e": 27136, "s": 27038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27160, "s": 27136, "text": "SQL Interview Questions" }, { "code": null, "e": 27171, "s": 27160, "text": "CTE in SQL" }, { "code": null, "e": 27202, "s": 27171, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 27268, "s": 27202, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27280, "s": 27268, "text": "SQL | Views" }, { "code": null, "e": 27319, "s": 27280, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27364, "s": 27319, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27396, "s": 27364, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27435, "s": 27396, "text": "Difference between DELETE and TRUNCATE" } ]
Count Hexadecimal Number - GeeksforGeeks
16 Apr, 2021 Given a range [L, R]. The task is to find the total number of Hexadecimal alphabets that are required to write every number in the range. Hexadecimal alphabets are the alphabets in the range [A, F] which are required to represent decimal numbers from the range [10, 15]Examples: Input: L = 10, R = 15 Output: 6 All the numbers from 10 to 15 contain a hexadecimal alphabet.Input: L = 15, R = 16 Output: 1 15 and 16 are represented in hexadecimal as F and 10 respectively. Approach: First of all, check if num ≥ 10 and num ≤ 15. If yes then increment the count as decimal numbers from 10 to 15 contain a hexadecimal alphabet.If num > 15 than update the number as num = num % 16. If it is greater than 10 than increment the count.Repeat 2nd step till number (for every number) is greater than 0. First of all, check if num ≥ 10 and num ≤ 15. If yes then increment the count as decimal numbers from 10 to 15 contain a hexadecimal alphabet. If num > 15 than update the number as num = num % 16. If it is greater than 10 than increment the count. Repeat 2nd step till number (for every number) is greater than 0. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that will count// total hexadecimal alphabetint countHexadecimal(int L, int R){ int count = 0; for (int i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { int k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codeint main(){ int L = 5, R = 100; cout << countHexadecimal(L, R); return 0;} // Java implementation of the approachclass GFG{ // Function that will count// total hexadecimal alphabetstatic int countHexadecimal(int L, int R){ int count = 0; for (int i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 // repeatedly till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { int k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codepublic static void main(String args[]){ int L = 5, R = 100; System.out.print(countHexadecimal(L, R));}} // This code is contributed// by Akanksha Rai # Python3 implementation of the approach # Function that will count# total hexadecimal alphabetdef countHexadecimal(L, R) : count = 0; for i in range(L, R + 1) : # All the numbers from 10 to 15 # contain a hexadecimal alphabet if (i >= 10 and i <= 15) : count += 1; # If i > 15 then perform mod by 16 # repeatedly till the number is > 0 # If number % 16 > 10 then # increase count elif (i > 15) : k = i; while (k != 0) : if (k % 16 >= 10) : count += 1; k = k // 16; return count; # Driver codeif __name__ == "__main__" : L = 5; R = 100; print(countHexadecimal(L, R)); # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ // Function that will count// total hexadecimal alphabetstatic int countHexadecimal(int L, int R){ int count = 0; for (int i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { int k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codepublic static void Main(){ int L = 5, R = 100; Console.Write(countHexadecimal(L, R));}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the approach // Function that will count// total hexadecimal alphabetfunction countHexadecimal($L, $R){ $count = 0; for ($i = $L; $i <= $R; $i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if ($i >= 10 && $i <= 15) $count++; // If i > 15 then perform mod by 16 // repeatedly till the number is > 0 // If number % 16 > 10 then increase count else if ($i > 15) { $k = $i; while ($k != 0) { if ($k % 16 >= 10) $count++; $k = $k / 16; } } } return $count;} // Driver code$L = 5;$R = 100;echo countHexadecimal($L, $R); // This code is contributed by Ita_c?> <script> // Javascript implementation of the approach // Function that will count// total hexadecimal alphabetfunction countHexadecimal(L, R){ var count = 0; for (var i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { var k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codevar L = 5, R = 100;document.write( countHexadecimal(L, R)); // This code is contributed by rutvik_56.</script> 36 ankthon Akanksha_Rai ukasp rutvik_56 base-conversion C++ Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Const keyword in C++ Handling the Divide by Zero Exception in C++ Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24137, "s": 24109, "text": "\n16 Apr, 2021" }, { "code": null, "e": 24418, "s": 24137, "text": "Given a range [L, R]. The task is to find the total number of Hexadecimal alphabets that are required to write every number in the range. Hexadecimal alphabets are the alphabets in the range [A, F] which are required to represent decimal numbers from the range [10, 15]Examples: " }, { "code": null, "e": 24612, "s": 24418, "text": "Input: L = 10, R = 15 Output: 6 All the numbers from 10 to 15 contain a hexadecimal alphabet.Input: L = 15, R = 16 Output: 1 15 and 16 are represented in hexadecimal as F and 10 respectively. " }, { "code": null, "e": 24626, "s": 24614, "text": "Approach: " }, { "code": null, "e": 24938, "s": 24626, "text": "First of all, check if num ≥ 10 and num ≤ 15. If yes then increment the count as decimal numbers from 10 to 15 contain a hexadecimal alphabet.If num > 15 than update the number as num = num % 16. If it is greater than 10 than increment the count.Repeat 2nd step till number (for every number) is greater than 0." }, { "code": null, "e": 25081, "s": 24938, "text": "First of all, check if num ≥ 10 and num ≤ 15. If yes then increment the count as decimal numbers from 10 to 15 contain a hexadecimal alphabet." }, { "code": null, "e": 25186, "s": 25081, "text": "If num > 15 than update the number as num = num % 16. If it is greater than 10 than increment the count." }, { "code": null, "e": 25252, "s": 25186, "text": "Repeat 2nd step till number (for every number) is greater than 0." }, { "code": null, "e": 25305, "s": 25252, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25309, "s": 25305, "text": "C++" }, { "code": null, "e": 25314, "s": 25309, "text": "Java" }, { "code": null, "e": 25322, "s": 25314, "text": "Python3" }, { "code": null, "e": 25325, "s": 25322, "text": "C#" }, { "code": null, "e": 25329, "s": 25325, "text": "PHP" }, { "code": null, "e": 25340, "s": 25329, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that will count// total hexadecimal alphabetint countHexadecimal(int L, int R){ int count = 0; for (int i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { int k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codeint main(){ int L = 5, R = 100; cout << countHexadecimal(L, R); return 0;}", "e": 26146, "s": 25340, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function that will count// total hexadecimal alphabetstatic int countHexadecimal(int L, int R){ int count = 0; for (int i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 // repeatedly till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { int k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codepublic static void main(String args[]){ int L = 5, R = 100; System.out.print(countHexadecimal(L, R));}} // This code is contributed// by Akanksha Rai", "e": 27022, "s": 26146, "text": null }, { "code": "# Python3 implementation of the approach # Function that will count# total hexadecimal alphabetdef countHexadecimal(L, R) : count = 0; for i in range(L, R + 1) : # All the numbers from 10 to 15 # contain a hexadecimal alphabet if (i >= 10 and i <= 15) : count += 1; # If i > 15 then perform mod by 16 # repeatedly till the number is > 0 # If number % 16 > 10 then # increase count elif (i > 15) : k = i; while (k != 0) : if (k % 16 >= 10) : count += 1; k = k // 16; return count; # Driver codeif __name__ == \"__main__\" : L = 5; R = 100; print(countHexadecimal(L, R)); # This code is contributed by Ryuga", "e": 27787, "s": 27022, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function that will count// total hexadecimal alphabetstatic int countHexadecimal(int L, int R){ int count = 0; for (int i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { int k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codepublic static void Main(){ int L = 5, R = 100; Console.Write(countHexadecimal(L, R));}} // This code is contributed// by Akanksha Rai", "e": 28659, "s": 27787, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that will count// total hexadecimal alphabetfunction countHexadecimal($L, $R){ $count = 0; for ($i = $L; $i <= $R; $i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if ($i >= 10 && $i <= 15) $count++; // If i > 15 then perform mod by 16 // repeatedly till the number is > 0 // If number % 16 > 10 then increase count else if ($i > 15) { $k = $i; while ($k != 0) { if ($k % 16 >= 10) $count++; $k = $k / 16; } } } return $count;} // Driver code$L = 5;$R = 100;echo countHexadecimal($L, $R); // This code is contributed by Ita_c?>", "e": 29453, "s": 28659, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that will count// total hexadecimal alphabetfunction countHexadecimal(L, R){ var count = 0; for (var i = L; i <= R; i++) { // All the numbers from 10 to 15 // contain a hexadecimal alphabet if (i >= 10 && i <= 15) count++; // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15) { var k = i; while (k != 0) { if (k % 16 >= 10) count++; k = k / 16; } } } return count;} // Driver codevar L = 5, R = 100;document.write( countHexadecimal(L, R)); // This code is contributed by rutvik_56.</script>", "e": 30254, "s": 29453, "text": null }, { "code": null, "e": 30257, "s": 30254, "text": "36" }, { "code": null, "e": 30267, "s": 30259, "text": "ankthon" }, { "code": null, "e": 30280, "s": 30267, "text": "Akanksha_Rai" }, { "code": null, "e": 30286, "s": 30280, "text": "ukasp" }, { "code": null, "e": 30296, "s": 30286, "text": "rutvik_56" }, { "code": null, "e": 30312, "s": 30296, "text": "base-conversion" }, { "code": null, "e": 30325, "s": 30312, "text": "C++ Programs" }, { "code": null, "e": 30344, "s": 30325, "text": "School Programming" }, { "code": null, "e": 30442, "s": 30344, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30451, "s": 30442, "text": "Comments" }, { "code": null, "e": 30464, "s": 30451, "text": "Old Comments" }, { "code": null, "e": 30505, "s": 30464, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 30564, "s": 30505, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 30576, "s": 30564, "text": "cout in C++" }, { "code": null, "e": 30597, "s": 30576, "text": "Const keyword in C++" }, { "code": null, "e": 30642, "s": 30597, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 30660, "s": 30642, "text": "Python Dictionary" }, { "code": null, "e": 30676, "s": 30660, "text": "Arrays in C/C++" }, { "code": null, "e": 30701, "s": 30676, "text": "Reverse a string in Java" }, { "code": null, "e": 30720, "s": 30701, "text": "Inheritance in C++" } ]
Laravel | Eloquent Model Basics - GeeksforGeeks
30 Dec, 2019 Laravel is an MVC based PHP framework. In MVC architecture, ‘M’ stands for ‘Model’. A Model is basically a way for querying data to and from the table in the database. Laravel provides a simple way to do that using Eloquent ORM (Object-Relational Mapping). Every table has a Model to interact with the table. Create a Model: To create an Eloquent Model, Laravel provides an Artisan Command as follows: php artisan make:model Article After running the command above, a file is created with the name Article.php in the app directory. The file content looks as follows: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { //} Retrieve Data: To retrieve data from the database, we can use two methods as described below: Here, the all() method will return all the data in the table in the form of an array and store it in the $articles variable.public function index() { $articles = \App\Article::all(); return view('gfg')->with('articles', $articles); } public function index() { $articles = \App\Article::all(); return view('gfg')->with('articles', $articles); } We can also get a particular record by using ‘where()’ as shown below:public function index() { $articles = \App\Article::all()->where('id', 1); return view('gfg')->with('articles', $articles); } public function index() { $articles = \App\Article::all()->where('id', 1); return view('gfg')->with('articles', $articles); } Insert Data: To insert data in the database, we will use save() method as shown below: Here, we create a new Article and store it in the $article variable. The topic and content attribute are used to store the data specified in the respective columns in the table. And then ‘save()’ method is used to insert the data in the database. Then a successful message will be shown if the insert is successful.public function insert() { $article = new Article; $article->topic = "View in Laravel"; $article->content = "View is the data display at the user end."; $article->save(); echo "Insert Successful!"; }Note: The created_at and updated_at field in the table will be automatically be inserted with the time stamp. public function insert() { $article = new Article; $article->topic = "View in Laravel"; $article->content = "View is the data display at the user end."; $article->save(); echo "Insert Successful!"; } Note: The created_at and updated_at field in the table will be automatically be inserted with the time stamp. Update Data: To update data in the database, we will again use save() method as shown below: Here, the find() method is used to specify the record that we want to update in the database. The number in the parenthesis is of id i.e. primary key. Now a new value is given to the topic field of the record which will change the old one. And then ‘save()’ method is used to insert the data in the database. Then a successful message will be shown if the update is successful.public function update() { $article = \App\Article::find(1); $article->topic = "Laravel"; $article->save(); echo "Update Successful!"; }Note: The updated_at field in the table will be automatically be inserted with the time stamp. public function update() { $article = \App\Article::find(1); $article->topic = "Laravel"; $article->save(); echo "Update Successful!"; } Note: The updated_at field in the table will be automatically be inserted with the time stamp. Delete Data: To delete data in the database, we will use delete() method as shown below: Here, the find() method is used to specify the record that we want to delete from the database. The number in the parenthesis is of id i.e. primary key. Then the delete() method is used. Then a successful message will be shown if the delete is successful.public function delete() { $article = \App\Article::find(1); $article->delete(); echo "Delete Successful!"; } public function delete() { $article = \App\Article::find(1); $article->delete(); echo "Delete Successful!"; } Below example illustrates each of them: Example: Create and Connect to a MySQL Database.Create a migration using the following Artisan command:php artisan make:migration create_articles_tableAnd then write the below code in the up() function in the migration file created at database/migrations directory.Schema::create('articles', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('topic'); $table->string('content'); $table->timestamps(); });Now run the migrate command to create migrations:php artisan migrateNow create a model using the below Artisan command:php artisan make:model ArticleThe Article.php file, which is created in the app directory, should look like as follows:<?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { //}Now create a controller using the below Artisan command:php artisan make:controller ArticleControllerThe ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows:<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ArticleController extends Controller { //}Now, you will have to change the controller file as below code or copy the code below and paste it in that controller file which was created in the previous step.<?php namespace App\Http\Controllers; use App\Article;use Illuminate\Http\Request; class ArticleController extends Controller { // Retrieve function public function index() { $articles = \App\Article::all(); return view('gfg')->with('articles', $articles); } // Insert function public function insert() { $article = new Article; $article->topic = "View in Laravel"; $article->content = "View is the data display at the user end."; $article->save(); echo "Insert Successful!"; } // Update function public function update() { $article = \App\Article::find(1); $article->topic = "Laravel"; $article->save(); echo "Update Successful!"; } // Delete function public function delete() { $article = \App\Article::find(1); $article->delete(); echo "Delete Successful!"; }}Now, create a view with the name ‘gfg.blade.php’ in the ‘resources/views’ directory and the below code in that file.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> body { font-size: 20px; } </style></head><body> <h2>Articles Topics</h2> <ol> @foreach($articles as $article) <li>{{ $article->topic }}</li> @endforeach </ol> </body></html>Now, create the routes by writing the following in the web.php file in the routes directory.Note: Comment or remove any previous routes from the file.Route::get('/', 'ArticleController@index'); Route::get('/insert', 'ArticleController@insert'); Route::get('/update', 'ArticleController@update'); Route::get('/delete', 'ArticleController@delete');Now run the Laravel app using the following Artisan command:php artisan serve Create and Connect to a MySQL Database. Create a migration using the following Artisan command:php artisan make:migration create_articles_tableAnd then write the below code in the up() function in the migration file created at database/migrations directory.Schema::create('articles', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('topic'); $table->string('content'); $table->timestamps(); }); php artisan make:migration create_articles_table And then write the below code in the up() function in the migration file created at database/migrations directory. Schema::create('articles', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('topic'); $table->string('content'); $table->timestamps(); }); Now run the migrate command to create migrations:php artisan migrate php artisan migrate Now create a model using the below Artisan command:php artisan make:model ArticleThe Article.php file, which is created in the app directory, should look like as follows:<?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { //} php artisan make:model Article The Article.php file, which is created in the app directory, should look like as follows: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { //} Now create a controller using the below Artisan command:php artisan make:controller ArticleControllerThe ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows:<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ArticleController extends Controller { //} php artisan make:controller ArticleController The ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ArticleController extends Controller { //} Now, you will have to change the controller file as below code or copy the code below and paste it in that controller file which was created in the previous step.<?php namespace App\Http\Controllers; use App\Article;use Illuminate\Http\Request; class ArticleController extends Controller { // Retrieve function public function index() { $articles = \App\Article::all(); return view('gfg')->with('articles', $articles); } // Insert function public function insert() { $article = new Article; $article->topic = "View in Laravel"; $article->content = "View is the data display at the user end."; $article->save(); echo "Insert Successful!"; } // Update function public function update() { $article = \App\Article::find(1); $article->topic = "Laravel"; $article->save(); echo "Update Successful!"; } // Delete function public function delete() { $article = \App\Article::find(1); $article->delete(); echo "Delete Successful!"; }} <?php namespace App\Http\Controllers; use App\Article;use Illuminate\Http\Request; class ArticleController extends Controller { // Retrieve function public function index() { $articles = \App\Article::all(); return view('gfg')->with('articles', $articles); } // Insert function public function insert() { $article = new Article; $article->topic = "View in Laravel"; $article->content = "View is the data display at the user end."; $article->save(); echo "Insert Successful!"; } // Update function public function update() { $article = \App\Article::find(1); $article->topic = "Laravel"; $article->save(); echo "Update Successful!"; } // Delete function public function delete() { $article = \App\Article::find(1); $article->delete(); echo "Delete Successful!"; }} Now, create a view with the name ‘gfg.blade.php’ in the ‘resources/views’ directory and the below code in that file.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> body { font-size: 20px; } </style></head><body> <h2>Articles Topics</h2> <ol> @foreach($articles as $article) <li>{{ $article->topic }}</li> @endforeach </ol> </body></html> <!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> body { font-size: 20px; } </style></head><body> <h2>Articles Topics</h2> <ol> @foreach($articles as $article) <li>{{ $article->topic }}</li> @endforeach </ol> </body></html> Now, create the routes by writing the following in the web.php file in the routes directory.Note: Comment or remove any previous routes from the file.Route::get('/', 'ArticleController@index'); Route::get('/insert', 'ArticleController@insert'); Route::get('/update', 'ArticleController@update'); Route::get('/delete', 'ArticleController@delete'); Note: Comment or remove any previous routes from the file. Route::get('/', 'ArticleController@index'); Route::get('/insert', 'ArticleController@insert'); Route::get('/update', 'ArticleController@update'); Route::get('/delete', 'ArticleController@delete'); Now run the Laravel app using the following Artisan command:php artisan serve php artisan serve Output: For Index Function:For Insert Function:For Update Function:For Delete Function: For Index Function: For Insert Function: For Update Function: For Delete Function: Reference: https://laravel.com/docs/6.x/eloquent Laravel PHP Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to receive JSON POST with PHP ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23937, "s": 23909, "text": "\n30 Dec, 2019" }, { "code": null, "e": 24246, "s": 23937, "text": "Laravel is an MVC based PHP framework. In MVC architecture, ‘M’ stands for ‘Model’. A Model is basically a way for querying data to and from the table in the database. Laravel provides a simple way to do that using Eloquent ORM (Object-Relational Mapping). Every table has a Model to interact with the table." }, { "code": null, "e": 24339, "s": 24246, "text": "Create a Model: To create an Eloquent Model, Laravel provides an Artisan Command as follows:" }, { "code": null, "e": 24370, "s": 24339, "text": "php artisan make:model Article" }, { "code": null, "e": 24504, "s": 24370, "text": "After running the command above, a file is created with the name Article.php in the app directory. The file content looks as follows:" }, { "code": "<?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class Article extends Model { //}", "e": 24603, "s": 24504, "text": null }, { "code": null, "e": 24697, "s": 24603, "text": "Retrieve Data: To retrieve data from the database, we can use two methods as described below:" }, { "code": null, "e": 24958, "s": 24697, "text": "Here, the all() method will return all the data in the table in the form of an array and store it in the $articles variable.public function index() {\n \n $articles = \\App\\Article::all();\n\n return view('gfg')->with('articles', $articles);\n\n}" }, { "code": null, "e": 25095, "s": 24958, "text": "public function index() {\n \n $articles = \\App\\Article::all();\n\n return view('gfg')->with('articles', $articles);\n\n}" }, { "code": null, "e": 25318, "s": 25095, "text": "We can also get a particular record by using ‘where()’ as shown below:public function index() {\n \n $articles = \\App\\Article::all()->where('id', 1);\n\n return view('gfg')->with('articles', $articles);\n\n}" }, { "code": null, "e": 25471, "s": 25318, "text": "public function index() {\n \n $articles = \\App\\Article::all()->where('id', 1);\n\n return view('gfg')->with('articles', $articles);\n\n}" }, { "code": null, "e": 25558, "s": 25471, "text": "Insert Data: To insert data in the database, we will use save() method as shown below:" }, { "code": null, "e": 26207, "s": 25558, "text": "Here, we create a new Article and store it in the $article variable. The topic and content attribute are used to store the data specified in the respective columns in the table. And then ‘save()’ method is used to insert the data in the database. Then a successful message will be shown if the insert is successful.public function insert() {\n\n $article = new Article;\n\n $article->topic = \"View in Laravel\";\n $article->content = \"View is the data display at the user end.\";\n\n $article->save();\n\n echo \"Insert Successful!\";\n\n}Note: The created_at and updated_at field in the table will be automatically be inserted with the time stamp." }, { "code": null, "e": 26432, "s": 26207, "text": "public function insert() {\n\n $article = new Article;\n\n $article->topic = \"View in Laravel\";\n $article->content = \"View is the data display at the user end.\";\n\n $article->save();\n\n echo \"Insert Successful!\";\n\n}" }, { "code": null, "e": 26542, "s": 26432, "text": "Note: The created_at and updated_at field in the table will be automatically be inserted with the time stamp." }, { "code": null, "e": 26635, "s": 26542, "text": "Update Data: To update data in the database, we will again use save() method as shown below:" }, { "code": null, "e": 27280, "s": 26635, "text": "Here, the find() method is used to specify the record that we want to update in the database. The number in the parenthesis is of id i.e. primary key. Now a new value is given to the topic field of the record which will change the old one. And then ‘save()’ method is used to insert the data in the database. Then a successful message will be shown if the update is successful.public function update() {\n\n $article = \\App\\Article::find(1);\n\n $article->topic = \"Laravel\";\n\n $article->save();\n\n echo \"Update Successful!\";\n\n}Note: The updated_at field in the table will be automatically be inserted with the time stamp." }, { "code": null, "e": 27454, "s": 27280, "text": "public function update() {\n\n $article = \\App\\Article::find(1);\n\n $article->topic = \"Laravel\";\n\n $article->save();\n\n echo \"Update Successful!\";\n\n}" }, { "code": null, "e": 27549, "s": 27454, "text": "Note: The updated_at field in the table will be automatically be inserted with the time stamp." }, { "code": null, "e": 27638, "s": 27549, "text": "Delete Data: To delete data in the database, we will use delete() method as shown below:" }, { "code": null, "e": 28031, "s": 27638, "text": "Here, the find() method is used to specify the record that we want to delete from the database. The number in the parenthesis is of id i.e. primary key. Then the delete() method is used. Then a successful message will be shown if the delete is successful.public function delete() {\n\n $article = \\App\\Article::find(1);\n\n $article->delete();\n\n echo \"Delete Successful!\";\n\n}" }, { "code": null, "e": 28169, "s": 28031, "text": "public function delete() {\n\n $article = \\App\\Article::find(1);\n\n $article->delete();\n\n echo \"Delete Successful!\";\n\n}" }, { "code": null, "e": 28209, "s": 28169, "text": "Below example illustrates each of them:" }, { "code": null, "e": 28218, "s": 28209, "text": "Example:" }, { "code": null, "e": 31281, "s": 28218, "text": "Create and Connect to a MySQL Database.Create a migration using the following Artisan command:php artisan make:migration create_articles_tableAnd then write the below code in the up() function in the migration file created at database/migrations directory.Schema::create('articles', function (Blueprint $table) {\n $table->bigIncrements('id');\n $table->string('topic');\n $table->string('content');\n $table->timestamps();\n});Now run the migrate command to create migrations:php artisan migrateNow create a model using the below Artisan command:php artisan make:model ArticleThe Article.php file, which is created in the app directory, should look like as follows:<?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class Article extends Model { //}Now create a controller using the below Artisan command:php artisan make:controller ArticleControllerThe ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows:<?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; class ArticleController extends Controller { //}Now, you will have to change the controller file as below code or copy the code below and paste it in that controller file which was created in the previous step.<?php namespace App\\Http\\Controllers; use App\\Article;use Illuminate\\Http\\Request; class ArticleController extends Controller { // Retrieve function public function index() { $articles = \\App\\Article::all(); return view('gfg')->with('articles', $articles); } // Insert function public function insert() { $article = new Article; $article->topic = \"View in Laravel\"; $article->content = \"View is the data display at the user end.\"; $article->save(); echo \"Insert Successful!\"; } // Update function public function update() { $article = \\App\\Article::find(1); $article->topic = \"Laravel\"; $article->save(); echo \"Update Successful!\"; } // Delete function public function delete() { $article = \\App\\Article::find(1); $article->delete(); echo \"Delete Successful!\"; }}Now, create a view with the name ‘gfg.blade.php’ in the ‘resources/views’ directory and the below code in that file.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> body { font-size: 20px; } </style></head><body> <h2>Articles Topics</h2> <ol> @foreach($articles as $article) <li>{{ $article->topic }}</li> @endforeach </ol> </body></html>Now, create the routes by writing the following in the web.php file in the routes directory.Note: Comment or remove any previous routes from the file.Route::get('/', 'ArticleController@index');\n\nRoute::get('/insert', 'ArticleController@insert');\n\nRoute::get('/update', 'ArticleController@update');\n\nRoute::get('/delete', 'ArticleController@delete');Now run the Laravel app using the following Artisan command:php artisan serve" }, { "code": null, "e": 31321, "s": 31281, "text": "Create and Connect to a MySQL Database." }, { "code": null, "e": 31718, "s": 31321, "text": "Create a migration using the following Artisan command:php artisan make:migration create_articles_tableAnd then write the below code in the up() function in the migration file created at database/migrations directory.Schema::create('articles', function (Blueprint $table) {\n $table->bigIncrements('id');\n $table->string('topic');\n $table->string('content');\n $table->timestamps();\n});" }, { "code": null, "e": 31767, "s": 31718, "text": "php artisan make:migration create_articles_table" }, { "code": null, "e": 31882, "s": 31767, "text": "And then write the below code in the up() function in the migration file created at database/migrations directory." }, { "code": null, "e": 32062, "s": 31882, "text": "Schema::create('articles', function (Blueprint $table) {\n $table->bigIncrements('id');\n $table->string('topic');\n $table->string('content');\n $table->timestamps();\n});" }, { "code": null, "e": 32131, "s": 32062, "text": "Now run the migrate command to create migrations:php artisan migrate" }, { "code": null, "e": 32151, "s": 32131, "text": "php artisan migrate" }, { "code": null, "e": 32422, "s": 32151, "text": "Now create a model using the below Artisan command:php artisan make:model ArticleThe Article.php file, which is created in the app directory, should look like as follows:<?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class Article extends Model { //}" }, { "code": null, "e": 32453, "s": 32422, "text": "php artisan make:model Article" }, { "code": null, "e": 32543, "s": 32453, "text": "The Article.php file, which is created in the app directory, should look like as follows:" }, { "code": "<?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class Article extends Model { //}", "e": 32644, "s": 32543, "text": null }, { "code": null, "e": 32983, "s": 32644, "text": "Now create a controller using the below Artisan command:php artisan make:controller ArticleControllerThe ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows:<?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; class ArticleController extends Controller { //}" }, { "code": null, "e": 33029, "s": 32983, "text": "php artisan make:controller ArticleController" }, { "code": null, "e": 33146, "s": 33029, "text": "The ArticleController.php file, which is created in the app/Http/Controllers directory, should look like as follows:" }, { "code": "<?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; class ArticleController extends Controller { //}", "e": 33268, "s": 33146, "text": null }, { "code": null, "e": 34369, "s": 33268, "text": "Now, you will have to change the controller file as below code or copy the code below and paste it in that controller file which was created in the previous step.<?php namespace App\\Http\\Controllers; use App\\Article;use Illuminate\\Http\\Request; class ArticleController extends Controller { // Retrieve function public function index() { $articles = \\App\\Article::all(); return view('gfg')->with('articles', $articles); } // Insert function public function insert() { $article = new Article; $article->topic = \"View in Laravel\"; $article->content = \"View is the data display at the user end.\"; $article->save(); echo \"Insert Successful!\"; } // Update function public function update() { $article = \\App\\Article::find(1); $article->topic = \"Laravel\"; $article->save(); echo \"Update Successful!\"; } // Delete function public function delete() { $article = \\App\\Article::find(1); $article->delete(); echo \"Delete Successful!\"; }}" }, { "code": "<?php namespace App\\Http\\Controllers; use App\\Article;use Illuminate\\Http\\Request; class ArticleController extends Controller { // Retrieve function public function index() { $articles = \\App\\Article::all(); return view('gfg')->with('articles', $articles); } // Insert function public function insert() { $article = new Article; $article->topic = \"View in Laravel\"; $article->content = \"View is the data display at the user end.\"; $article->save(); echo \"Insert Successful!\"; } // Update function public function update() { $article = \\App\\Article::find(1); $article->topic = \"Laravel\"; $article->save(); echo \"Update Successful!\"; } // Delete function public function delete() { $article = \\App\\Article::find(1); $article->delete(); echo \"Delete Successful!\"; }}", "e": 35308, "s": 34369, "text": null }, { "code": null, "e": 35734, "s": 35308, "text": "Now, create a view with the name ‘gfg.blade.php’ in the ‘resources/views’ directory and the below code in that file.<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> body { font-size: 20px; } </style></head><body> <h2>Articles Topics</h2> <ol> @foreach($articles as $article) <li>{{ $article->topic }}</li> @endforeach </ol> </body></html>" }, { "code": "<!DOCTYPE html><html><head> <title>GeeksforGeeks</title> <style> body { font-size: 20px; } </style></head><body> <h2>Articles Topics</h2> <ol> @foreach($articles as $article) <li>{{ $article->topic }}</li> @endforeach </ol> </body></html>", "e": 36044, "s": 35734, "text": null }, { "code": null, "e": 36394, "s": 36044, "text": "Now, create the routes by writing the following in the web.php file in the routes directory.Note: Comment or remove any previous routes from the file.Route::get('/', 'ArticleController@index');\n\nRoute::get('/insert', 'ArticleController@insert');\n\nRoute::get('/update', 'ArticleController@update');\n\nRoute::get('/delete', 'ArticleController@delete');" }, { "code": null, "e": 36453, "s": 36394, "text": "Note: Comment or remove any previous routes from the file." }, { "code": null, "e": 36653, "s": 36453, "text": "Route::get('/', 'ArticleController@index');\n\nRoute::get('/insert', 'ArticleController@insert');\n\nRoute::get('/update', 'ArticleController@update');\n\nRoute::get('/delete', 'ArticleController@delete');" }, { "code": null, "e": 36731, "s": 36653, "text": "Now run the Laravel app using the following Artisan command:php artisan serve" }, { "code": null, "e": 36749, "s": 36731, "text": "php artisan serve" }, { "code": null, "e": 36757, "s": 36749, "text": "Output:" }, { "code": null, "e": 36837, "s": 36757, "text": "For Index Function:For Insert Function:For Update Function:For Delete Function:" }, { "code": null, "e": 36857, "s": 36837, "text": "For Index Function:" }, { "code": null, "e": 36878, "s": 36857, "text": "For Insert Function:" }, { "code": null, "e": 36899, "s": 36878, "text": "For Update Function:" }, { "code": null, "e": 36920, "s": 36899, "text": "For Delete Function:" }, { "code": null, "e": 36969, "s": 36920, "text": "Reference: https://laravel.com/docs/6.x/eloquent" }, { "code": null, "e": 36977, "s": 36969, "text": "Laravel" }, { "code": null, "e": 36981, "s": 36977, "text": "PHP" }, { "code": null, "e": 37000, "s": 36981, "text": "Technical Scripter" }, { "code": null, "e": 37017, "s": 37000, "text": "Web Technologies" }, { "code": null, "e": 37021, "s": 37017, "text": "PHP" }, { "code": null, "e": 37119, "s": 37021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37128, "s": 37119, "text": "Comments" }, { "code": null, "e": 37141, "s": 37128, "text": "Old Comments" }, { "code": null, "e": 37191, "s": 37141, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 37231, "s": 37191, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 37292, "s": 37231, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 37342, "s": 37292, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 37378, "s": 37342, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 37434, "s": 37378, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 37467, "s": 37434, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37529, "s": 37467, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37572, "s": 37529, "text": "How to fetch data from an API in ReactJS ?" } ]
TypeScript - For Loop
The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as below − for (initial_count_value; termination-condition; step) { //statements } The loop uses a count variable to keep track of the iterations. The loop initializes the iteration by setting the value of count to its initial value. It executes the code block, each time the value of count satisfies the termination_condtion. The step changes the value of count after every iteration. var num:number = 5; var i:number; var factorial = 1; for(i = num;i>=1;i--) { factorial *= i; } console.log(factorial) The program calculates the factorial of the number 5 and displays the same. The for loop generates the sequence of numbers from 5 to 1, calculating the product of the numbers in every iteration. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var num = 5; var factorial = 1; while (num >= 1) { factorial = factorial * num; num--; } console.log("The factorial is " + factorial); The code produces the following output − 120 Another variation of the for loop is the for... in loop. The for... in loop can be used to iterate over a set of values as in the case of an array or a tuple. The syntax for the same is given below − The for...in loop is used to iterate through a list or collection of values. The data type of val here should be string or any. The syntax of the for..in loop is as given below − for (var val in list) { //statements } Let’s take a look at the following example − var j:any; var n:any = "a b c" for(j in n) { console.log(n[j]) } On compiling, it will generate the following JavaScript code − //Generated by typescript 1.8.10 var j; var n = "a b c"; for (j in n) { console.log(n[j]); } It will produce the following output − a b c 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2231, "s": 2048, "text": "The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as below −" }, { "code": null, "e": 2308, "s": 2231, "text": "for (initial_count_value; termination-condition; step) {\n //statements \n}\n" }, { "code": null, "e": 2611, "s": 2308, "text": "The loop uses a count variable to keep track of the iterations. The loop initializes the iteration by setting the value of count to its initial value. It executes the code block, each time the value of count satisfies the termination_condtion. The step changes the value of count after every iteration." }, { "code": null, "e": 2737, "s": 2611, "text": "var num:number = 5; \nvar i:number; \nvar factorial = 1; \n\nfor(i = num;i>=1;i--) {\n factorial *= i;\n}\nconsole.log(factorial)\n" }, { "code": null, "e": 2932, "s": 2737, "text": "The program calculates the factorial of the number 5 and displays the same. The for loop generates the sequence of numbers from 5 to 1, calculating the product of the numbers in every iteration." }, { "code": null, "e": 2990, "s": 2932, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 3174, "s": 2990, "text": "//Generated by typescript 1.8.10 \nvar num = 5; \nvar factorial = 1; \nwhile (num >= 1) { \n factorial = factorial * num; \n num--; \n} \nconsole.log(\"The factorial is \" + factorial); \n" }, { "code": null, "e": 3215, "s": 3174, "text": "The code produces the following output −" }, { "code": null, "e": 3220, "s": 3215, "text": "120\n" }, { "code": null, "e": 3420, "s": 3220, "text": "Another variation of the for loop is the for... in loop. The for... in loop can be used to iterate over a set of values as in the case of an array or a tuple. The syntax for the same is given below −" }, { "code": null, "e": 3599, "s": 3420, "text": "The for...in loop is used to iterate through a list or collection of values. The data type of val here should be string or any. The syntax of the for..in loop is as given below −" }, { "code": null, "e": 3644, "s": 3599, "text": "for (var val in list) { \n //statements \n}\n" }, { "code": null, "e": 3689, "s": 3644, "text": "Let’s take a look at the following example −" }, { "code": null, "e": 3763, "s": 3689, "text": "var j:any; \nvar n:any = \"a b c\" \n\nfor(j in n) {\n console.log(n[j]) \n}\n" }, { "code": null, "e": 3826, "s": 3763, "text": "On compiling, it will generate the following JavaScript code −" }, { "code": null, "e": 3924, "s": 3826, "text": "//Generated by typescript 1.8.10\nvar j;\nvar n = \"a b c\";\n\nfor (j in n) {\n console.log(n[j]);\n}\n" }, { "code": null, "e": 3963, "s": 3924, "text": "It will produce the following output −" }, { "code": null, "e": 3972, "s": 3963, "text": "a \nb \nc\n" }, { "code": null, "e": 4005, "s": 3972, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 4019, "s": 4005, "text": " Antonio Papa" }, { "code": null, "e": 4052, "s": 4019, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 4066, "s": 4052, "text": " Haider Malik" }, { "code": null, "e": 4101, "s": 4066, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4121, "s": 4101, "text": " Skillbakerystudios" }, { "code": null, "e": 4154, "s": 4121, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 4168, "s": 4154, "text": " Sean Bradley" }, { "code": null, "e": 4203, "s": 4168, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4219, "s": 4203, "text": " TELCOMA Global" }, { "code": null, "e": 4252, "s": 4219, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 4272, "s": 4252, "text": " Christopher Frewin" }, { "code": null, "e": 4279, "s": 4272, "text": " Print" }, { "code": null, "e": 4290, "s": 4279, "text": " Add Notes" } ]
Amazon Interview Experience for SDE-1 (Off-Campus) - GeeksforGeeks
17 Oct, 2021 Round 1: Online Assessment Amazon Fresh Deliveries: Given all Locations list of co-ordinates (x,y) you have to find the X – closest locations from truck’s location which is (0,0). Distance is calculated using the formula (x^2 + y^2). If there is a tie then choose the co-ordinate with the least x value. Sample Input : All Locations : [ [1, 2] , [1, -1], [3, 4] ] numOfDeliveries : 2 Sample Output : [ [1, -1], [1 , 2] ] The output list can be in any order. This question was basically K closest points to the origin (0,0) with added tie condition. Demolition Robot: Given a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1. The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix. Sample Input : [1, 0, 0], [1, 0, 0], [1, 9, 1]] Sample Output : 3 This question can be solved by using BFS or DFS. Round 2: Interviews Generate the sequence of N magic numbers. A magic number is Consists of digits 4 and 5 Must be an even palindrome Expression evaluation (using stacks). The expression may contain parenthesis or not . Round 3: Difference between linear and non linear data structure. Internal working of the map, including its implementation. First non repeating character in a stream of data in O(1) time complexity. Creation of a binary tree. Round 4: Technical Interview Variation of word-ladder problem. Tips: You must know how to calculate time and space complexities. In each round they ask you about the project you recently did/ the project you liked working on most/ most challenging work etc- so you should be prepared well for at least one project with in-depth details. Start with the naive approach for each question asked and then proceed with solutions with better space and time complexities. Behavioral questions were also asked in each round – Some questions asked were : Out of amazon leadership principles ,which one you identify yourself with and why ? Give real-life example. Was there any situation in which you went out of your designated responsibilities? All the best ! Amazon Marketing Off-Campus Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE-1 Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Oracle Interview Experience | Set 69 (Application Engineer) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 24807, "s": 24779, "text": "\n17 Oct, 2021" }, { "code": null, "e": 24834, "s": 24807, "text": "Round 1: Online Assessment" }, { "code": null, "e": 25126, "s": 24834, "text": "Amazon Fresh Deliveries: Given all Locations list of co-ordinates (x,y) you have to find the X – closest locations from truck’s location which is (0,0). Distance is calculated using the formula (x^2 + y^2). If there is a tie then choose the co-ordinate with the least x value. Sample Input :" }, { "code": null, "e": 25228, "s": 25126, "text": "All Locations : [ [1, 2] , [1, -1], [3, 4] ]\nnumOfDeliveries : 2\nSample Output :\n[ [1, -1], [1 , 2] ]" }, { "code": null, "e": 25356, "s": 25228, "text": "The output list can be in any order. This question was basically K closest points to the origin (0,0) with added tie condition." }, { "code": null, "e": 25535, "s": 25356, "text": "Demolition Robot: Given a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1." }, { "code": null, "e": 25749, "s": 25535, "text": "The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix." }, { "code": null, "e": 25815, "s": 25749, "text": "Sample Input :\n[1, 0, 0],\n[1, 0, 0],\n[1, 9, 1]]\nSample Output :\n3" }, { "code": null, "e": 25864, "s": 25815, "text": "This question can be solved by using BFS or DFS." }, { "code": null, "e": 25884, "s": 25864, "text": "Round 2: Interviews" }, { "code": null, "e": 25945, "s": 25884, "text": "Generate the sequence of N magic numbers. A magic number is " }, { "code": null, "e": 25972, "s": 25945, "text": "Consists of digits 4 and 5" }, { "code": null, "e": 25999, "s": 25972, "text": "Must be an even palindrome" }, { "code": null, "e": 26085, "s": 25999, "text": "Expression evaluation (using stacks). The expression may contain parenthesis or not ." }, { "code": null, "e": 26095, "s": 26085, "text": "Round 3: " }, { "code": null, "e": 26152, "s": 26095, "text": "Difference between linear and non linear data structure." }, { "code": null, "e": 26211, "s": 26152, "text": "Internal working of the map, including its implementation." }, { "code": null, "e": 26286, "s": 26211, "text": "First non repeating character in a stream of data in O(1) time complexity." }, { "code": null, "e": 26313, "s": 26286, "text": "Creation of a binary tree." }, { "code": null, "e": 26342, "s": 26313, "text": "Round 4: Technical Interview" }, { "code": null, "e": 26376, "s": 26342, "text": "Variation of word-ladder problem." }, { "code": null, "e": 26383, "s": 26376, "text": "Tips: " }, { "code": null, "e": 26443, "s": 26383, "text": "You must know how to calculate time and space complexities." }, { "code": null, "e": 26651, "s": 26443, "text": "In each round they ask you about the project you recently did/ the project you liked working on most/ most challenging work etc- so you should be prepared well for at least one project with in-depth details." }, { "code": null, "e": 26778, "s": 26651, "text": "Start with the naive approach for each question asked and then proceed with solutions with better space and time complexities." }, { "code": null, "e": 26859, "s": 26778, "text": "Behavioral questions were also asked in each round – Some questions asked were :" }, { "code": null, "e": 26967, "s": 26859, "text": "Out of amazon leadership principles ,which one you identify yourself with and why ? Give real-life example." }, { "code": null, "e": 27050, "s": 26967, "text": "Was there any situation in which you went out of your designated responsibilities?" }, { "code": null, "e": 27065, "s": 27050, "text": "All the best !" }, { "code": null, "e": 27072, "s": 27065, "text": "Amazon" }, { "code": null, "e": 27082, "s": 27072, "text": "Marketing" }, { "code": null, "e": 27093, "s": 27082, "text": "Off-Campus" }, { "code": null, "e": 27115, "s": 27093, "text": "Interview Experiences" }, { "code": null, "e": 27122, "s": 27115, "text": "Amazon" }, { "code": null, "e": 27220, "s": 27122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27229, "s": 27220, "text": "Comments" }, { "code": null, "e": 27242, "s": 27229, "text": "Old Comments" }, { "code": null, "e": 27301, "s": 27242, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27351, "s": 27301, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 27389, "s": 27351, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 27461, "s": 27389, "text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022" }, { "code": null, "e": 27526, "s": 27461, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 27576, "s": 27526, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 27622, "s": 27576, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 27682, "s": 27622, "text": "Oracle Interview Experience | Set 69 (Application Engineer)" }, { "code": null, "e": 27720, "s": 27682, "text": "Amazon Interview Experience for SDE-1" } ]
How to Get a Job with Python. It is a simple use of Python, you do... | by Lazar Gugleta | Towards Data Science
There are so many websites out there offering job listings for different fields of jobs. Even though you might be at a certain position you should always look for a job and that can get boring. But here comes a simple solution in order to get through so many of those job offers with ease! We are going to build an easy Python script to get job listings and filter them to your likings. It is a simple use of Python and you do not need any specific skills to do this with me. We will go step by step and build everything together. Let’s just jump right into it! First, we have to find the job listing website that we are going to get the offers from. I choose a website called Indeed. (It is just an example for this tutorial, but If you have a website you prefer to use for job hunting, please feel free to do so!) Here is what we are going to do: Filter the criteria of jobs that fit us and perform scraping on those. Here is what Indeed’s website looks like after I search for Data Science in United States. In the end, once we have our data, we are going to pack it into DataFrames and get a CSV file, which can be opened easily with Excel or Libre Office. You are going to have to install a ChromeDriver and use it with Selenium, which is going to enable us to manipulate the browser and send commands to it for testing and after for use. Open the link and download the file for your operating system. I recommend the latest stable release unless you know what you are doing already. Next up, you need to unzip that file. I would recommend going into Files and doing it manually by right-clicking and then “Extract here”. Inside the folder, there is a file called “chromedriver”, which we have to move to a specific folder on your computer. Open the terminal and type these commands: sudo su #enter the root modecd #go back to base from the current locationmv /home/*your_pc_name*/Downloads/chromedriver /usr/local/bin #move the file to the right location Just instead of *your_pc_name* insert your actual name of the computer. There are a few more libraries needed for this to work: In that terminal you should install these: pip3 install pandas Pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool, built on top of the Python programming language. sudo pip3 install beautifulsoup4 Beautiful Soup is a Python library for getting data out of HTML, XML, and other markup languages. Once we are done with that, we open the editor. My personal choice is Visual Studio Code. It is straightforward to use, customizable, and light for your computer. Open a new Project where ever you like and create two new files. This is an example of how mine looks like to help you: In the VS Code, there is a “Terminal” tab with which you can open an internal terminal inside the VS Code, which is very useful to have everything in one place. When you have that open, there is few more thing we need to install and that is the virtual environment and selenium for web driver. Type these commands into your terminal. pip3 install virtualenvsource venv/bin/activatepip3 install selenium After activating the virtual environment, we are completely ready to go. We have everything set up and now we are going to code! First, as mentioned before, we have to import installed libraries. from selenium import webdriverimport pandas as pdfrom bs4 import BeautifulSoupfrom time import sleep Create your tool with any name and start the driver for Chrome. class FindJob(): def __init__(self): self.driver = webdriver.Chrome() That is all we need to start developing. Now go to your terminal and type: python -i findJob.py This command lets us our file as an interactive playground. The new tab of the browser will be opened and we can start issuing commands to it.If you want to experiment you can use the command line instead of just typing it directly to your source file. Just instead of self use bot. For Terminal: bot = FindJob() bot.driver.get('https://www.indeed.com/jobs?q=data+science&l=United+States&start=') And now for the source code: self.driver.get('https://www.indeed.com/jobs?q=data+science&l=United+States&start=') Creating the DataFrame we are going to be using is easy, so let’s begin there! For this data frame, we need to have “Title”, “Location”, “Company”, “Salary”, “Description” all related to the jobs we are going to scrape. dataframe = pd.DataFrame( columns=["Title", "Location", "Company", "Salary", "Description"]) We will use this DataFrame as a Column names for our CSV file. The thing with this website is that on every page there are 10 job offers and the link changes as you go to the next page. Once I have figured that out, I made a for loop that checks every page and after it is done it goes to the next one. Here is what that looks like: for cnt in range(0, 50, 10): self.driver.get("https://www.indeed.com/jobs?q=data+science&l=United+States&start=" + str(cnt)) I set up a counter variable ‘cnt’ and add that number, converted to string to my link. The for loop specifically begins with 0 goes up to 50 and does it in iterations of 10 because that is how many jobs per page Indeed shows us. When we get to the first page, we need to scrape the table of offers one by one and we are going to do it this way: In the image above, where you see offers, they are packed in a table and we can find that table by pressing F12 on keyboard or right-click -> Inspect. Here is what that looks like: We will find the table by the class name and we enter this line: jobs = self.driver.find_elements_by_class_name('result') That saves all Web elements that it has found by the class name result. Once we have those saved we can create another for loop and go through every element inside that table and use that data we found inside. Before I show you more code on scraping those offers, we should go through a couple of things. For this part, we are going to use BeautifulSoup since I find it to work way faster. We have to set up a few things for BeatifulSoup, and those are the actual data that we give it to perform its search on and parser that we say it should use: result = job.get_attribute('innerHTML')soup = BeautifulSoup(result, 'html.parser') Once we get those, we just have to find elements inside the ‘soup’ defined variable, which is just a prepared data by BeautifulSoup. We get the data for the DataFrame that we want: title = soup.find("a", class_="jobtitle").text.replace('\n', '')location = soup.find(class_="location").textemployer = soup.find(class_="company").text.replace('\n', '').strip()try: salary = soup.find(class_="salary").text.replace( '\n', '').strip()except: salary = 'None' I did a salary part in such a manner because sometimes it is not defined and we have to set None or empty for that particular cell. Since I am working in the terminal for testing my code, you can also print what you found so far: print(title, location, employer, salary) Once this script is done, it will look like this: The last thing missing for the DataFrame is the Description of the job and left this out because, in order to get the text for the job description, you have to click the job offer first. I do it this way: summ = job.find_elements_by_class_name("summary")[0]summ.click()job_desc = self.driver.find_element_by_id('vjs-desc').text After we got all elements that should go into the DataFrame, we fill it: dataframe = dataframe.append( {'Title': title, 'Location': location, 'Employer': employer, 'Description': job_desc}, ignore_index=True) One more thing that I have to mention before you start testing this for yourself. Once you go to the second page of the website, there is a popup that blocks you from clicking further on anything! I also thought of that and created a try-expect, which will close the popup and continue scraping data! pop_up = self.driver.find_element_by_xpath('/html/body/table[2]/tbody/tr/td/div[2]/div[2]/div[4]/div[3]/div[2]/a')pop_up.click() Once the for loop finishes, we copy the data frame data to CSV called ‘jobs’: dataframe.to_csv("jobs.csv", index=False) We are done! The complete code is under here on my GitHub account: github.com You can take this script to another level by implementing a comparison between different websites and get the best offers on the internet overall. Until then, follow me for more! 😎 Thanks for reading!
[ { "code": null, "e": 462, "s": 172, "text": "There are so many websites out there offering job listings for different fields of jobs. Even though you might be at a certain position you should always look for a job and that can get boring. But here comes a simple solution in order to get through so many of those job offers with ease!" }, { "code": null, "e": 559, "s": 462, "text": "We are going to build an easy Python script to get job listings and filter them to your likings." }, { "code": null, "e": 703, "s": 559, "text": "It is a simple use of Python and you do not need any specific skills to do this with me. We will go step by step and build everything together." }, { "code": null, "e": 734, "s": 703, "text": "Let’s just jump right into it!" }, { "code": null, "e": 823, "s": 734, "text": "First, we have to find the job listing website that we are going to get the offers from." }, { "code": null, "e": 988, "s": 823, "text": "I choose a website called Indeed. (It is just an example for this tutorial, but If you have a website you prefer to use for job hunting, please feel free to do so!)" }, { "code": null, "e": 1021, "s": 988, "text": "Here is what we are going to do:" }, { "code": null, "e": 1092, "s": 1021, "text": "Filter the criteria of jobs that fit us and perform scraping on those." }, { "code": null, "e": 1183, "s": 1092, "text": "Here is what Indeed’s website looks like after I search for Data Science in United States." }, { "code": null, "e": 1333, "s": 1183, "text": "In the end, once we have our data, we are going to pack it into DataFrames and get a CSV file, which can be opened easily with Excel or Libre Office." }, { "code": null, "e": 1516, "s": 1333, "text": "You are going to have to install a ChromeDriver and use it with Selenium, which is going to enable us to manipulate the browser and send commands to it for testing and after for use." }, { "code": null, "e": 1661, "s": 1516, "text": "Open the link and download the file for your operating system. I recommend the latest stable release unless you know what you are doing already." }, { "code": null, "e": 1799, "s": 1661, "text": "Next up, you need to unzip that file. I would recommend going into Files and doing it manually by right-clicking and then “Extract here”." }, { "code": null, "e": 1918, "s": 1799, "text": "Inside the folder, there is a file called “chromedriver”, which we have to move to a specific folder on your computer." }, { "code": null, "e": 1961, "s": 1918, "text": "Open the terminal and type these commands:" }, { "code": null, "e": 2138, "s": 1961, "text": "sudo su #enter the root modecd #go back to base from the current locationmv /home/*your_pc_name*/Downloads/chromedriver /usr/local/bin #move the file to the right location" }, { "code": null, "e": 2210, "s": 2138, "text": "Just instead of *your_pc_name* insert your actual name of the computer." }, { "code": null, "e": 2266, "s": 2210, "text": "There are a few more libraries needed for this to work:" }, { "code": null, "e": 2309, "s": 2266, "text": "In that terminal you should install these:" }, { "code": null, "e": 2329, "s": 2309, "text": "pip3 install pandas" }, { "code": null, "e": 2481, "s": 2329, "text": "Pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool, built on top of the Python programming language." }, { "code": null, "e": 2514, "s": 2481, "text": "sudo pip3 install beautifulsoup4" }, { "code": null, "e": 2612, "s": 2514, "text": "Beautiful Soup is a Python library for getting data out of HTML, XML, and other markup languages." }, { "code": null, "e": 2775, "s": 2612, "text": "Once we are done with that, we open the editor. My personal choice is Visual Studio Code. It is straightforward to use, customizable, and light for your computer." }, { "code": null, "e": 2895, "s": 2775, "text": "Open a new Project where ever you like and create two new files. This is an example of how mine looks like to help you:" }, { "code": null, "e": 3056, "s": 2895, "text": "In the VS Code, there is a “Terminal” tab with which you can open an internal terminal inside the VS Code, which is very useful to have everything in one place." }, { "code": null, "e": 3229, "s": 3056, "text": "When you have that open, there is few more thing we need to install and that is the virtual environment and selenium for web driver. Type these commands into your terminal." }, { "code": null, "e": 3298, "s": 3229, "text": "pip3 install virtualenvsource venv/bin/activatepip3 install selenium" }, { "code": null, "e": 3371, "s": 3298, "text": "After activating the virtual environment, we are completely ready to go." }, { "code": null, "e": 3427, "s": 3371, "text": "We have everything set up and now we are going to code!" }, { "code": null, "e": 3494, "s": 3427, "text": "First, as mentioned before, we have to import installed libraries." }, { "code": null, "e": 3595, "s": 3494, "text": "from selenium import webdriverimport pandas as pdfrom bs4 import BeautifulSoupfrom time import sleep" }, { "code": null, "e": 3659, "s": 3595, "text": "Create your tool with any name and start the driver for Chrome." }, { "code": null, "e": 3733, "s": 3659, "text": "class FindJob(): def __init__(self): self.driver = webdriver.Chrome()" }, { "code": null, "e": 3808, "s": 3733, "text": "That is all we need to start developing. Now go to your terminal and type:" }, { "code": null, "e": 3829, "s": 3808, "text": "python -i findJob.py" }, { "code": null, "e": 4112, "s": 3829, "text": "This command lets us our file as an interactive playground. The new tab of the browser will be opened and we can start issuing commands to it.If you want to experiment you can use the command line instead of just typing it directly to your source file. Just instead of self use bot." }, { "code": null, "e": 4126, "s": 4112, "text": "For Terminal:" }, { "code": null, "e": 4227, "s": 4126, "text": "bot = FindJob() bot.driver.get('https://www.indeed.com/jobs?q=data+science&l=United+States&start=')" }, { "code": null, "e": 4256, "s": 4227, "text": "And now for the source code:" }, { "code": null, "e": 4341, "s": 4256, "text": "self.driver.get('https://www.indeed.com/jobs?q=data+science&l=United+States&start=')" }, { "code": null, "e": 4420, "s": 4341, "text": "Creating the DataFrame we are going to be using is easy, so let’s begin there!" }, { "code": null, "e": 4561, "s": 4420, "text": "For this data frame, we need to have “Title”, “Location”, “Company”, “Salary”, “Description” all related to the jobs we are going to scrape." }, { "code": null, "e": 4655, "s": 4561, "text": "dataframe = pd.DataFrame( columns=[\"Title\", \"Location\", \"Company\", \"Salary\", \"Description\"])" }, { "code": null, "e": 4718, "s": 4655, "text": "We will use this DataFrame as a Column names for our CSV file." }, { "code": null, "e": 4988, "s": 4718, "text": "The thing with this website is that on every page there are 10 job offers and the link changes as you go to the next page. Once I have figured that out, I made a for loop that checks every page and after it is done it goes to the next one. Here is what that looks like:" }, { "code": null, "e": 5114, "s": 4988, "text": "for cnt in range(0, 50, 10): self.driver.get(\"https://www.indeed.com/jobs?q=data+science&l=United+States&start=\" + str(cnt))" }, { "code": null, "e": 5343, "s": 5114, "text": "I set up a counter variable ‘cnt’ and add that number, converted to string to my link. The for loop specifically begins with 0 goes up to 50 and does it in iterations of 10 because that is how many jobs per page Indeed shows us." }, { "code": null, "e": 5459, "s": 5343, "text": "When we get to the first page, we need to scrape the table of offers one by one and we are going to do it this way:" }, { "code": null, "e": 5610, "s": 5459, "text": "In the image above, where you see offers, they are packed in a table and we can find that table by pressing F12 on keyboard or right-click -> Inspect." }, { "code": null, "e": 5640, "s": 5610, "text": "Here is what that looks like:" }, { "code": null, "e": 5705, "s": 5640, "text": "We will find the table by the class name and we enter this line:" }, { "code": null, "e": 5762, "s": 5705, "text": "jobs = self.driver.find_elements_by_class_name('result')" }, { "code": null, "e": 5834, "s": 5762, "text": "That saves all Web elements that it has found by the class name result." }, { "code": null, "e": 5972, "s": 5834, "text": "Once we have those saved we can create another for loop and go through every element inside that table and use that data we found inside." }, { "code": null, "e": 6067, "s": 5972, "text": "Before I show you more code on scraping those offers, we should go through a couple of things." }, { "code": null, "e": 6152, "s": 6067, "text": "For this part, we are going to use BeautifulSoup since I find it to work way faster." }, { "code": null, "e": 6310, "s": 6152, "text": "We have to set up a few things for BeatifulSoup, and those are the actual data that we give it to perform its search on and parser that we say it should use:" }, { "code": null, "e": 6393, "s": 6310, "text": "result = job.get_attribute('innerHTML')soup = BeautifulSoup(result, 'html.parser')" }, { "code": null, "e": 6526, "s": 6393, "text": "Once we get those, we just have to find elements inside the ‘soup’ defined variable, which is just a prepared data by BeautifulSoup." }, { "code": null, "e": 6574, "s": 6526, "text": "We get the data for the DataFrame that we want:" }, { "code": null, "e": 6854, "s": 6574, "text": "title = soup.find(\"a\", class_=\"jobtitle\").text.replace('\\n', '')location = soup.find(class_=\"location\").textemployer = soup.find(class_=\"company\").text.replace('\\n', '').strip()try: salary = soup.find(class_=\"salary\").text.replace( '\\n', '').strip()except: salary = 'None'" }, { "code": null, "e": 6986, "s": 6854, "text": "I did a salary part in such a manner because sometimes it is not defined and we have to set None or empty for that particular cell." }, { "code": null, "e": 7084, "s": 6986, "text": "Since I am working in the terminal for testing my code, you can also print what you found so far:" }, { "code": null, "e": 7125, "s": 7084, "text": "print(title, location, employer, salary)" }, { "code": null, "e": 7175, "s": 7125, "text": "Once this script is done, it will look like this:" }, { "code": null, "e": 7380, "s": 7175, "text": "The last thing missing for the DataFrame is the Description of the job and left this out because, in order to get the text for the job description, you have to click the job offer first. I do it this way:" }, { "code": null, "e": 7503, "s": 7380, "text": "summ = job.find_elements_by_class_name(\"summary\")[0]summ.click()job_desc = self.driver.find_element_by_id('vjs-desc').text" }, { "code": null, "e": 7576, "s": 7503, "text": "After we got all elements that should go into the DataFrame, we fill it:" }, { "code": null, "e": 7713, "s": 7576, "text": "dataframe = dataframe.append( {'Title': title, 'Location': location, 'Employer': employer, 'Description': job_desc}, ignore_index=True)" }, { "code": null, "e": 7795, "s": 7713, "text": "One more thing that I have to mention before you start testing this for yourself." }, { "code": null, "e": 7910, "s": 7795, "text": "Once you go to the second page of the website, there is a popup that blocks you from clicking further on anything!" }, { "code": null, "e": 8014, "s": 7910, "text": "I also thought of that and created a try-expect, which will close the popup and continue scraping data!" }, { "code": null, "e": 8143, "s": 8014, "text": "pop_up = self.driver.find_element_by_xpath('/html/body/table[2]/tbody/tr/td/div[2]/div[2]/div[4]/div[3]/div[2]/a')pop_up.click()" }, { "code": null, "e": 8221, "s": 8143, "text": "Once the for loop finishes, we copy the data frame data to CSV called ‘jobs’:" }, { "code": null, "e": 8263, "s": 8221, "text": "dataframe.to_csv(\"jobs.csv\", index=False)" }, { "code": null, "e": 8276, "s": 8263, "text": "We are done!" }, { "code": null, "e": 8330, "s": 8276, "text": "The complete code is under here on my GitHub account:" }, { "code": null, "e": 8341, "s": 8330, "text": "github.com" }, { "code": null, "e": 8488, "s": 8341, "text": "You can take this script to another level by implementing a comparison between different websites and get the best offers on the internet overall." }, { "code": null, "e": 8522, "s": 8488, "text": "Until then, follow me for more! 😎" } ]
Python | Split string in groups of n consecutive characters - GeeksforGeeks
24 Jun, 2020 Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character. Examples: Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'oor', 'gee', 'ks'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567] Method #1: Using list comprehension # Python code to split string# by every 3rd number # String initializationstring = "Geeksforgeeks" # Defining splitting pointn = 3 # Using list comprehensionout = [(string[i:i+n]) for i in range(0, len(string), n)] # Printing outputprint(out) ['Gee', 'ksf', 'org', 'eek', 's'] Method #2: Using zip_longest # Python code to split string of number# and character into every 4th number # Importingfrom itertools import zip_longest # Group function using zip_longest to splitdef group(n, iterable, fillvalue=None): args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) # String initializationstr = '123GeeksForGeeks4567' # Split pointn=4 # list of separated stringout_string = [''.join(lis) for lis in group(n, str, '')] # Output list initializationout_no = [] # Converting list of string into list of integerfor a in out_string: out_no.append(a) # Printing listprint(out_no) ['123G', 'eeks', 'ForG', 'eeks', '4567'] nidhi_biet Marketing Python string-programs python-string Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python program to check whether a number is Prime or not Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24138, "s": 24110, "text": "\n24 Jun, 2020" }, { "code": null, "e": 24268, "s": 24138, "text": "Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character." }, { "code": null, "e": 24278, "s": 24268, "text": "Examples:" }, { "code": null, "e": 24434, "s": 24278, "text": "Input : str = \"Geeksforgeeks\", n = 3\nOutput : ['Gee', 'ksf', 'oor', 'gee', 'ks']\n\nInput : str = \"1234567891234567\", n = 4\nOutput : [1234, 5678, 9123, 4567]" }, { "code": null, "e": 24471, "s": 24434, "text": " Method #1: Using list comprehension" }, { "code": "# Python code to split string# by every 3rd number # String initializationstring = \"Geeksforgeeks\" # Defining splitting pointn = 3 # Using list comprehensionout = [(string[i:i+n]) for i in range(0, len(string), n)] # Printing outputprint(out)", "e": 24718, "s": 24471, "text": null }, { "code": null, "e": 24753, "s": 24718, "text": "['Gee', 'ksf', 'org', 'eek', 's']\n" }, { "code": null, "e": 24783, "s": 24753, "text": " Method #2: Using zip_longest" }, { "code": "# Python code to split string of number# and character into every 4th number # Importingfrom itertools import zip_longest # Group function using zip_longest to splitdef group(n, iterable, fillvalue=None): args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) # String initializationstr = '123GeeksForGeeks4567' # Split pointn=4 # list of separated stringout_string = [''.join(lis) for lis in group(n, str, '')] # Output list initializationout_no = [] # Converting list of string into list of integerfor a in out_string: out_no.append(a) # Printing listprint(out_no)", "e": 25387, "s": 24783, "text": null }, { "code": null, "e": 25429, "s": 25387, "text": "['123G', 'eeks', 'ForG', 'eeks', '4567']\n" }, { "code": null, "e": 25440, "s": 25429, "text": "nidhi_biet" }, { "code": null, "e": 25450, "s": 25440, "text": "Marketing" }, { "code": null, "e": 25473, "s": 25450, "text": "Python string-programs" }, { "code": null, "e": 25487, "s": 25473, "text": "python-string" }, { "code": null, "e": 25494, "s": 25487, "text": "Python" }, { "code": null, "e": 25510, "s": 25494, "text": "Python Programs" }, { "code": null, "e": 25608, "s": 25510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25617, "s": 25608, "text": "Comments" }, { "code": null, "e": 25630, "s": 25617, "text": "Old Comments" }, { "code": null, "e": 25648, "s": 25630, "text": "Python Dictionary" }, { "code": null, "e": 25670, "s": 25648, "text": "Enumerate() in Python" }, { "code": null, "e": 25702, "s": 25670, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25744, "s": 25702, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25770, "s": 25744, "text": "Python String | replace()" }, { "code": null, "e": 25792, "s": 25770, "text": "Defaultdict in Python" }, { "code": null, "e": 25831, "s": 25792, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25888, "s": 25831, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 25926, "s": 25888, "text": "Python | Convert a list to dictionary" } ]
Inserting the current datetime in MongoDB?
To insert current datetime in MongoDB, use the $setOnInsert operator. Let us first implement the following query to create a collection with documents >db.addCurrentDateTimeDemo.insertOne({"StudentName":"John","StudentAdmissionDate":new Date("2012-01-21") }); { "acknowledged" : true, "insertedId" : ObjectId("5c97ae45330fd0aa0d2fe49f") } >db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2013-05-24") }); { "acknowledged" : true, "insertedId" : ObjectId("5c97ae54330fd0aa0d2fe4a0") } >db.addCurrentDateTimeDemo.insertOne({"StudentName":"Carol","StudentAdmissionDate":new Date("2019-07-26") }); { "acknowledged" : true, "insertedId" : ObjectId("5c97ae5f330fd0aa0d2fe4a1") } Following is the query to display all documents from a collection with the help of find() method > db.addCurrentDateTimeDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c97ae45330fd0aa0d2fe49f"), "StudentName" : "John", "StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z") } { "_id" : ObjectId("5c97ae54330fd0aa0d2fe4a0"), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z") } { "_id" : ObjectId("5c97ae5f330fd0aa0d2fe4a1"), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z") } Following is the query to insert current date time. We are inserting a new Student record and within that the current date time > db.addCurrentDateTimeDemo.update( { _id: 1 }, { $set: { StudentName: "Robert" }, $setOnInsert: { StudentAdmissiondate: new Date() } }, { upsert: true } ); WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 }) Following is the query to display all documents in order to verify that the current date time is inserted or not > db.addCurrentDateTimeDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c97ae45330fd0aa0d2fe49f"), "StudentName" : "John", "StudentAdmissionDate" : ISODate("2012-01-21T00:00:00Z") } { "_id" : ObjectId("5c97ae54330fd0aa0d2fe4a0"), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2013-05-24T00:00:00Z") } { "_id" : ObjectId("5c97ae5f330fd0aa0d2fe4a1"), "StudentName" : "Carol", "StudentAdmissionDate" : ISODate("2019-07-26T00:00:00Z") } { "_id" : 1, "StudentAdmissiondate" : ISODate("2019-03-24T16:21:21.269Z"), "StudentName" : "Robert" } Look at the above sample output, we have inserted current date time, which is “2019-03-24T16:21:21.269Z”.
[ { "code": null, "e": 1213, "s": 1062, "text": "To insert current datetime in MongoDB, use the $setOnInsert operator. Let us first implement the following query to create a collection with documents" }, { "code": null, "e": 1797, "s": 1213, "text": ">db.addCurrentDateTimeDemo.insertOne({\"StudentName\":\"John\",\"StudentAdmissionDate\":new Date(\"2012-01-21\") });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c97ae45330fd0aa0d2fe49f\")\n}\n>db.addCurrentDateTimeDemo.insertOne({\"StudentName\":\"Carol\",\"StudentAdmissionDate\":new Date(\"2013-05-24\") });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c97ae54330fd0aa0d2fe4a0\")\n}\n>db.addCurrentDateTimeDemo.insertOne({\"StudentName\":\"Carol\",\"StudentAdmissionDate\":new Date(\"2019-07-26\") });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c97ae5f330fd0aa0d2fe4a1\")\n}" }, { "code": null, "e": 1894, "s": 1797, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1939, "s": 1894, "text": "> db.addCurrentDateTimeDemo.find().pretty();" }, { "code": null, "e": 1978, "s": 1939, "text": "This will produce the following output" }, { "code": null, "e": 2400, "s": 1978, "text": "{\n \"_id\" : ObjectId(\"5c97ae45330fd0aa0d2fe49f\"),\n \"StudentName\" : \"John\",\n \"StudentAdmissionDate\" : ISODate(\"2012-01-21T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c97ae54330fd0aa0d2fe4a0\"),\n \"StudentName\" : \"Carol\",\n \"StudentAdmissionDate\" : ISODate(\"2013-05-24T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c97ae5f330fd0aa0d2fe4a1\"),\n \"StudentName\" : \"Carol\",\n \"StudentAdmissionDate\" : ISODate(\"2019-07-26T00:00:00Z\")\n}" }, { "code": null, "e": 2528, "s": 2400, "text": "Following is the query to insert current date time. We are inserting a new Student record and within that the current date time" }, { "code": null, "e": 2762, "s": 2528, "text": "> db.addCurrentDateTimeDemo.update( { _id: 1 }, { $set: { StudentName: \"Robert\" }, $setOnInsert: { StudentAdmissiondate: new Date() } }, { upsert: true } );\nWriteResult({ \"nMatched\" : 0, \"nUpserted\" : 1, \"nModified\" : 0, \"_id\" : 1 })" }, { "code": null, "e": 2875, "s": 2762, "text": "Following is the query to display all documents in order to verify that the current date time is inserted or not" }, { "code": null, "e": 2920, "s": 2875, "text": "> db.addCurrentDateTimeDemo.find().pretty();" }, { "code": null, "e": 2959, "s": 2920, "text": "This will produce the following output" }, { "code": null, "e": 3492, "s": 2959, "text": "{\n \"_id\" : ObjectId(\"5c97ae45330fd0aa0d2fe49f\"),\n \"StudentName\" : \"John\",\n \"StudentAdmissionDate\" : ISODate(\"2012-01-21T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c97ae54330fd0aa0d2fe4a0\"),\n \"StudentName\" : \"Carol\",\n \"StudentAdmissionDate\" : ISODate(\"2013-05-24T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c97ae5f330fd0aa0d2fe4a1\"),\n \"StudentName\" : \"Carol\",\n \"StudentAdmissionDate\" : ISODate(\"2019-07-26T00:00:00Z\")\n}\n{\n \"_id\" : 1,\n \"StudentAdmissiondate\" : ISODate(\"2019-03-24T16:21:21.269Z\"),\n \"StudentName\" : \"Robert\"\n}" }, { "code": null, "e": 3598, "s": 3492, "text": "Look at the above sample output, we have inserted current date time, which is “2019-03-24T16:21:21.269Z”." } ]
Interactive Time Series with Python and API: Generating Heatmap of Taxis in Singapore | by Shawn Tham | Towards Data Science
Land Transport Authority (LTA) of Singapore has an API that shows live coordinates of all taxis. It is quite a cool API that shows real-time taxi movement that is refreshed every 30 seconds. However, there is little work done with this API after searching up for more information on it. Hence, in this article, I will walk through the steps on how to collect data from this API and present it in a time series heatmap below using Folium! Step 1: Importing the relevant packages import foliumimport folium.plugins as pluginsimport pandas as pdimport jsonimport requestsimport timefrom folium.plugins import HeatMapWithTimeimport datetime Step 2: Pulling Data from API and storing it as a dataset I start by creating an empty data frame so that I can append the live data into it. cumulative = pd.DataFrame() Next, using a simple input function, I am able to key in the duration of taxi movement. This will determine the amount of times the loop will run. mins = input('How many mins do you want to see? ')number_of_times = (int(mins)*60)/30 Next, write a for loop to continuously pull data from the API. As the API refreshes every 30 seconds, I use Python time Module to rerun the script every 30 seconds. Meanwhile, I only extract the coordinates and the timestamp from the Geojson object and append it into my pandas data frame. This will allow me to compile past data into a data frame for easy manipulation later on. startTime = time.time()for i in range(int(number_of_times)): url = ("https://api.data.gov.sg/v1/transport/taxi-availability") response = requests.get(url) data = response.json() df = pd.io.json.json_normalize(data['features']) coordinateslist = df['geometry.coordinates'].tolist() df1 = pd.DataFrame(coordinateslist) result = df1.transpose() result.columns = ['coordinates'] result['Timestamp'] = (df['properties.timestamp'][0]) cumulative = cumulative.append(result) time.sleep(30)endTime = time.time()elapsedTime = endTime - startTimeprint("Elapsed Time = %s" % elapsedTime,'seconds') Step 3: Data Wrangling with for loops Now it is time to manipulate the data so that it is easy for us to utilize it. I start by splitting the coordinates into latitude and longitude columns. cumulative['coordinates'] = cumulative['coordinates'].astype(str)Latitude = []Longitude = []coordinates = []for i in cumulative['coordinates']: i = i.split(", ") lat = i[1][:-1] long = i[0][1:] Latitude.append(lat) Longitude.append(long)cumulative['Latitude'] = Latitudecumulative['Longitude'] = Longitude Your data frame should resemble the one below before we process it into the format we want in order to plot it into Folium. Next, we need to put the latitude and longitude into a nested list in order for us to use folium.plugins.HeatMapWithTime to generate the time series heatmap. lat_long_list = []for i in cumulative['Timestamp'].unique(): temp=[] for index, instance in cumulative[cumulative['Timestamp'] == i].iterrows(): temp.append([instance['Latitude'],instance['Longitude']]) lat_long_list.append(temp) Step 4: Creating a time index and formatted it Next, we have to convert the Timestamp into a datetime format so that we can convert it into a neater and more readable layout. This will also be the index that is used in the play button to show the time and date. #converting it to datetime formatcumulative['Timestamp']= pd.to_datetime(cumulative['Timestamp'])#creating a time indextime_index = []for i in cumulative['Timestamp'].unique(): time_index.append(i)#formatting the indexdate_strings = [d.strftime('%d/%m/%Y, %H:%M:%S') for d in time_index] Step 5: Plotting the time series heatmap Finally, we can generate the map! I choose a dark themed map of Singapore so that the heatmap will look more vibrant. #Choosing the map type m = folium.Map(location=[1.352083,103.819839],zoom_start = 11, tiles="https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png",attr="Stadia.AlidadeSmoothDark")#Plot it on the mapHeatMapWithTime(lat_long_list,radius=5,auto_play=True,position='bottomright',name="cluster",index=date_strings,max_opacity=0.7).add_to(m)# Display the mapm Summary Step 1: Importing the relevant packages Step 2: Pulling Data from API and storing it as a dataset Step 3: Data Wrangling with for loops Step 4: Creating a time index and formatted it Step 5: Plotting the time series heatmap Feel free to save it as a html file so that you can send to your friends and colleagues. You can check out the full code on my Github here.
[ { "code": null, "e": 610, "s": 172, "text": "Land Transport Authority (LTA) of Singapore has an API that shows live coordinates of all taxis. It is quite a cool API that shows real-time taxi movement that is refreshed every 30 seconds. However, there is little work done with this API after searching up for more information on it. Hence, in this article, I will walk through the steps on how to collect data from this API and present it in a time series heatmap below using Folium!" }, { "code": null, "e": 650, "s": 610, "text": "Step 1: Importing the relevant packages" }, { "code": null, "e": 809, "s": 650, "text": "import foliumimport folium.plugins as pluginsimport pandas as pdimport jsonimport requestsimport timefrom folium.plugins import HeatMapWithTimeimport datetime" }, { "code": null, "e": 867, "s": 809, "text": "Step 2: Pulling Data from API and storing it as a dataset" }, { "code": null, "e": 951, "s": 867, "text": "I start by creating an empty data frame so that I can append the live data into it." }, { "code": null, "e": 979, "s": 951, "text": "cumulative = pd.DataFrame()" }, { "code": null, "e": 1126, "s": 979, "text": "Next, using a simple input function, I am able to key in the duration of taxi movement. This will determine the amount of times the loop will run." }, { "code": null, "e": 1212, "s": 1126, "text": "mins = input('How many mins do you want to see? ')number_of_times = (int(mins)*60)/30" }, { "code": null, "e": 1592, "s": 1212, "text": "Next, write a for loop to continuously pull data from the API. As the API refreshes every 30 seconds, I use Python time Module to rerun the script every 30 seconds. Meanwhile, I only extract the coordinates and the timestamp from the Geojson object and append it into my pandas data frame. This will allow me to compile past data into a data frame for easy manipulation later on." }, { "code": null, "e": 2213, "s": 1592, "text": "startTime = time.time()for i in range(int(number_of_times)): url = (\"https://api.data.gov.sg/v1/transport/taxi-availability\") response = requests.get(url) data = response.json() df = pd.io.json.json_normalize(data['features']) coordinateslist = df['geometry.coordinates'].tolist() df1 = pd.DataFrame(coordinateslist) result = df1.transpose() result.columns = ['coordinates'] result['Timestamp'] = (df['properties.timestamp'][0]) cumulative = cumulative.append(result) time.sleep(30)endTime = time.time()elapsedTime = endTime - startTimeprint(\"Elapsed Time = %s\" % elapsedTime,'seconds')" }, { "code": null, "e": 2251, "s": 2213, "text": "Step 3: Data Wrangling with for loops" }, { "code": null, "e": 2404, "s": 2251, "text": "Now it is time to manipulate the data so that it is easy for us to utilize it. I start by splitting the coordinates into latitude and longitude columns." }, { "code": null, "e": 2725, "s": 2404, "text": "cumulative['coordinates'] = cumulative['coordinates'].astype(str)Latitude = []Longitude = []coordinates = []for i in cumulative['coordinates']: i = i.split(\", \") lat = i[1][:-1] long = i[0][1:] Latitude.append(lat) Longitude.append(long)cumulative['Latitude'] = Latitudecumulative['Longitude'] = Longitude" }, { "code": null, "e": 2849, "s": 2725, "text": "Your data frame should resemble the one below before we process it into the format we want in order to plot it into Folium." }, { "code": null, "e": 3007, "s": 2849, "text": "Next, we need to put the latitude and longitude into a nested list in order for us to use folium.plugins.HeatMapWithTime to generate the time series heatmap." }, { "code": null, "e": 3253, "s": 3007, "text": "lat_long_list = []for i in cumulative['Timestamp'].unique(): temp=[] for index, instance in cumulative[cumulative['Timestamp'] == i].iterrows(): temp.append([instance['Latitude'],instance['Longitude']]) lat_long_list.append(temp)" }, { "code": null, "e": 3300, "s": 3253, "text": "Step 4: Creating a time index and formatted it" }, { "code": null, "e": 3515, "s": 3300, "text": "Next, we have to convert the Timestamp into a datetime format so that we can convert it into a neater and more readable layout. This will also be the index that is used in the play button to show the time and date." }, { "code": null, "e": 3806, "s": 3515, "text": "#converting it to datetime formatcumulative['Timestamp']= pd.to_datetime(cumulative['Timestamp'])#creating a time indextime_index = []for i in cumulative['Timestamp'].unique(): time_index.append(i)#formatting the indexdate_strings = [d.strftime('%d/%m/%Y, %H:%M:%S') for d in time_index]" }, { "code": null, "e": 3847, "s": 3806, "text": "Step 5: Plotting the time series heatmap" }, { "code": null, "e": 3965, "s": 3847, "text": "Finally, we can generate the map! I choose a dark themed map of Singapore so that the heatmap will look more vibrant." }, { "code": null, "e": 4340, "s": 3965, "text": "#Choosing the map type m = folium.Map(location=[1.352083,103.819839],zoom_start = 11, tiles=\"https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png\",attr=\"Stadia.AlidadeSmoothDark\")#Plot it on the mapHeatMapWithTime(lat_long_list,radius=5,auto_play=True,position='bottomright',name=\"cluster\",index=date_strings,max_opacity=0.7).add_to(m)# Display the mapm" }, { "code": null, "e": 4348, "s": 4340, "text": "Summary" }, { "code": null, "e": 4388, "s": 4348, "text": "Step 1: Importing the relevant packages" }, { "code": null, "e": 4446, "s": 4388, "text": "Step 2: Pulling Data from API and storing it as a dataset" }, { "code": null, "e": 4484, "s": 4446, "text": "Step 3: Data Wrangling with for loops" }, { "code": null, "e": 4531, "s": 4484, "text": "Step 4: Creating a time index and formatted it" }, { "code": null, "e": 4572, "s": 4531, "text": "Step 5: Plotting the time series heatmap" } ]
Build a web data dashboard in just minutes with Python | by JP Hwang | Towards Data Science
I don’t know about you, but I occasionally find it a little bit intimidating to have to code something. This is doubly so when I’m building something akin to web development rather than doing some local data analysis and visualisation. I’m a competent Python coder, but I wouldn’t call myself a web developer at all, even after having more than dabbled with Django and Flask. Still, converting your data outputs to a web app leads to a few non-trivial improvements for your project. It is just much easier to build in true, powerful interactivity into a web app. It also means that you can control exactly how the data is presented, as the web app can become the de facto report as well as the access point to your data. Lastly, and most importantly, you can exponentially scale the accessibility to your outputs; making them available anywhere, any time. There is always a web browser at a user’s fingertips. So, I bit the bullet and started to do just this with some of my data projects recently, with surprisingly fast speed and efficiency. I converted one of my outputs from this article to a web app here in just a couple of hours. I thought this was rather cool, and wanted to share how this came together in just a few lines of code. As always, I include everything you need to replicate my steps (data & code), and the article is not really about basketball. So do not worry if you are unfamiliar with it, and let’s get going. I include the code and data in my GitLab repo here (dash_simple_nba directory). So please feel free to play with it / improve upon it. I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky, though. You’ll need pandas, plotly and dash. Install each (in your virtual environment) with a simple pip install [PACKAGE_NAME]. For this tutorial, I am simply going to skip *most* of the steps taken to create the local version of our visualisation. If you’re interested in what is going on, take a look at this article: towardsdatascience.com We will have a recap session, though, so you can see what is happening between plotting the chart locally with Plotly, and how to port that to a web app with Plotly Dash. I have pre-processed the data, and saved it as a CSV file. It is a collection of player data for the current NBA season (as of 26/Feb/2020), which shows: What share of their team’s shots they are taking, and How efficient / effective they are at doing it. For this portion, follow along by opening local_plot.py in my repo. Load the data with: all_teams_df = pd.read_csv(‘srcdata/shot_dist_compiled_data_2019_20.csv’) Inspect the data with all_teams_df.head(), and you should see: Each player’s data has been compiled for each minute of the game (excluding overtime), with stats pl_acc and pl_pps being the only exception, as they have been compiled per quarter of the game (for each 12 minute period). The dataframe contains all NBA players, so let’s break it down to a manageable size, by filtering for a team. For instance, the New Orleans Pelicans’ players can be chosen with: all_teams_df[all_teams_df.group == 'NOP'] Then, our data can be visualised in Plotly, as below: import plotly.express as pxfig = px.scatter(all_teams_df[all_teams_df.group == 'NOP'], x='min_mid', y='player', size='shots_freq', color='pl_pps')fig.show() At the risk of doing this: I do add a few small details to my chart, to produce this version of the same graph. This is the code that I used to do it. Now, while it’s a lot of formatting code, I thought it useful to show you how I did it, because we are going to be re-using these functions in our Dash version of the code. Now, let’s get to the main event — how to create a web app out of these plots. You can read more about Plotly Dash here, but for now all you need to know that it is an open-source software package developed to abstract away the difficulties in putting your visualisations on the web. It works with Flask under the hood, and you can happily reuse most of the code that you used to develop plots in plotly.py. This is the simple version that I put together: Try it out! It should open this plot on your browser. What’s the big deal? Well, for one — it is a live web app, in under 25 lines of code. And notice the drop-down menu on the top left? Try changing the values on it, and watch the graph change *magically*. Go on, I’ll wait. Okay? Done. Let’s briefly go through the code. At a high level, what I’m doing here is to: Initialise a Dash app; Get a list of available team names, and provide it to a dropdown menu (with DOM id group-select) with a default value or ‘TOR’; Instantiate a Graph object as the shot-dist-graph identifier within Dash; and Create a callback function where if any of the values are changed, it will call the update_graph function and pass the returned object to the Output. If you take a look at the code, so many of what is probably trivial for web devs but annoying for me is abstracted away. dcc.Graph wraps the figure object from plotly.py into my web app and HTML components like divs can be called and set up conveniently with html.Div objects. Most gratifying for me personally is that Input objects and callbacks from those inputs are declaratively set up, and I can avoid having to deal with things like HTML forms or JavaScript. And the resulting app still works beautifully. The graph is updated the moment that the pulldown menu is used to select another value. And we did all that in fewer than 25 lines of code. At this point, you might be asking — why Dash? We can do all this with a JS framework front end, and Flask, or any one of myriad other combinations. To someone like me who prefers the comfort of Python than natively dealing with HTML and CSS, using Dash abstracts away a lot of stuff that doesn’t add a lot of value to the end product. Take, for instance, a version of this app that includes further formatting and notes for the audience: (It is simple_dash_w_format.py in the git repo) Most of the changes are cosmetic, but I will note that here, I just write the body text in Markdown, and simply carry over my formatting functions from Plotly to be used in the formatting the graphs in Dash. This saves me a tremendous amount of time between doing data analysis and visualisation to deployment to clients’ views. All in all, from starting with my initial graph, I think it probably took less than an hour to deploy it to Heroku. Which is pretty amazing. I will get into more advanced features of Dash, and actually doing some cool things with it functionality-wise, but I was very happy with this outcome in terms of ease and speed. Try it out yourself — I think that you’d be very impressed. Next time, I plan to write about some really cool things you can do with Dash, and building truly interactive dashboards. Edit: I’m starting a Substack for all things Data and Visualisation — it is going to be a way for me to engage directly with you. I would love for you to join me here. visualnoise.substack.com I also wrote a little about why I’m starting a Substack. If you liked this, say 👋 / follow on twitter, or follow for updates. This is the article that the data viz is based on: towardsdatascience.com Also, here is another article I wrote about improving data-based storytelling through better visualisation of time series data:
[ { "code": null, "e": 548, "s": 172, "text": "I don’t know about you, but I occasionally find it a little bit intimidating to have to code something. This is doubly so when I’m building something akin to web development rather than doing some local data analysis and visualisation. I’m a competent Python coder, but I wouldn’t call myself a web developer at all, even after having more than dabbled with Django and Flask." }, { "code": null, "e": 655, "s": 548, "text": "Still, converting your data outputs to a web app leads to a few non-trivial improvements for your project." }, { "code": null, "e": 1082, "s": 655, "text": "It is just much easier to build in true, powerful interactivity into a web app. It also means that you can control exactly how the data is presented, as the web app can become the de facto report as well as the access point to your data. Lastly, and most importantly, you can exponentially scale the accessibility to your outputs; making them available anywhere, any time. There is always a web browser at a user’s fingertips." }, { "code": null, "e": 1309, "s": 1082, "text": "So, I bit the bullet and started to do just this with some of my data projects recently, with surprisingly fast speed and efficiency. I converted one of my outputs from this article to a web app here in just a couple of hours." }, { "code": null, "e": 1413, "s": 1309, "text": "I thought this was rather cool, and wanted to share how this came together in just a few lines of code." }, { "code": null, "e": 1607, "s": 1413, "text": "As always, I include everything you need to replicate my steps (data & code), and the article is not really about basketball. So do not worry if you are unfamiliar with it, and let’s get going." }, { "code": null, "e": 1742, "s": 1607, "text": "I include the code and data in my GitLab repo here (dash_simple_nba directory). So please feel free to play with it / improve upon it." }, { "code": null, "e": 1858, "s": 1742, "text": "I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky, though." }, { "code": null, "e": 1980, "s": 1858, "text": "You’ll need pandas, plotly and dash. Install each (in your virtual environment) with a simple pip install [PACKAGE_NAME]." }, { "code": null, "e": 2172, "s": 1980, "text": "For this tutorial, I am simply going to skip *most* of the steps taken to create the local version of our visualisation. If you’re interested in what is going on, take a look at this article:" }, { "code": null, "e": 2195, "s": 2172, "text": "towardsdatascience.com" }, { "code": null, "e": 2366, "s": 2195, "text": "We will have a recap session, though, so you can see what is happening between plotting the chart locally with Plotly, and how to port that to a web app with Plotly Dash." }, { "code": null, "e": 2520, "s": 2366, "text": "I have pre-processed the data, and saved it as a CSV file. It is a collection of player data for the current NBA season (as of 26/Feb/2020), which shows:" }, { "code": null, "e": 2574, "s": 2520, "text": "What share of their team’s shots they are taking, and" }, { "code": null, "e": 2622, "s": 2574, "text": "How efficient / effective they are at doing it." }, { "code": null, "e": 2690, "s": 2622, "text": "For this portion, follow along by opening local_plot.py in my repo." }, { "code": null, "e": 2710, "s": 2690, "text": "Load the data with:" }, { "code": null, "e": 2784, "s": 2710, "text": "all_teams_df = pd.read_csv(‘srcdata/shot_dist_compiled_data_2019_20.csv’)" }, { "code": null, "e": 2847, "s": 2784, "text": "Inspect the data with all_teams_df.head(), and you should see:" }, { "code": null, "e": 3069, "s": 2847, "text": "Each player’s data has been compiled for each minute of the game (excluding overtime), with stats pl_acc and pl_pps being the only exception, as they have been compiled per quarter of the game (for each 12 minute period)." }, { "code": null, "e": 3247, "s": 3069, "text": "The dataframe contains all NBA players, so let’s break it down to a manageable size, by filtering for a team. For instance, the New Orleans Pelicans’ players can be chosen with:" }, { "code": null, "e": 3289, "s": 3247, "text": "all_teams_df[all_teams_df.group == 'NOP']" }, { "code": null, "e": 3343, "s": 3289, "text": "Then, our data can be visualised in Plotly, as below:" }, { "code": null, "e": 3500, "s": 3343, "text": "import plotly.express as pxfig = px.scatter(all_teams_df[all_teams_df.group == 'NOP'], x='min_mid', y='player', size='shots_freq', color='pl_pps')fig.show()" }, { "code": null, "e": 3527, "s": 3500, "text": "At the risk of doing this:" }, { "code": null, "e": 3612, "s": 3527, "text": "I do add a few small details to my chart, to produce this version of the same graph." }, { "code": null, "e": 3651, "s": 3612, "text": "This is the code that I used to do it." }, { "code": null, "e": 3824, "s": 3651, "text": "Now, while it’s a lot of formatting code, I thought it useful to show you how I did it, because we are going to be re-using these functions in our Dash version of the code." }, { "code": null, "e": 3903, "s": 3824, "text": "Now, let’s get to the main event — how to create a web app out of these plots." }, { "code": null, "e": 4108, "s": 3903, "text": "You can read more about Plotly Dash here, but for now all you need to know that it is an open-source software package developed to abstract away the difficulties in putting your visualisations on the web." }, { "code": null, "e": 4232, "s": 4108, "text": "It works with Flask under the hood, and you can happily reuse most of the code that you used to develop plots in plotly.py." }, { "code": null, "e": 4280, "s": 4232, "text": "This is the simple version that I put together:" }, { "code": null, "e": 4334, "s": 4280, "text": "Try it out! It should open this plot on your browser." }, { "code": null, "e": 4538, "s": 4334, "text": "What’s the big deal? Well, for one — it is a live web app, in under 25 lines of code. And notice the drop-down menu on the top left? Try changing the values on it, and watch the graph change *magically*." }, { "code": null, "e": 4556, "s": 4538, "text": "Go on, I’ll wait." }, { "code": null, "e": 4568, "s": 4556, "text": "Okay? Done." }, { "code": null, "e": 4603, "s": 4568, "text": "Let’s briefly go through the code." }, { "code": null, "e": 4647, "s": 4603, "text": "At a high level, what I’m doing here is to:" }, { "code": null, "e": 4670, "s": 4647, "text": "Initialise a Dash app;" }, { "code": null, "e": 4798, "s": 4670, "text": "Get a list of available team names, and provide it to a dropdown menu (with DOM id group-select) with a default value or ‘TOR’;" }, { "code": null, "e": 4876, "s": 4798, "text": "Instantiate a Graph object as the shot-dist-graph identifier within Dash; and" }, { "code": null, "e": 5026, "s": 4876, "text": "Create a callback function where if any of the values are changed, it will call the update_graph function and pass the returned object to the Output." }, { "code": null, "e": 5147, "s": 5026, "text": "If you take a look at the code, so many of what is probably trivial for web devs but annoying for me is abstracted away." }, { "code": null, "e": 5303, "s": 5147, "text": "dcc.Graph wraps the figure object from plotly.py into my web app and HTML components like divs can be called and set up conveniently with html.Div objects." }, { "code": null, "e": 5491, "s": 5303, "text": "Most gratifying for me personally is that Input objects and callbacks from those inputs are declaratively set up, and I can avoid having to deal with things like HTML forms or JavaScript." }, { "code": null, "e": 5626, "s": 5491, "text": "And the resulting app still works beautifully. The graph is updated the moment that the pulldown menu is used to select another value." }, { "code": null, "e": 5678, "s": 5626, "text": "And we did all that in fewer than 25 lines of code." }, { "code": null, "e": 5827, "s": 5678, "text": "At this point, you might be asking — why Dash? We can do all this with a JS framework front end, and Flask, or any one of myriad other combinations." }, { "code": null, "e": 6014, "s": 5827, "text": "To someone like me who prefers the comfort of Python than natively dealing with HTML and CSS, using Dash abstracts away a lot of stuff that doesn’t add a lot of value to the end product." }, { "code": null, "e": 6117, "s": 6014, "text": "Take, for instance, a version of this app that includes further formatting and notes for the audience:" }, { "code": null, "e": 6165, "s": 6117, "text": "(It is simple_dash_w_format.py in the git repo)" }, { "code": null, "e": 6373, "s": 6165, "text": "Most of the changes are cosmetic, but I will note that here, I just write the body text in Markdown, and simply carry over my formatting functions from Plotly to be used in the formatting the graphs in Dash." }, { "code": null, "e": 6494, "s": 6373, "text": "This saves me a tremendous amount of time between doing data analysis and visualisation to deployment to clients’ views." }, { "code": null, "e": 6635, "s": 6494, "text": "All in all, from starting with my initial graph, I think it probably took less than an hour to deploy it to Heroku. Which is pretty amazing." }, { "code": null, "e": 6814, "s": 6635, "text": "I will get into more advanced features of Dash, and actually doing some cool things with it functionality-wise, but I was very happy with this outcome in terms of ease and speed." }, { "code": null, "e": 6996, "s": 6814, "text": "Try it out yourself — I think that you’d be very impressed. Next time, I plan to write about some really cool things you can do with Dash, and building truly interactive dashboards." }, { "code": null, "e": 7164, "s": 6996, "text": "Edit: I’m starting a Substack for all things Data and Visualisation — it is going to be a way for me to engage directly with you. I would love for you to join me here." }, { "code": null, "e": 7189, "s": 7164, "text": "visualnoise.substack.com" }, { "code": null, "e": 7246, "s": 7189, "text": "I also wrote a little about why I’m starting a Substack." }, { "code": null, "e": 7366, "s": 7246, "text": "If you liked this, say 👋 / follow on twitter, or follow for updates. This is the article that the data viz is based on:" }, { "code": null, "e": 7389, "s": 7366, "text": "towardsdatascience.com" } ]
Convert one base to other bases in a single Java Program
Let’s say we have an Octal number. To convert Octal to other bases like binary, hexadecimal, etc, the Java code is as follows − Live Demo public class Demo{ public static String base_convert(String num, int source, int destination){ return Integer.toString(Integer.parseInt(num, source), destination); } public static void main(String[] args){ String my_num = "345"; int source = 8; int destination = 2; System.out.println("Converting the number from octal to binary: "+ base_convert (my_num, source, destination)); destination = 10; System.out.println("Converting the number from octal to decimal : "+ base_convert (my_num, source, destination)); destination = 16; System.out.println("Converting the number from octal to hexadecimal: "+ base_convert (my_num, source, destination)); } } Converting the number from octal to binary: 11100101 Converting the number from octal to decimal : 229 Converting the number from octal to hexadecimal: e5 A class named Demo contains a function named ‘base_convert’ is defined. This function parses the integer from source base to the destination base, converts it into a string and returns it as output. In the main function, the value for number, for source base and for different destination bases are defined. The ‘base_convert’ function is called with the number, source and destination as parameters. Relevant output is displayed.
[ { "code": null, "e": 1190, "s": 1062, "text": "Let’s say we have an Octal number. To convert Octal to other bases like binary, hexadecimal, etc, the Java code is as follows −" }, { "code": null, "e": 1201, "s": 1190, "text": " Live Demo" }, { "code": null, "e": 1916, "s": 1201, "text": "public class Demo{\n public static String base_convert(String num, int source, int destination){\n return Integer.toString(Integer.parseInt(num, source), destination);\n }\n public static void main(String[] args){\n String my_num = \"345\";\n int source = 8;\n int destination = 2;\n System.out.println(\"Converting the number from octal to binary: \"+ base_convert (my_num, source, destination));\n destination = 10;\n System.out.println(\"Converting the number from octal to decimal : \"+ base_convert (my_num, source, destination));\n destination = 16;\n System.out.println(\"Converting the number from octal to hexadecimal: \"+ base_convert (my_num, source, destination));\n }\n}" }, { "code": null, "e": 2071, "s": 1916, "text": "Converting the number from octal to binary: 11100101\nConverting the number from octal to decimal : 229\nConverting the number from octal to hexadecimal: e5" }, { "code": null, "e": 2502, "s": 2071, "text": "A class named Demo contains a function named ‘base_convert’ is defined. This function parses the integer from source base to the destination base, converts it into a string and returns it as output. In the main function, the value for number, for source base and for different destination bases are defined. The ‘base_convert’ function is called with the number, source and destination as parameters. Relevant output is displayed." } ]
Booleans are Fun and Mysterious. Some fun puzzles with answers about the... | by Naser Tamimi | Towards Data Science
In data science and programming, boolean (True and False) data are considered simple and boring. I believe booleans are fun and sometimes unpredictable if you don’t know their logic. I will convince many of you that some interesting features are associated with boolean objects that you probably ignored. Let me start with an easy one. This code should be able to recognize int and boolean objects. If the input object is not boolean or integer, it tells you that the object is “Something Else!”. In the end, I tested the function with four examples. What is your guess about the outputs of this piece of code? It seems easy, right? An int object.Something else!A bool object.A bool object. If your guess was like the above outputs, you are as WRONG as I was for the first time. Actually, the right answer is: An int object.Something else!An int object.An int object. Why are the boolean objects (Ture and False) identified as integer objects? In fact, in Python, the boolean class is inherited from the integer class. To make a long story short, there was no boolean object in initial versions of Python, and they used 1 and 0 instead of True and False. When they decided to incorporate boolean objects in Python, they inherited the boolean class from the integer class (read this story here). When you run the code, because the code recognized True and False as types of int, it prints “An int object.” and makes you confused and surprised. Okay, this one was easy. Let me show you another piece of code and ask you to guess the outputs. The first time I faced this challenge, it seemed super easy. I thought, first of all, both functions are almost the same and should give me the same results. The 0 is False, 1 is True, and 2 should be False. Simply, I expected something like: FalseTrueFalseFalseTrueFalse But, as you guess, my answer was not correct. The correct answer is: FalseTrueTrueFalseTrueFalse What?! It means if 2 and if 2 == True are not equal in Python, seriously? The first expression is True, and the second one is False. How is it possible?! Let me tell you why does it happen. We have two if expressions. Let’s start with the easy one, which is if 2 == True. As you know, in Python, True is equal to 1. Therefore 2 == True is simply False, and that’s why the code block associated with if 2 == True does not get executed. It is easy to understand. The mystery is why the code block corresponding to if 2 (in func1()) gets executed and returns True? Does it mean that 2 is equal to True? If 2 is equal to True , why 2 == True is not True. Confusing, right? If you are curious to know the answer, here is it. The answer is in object-oriented programming which is the foundation of Python. As you know, everything in Python is an object. Objects have attributes and methods. Some attributes and methods are called magic methods or attributes. Although it is not necessary for the rest of this article, I encourage you to read my trilogy on object-oriented programming in Python. Part 1 | Part 2 | Part 3 One of the magic methods that you can define for every class and object is __bool__. This magic method can return either False or True. When you use if and an object (e.g., if obj:), if calls __bool__ method and based on its returned value, execute or does not execute the corresponding block. Let’s do a quick test in Python and check what does __bool__ method returns for integer object 2 and 0 . >>> n = 2>>> n.__bool__()True>>> n = 0>>> n.__bool__()False You can also check the boolean value of an object using a built-in faction called bool(). >>> n = 2>>> bool(n)True You can take advantage of __bool__ to improve object-oriented programming. Think what is the most important boolean aspect of your object, and based on that, return a proper boolean value through __bool__ method. For example, suppose you are working on a reinforcement learning project and have an object for your robot or agent. The most important aspect of a robot/agent, in my opinion, is if it is alive or not. Therefore, I define the __bool__ method to reflect this property in its returned value. Here is an example of how I will define this class of objects: In this example, there is an attribute called score, which stores the robot object's score. While the score is above 0, your robot is alive and bool() returns True. We reduce the robot score by 10 and then 90 (the initial score was 100). As soon as the score becomes 0, the object returns False in response to any functions that call its boolean value. The user can take advantage of this property in her/his code, for example, while r: ... or if r: .... If there is no __bool__ method for the object, if, bool() and similar functions look for another magic method which is called __len__. This method normally returns the length of the object. If __len__ return 0, bool() returns False; otherwise, it returns True. In the previous example, simply we could return the score through __len__ , and we did not need to define __bool__ anymore. Here is how we can change the code and get the same results. With all knowledge that you learned, you must be able to answer my last puzzle. What is the output of the following code? bool("") To understand the behavior of boolean data types and objects in Python, you must know that this data type is inherited from the integer class. Also, magic methods such as __bool__ and __len__ define how an object response to functions like bool(obj). Follow me on Twitter for the latest stories: https://twitter.com/TamimiNas
[ { "code": null, "e": 477, "s": 172, "text": "In data science and programming, boolean (True and False) data are considered simple and boring. I believe booleans are fun and sometimes unpredictable if you don’t know their logic. I will convince many of you that some interesting features are associated with boolean objects that you probably ignored." }, { "code": null, "e": 508, "s": 477, "text": "Let me start with an easy one." }, { "code": null, "e": 805, "s": 508, "text": "This code should be able to recognize int and boolean objects. If the input object is not boolean or integer, it tells you that the object is “Something Else!”. In the end, I tested the function with four examples. What is your guess about the outputs of this piece of code? It seems easy, right?" }, { "code": null, "e": 863, "s": 805, "text": "An int object.Something else!A bool object.A bool object." }, { "code": null, "e": 982, "s": 863, "text": "If your guess was like the above outputs, you are as WRONG as I was for the first time. Actually, the right answer is:" }, { "code": null, "e": 1040, "s": 982, "text": "An int object.Something else!An int object.An int object." }, { "code": null, "e": 1116, "s": 1040, "text": "Why are the boolean objects (Ture and False) identified as integer objects?" }, { "code": null, "e": 1467, "s": 1116, "text": "In fact, in Python, the boolean class is inherited from the integer class. To make a long story short, there was no boolean object in initial versions of Python, and they used 1 and 0 instead of True and False. When they decided to incorporate boolean objects in Python, they inherited the boolean class from the integer class (read this story here)." }, { "code": null, "e": 1615, "s": 1467, "text": "When you run the code, because the code recognized True and False as types of int, it prints “An int object.” and makes you confused and surprised." }, { "code": null, "e": 1712, "s": 1615, "text": "Okay, this one was easy. Let me show you another piece of code and ask you to guess the outputs." }, { "code": null, "e": 1955, "s": 1712, "text": "The first time I faced this challenge, it seemed super easy. I thought, first of all, both functions are almost the same and should give me the same results. The 0 is False, 1 is True, and 2 should be False. Simply, I expected something like:" }, { "code": null, "e": 1984, "s": 1955, "text": "FalseTrueFalseFalseTrueFalse" }, { "code": null, "e": 2053, "s": 1984, "text": "But, as you guess, my answer was not correct. The correct answer is:" }, { "code": null, "e": 2081, "s": 2053, "text": "FalseTrueTrueFalseTrueFalse" }, { "code": null, "e": 2235, "s": 2081, "text": "What?! It means if 2 and if 2 == True are not equal in Python, seriously? The first expression is True, and the second one is False. How is it possible?!" }, { "code": null, "e": 2542, "s": 2235, "text": "Let me tell you why does it happen. We have two if expressions. Let’s start with the easy one, which is if 2 == True. As you know, in Python, True is equal to 1. Therefore 2 == True is simply False, and that’s why the code block associated with if 2 == True does not get executed. It is easy to understand." }, { "code": null, "e": 2750, "s": 2542, "text": "The mystery is why the code block corresponding to if 2 (in func1()) gets executed and returns True? Does it mean that 2 is equal to True? If 2 is equal to True , why 2 == True is not True. Confusing, right?" }, { "code": null, "e": 3034, "s": 2750, "text": "If you are curious to know the answer, here is it. The answer is in object-oriented programming which is the foundation of Python. As you know, everything in Python is an object. Objects have attributes and methods. Some attributes and methods are called magic methods or attributes." }, { "code": null, "e": 3170, "s": 3034, "text": "Although it is not necessary for the rest of this article, I encourage you to read my trilogy on object-oriented programming in Python." }, { "code": null, "e": 3195, "s": 3170, "text": "Part 1 | Part 2 | Part 3" }, { "code": null, "e": 3594, "s": 3195, "text": "One of the magic methods that you can define for every class and object is __bool__. This magic method can return either False or True. When you use if and an object (e.g., if obj:), if calls __bool__ method and based on its returned value, execute or does not execute the corresponding block. Let’s do a quick test in Python and check what does __bool__ method returns for integer object 2 and 0 ." }, { "code": null, "e": 3654, "s": 3594, "text": ">>> n = 2>>> n.__bool__()True>>> n = 0>>> n.__bool__()False" }, { "code": null, "e": 3744, "s": 3654, "text": "You can also check the boolean value of an object using a built-in faction called bool()." }, { "code": null, "e": 3769, "s": 3744, "text": ">>> n = 2>>> bool(n)True" }, { "code": null, "e": 4335, "s": 3769, "text": "You can take advantage of __bool__ to improve object-oriented programming. Think what is the most important boolean aspect of your object, and based on that, return a proper boolean value through __bool__ method. For example, suppose you are working on a reinforcement learning project and have an object for your robot or agent. The most important aspect of a robot/agent, in my opinion, is if it is alive or not. Therefore, I define the __bool__ method to reflect this property in its returned value. Here is an example of how I will define this class of objects:" }, { "code": null, "e": 4790, "s": 4335, "text": "In this example, there is an attribute called score, which stores the robot object's score. While the score is above 0, your robot is alive and bool() returns True. We reduce the robot score by 10 and then 90 (the initial score was 100). As soon as the score becomes 0, the object returns False in response to any functions that call its boolean value. The user can take advantage of this property in her/his code, for example, while r: ... or if r: ...." }, { "code": null, "e": 5236, "s": 4790, "text": "If there is no __bool__ method for the object, if, bool() and similar functions look for another magic method which is called __len__. This method normally returns the length of the object. If __len__ return 0, bool() returns False; otherwise, it returns True. In the previous example, simply we could return the score through __len__ , and we did not need to define __bool__ anymore. Here is how we can change the code and get the same results." }, { "code": null, "e": 5358, "s": 5236, "text": "With all knowledge that you learned, you must be able to answer my last puzzle. What is the output of the following code?" }, { "code": null, "e": 5367, "s": 5358, "text": "bool(\"\")" }, { "code": null, "e": 5618, "s": 5367, "text": "To understand the behavior of boolean data types and objects in Python, you must know that this data type is inherited from the integer class. Also, magic methods such as __bool__ and __len__ define how an object response to functions like bool(obj)." } ]
Jython - Functions
A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement. Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear. #definition of function defSayHello(): "optional documentation string" print "Hello World" return #calling the function SayHello() A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception. #defining function with two arguments def area(l,b): area = l*b print "area = ",area return #calling function length = 10 breadth = 20 #with two arguments. This is OK area(length, breadth) #only one argument provided. This will throw TypeError area(length) The output will be as follows − area = 200 Traceback (most recent call last): File "area.py", line 11, in <module> area(length) TypeError: area() takes exactly 2 arguments (1 given) After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function. #defining function def area(l,b): area = l*b print "area = ",area return area #calling function length = 10 breadth = 20 #calling function and obtaining its reurned value result = area(length, breadth) print "value returned by function : ", result The following output is obtained if the above script is executed from the Jython prompt. area = 200 value returned by function : 200 Print Add Notes Bookmark this page
[ { "code": null, "e": 2467, "s": 2081, "text": "A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement." }, { "code": null, "e": 2600, "s": 2467, "text": "Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear." }, { "code": null, "e": 2741, "s": 2600, "text": "#definition of function\ndefSayHello():\n \"optional documentation string\"\n print \"Hello World\"\n return\n\n#calling the function\nSayHello()" }, { "code": null, "e": 3055, "s": 2741, "text": "A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception." }, { "code": null, "e": 3322, "s": 3055, "text": "#defining function with two arguments\ndef area(l,b):\n area = l*b\n print \"area = \",area\n return\n\n#calling function\nlength = 10\nbreadth = 20\n#with two arguments. This is OK\narea(length, breadth)\n#only one argument provided. This will throw TypeError\narea(length)" }, { "code": null, "e": 3354, "s": 3322, "text": "The output will be as follows −" }, { "code": null, "e": 3511, "s": 3354, "text": "area = 200\nTraceback (most recent call last):\n File \"area.py\", line 11, in <module>\n area(length)\nTypeError: area() takes exactly 2 arguments (1 given)\n" }, { "code": null, "e": 3733, "s": 3511, "text": "After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function." }, { "code": null, "e": 3991, "s": 3733, "text": "#defining function\ndef area(l,b):\n area = l*b\n print \"area = \",area\n return area\n\n#calling function\nlength = 10\nbreadth = 20\n#calling function and obtaining its reurned value\nresult = area(length, breadth)\nprint \"value returned by function : \", result" }, { "code": null, "e": 4080, "s": 3991, "text": "The following output is obtained if the above script is executed from the Jython prompt." }, { "code": null, "e": 4125, "s": 4080, "text": "area = 200\nvalue returned by function : 200\n" }, { "code": null, "e": 4132, "s": 4125, "text": " Print" }, { "code": null, "e": 4143, "s": 4132, "text": " Add Notes" } ]
How to create String object in Java?
You can create a String by - Assigning a string value wrapped in " " to a String type variable. Assigning a string value wrapped in " " to a String type variable. String message = "Hello Welcome to Tutorialspoint"; Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor. Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor. String message = new String ("Hello Welcome to Tutorialspoint"); Passing a character array to the String constructor. Passing a character array to the String constructor. char arr[] = {'H','e','l','l','o'}; String message = new String(arr);
[ { "code": null, "e": 1091, "s": 1062, "text": "You can create a String by -" }, { "code": null, "e": 1158, "s": 1091, "text": "Assigning a string value wrapped in \" \" to a String type variable." }, { "code": null, "e": 1225, "s": 1158, "text": "Assigning a string value wrapped in \" \" to a String type variable." }, { "code": null, "e": 1277, "s": 1225, "text": "String message = \"Hello Welcome to Tutorialspoint\";" }, { "code": null, "e": 1401, "s": 1277, "text": "Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor." }, { "code": null, "e": 1525, "s": 1401, "text": "Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor." }, { "code": null, "e": 1590, "s": 1525, "text": "String message = new String (\"Hello Welcome to Tutorialspoint\");" }, { "code": null, "e": 1643, "s": 1590, "text": "Passing a character array to the String constructor." }, { "code": null, "e": 1696, "s": 1643, "text": "Passing a character array to the String constructor." }, { "code": null, "e": 1766, "s": 1696, "text": "char arr[] = {'H','e','l','l','o'};\nString message = new String(arr);" } ]
Update array of objects with JavaScript?
Let’s say the following are our array of objects − var studentDetails = [ { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']}, {firstName: "David", listOfSubject: ['Java', 'C'] }] We need to add the following in the already created array of objects − {firstName: "Bob", listOfSubject: ['JavaScript']}; var studentDetails = [ { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']}, {firstName: "David", listOfSubject: ['Java', 'C']}]; updateThisObject = {firstName: "Bob", listOfSubject: ['JavaScript']}; function forLoopExample(studentObjects, updateObj){ for(var index = 0;index < studentObjects.length; index++) { if(updateObj.listOfSubject.join("") === studentObjects[index].listOfSubject.join("")) { studentObjects[index] = updateObj; return; } } studentObjects.push(updateObj); } forLoopExample(studentDetails, updateThisObject); console.log(studentDetails); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo100.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo100.js [ { firstName: 'John', listOfSubject: [ 'MySQL', 'MongoDB' ] }, { firstName: 'David', listOfSubject: [ 'Java', 'C' ] }, { firstName: 'Bob', listOfSubject: [ 'JavaScript' ] } ]
[ { "code": null, "e": 1113, "s": 1062, "text": "Let’s say the following are our array of objects −" }, { "code": null, "e": 1254, "s": 1113, "text": "var studentDetails = [\n { firstName: \"John\", listOfSubject: ['MySQL', 'MongoDB']},\n {firstName: \"David\", listOfSubject: ['Java', 'C']\n}]" }, { "code": null, "e": 1325, "s": 1254, "text": "We need to add the following in the already created array of objects −" }, { "code": null, "e": 1376, "s": 1325, "text": "{firstName: \"Bob\", listOfSubject: ['JavaScript']};" }, { "code": null, "e": 2001, "s": 1376, "text": "var studentDetails = [\n { firstName: \"John\", listOfSubject: ['MySQL', 'MongoDB']},\n {firstName: \"David\", listOfSubject: ['Java', 'C']}];\n updateThisObject = {firstName: \"Bob\", listOfSubject: ['JavaScript']};\n function forLoopExample(studentObjects, updateObj){\n for(var index = 0;index < studentObjects.length; index++) {\n if(updateObj.listOfSubject.join(\"\") ===\n studentObjects[index].listOfSubject.join(\"\")) {\n studentObjects[index] = updateObj;\n return;\n }\n }\n studentObjects.push(updateObj);\n}\nforLoopExample(studentDetails, updateThisObject);\nconsole.log(studentDetails);" }, { "code": null, "e": 2067, "s": 2001, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 2085, "s": 2067, "text": "node fileName.js." }, { "code": null, "e": 2119, "s": 2085, "text": "Here, my file name is demo100.js." }, { "code": null, "e": 2160, "s": 2119, "text": "This will produce the following output −" }, { "code": null, "e": 2395, "s": 2160, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo100.js\n[\n { firstName: 'John', listOfSubject: [ 'MySQL', 'MongoDB' ] },\n { firstName: 'David', listOfSubject: [ 'Java', 'C' ] },\n { firstName: 'Bob', listOfSubject: [ 'JavaScript' ] }\n]" } ]
How to change the size of correlation coefficient value in correlation matrix plot using corrplot in R?
The correlation coefficient value size in correlation matrix plot created by using corrplot function ranges from 0 to 1, 0 referring to the smallest and 1 referring to the largest, by default it is 1. To change this size, we need to use number.cex argument. For example, if we want to decrease the size to half then we can use number.cex = 0.5. Consider the below matrix − Live Demo set.seed(99) M<-matrix(rpois(100,10),ncol=10) M [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 10 10 14 14 7 9 14 14 13 10 [2,] 11 8 9 13 9 9 5 12 7 6 [3,] 10 12 6 11 5 8 10 4 11 15 [4,] 11 7 12 9 5 10 7 10 10 9 [5,] 8 8 8 16 8 6 7 14 12 8 [6,] 10 4 5 10 6 8 14 9 14 11 [7,] 7 12 9 4 14 18 7 12 12 9 [8,] 11 16 8 6 18 12 9 9 10 16 [9,] 5 9 11 13 8 10 12 10 10 9 [10,] 7 14 13 9 7 10 10 15 11 16 Loading corrplot package and creating a correlation matrix plot − library(corrplot) > corrplot(cor(M),addCoef.col="black") Changing the size of correlation coefficient value to 0.75 − corrplot(cor(M),addCoef.col="black",number.cex=0.75) Changing the size of correlation coefficient value to 0.30 − > corrplot(cor(M),addCoef.col="black",number.cex=0.30)
[ { "code": null, "e": 1407, "s": 1062, "text": "The correlation coefficient value size in correlation matrix plot created by using corrplot function ranges from 0 to 1, 0 referring to the smallest and 1 referring to the largest, by default it is 1. To change this size, we need to use number.cex argument. For example, if we want to decrease the size to half then we can use number.cex = 0.5." }, { "code": null, "e": 1435, "s": 1407, "text": "Consider the below matrix −" }, { "code": null, "e": 1446, "s": 1435, "text": " Live Demo" }, { "code": null, "e": 1494, "s": 1446, "text": "set.seed(99)\nM<-matrix(rpois(100,10),ncol=10)\nM" }, { "code": null, "e": 2144, "s": 1494, "text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 10 10 14 14 7 9 14 14 13 10\n[2,] 11 8 9 13 9 9 5 12 7 6\n[3,] 10 12 6 11 5 8 10 4 11 15\n[4,] 11 7 12 9 5 10 7 10 10 9\n[5,] 8 8 8 16 8 6 7 14 12 8\n[6,] 10 4 5 10 6 8 14 9 14 11\n[7,] 7 12 9 4 14 18 7 12 12 9\n[8,] 11 16 8 6 18 12 9 9 10 16\n[9,] 5 9 11 13 8 10 12 10 10 9\n[10,] 7 14 13 9 7 10 10 15 11 16" }, { "code": null, "e": 2210, "s": 2144, "text": "Loading corrplot package and creating a correlation matrix plot −" }, { "code": null, "e": 2267, "s": 2210, "text": "library(corrplot) > corrplot(cor(M),addCoef.col=\"black\")" }, { "code": null, "e": 2328, "s": 2267, "text": "Changing the size of correlation coefficient value to 0.75 −" }, { "code": null, "e": 2381, "s": 2328, "text": "corrplot(cor(M),addCoef.col=\"black\",number.cex=0.75)" }, { "code": null, "e": 2442, "s": 2381, "text": "Changing the size of correlation coefficient value to 0.30 −" }, { "code": null, "e": 2497, "s": 2442, "text": "> corrplot(cor(M),addCoef.col=\"black\",number.cex=0.30)" } ]
How to add transition on hover with CSS?
To add transition with hover on CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; } .scaleBtn { display: inline-block; background-color: #0c1377; border: none; color: white; padding: 16px 32px; text-align: center; font-size: 16px; transition: 0.3s; margin: 20px; } .scaleBtn:hover { transform: scale(1.5); } </style> </head> <body> <h1>Transition on hover example</h1> <button class="scaleBtn">Hover Here</button> </body> </html> The above code will produce the following output − On hovering above the “Hover Here” button −
[ { "code": null, "e": 1124, "s": 1062, "text": "To add transition with hover on CSS, the code is as follows −" }, { "code": null, "e": 1135, "s": 1124, "text": " Live Demo" }, { "code": null, "e": 1766, "s": 1135, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n padding: 20px;\n }\n .scaleBtn {\n display: inline-block;\n background-color: #0c1377;\n border: none;\n color: white;\n padding: 16px 32px;\n text-align: center;\n font-size: 16px;\n transition: 0.3s;\n margin: 20px;\n }\n .scaleBtn:hover {\n transform: scale(1.5);\n }\n</style>\n</head>\n<body>\n<h1>Transition on hover example</h1>\n<button class=\"scaleBtn\">Hover Here</button>\n</body>\n</html>" }, { "code": null, "e": 1817, "s": 1766, "text": "The above code will produce the following output −" }, { "code": null, "e": 1861, "s": 1817, "text": "On hovering above the “Hover Here” button −" } ]
Everything You Need to Know about Indexing in Python | by Emmett Boudreau | Towards Data Science
In general-purpose programming, it is quite common to work with data structures. Data structures are types that are composed of smaller data-types. An example of a data structure is list, or a dictionary. Data structures allow us to organize and work with several components conveniently as members of the same consistent variable. As you might imagine, this makes data structures a very important component in Data Science. Given that data structures are made of smaller components, there surely is a way to access individual components based on some feature. For this, we use indexing. Indexing is important because it allows us to call a portion of a data structure quite effortlessly in order to work with components inside of a structure individually. Of course, this is a very important thing to master for Data Science, as it is probably quite frequently that a Data Scientist is going to be working with data structures. Notebook Before we get into working with indexes, let us look at what types can actually be indexed. In the Python programming language, types can be attributed the ability to be indexed using the __getitem__() method in a given class. This means that we can apply the indexing methodology to any sort of types by simply adding this method with an accurate return. To try this, we will first make a class. Consider the following example: class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third Now we can add the __getitem__() method to this new class. This will add the ability to easily get our placements out of the class using simple indexes. def __getitem__(self, x): For this example, I thought the best method of attack was to create a dictionary on the initialization of this class’s constructor. With this method, we will be able to simply call indexes of the dictionary based on numbers in order to receive the placements for this race. class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third self.index = dict({1 : self.first, 2 : self.second, 3 : self.third}) Now finally, we will finish off our __getitem__() method by simply calling the dictionary key with the number provided: class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third self.index = dict({1 : self.first, 2 : self.second, 3 : self.third}) def __getitem__(self, x): return(self.index[x]) While this is certainly fine, let us remember that we are only logging winners here, so anyone beyond the point of 4 is not contained in this class. That in mind, if we were to call the index of 4 on this class, we would get a KeyError in return. Whenever we create software, especially in classes that users of our software likely will not ever look at, we will want to make throws to make errors a little more obvious than that. That in mind, we will add a try and catch into this method in order to print out a more detailed error. The final result looks a little something like this: class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third self.index = dict({1 : self.first, 2 : self.second, 3 : self.third}) def __getitem__(self, x): try: return(self.index[x]) except KeyError: print("""KeyError!\nOnly keys 1-3 are stored in this class!""") Now let us try and index this type. First of course we will need to initialize a new instance of this object, then we will index it. This is done with the [] syntax: race_winners = Winners("Nancy", "Bobby", "Reagan") First let us try to index it with a 4 in order to see what kind of return we get! race_winners[4]KeyError!Only keys 1-3 are stored in this class! And now we will print 1:3 in the indexes of this class: print(race_winners[1])print(race_winners[2])print(race_winners[3])NancyBobbyReagan The Python programming language comes with several data-types and data-structures that can be indexed right off the bat. The first that we are to take a look at in this article is the dictionary data structure. dct = dict({"A" : [5, 10, 15], "B" : [5, 10, 15]}) We can index a dictionary using a corresponding dictionary key. This will give us the value pair for this given key. Which conveniently will give us our next data structure, the list: lst = dct["A"] A list can be indexed with the position of the element we would like to access. For example, the second element of our new lst list is ten. We can call on this ten using lst[1] Of course, this is one, not two, as indexes start at zero in Python. Needless to say, with lists indexes can certainly come in handy. Another type we can index is a string: "Hello"[1]'e' Equally as important as calling indexes is setting indexes. Setting indexes allows us to not only create new positions on lists and other iterable data-structures, but also alter existing values inside of data structures. Additionally, we can push keys into dictionaries, add columns to Pandas dataframes, and more using this method. In Python, index setting calls the __setitem__() method. Let us go ahead and write a function for this: def __setitem__(self, x, y): pass Now we will write a bit of logic into this new function, allowing it to set a corresponding dictionary key’s value into our new input value: def __setitem__(self, x, y):self.index[x] = y Now we can set indexes of our race positions to new values: print(race_winners.index.values())dict_values(['Nancy', 'Bobby', 'Reagan'])race_winners[2] = "John"print(race_winners.index.values())dict_values(['Nancy', 'John', 'Reagan']) Of course, this same exact concept applies for all of the data-structures in Python. We can apply this to lists, dictionary values, but NOT strings as follows: z = [5, 10]z[1] = 1d = dict({"h" : 5, "z" : 6})d["z"] = 5assert d["z"] == d["h"]assert z[1] < z[0] Now that we understand the basics of indexing, let us look a bit into some vital functions we might want to use when working with data structures. Many of these functions are incredibly useful for working with copious amounts of data. It should be noted that these are primarily for lists and matrices, though some functions might work on other structures. This will be the list we are going to work with for these functions: lst = [5, 1, 6, 4, 5, 7, 3,5, 4, 3, 1, 2, 3, 4,] The first useful function is insert. Insert will allow you to place any value at any index in an array. This can be useful if you want a specific array to contain a specific component in a location. It is very easy to use, just add the two arguments, position and then the value that you wish to add. lst.insert(5, 3) The next function is the append function. This function is very frequently used to generate lists, usually in iteration. This will add a value to the next available index, and only requires a single value as an argument. lst.append(5) While a better method for this particular case might be lambda with mapping, or perhaps the apply method if this were a series type, in this case I will use an iterative loop and the append function in order to demonstrate how it can be used in this way: lst2 = []for z in lst: lst2.append(z * 3 + 2) Remove will remove a value from a given list. Note that this takes a value, not an index! It will also only remove only one instance of the given value. lst.remove(1) The extend function is essentially just the append() method, but allows us to append a list to the end of our list: lst.extend([101, 503]) Count will return an integer that is a count of all instances of an element in a given list. lst.count(5)4 A great example of a use case for this function is calculating the mode. Observe how I use count and a dictionary to get the mode in an iterative loop: digit_n = {}for x in set(lst): cnt = lst.count(x) digit_n[cnt] = x mode = digit_n[max(digit_n.keys())]print(mode)5 The last vital list function I wanted to discuss is the sort() function. This function takes no parameters, and will sort a list logically, or as specified with key-word arguments. In the following example, I use sort to find the median of our list: lst.sort()medianindex = int(len(lst) / 2)print(medianindex)print(lst[medianindex]) Needless to say, indexing is an important thing to know well when it comes to writing just about any code involving data. The standard functions of the list class can also come in handy very frequently for manipulating, creating, and getting insights from data. I think this is just about all anyone could want to know about indexing in Python. Thank you very much for reading, and I hope you have a wonderful rest of your day or night!
[ { "code": null, "e": 760, "s": 172, "text": "In general-purpose programming, it is quite common to work with data structures. Data structures are types that are composed of smaller data-types. An example of a data structure is list, or a dictionary. Data structures allow us to organize and work with several components conveniently as members of the same consistent variable. As you might imagine, this makes data structures a very important component in Data Science. Given that data structures are made of smaller components, there surely is a way to access individual components based on some feature. For this, we use indexing." }, { "code": null, "e": 1101, "s": 760, "text": "Indexing is important because it allows us to call a portion of a data structure quite effortlessly in order to work with components inside of a structure individually. Of course, this is a very important thing to master for Data Science, as it is probably quite frequently that a Data Scientist is going to be working with data structures." }, { "code": null, "e": 1110, "s": 1101, "text": "Notebook" }, { "code": null, "e": 1539, "s": 1110, "text": "Before we get into working with indexes, let us look at what types can actually be indexed. In the Python programming language, types can be attributed the ability to be indexed using the __getitem__() method in a given class. This means that we can apply the indexing methodology to any sort of types by simply adding this method with an accurate return. To try this, we will first make a class. Consider the following example:" }, { "code": null, "e": 1674, "s": 1539, "text": "class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third" }, { "code": null, "e": 1827, "s": 1674, "text": "Now we can add the __getitem__() method to this new class. This will add the ability to easily get our placements out of the class using simple indexes." }, { "code": null, "e": 1853, "s": 1827, "text": "def __getitem__(self, x):" }, { "code": null, "e": 2127, "s": 1853, "text": "For this example, I thought the best method of attack was to create a dictionary on the initialization of this class’s constructor. With this method, we will be able to simply call indexes of the dictionary based on numbers in order to receive the placements for this race." }, { "code": null, "e": 2363, "s": 2127, "text": "class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third self.index = dict({1 : self.first, 2 : self.second, 3 : self.third})" }, { "code": null, "e": 2483, "s": 2363, "text": "Now finally, we will finish off our __getitem__() method by simply calling the dictionary key with the number provided:" }, { "code": null, "e": 2791, "s": 2483, "text": "class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third self.index = dict({1 : self.first, 2 : self.second, 3 : self.third}) def __getitem__(self, x): return(self.index[x])" }, { "code": null, "e": 3379, "s": 2791, "text": "While this is certainly fine, let us remember that we are only logging winners here, so anyone beyond the point of 4 is not contained in this class. That in mind, if we were to call the index of 4 on this class, we would get a KeyError in return. Whenever we create software, especially in classes that users of our software likely will not ever look at, we will want to make throws to make errors a little more obvious than that. That in mind, we will add a try and catch into this method in order to print out a more detailed error. The final result looks a little something like this:" }, { "code": null, "e": 3805, "s": 3379, "text": "class Winners: def __init__(self, first, second, third): self.first, self.second = first, second self.third = third self.index = dict({1 : self.first, 2 : self.second, 3 : self.third}) def __getitem__(self, x): try: return(self.index[x]) except KeyError: print(\"\"\"KeyError!\\nOnly keys 1-3 are stored in this class!\"\"\")" }, { "code": null, "e": 3971, "s": 3805, "text": "Now let us try and index this type. First of course we will need to initialize a new instance of this object, then we will index it. This is done with the [] syntax:" }, { "code": null, "e": 4022, "s": 3971, "text": "race_winners = Winners(\"Nancy\", \"Bobby\", \"Reagan\")" }, { "code": null, "e": 4104, "s": 4022, "text": "First let us try to index it with a 4 in order to see what kind of return we get!" }, { "code": null, "e": 4168, "s": 4104, "text": "race_winners[4]KeyError!Only keys 1-3 are stored in this class!" }, { "code": null, "e": 4224, "s": 4168, "text": "And now we will print 1:3 in the indexes of this class:" }, { "code": null, "e": 4307, "s": 4224, "text": "print(race_winners[1])print(race_winners[2])print(race_winners[3])NancyBobbyReagan" }, { "code": null, "e": 4518, "s": 4307, "text": "The Python programming language comes with several data-types and data-structures that can be indexed right off the bat. The first that we are to take a look at in this article is the dictionary data structure." }, { "code": null, "e": 4569, "s": 4518, "text": "dct = dict({\"A\" : [5, 10, 15], \"B\" : [5, 10, 15]})" }, { "code": null, "e": 4753, "s": 4569, "text": "We can index a dictionary using a corresponding dictionary key. This will give us the value pair for this given key. Which conveniently will give us our next data structure, the list:" }, { "code": null, "e": 4768, "s": 4753, "text": "lst = dct[\"A\"]" }, { "code": null, "e": 4938, "s": 4768, "text": "A list can be indexed with the position of the element we would like to access. For example, the second element of our new lst list is ten. We can call on this ten using" }, { "code": null, "e": 4945, "s": 4938, "text": "lst[1]" }, { "code": null, "e": 5118, "s": 4945, "text": "Of course, this is one, not two, as indexes start at zero in Python. Needless to say, with lists indexes can certainly come in handy. Another type we can index is a string:" }, { "code": null, "e": 5132, "s": 5118, "text": "\"Hello\"[1]'e'" }, { "code": null, "e": 5570, "s": 5132, "text": "Equally as important as calling indexes is setting indexes. Setting indexes allows us to not only create new positions on lists and other iterable data-structures, but also alter existing values inside of data structures. Additionally, we can push keys into dictionaries, add columns to Pandas dataframes, and more using this method. In Python, index setting calls the __setitem__() method. Let us go ahead and write a function for this:" }, { "code": null, "e": 5607, "s": 5570, "text": "def __setitem__(self, x, y): pass" }, { "code": null, "e": 5748, "s": 5607, "text": "Now we will write a bit of logic into this new function, allowing it to set a corresponding dictionary key’s value into our new input value:" }, { "code": null, "e": 5794, "s": 5748, "text": "def __setitem__(self, x, y):self.index[x] = y" }, { "code": null, "e": 5854, "s": 5794, "text": "Now we can set indexes of our race positions to new values:" }, { "code": null, "e": 6028, "s": 5854, "text": "print(race_winners.index.values())dict_values(['Nancy', 'Bobby', 'Reagan'])race_winners[2] = \"John\"print(race_winners.index.values())dict_values(['Nancy', 'John', 'Reagan'])" }, { "code": null, "e": 6188, "s": 6028, "text": "Of course, this same exact concept applies for all of the data-structures in Python. We can apply this to lists, dictionary values, but NOT strings as follows:" }, { "code": null, "e": 6287, "s": 6188, "text": "z = [5, 10]z[1] = 1d = dict({\"h\" : 5, \"z\" : 6})d[\"z\"] = 5assert d[\"z\"] == d[\"h\"]assert z[1] < z[0]" }, { "code": null, "e": 6713, "s": 6287, "text": "Now that we understand the basics of indexing, let us look a bit into some vital functions we might want to use when working with data structures. Many of these functions are incredibly useful for working with copious amounts of data. It should be noted that these are primarily for lists and matrices, though some functions might work on other structures. This will be the list we are going to work with for these functions:" }, { "code": null, "e": 6762, "s": 6713, "text": "lst = [5, 1, 6, 4, 5, 7, 3,5, 4, 3, 1, 2, 3, 4,]" }, { "code": null, "e": 7063, "s": 6762, "text": "The first useful function is insert. Insert will allow you to place any value at any index in an array. This can be useful if you want a specific array to contain a specific component in a location. It is very easy to use, just add the two arguments, position and then the value that you wish to add." }, { "code": null, "e": 7080, "s": 7063, "text": "lst.insert(5, 3)" }, { "code": null, "e": 7301, "s": 7080, "text": "The next function is the append function. This function is very frequently used to generate lists, usually in iteration. This will add a value to the next available index, and only requires a single value as an argument." }, { "code": null, "e": 7315, "s": 7301, "text": "lst.append(5)" }, { "code": null, "e": 7570, "s": 7315, "text": "While a better method for this particular case might be lambda with mapping, or perhaps the apply method if this were a series type, in this case I will use an iterative loop and the append function in order to demonstrate how it can be used in this way:" }, { "code": null, "e": 7620, "s": 7570, "text": "lst2 = []for z in lst: lst2.append(z * 3 + 2)" }, { "code": null, "e": 7773, "s": 7620, "text": "Remove will remove a value from a given list. Note that this takes a value, not an index! It will also only remove only one instance of the given value." }, { "code": null, "e": 7787, "s": 7773, "text": "lst.remove(1)" }, { "code": null, "e": 7903, "s": 7787, "text": "The extend function is essentially just the append() method, but allows us to append a list to the end of our list:" }, { "code": null, "e": 7926, "s": 7903, "text": "lst.extend([101, 503])" }, { "code": null, "e": 8019, "s": 7926, "text": "Count will return an integer that is a count of all instances of an element in a given list." }, { "code": null, "e": 8033, "s": 8019, "text": "lst.count(5)4" }, { "code": null, "e": 8185, "s": 8033, "text": "A great example of a use case for this function is calculating the mode. Observe how I use count and a dictionary to get the mode in an iterative loop:" }, { "code": null, "e": 8310, "s": 8185, "text": "digit_n = {}for x in set(lst): cnt = lst.count(x) digit_n[cnt] = x mode = digit_n[max(digit_n.keys())]print(mode)5" }, { "code": null, "e": 8560, "s": 8310, "text": "The last vital list function I wanted to discuss is the sort() function. This function takes no parameters, and will sort a list logically, or as specified with key-word arguments. In the following example, I use sort to find the median of our list:" }, { "code": null, "e": 8643, "s": 8560, "text": "lst.sort()medianindex = int(len(lst) / 2)print(medianindex)print(lst[medianindex])" } ]
How to use Thread in Tkinter Python?
With Tkinter, we can call multiple functions at a time using Threading. It provides asynchronous execution of some functions in an application. In order to use a thread in Python, we can import a module called threading and subclass its Thread class. Inside our new class, we need to overwrite the Run method and perform our logic in there. So, basically with threading, we can do multiple work at a time. To achieve threading in our application, Tkinter provides the Thread() function. Let us take an example and create a thread which will sleep for some time and then execute another function in parallel. For this example, we will import the Time module and the threading module defined in the Tkinter library. #Import all the necessary libraries from tkinter import * import time import threading #Define the tkinter instance win= Tk() #Define the size of the tkinter frame win.geometry("700x400") #Define the function to start the thread def thread_fun(): label.config(text="You can Click the button or Wait") time.sleep(5) label.config(text= "5 seconds Up!") label= Label(win) label.pack(pady=20) #Create button b1= Button(win,text= "Start", command=threading.Thread(target=thread_fun).start()) b1.pack(pady=20) win.mainloop() Running the above code will create a button and a thread which works on a label. After 5 seconds, the thread will automatically pause.
[ { "code": null, "e": 1331, "s": 1187, "text": "With Tkinter, we can call multiple functions at a time using Threading. It provides\nasynchronous execution of some functions in an application." }, { "code": null, "e": 1528, "s": 1331, "text": "In order to use a thread in Python, we can import a module called threading and subclass its Thread class. Inside our new class, we need to overwrite the Run method and perform our logic in there." }, { "code": null, "e": 1674, "s": 1528, "text": "So, basically with threading, we can do multiple work at a time. To achieve threading in our application, Tkinter provides the Thread() function." }, { "code": null, "e": 1795, "s": 1674, "text": "Let us take an example and create a thread which will sleep for some time and then\nexecute another function in parallel." }, { "code": null, "e": 1901, "s": 1795, "text": "For this example, we will import the Time module and the threading module defined in the Tkinter library." }, { "code": null, "e": 2437, "s": 1901, "text": "#Import all the necessary libraries\nfrom tkinter import *\nimport time\nimport threading\n\n#Define the tkinter instance\nwin= Tk()\n\n#Define the size of the tkinter frame\nwin.geometry(\"700x400\")\n\n#Define the function to start the thread\ndef thread_fun():\n label.config(text=\"You can Click the button or Wait\")\n time.sleep(5)\n label.config(text= \"5 seconds Up!\")\n \nlabel= Label(win)\nlabel.pack(pady=20)\n#Create button\nb1= Button(win,text= \"Start\", command=threading.Thread(target=thread_fun).start())\nb1.pack(pady=20)\n\nwin.mainloop()" }, { "code": null, "e": 2518, "s": 2437, "text": "Running the above code will create a button and a thread which works on a label." }, { "code": null, "e": 2572, "s": 2518, "text": "After 5 seconds, the thread will automatically pause." } ]
JavaScript RangeError | Precision is out of range
22 Jul, 2020 This JavaScript exception precision is out of range occurs if a number which is outside the range of 0 and 20 (or 21) is passed into toFixed(), toPrecision(), or toExponential() method. Error Message: RangeError: The number of fractional digits is out of range (Edge)RangeError: The precision is out of range (Edge)RangeError: precision {0} out of range (Firefox)RangeError: toExponential() argument must be between 0 and 20 (Chrome)RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)RangeError: toPrecision() argument must be between 1 and 21 (Chrome) Error Type: RangeError What Happened? There is a precision argument that is out of range in one of the methods, toExponential(), toFixed(), and toPrecision(). Example 1: In this example, the RangeError occurred as -100 to toFixed() is passed. HTML <!DOCTYPE HTML><html> <head> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> JavaScript RangeError | Precision is out of range </p> <button onclick="Geeks();"> click here </button> <p id="GFG_DOWN"></p> <script> var el_down = document.getElementById("GFG_DOWN"); function Geeks() { try { 3.54.toFixed(-100); el_down.innerHTML = "'Precision out of range'" + " error has not occurred"; } catch (e) { el_down.innerHTML = "'Precision out of range'" + " error has occurred"; } } </script></body> </html> Output: Example 2: In this example, the argument passed to toExponential() is -4, So the RangeError has occurred. HTML <!DOCTYPE HTML><html> <head> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> JavaScript RangeError | Precision is out of range </p> <button onclick="Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_down = document.getElementById("GFG_DOWN"); function Geeks() { try { 77.1234.toExponential(-4); el_down.innerHTML = "'Precision out of range'" + " error has not occurred"; } catch (e) { el_down.innerHTML = "'Precision out of range'" + " error has occurred"; } } </script></body> </html> Output: Example 3: In this example, the RangeError occurred as -1 to toPrecision() is passed. HTML <!DOCTYPE HTML><html> <head> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> JavaScript RangeError | Precision is out of range </p> <button onclick="Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_down = document.getElementById("GFG_DOWN"); function Geeks() { try { 5643.9.toPrecision(-1); el_down.innerHTML = "'Precision out of range'" + " error has not occurred"; } catch (e) { el_down.innerHTML = "'Precision out of range'" + " error has occurred"; } } </script></body> </html> Output: JavaScript-Misc 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": "\n22 Jul, 2020" }, { "code": null, "e": 214, "s": 28, "text": "This JavaScript exception precision is out of range occurs if a number which is outside the range of 0 and 20 (or 21) is passed into toFixed(), toPrecision(), or toExponential() method." }, { "code": null, "e": 229, "s": 214, "text": "Error Message:" }, { "code": null, "e": 601, "s": 229, "text": "RangeError: The number of fractional digits is out of range (Edge)RangeError: The precision is out of range (Edge)RangeError: precision {0} out of range (Firefox)RangeError: toExponential() argument must be between 0 and 20 (Chrome)RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)RangeError: toPrecision() argument must be between 1 and 21 (Chrome)" }, { "code": null, "e": 613, "s": 601, "text": "Error Type:" }, { "code": null, "e": 624, "s": 613, "text": "RangeError" }, { "code": null, "e": 639, "s": 624, "text": "What Happened?" }, { "code": null, "e": 760, "s": 639, "text": "There is a precision argument that is out of range in one of the methods, toExponential(), toFixed(), and toPrecision()." }, { "code": null, "e": 844, "s": 760, "text": "Example 1: In this example, the RangeError occurred as -100 to toFixed() is passed." }, { "code": null, "e": 849, "s": 844, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> JavaScript RangeError | Precision is out of range </p> <button onclick=\"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"></p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function Geeks() { try { 3.54.toFixed(-100); el_down.innerHTML = \"'Precision out of range'\" + \" error has not occurred\"; } catch (e) { el_down.innerHTML = \"'Precision out of range'\" + \" error has occurred\"; } } </script></body> </html>", "e": 1667, "s": 849, "text": null }, { "code": null, "e": 1675, "s": 1667, "text": "Output:" }, { "code": null, "e": 1781, "s": 1675, "text": "Example 2: In this example, the argument passed to toExponential() is -4, So the RangeError has occurred." }, { "code": null, "e": 1786, "s": 1781, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> JavaScript RangeError | Precision is out of range </p> <button onclick=\"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function Geeks() { try { 77.1234.toExponential(-4); el_down.innerHTML = \"'Precision out of range'\" + \" error has not occurred\"; } catch (e) { el_down.innerHTML = \"'Precision out of range'\" + \" error has occurred\"; } } </script></body> </html>", "e": 2621, "s": 1786, "text": null }, { "code": null, "e": 2629, "s": 2621, "text": "Output:" }, { "code": null, "e": 2715, "s": 2629, "text": "Example 3: In this example, the RangeError occurred as -1 to toPrecision() is passed." }, { "code": null, "e": 2720, "s": 2715, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> JavaScript RangeError | Precision is out of range </p> <button onclick=\"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function Geeks() { try { 5643.9.toPrecision(-1); el_down.innerHTML = \"'Precision out of range'\" + \" error has not occurred\"; } catch (e) { el_down.innerHTML = \"'Precision out of range'\" + \" error has occurred\"; } } </script></body> </html>", "e": 3552, "s": 2720, "text": null }, { "code": null, "e": 3560, "s": 3552, "text": "Output:" }, { "code": null, "e": 3576, "s": 3560, "text": "JavaScript-Misc" }, { "code": null, "e": 3587, "s": 3576, "text": "JavaScript" }, { "code": null, "e": 3604, "s": 3587, "text": "Web Technologies" } ]
Overloading New and Delete operator in c++
26 Jan, 2022 The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class. If overloading is done outside a class (i.e. it is not a member function of a class), the overloaded ‘new’ and ‘delete’ will be called anytime you make use of these operators (within classes or outside classes). This is global overloading. Syntax for overloading the new operator : void* operator new(size_t size); The overloaded new operator receives size of type size_t, which specifies the number of bytes of memory to be allocated. The return type of the overloaded new must be void*.The overloaded function returns a pointer to the beginning of the block of memory allocated.Syntax for overloading the delete operator : void operator delete(void*); The function receives a parameter of type void* which has to be deleted. Function should not return anything. NOTE: Both overloaded new and delete operator functions are static members by default. Therefore, they don’t have access to this pointer .Overloading new and delete operator for a specific class: CPP // CPP program to demonstrate// Overloading new and delete operator// for a specific class#include<iostream>#include<stdlib.h> using namespace std;class student{ string name; int age;public: student() { cout<< "Constructor is called\n" ; } student(string name, int age) { this->name = name; this->age = age; } void display() { cout<< "Name:" << name << endl; cout<< "Age:" << age << endl; } void * operator new(size_t size) { cout<< "Overloading new operator with size: " << size << endl; void * p = ::operator new(size); //void * p = malloc(size); will also work fine return p; } void operator delete(void * p) { cout<< "Overloading delete operator " << endl; free(p); }}; int main(){ student * p = new student("Yash", 24); p->display(); delete p;} Overloading new operator with size: 40 Name:Yash Age:24 Overloading delete operator NOTE: In the above new overloaded function, we have allocated dynamic memory through new operator, but it should be global new operator otherwise it will go in recursion void *p = new student(); // this will go in recursion asnew will be overloaded again and again void *p = ::new student(); // this is correct Global overloading of new and delete operator CPP // CPP program to demonstrate// Global overloading of// new and delete operator#include<iostream>#include<stdlib.h> using namespace std;void * operator new(size_t size){ cout << "New operator overloading " << endl; void * p = malloc(size); return p;} void operator delete(void * p){ cout << "Delete operator overloading " << endl; free(p);} int main(){ int n = 5, i; int * p = new int[3]; for (i = 0; i<n; i++) p[i]= i; cout << "Array: "; for(i = 0; i<n; i++) cout << p[i] << " "; cout << endl; delete [] p;} New operator overloading Array: 0 1 2 3 4 Delete operator overloading NOTE: In the code above, in new overloaded function we cannot allocate memory using ::new int[5] as it will go in recursion. We need to allocate memory using malloc only. Why to overload new and delete? 1. The overloaded new operator function can accept arguments; therefore, a class can have multiple overloaded new operator functions. This gives the programmer more flexibility in customizing memory allocation for objects. For example: C void *operator new(size_t size, char c){ void *ptr; ptr = malloc(size); if (ptr!=NULL) *ptr = c;return ptr;}main(){ char *ch = new('#') char;} 2. NOTE: Code will not only allocate memory for single character but will also initialize the allocated memory with # character. 3. Overloaded new or delete operators also provide Garbage Collection for class’s object. 4. Exception handling routine can be added in overloaded new operator function. 5. Sometimes you want operators new and delete to do something customized that the compiler-provided versions don’t offer. For example, You might write a custom operator delete that overwrites deallocated memory with zeros in order to increase the security of application data. 6. We can use realloc() function in new function to re-allocate memory dynamically. 7. Overloaded new operator also enables programmers to squeeze some extra performance out of their programs. For example, In a class, to speed up the allocation of new nodes, a list of deleted nodes is maintained so that their memory can be reused when new nodes are allocated.In this case, the overloaded delete operator will add nodes to the list of deleted nodes and the overloaded new operator will allocate memory from this list rather than from the heap to speedup memory allocation. Memory from the heap can be used when the list of deleted nodes is empty. This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. JamesHammer nirbhay.kr07 whitenoise cpp-operator-overloading cpp-overloading Dynamic Memory Allocation 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++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) vector insert() function in C++ STL
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Jan, 2022" }, { "code": null, "e": 236, "s": 54, "text": "The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes. " }, { "code": null, "e": 380, "s": 236, "text": "If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class." }, { "code": null, "e": 620, "s": 380, "text": "If overloading is done outside a class (i.e. it is not a member function of a class), the overloaded ‘new’ and ‘delete’ will be called anytime you make use of these operators (within classes or outside classes). This is global overloading." }, { "code": null, "e": 663, "s": 620, "text": "Syntax for overloading the new operator : " }, { "code": null, "e": 696, "s": 663, "text": "void* operator new(size_t size);" }, { "code": null, "e": 1008, "s": 696, "text": "The overloaded new operator receives size of type size_t, which specifies the number of bytes of memory to be allocated. The return type of the overloaded new must be void*.The overloaded function returns a pointer to the beginning of the block of memory allocated.Syntax for overloading the delete operator : " }, { "code": null, "e": 1037, "s": 1008, "text": "void operator delete(void*);" }, { "code": null, "e": 1343, "s": 1037, "text": "The function receives a parameter of type void* which has to be deleted. Function should not return anything. NOTE: Both overloaded new and delete operator functions are static members by default. Therefore, they don’t have access to this pointer .Overloading new and delete operator for a specific class:" }, { "code": null, "e": 1347, "s": 1343, "text": "CPP" }, { "code": "// CPP program to demonstrate// Overloading new and delete operator// for a specific class#include<iostream>#include<stdlib.h> using namespace std;class student{ string name; int age;public: student() { cout<< \"Constructor is called\\n\" ; } student(string name, int age) { this->name = name; this->age = age; } void display() { cout<< \"Name:\" << name << endl; cout<< \"Age:\" << age << endl; } void * operator new(size_t size) { cout<< \"Overloading new operator with size: \" << size << endl; void * p = ::operator new(size); //void * p = malloc(size); will also work fine return p; } void operator delete(void * p) { cout<< \"Overloading delete operator \" << endl; free(p); }}; int main(){ student * p = new student(\"Yash\", 24); p->display(); delete p;}", "e": 2241, "s": 1347, "text": null }, { "code": null, "e": 2327, "s": 2241, "text": "Overloading new operator with size: 40\nName:Yash\nAge:24\nOverloading delete operator \n" }, { "code": null, "e": 2638, "s": 2327, "text": "NOTE: In the above new overloaded function, we have allocated dynamic memory through new operator, but it should be global new operator otherwise it will go in recursion void *p = new student(); // this will go in recursion asnew will be overloaded again and again void *p = ::new student(); // this is correct" }, { "code": null, "e": 2685, "s": 2638, "text": "Global overloading of new and delete operator " }, { "code": null, "e": 2689, "s": 2685, "text": "CPP" }, { "code": "// CPP program to demonstrate// Global overloading of// new and delete operator#include<iostream>#include<stdlib.h> using namespace std;void * operator new(size_t size){ cout << \"New operator overloading \" << endl; void * p = malloc(size); return p;} void operator delete(void * p){ cout << \"Delete operator overloading \" << endl; free(p);} int main(){ int n = 5, i; int * p = new int[3]; for (i = 0; i<n; i++) p[i]= i; cout << \"Array: \"; for(i = 0; i<n; i++) cout << p[i] << \" \"; cout << endl; delete [] p;}", "e": 3256, "s": 2689, "text": null }, { "code": null, "e": 3330, "s": 3256, "text": "New operator overloading \nArray: 0 1 2 3 4 \nDelete operator overloading \n" }, { "code": null, "e": 3502, "s": 3330, "text": "NOTE: In the code above, in new overloaded function we cannot allocate memory using ::new int[5] as it will go in recursion. We need to allocate memory using malloc only. " }, { "code": null, "e": 3535, "s": 3502, "text": "Why to overload new and delete? " }, { "code": null, "e": 3772, "s": 3535, "text": "1. The overloaded new operator function can accept arguments; therefore, a class can have multiple overloaded new operator functions. This gives the programmer more flexibility in customizing memory allocation for objects. For example: " }, { "code": null, "e": 3774, "s": 3772, "text": "C" }, { "code": "void *operator new(size_t size, char c){ void *ptr; ptr = malloc(size); if (ptr!=NULL) *ptr = c;return ptr;}main(){ char *ch = new('#') char;}", "e": 3930, "s": 3774, "text": null }, { "code": null, "e": 4060, "s": 3930, "text": "2. NOTE: Code will not only allocate memory for single character but will also initialize the allocated memory with # character. " }, { "code": null, "e": 4150, "s": 4060, "text": "3. Overloaded new or delete operators also provide Garbage Collection for class’s object." }, { "code": null, "e": 4230, "s": 4150, "text": "4. Exception handling routine can be added in overloaded new operator function." }, { "code": null, "e": 4508, "s": 4230, "text": "5. Sometimes you want operators new and delete to do something customized that the compiler-provided versions don’t offer. For example, You might write a custom operator delete that overwrites deallocated memory with zeros in order to increase the security of application data." }, { "code": null, "e": 4592, "s": 4508, "text": "6. We can use realloc() function in new function to re-allocate memory dynamically." }, { "code": null, "e": 5156, "s": 4592, "text": "7. Overloaded new operator also enables programmers to squeeze some extra performance out of their programs. For example, In a class, to speed up the allocation of new nodes, a list of deleted nodes is maintained so that their memory can be reused when new nodes are allocated.In this case, the overloaded delete operator will add nodes to the list of deleted nodes and the overloaded new operator will allocate memory from this list rather than from the heap to speedup memory allocation. Memory from the heap can be used when the list of deleted nodes is empty." }, { "code": null, "e": 5575, "s": 5156, "text": "This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5587, "s": 5575, "text": "JamesHammer" }, { "code": null, "e": 5600, "s": 5587, "text": "nirbhay.kr07" }, { "code": null, "e": 5611, "s": 5600, "text": "whitenoise" }, { "code": null, "e": 5636, "s": 5611, "text": "cpp-operator-overloading" }, { "code": null, "e": 5652, "s": 5636, "text": "cpp-overloading" }, { "code": null, "e": 5678, "s": 5652, "text": "Dynamic Memory Allocation" }, { "code": null, "e": 5682, "s": 5678, "text": "C++" }, { "code": null, "e": 5686, "s": 5682, "text": "CPP" }, { "code": null, "e": 5784, "s": 5686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5808, "s": 5784, "text": "Sorting a vector in C++" }, { "code": null, "e": 5828, "s": 5808, "text": "Polymorphism in C++" }, { "code": null, "e": 5861, "s": 5828, "text": "Friend class and function in C++" }, { "code": null, "e": 5905, "s": 5861, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 5930, "s": 5905, "text": "std::string class in C++" }, { "code": null, "e": 5975, "s": 5930, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6023, "s": 5975, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6040, "s": 6023, "text": "std::find in C++" }, { "code": null, "e": 6084, "s": 6040, "text": "List in C++ Standard Template Library (STL)" } ]
std::is_enum Template in C++
19 Nov, 2018 The std::is_enum template of C++ STL is used to check whether the given type is enum or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_enum; Parameter: This template accepts single parameter T (Trait class) to check whether T is a enumeration type or not. Return Value: This template returns a boolean value as shown below: True: if the type is a enumeration. False: if the type is a non-enumeration. Below programs illustrate the std::is_enum template in C++: Program 1:: // C++ program to illustrate// is_enum template #include <iostream>#include <type_traits>using namespace std; class GFG1 {};enum class GFG2 { var1, var2, var3, var4}; // Driver codeint main(){ cout << boolalpha; cout << "is_enum:" << endl; cout << "GFG1: " << is_enum<GFG1>::value << endl; cout << "GFG2: " << is_enum<GFG2>::value << endl; return 0;} is_enum: GFG1: false GFG2: true Program 2:: // C++ program to illustrate// is_enum template #include <iostream>#include <type_traits>using namespace std; class GFG1 {}; enum class GFG2 : int {}; // Driver codeint main(){ cout << boolalpha; cout << "is_enum:" << endl; cout << "GFG1: " << is_enum<GFG1>::value << '\n'; cout << "GFG2: " << is_enum<GFG2>::value << '\n'; cout << "int: " << is_enum<int>::value << '\n'; return 0;} is_enum: GFG1: false GFG2: true int: false C++-Templates cpp-template STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2018" }, { "code": null, "e": 166, "s": 28, "text": "The std::is_enum template of C++ STL is used to check whether the given type is enum or not. It returns a boolean value showing the same." }, { "code": null, "e": 174, "s": 166, "text": "Syntax:" }, { "code": null, "e": 209, "s": 174, "text": "template <class T> struct is_enum;" }, { "code": null, "e": 324, "s": 209, "text": "Parameter: This template accepts single parameter T (Trait class) to check whether T is a enumeration type or not." }, { "code": null, "e": 392, "s": 324, "text": "Return Value: This template returns a boolean value as shown below:" }, { "code": null, "e": 428, "s": 392, "text": "True: if the type is a enumeration." }, { "code": null, "e": 469, "s": 428, "text": "False: if the type is a non-enumeration." }, { "code": null, "e": 529, "s": 469, "text": "Below programs illustrate the std::is_enum template in C++:" }, { "code": null, "e": 541, "s": 529, "text": "Program 1::" }, { "code": "// C++ program to illustrate// is_enum template #include <iostream>#include <type_traits>using namespace std; class GFG1 {};enum class GFG2 { var1, var2, var3, var4}; // Driver codeint main(){ cout << boolalpha; cout << \"is_enum:\" << endl; cout << \"GFG1: \" << is_enum<GFG1>::value << endl; cout << \"GFG2: \" << is_enum<GFG2>::value << endl; return 0;}", "e": 979, "s": 541, "text": null }, { "code": null, "e": 1012, "s": 979, "text": "is_enum:\nGFG1: false\nGFG2: true\n" }, { "code": null, "e": 1024, "s": 1012, "text": "Program 2::" }, { "code": "// C++ program to illustrate// is_enum template #include <iostream>#include <type_traits>using namespace std; class GFG1 {}; enum class GFG2 : int {}; // Driver codeint main(){ cout << boolalpha; cout << \"is_enum:\" << endl; cout << \"GFG1: \" << is_enum<GFG1>::value << '\\n'; cout << \"GFG2: \" << is_enum<GFG2>::value << '\\n'; cout << \"int: \" << is_enum<int>::value << '\\n'; return 0;}", "e": 1453, "s": 1024, "text": null }, { "code": null, "e": 1497, "s": 1453, "text": "is_enum:\nGFG1: false\nGFG2: true\nint: false\n" }, { "code": null, "e": 1511, "s": 1497, "text": "C++-Templates" }, { "code": null, "e": 1524, "s": 1511, "text": "cpp-template" }, { "code": null, "e": 1528, "s": 1524, "text": "STL" }, { "code": null, "e": 1532, "s": 1528, "text": "C++" }, { "code": null, "e": 1536, "s": 1532, "text": "STL" }, { "code": null, "e": 1540, "s": 1536, "text": "CPP" } ]
Ulam Number Sequence
18 Aug, 2021 Given a positive integer n , the task is to print nth Number of the Ulam Number SequenceUlam Number: In Mathematics, An Ulam number is the member of an Integer sequence that starts with the term U1 = 1 and U1 = 2 and then for every n > 2, Un is defined is smallest positive integer greater than Un-1 which can be expressed as sum of two distinct earlier term of the sequence in exactly one way. For example, 3 is an Ulam Number as it can be expressed as sum of two distinct earlier terms in exactly one way ( i.e 1 + 2 ) 4 is also an Ulam number. Other than ( 1 + 3) we can express 4 as ( 2 + 2 ) but in (2 + 2) terms are not distinct. So we have only one way 5 can be expressed as sum of two distinct earlier terms of the sequence in two ways as ( 1 + 4 ) and ( 2 + 3), So, 5 is not an Ulam Number The first few terms of the Ulam number sequence are- 1, 2, 3, 4, 6, 8, 11, 13, 16, 18, 26, 28, 36, 38, 47, 48, 53, 57, 62, 69, 72, 77, 82, 87, 97, 99, 102 Examples: Input : 5 Output : 6 Input : 9 Output : 16 A Simple Solution to print nth term of the Ulam number sequence is to generate entire ulam sequence up to n and print nth term, As we can not compute nth term directly. Approach to generate ulam number sequence: As, We have first two term of the sequence as U1=1 and U2=2. we can start our search from i=3 for next Ulam number. For every value of ‘i’ traverse the earlier terms of the sequence using two loops and check if on adding two distinct term of sequence we can get sum as i in exactly one way or not If Yes, Then ‘i’ is next Ulam number, Store it. and then search for next ulam number If not, then increment ‘i’ and repeat the same Keep searching ulam number, until we get our nth term Below is the implementation of the above idea: C++ Java Python3 C# Javascript // CPP code to print nth// Ulam number #include <bits/stdc++.h>using namespace std; #define MAX 10000 // Array to store Ulam Numbervector<int> arr; // function to compute ulam Numbervoid ulam(){ // push First 2 two term of the sequence // in the array // for further calculation arr.push_back(1); arr.push_back(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size() - 1; j++) { for (int k = j + 1; k < arr.size(); k++) { if (arr[j] + arr[k] == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 1 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.push_back(i); } }} // Driver codeint main(){ // Pre compute Ulam Number sequence ulam(); int n = 9; // Print nth Ulam number cout << arr[n - 1]; return 0;} // JAVA code to print nth// Ulam number import java.util.*;class GFG { static final int MAX = 1000; // Array to store Ulam Number static Vector<Integer> arr = new Vector<Integer>(); // Function to compute ulam Number static void ulam() { // push First 2 two term of the sequence // in the array // for further calculation arr.add(1); arr.add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size() - 1; j++) { for (int k = j + 1; k < arr.size(); k++) { if (arr.get(j) + arr.get(k) == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.add(i); } } } // Driver code public static void main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number System.out.println(arr.get(n - 1)); }} # Python3 code to print nth# Ulam numberMAX = 1000 # Array to store Ulam Numberarr = [] # function to compute ulam Numberdef ulam(): # push First 2 two term of the sequence # in the array # for further calculation arr.append(1); arr.append(2); # loop to generate Ulam number for i in range(3, MAX): count = 0; # traverse the array and check if # i can be represented as sum of # two distinct element of the array for j in range(len(arr) - 1): for k in range(j + 1, len(arr)): if (arr[j] + arr[k] == i): count += 1 if (count > 1): break; if (count > 1): break; # If count is 1 that means # i can be represented as sum of # two distinct terms of the sequence if (count == 1): # i is ulam number arr.append(i); # Driver codeif __name__=='__main__': # Pre compute Ulam Number sequence ulam(); n = 9; # Print nth Ulam number print(arr[n - 1]) # This code is contributed by rutvik_56. // C# code to print nth// Ulam numberusing System;using System.Collections.Generic; class GFG{ static readonly int MAX = 1000; // Array to store Ulam Number static List<int> arr = new List<int>(); // Function to compute ulam Number static void ulam() { // push First 2 two term of // the sequence in the array // for further calculation arr.Add(1); arr.Add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.Count - 1; j++) { for (int k = j + 1; k < arr.Count; k++) { if (arr[j] + arr[k] == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.Add(i); } } } // Driver code public static void Main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number Console.WriteLine(arr[n - 1]); }} // This code is contributed by Rajput-JI <script>// Javascript code to print nth// Ulam number var MAX = 10000; // Array to store Ulam Numbervar arr = []; // function to compute ulam Numberfunction ulam(){ // push First 2 two term of the sequence // in the array // for further calculation arr.push(1); arr.push(2); // loop to generate Ulam number for (var i = 3; i < MAX; i++) { var count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (var j = 0; j < arr.length - 1; j++) { for (var k = j + 1; k < arr.length; k++) { if (arr[j] + arr[k] == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 1 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.push(i); } }} // Driver code// Pre compute Ulam Number sequenceulam();var n = 9; // Print nth Ulam numberdocument.write( arr[n - 1]); // This code is contributed by noob2000.</script> 16 An Efficient solution is to use a hash table to store the earlier number of the sequence so that instead of using two loops to check if ‘i’ can be expressed as the sum of two distinct terms in exactly one way or not, we can do it in a single loop. Searching will be fast if we will use a hash table. Below is the Implementation of above idea: C++ Java Python3 C# // Cpp code to print nth// Ulam number #include <bits/stdc++.h>using namespace std; #define MAX 10000 // Array to store Ulam Numbervector<int> arr; // function to compute ulam Numbervoid ulam(){ // Set to search specific Ulam number efficiently unordered_set<int> s; // push First 2 two term of the sequence // in the array and set // for further calculation arr.push_back(1); s.insert(1); arr.push_back(2); s.insert(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size(); j++) { // Check if i-arr[j] exist in the array or not using set // If yes, Then i can be represented as // sum of arr[j] + (i- arr[j]) if (s.find(i - arr[j]) != s.end() && arr[j] != (i - arr[j])) count++; // if Count is greater than 2 // break the loop if (count > 2) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 2) { // i is ulam number arr.push_back(i); s.insert(i); } }} // Driver codeint main(){ // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number cout << arr[n - 1]; return 0;} // JAVA code to print nth// Ulam number import java.util.*;class GFG { static final int MAX = 10000; // Array to store Ulam Number static Vector<Integer> arr = new Vector<Integer>(); // function to compute ulam Number static void ulam() { // Set to search specific Ulam number efficiently Set<Integer> s = new HashSet<Integer>(); // push First 2 two term of the sequence // in the array and set // for further calculation arr.add(1); s.add(1); arr.add(2); s.add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size(); j++) { // Check if i-arr[j] exist in the array or not using set // If yes, Then i can be represented as // sum of arr[j] + (i- arr[j]) if (s.contains(i - arr.get(j)) && arr.get(j) != (i - arr.get(j))) count++; // if Count is greater than 2 // break the loop if (count > 2) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 2) { // i is ulam number arr.add(i); s.add(i); } } } // Driver code public static void main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number System.out.println(arr.get(n - 1)); }} # Python3 code to print nth Ulam numberMAX = 10000 # Array to store Ulam Numberarr = [] # function to compute ulam Numberdef ulam(): # Set to search specific Ulam # number efficiently s = set() # push First 2 two term of the # sequence in the array and set # for further calculation arr.append(1) s.add(1) arr.append(2) s.add(2) # loop to generate Ulam number for i in range(3, MAX): count = 0 # traverse the array and check if # i can be represented as sum of # two distinct element of the array for j in range(0, len(arr)): # Check if i-arr[j] exist in the array # or not using set. If yes, Then i can # be represented as sum of arr[j] + (i- arr[j]) if (i - arr[j]) in s and arr[j] != (i - arr[j]): count += 1 # if Count is greater than 2 # break the loop if count > 2: break # If count is 2 that means # i can be represented as sum of # two distinct terms of the sequence if count == 2: # i is ulam number arr.append(i) s.add(i) # Driver Code if __name__ == "__main__": # pre compute Ulam Number sequence ulam() n = 9 # print nth Ulam number print(arr[n - 1]) # This code is contributed by Rituraj Jain // C# code to print nth// Ulam numberusing System;using System.Collections.Generic; class GFG{ static readonly int MAX = 10000; // Array to store Ulam Number static List<int> arr = new List<int>(); // function to compute ulam Number static void ulam() { // Set to search specific Ulam number efficiently HashSet<int> s = new HashSet<int>(); // push First 2 two term of the sequence // in the array and set // for further calculation arr.Add(1); s.Add(1); arr.Add(2); s.Add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.Count; j++) { // Check if i-arr[j] exist in the array // or not using set If yes, // Then i can be represented as // sum of arr[j] + (i- arr[j]) if (s.Contains(i - arr[j]) && arr[j] != (i - arr[j])) count++; // if Count is greater than 2 // break the loop if (count > 2) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 2) { // i is ulam number arr.Add(i); s.Add(i); } } } // Driver code public static void Main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number Console.WriteLine(arr[n - 1]); }} // This code is contributed by Rajput-Ji 16 rituraj_jain Rajput-Ji rutvik_56 noob2000 abhishek0719kadiyan surinderdawra388 number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Minimum number of jumps to reach end Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Modulo Operator (%) in C/C++ with Examples Program for Decimal to Binary Conversion
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2021" }, { "code": null, "e": 438, "s": 28, "text": "Given a positive integer n , the task is to print nth Number of the Ulam Number SequenceUlam Number: In Mathematics, An Ulam number is the member of an Integer sequence that starts with the term U1 = 1 and U1 = 2 and then for every n > 2, Un is defined is smallest positive integer greater than Un-1 which can be expressed as sum of two distinct earlier term of the sequence in exactly one way. For example, " }, { "code": null, "e": 551, "s": 438, "text": "3 is an Ulam Number as it can be expressed as sum of two distinct earlier terms in exactly one way ( i.e 1 + 2 )" }, { "code": null, "e": 690, "s": 551, "text": "4 is also an Ulam number. Other than ( 1 + 3) we can express 4 as ( 2 + 2 ) but in (2 + 2) terms are not distinct. So we have only one way" }, { "code": null, "e": 829, "s": 690, "text": "5 can be expressed as sum of two distinct earlier terms of the sequence in two ways as ( 1 + 4 ) and ( 2 + 3), So, 5 is not an Ulam Number" }, { "code": null, "e": 884, "s": 829, "text": "The first few terms of the Ulam number sequence are- " }, { "code": null, "e": 988, "s": 884, "text": "1, 2, 3, 4, 6, 8, 11, 13, 16, 18, 26, 28, 36, 38, 47, 48, 53, 57, 62, 69, 72, 77, 82, 87, 97, 99, 102 " }, { "code": null, "e": 1000, "s": 988, "text": "Examples: " }, { "code": null, "e": 1045, "s": 1000, "text": "Input : 5\nOutput : 6\n\nInput : 9\nOutput : 16" }, { "code": null, "e": 1261, "s": 1047, "text": "A Simple Solution to print nth term of the Ulam number sequence is to generate entire ulam sequence up to n and print nth term, As we can not compute nth term directly. Approach to generate ulam number sequence: " }, { "code": null, "e": 1377, "s": 1261, "text": "As, We have first two term of the sequence as U1=1 and U2=2. we can start our search from i=3 for next Ulam number." }, { "code": null, "e": 1558, "s": 1377, "text": "For every value of ‘i’ traverse the earlier terms of the sequence using two loops and check if on adding two distinct term of sequence we can get sum as i in exactly one way or not" }, { "code": null, "e": 1643, "s": 1558, "text": "If Yes, Then ‘i’ is next Ulam number, Store it. and then search for next ulam number" }, { "code": null, "e": 1690, "s": 1643, "text": "If not, then increment ‘i’ and repeat the same" }, { "code": null, "e": 1744, "s": 1690, "text": "Keep searching ulam number, until we get our nth term" }, { "code": null, "e": 1793, "s": 1744, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 1797, "s": 1793, "text": "C++" }, { "code": null, "e": 1802, "s": 1797, "text": "Java" }, { "code": null, "e": 1810, "s": 1802, "text": "Python3" }, { "code": null, "e": 1813, "s": 1810, "text": "C#" }, { "code": null, "e": 1824, "s": 1813, "text": "Javascript" }, { "code": "// CPP code to print nth// Ulam number #include <bits/stdc++.h>using namespace std; #define MAX 10000 // Array to store Ulam Numbervector<int> arr; // function to compute ulam Numbervoid ulam(){ // push First 2 two term of the sequence // in the array // for further calculation arr.push_back(1); arr.push_back(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size() - 1; j++) { for (int k = j + 1; k < arr.size(); k++) { if (arr[j] + arr[k] == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 1 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.push_back(i); } }} // Driver codeint main(){ // Pre compute Ulam Number sequence ulam(); int n = 9; // Print nth Ulam number cout << arr[n - 1]; return 0;}", "e": 3081, "s": 1824, "text": null }, { "code": "// JAVA code to print nth// Ulam number import java.util.*;class GFG { static final int MAX = 1000; // Array to store Ulam Number static Vector<Integer> arr = new Vector<Integer>(); // Function to compute ulam Number static void ulam() { // push First 2 two term of the sequence // in the array // for further calculation arr.add(1); arr.add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size() - 1; j++) { for (int k = j + 1; k < arr.size(); k++) { if (arr.get(j) + arr.get(k) == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.add(i); } } } // Driver code public static void main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number System.out.println(arr.get(n - 1)); }}", "e": 4584, "s": 3081, "text": null }, { "code": "# Python3 code to print nth# Ulam numberMAX = 1000 # Array to store Ulam Numberarr = [] # function to compute ulam Numberdef ulam(): # push First 2 two term of the sequence # in the array # for further calculation arr.append(1); arr.append(2); # loop to generate Ulam number for i in range(3, MAX): count = 0; # traverse the array and check if # i can be represented as sum of # two distinct element of the array for j in range(len(arr) - 1): for k in range(j + 1, len(arr)): if (arr[j] + arr[k] == i): count += 1 if (count > 1): break; if (count > 1): break; # If count is 1 that means # i can be represented as sum of # two distinct terms of the sequence if (count == 1): # i is ulam number arr.append(i); # Driver codeif __name__=='__main__': # Pre compute Ulam Number sequence ulam(); n = 9; # Print nth Ulam number print(arr[n - 1]) # This code is contributed by rutvik_56.", "e": 5733, "s": 4584, "text": null }, { "code": "// C# code to print nth// Ulam numberusing System;using System.Collections.Generic; class GFG{ static readonly int MAX = 1000; // Array to store Ulam Number static List<int> arr = new List<int>(); // Function to compute ulam Number static void ulam() { // push First 2 two term of // the sequence in the array // for further calculation arr.Add(1); arr.Add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.Count - 1; j++) { for (int k = j + 1; k < arr.Count; k++) { if (arr[j] + arr[k] == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.Add(i); } } } // Driver code public static void Main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number Console.WriteLine(arr[n - 1]); }} // This code is contributed by Rajput-JI", "e": 7334, "s": 5733, "text": null }, { "code": "<script>// Javascript code to print nth// Ulam number var MAX = 10000; // Array to store Ulam Numbervar arr = []; // function to compute ulam Numberfunction ulam(){ // push First 2 two term of the sequence // in the array // for further calculation arr.push(1); arr.push(2); // loop to generate Ulam number for (var i = 3; i < MAX; i++) { var count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (var j = 0; j < arr.length - 1; j++) { for (var k = j + 1; k < arr.length; k++) { if (arr[j] + arr[k] == i) { count++; } if (count > 1) break; } if (count > 1) break; } // If count is 1 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 1) { // i is ulam number arr.push(i); } }} // Driver code// Pre compute Ulam Number sequenceulam();var n = 9; // Print nth Ulam numberdocument.write( arr[n - 1]); // This code is contributed by noob2000.</script>", "e": 8572, "s": 7334, "text": null }, { "code": null, "e": 8575, "s": 8572, "text": "16" }, { "code": null, "e": 8922, "s": 8577, "text": "An Efficient solution is to use a hash table to store the earlier number of the sequence so that instead of using two loops to check if ‘i’ can be expressed as the sum of two distinct terms in exactly one way or not, we can do it in a single loop. Searching will be fast if we will use a hash table. Below is the Implementation of above idea: " }, { "code": null, "e": 8926, "s": 8922, "text": "C++" }, { "code": null, "e": 8931, "s": 8926, "text": "Java" }, { "code": null, "e": 8939, "s": 8931, "text": "Python3" }, { "code": null, "e": 8942, "s": 8939, "text": "C#" }, { "code": "// Cpp code to print nth// Ulam number #include <bits/stdc++.h>using namespace std; #define MAX 10000 // Array to store Ulam Numbervector<int> arr; // function to compute ulam Numbervoid ulam(){ // Set to search specific Ulam number efficiently unordered_set<int> s; // push First 2 two term of the sequence // in the array and set // for further calculation arr.push_back(1); s.insert(1); arr.push_back(2); s.insert(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size(); j++) { // Check if i-arr[j] exist in the array or not using set // If yes, Then i can be represented as // sum of arr[j] + (i- arr[j]) if (s.find(i - arr[j]) != s.end() && arr[j] != (i - arr[j])) count++; // if Count is greater than 2 // break the loop if (count > 2) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 2) { // i is ulam number arr.push_back(i); s.insert(i); } }} // Driver codeint main(){ // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number cout << arr[n - 1]; return 0;}", "e": 10455, "s": 8942, "text": null }, { "code": "// JAVA code to print nth// Ulam number import java.util.*;class GFG { static final int MAX = 10000; // Array to store Ulam Number static Vector<Integer> arr = new Vector<Integer>(); // function to compute ulam Number static void ulam() { // Set to search specific Ulam number efficiently Set<Integer> s = new HashSet<Integer>(); // push First 2 two term of the sequence // in the array and set // for further calculation arr.add(1); s.add(1); arr.add(2); s.add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.size(); j++) { // Check if i-arr[j] exist in the array or not using set // If yes, Then i can be represented as // sum of arr[j] + (i- arr[j]) if (s.contains(i - arr.get(j)) && arr.get(j) != (i - arr.get(j))) count++; // if Count is greater than 2 // break the loop if (count > 2) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 2) { // i is ulam number arr.add(i); s.add(i); } } } // Driver code public static void main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number System.out.println(arr.get(n - 1)); }}", "e": 12241, "s": 10455, "text": null }, { "code": "# Python3 code to print nth Ulam numberMAX = 10000 # Array to store Ulam Numberarr = [] # function to compute ulam Numberdef ulam(): # Set to search specific Ulam # number efficiently s = set() # push First 2 two term of the # sequence in the array and set # for further calculation arr.append(1) s.add(1) arr.append(2) s.add(2) # loop to generate Ulam number for i in range(3, MAX): count = 0 # traverse the array and check if # i can be represented as sum of # two distinct element of the array for j in range(0, len(arr)): # Check if i-arr[j] exist in the array # or not using set. If yes, Then i can # be represented as sum of arr[j] + (i- arr[j]) if (i - arr[j]) in s and arr[j] != (i - arr[j]): count += 1 # if Count is greater than 2 # break the loop if count > 2: break # If count is 2 that means # i can be represented as sum of # two distinct terms of the sequence if count == 2: # i is ulam number arr.append(i) s.add(i) # Driver Code if __name__ == \"__main__\": # pre compute Ulam Number sequence ulam() n = 9 # print nth Ulam number print(arr[n - 1]) # This code is contributed by Rituraj Jain", "e": 13631, "s": 12241, "text": null }, { "code": "// C# code to print nth// Ulam numberusing System;using System.Collections.Generic; class GFG{ static readonly int MAX = 10000; // Array to store Ulam Number static List<int> arr = new List<int>(); // function to compute ulam Number static void ulam() { // Set to search specific Ulam number efficiently HashSet<int> s = new HashSet<int>(); // push First 2 two term of the sequence // in the array and set // for further calculation arr.Add(1); s.Add(1); arr.Add(2); s.Add(2); // loop to generate Ulam number for (int i = 3; i < MAX; i++) { int count = 0; // traverse the array and check if // i can be represented as sum of // two distinct element of the array for (int j = 0; j < arr.Count; j++) { // Check if i-arr[j] exist in the array // or not using set If yes, // Then i can be represented as // sum of arr[j] + (i- arr[j]) if (s.Contains(i - arr[j]) && arr[j] != (i - arr[j])) count++; // if Count is greater than 2 // break the loop if (count > 2) break; } // If count is 2 that means // i can be represented as sum of // two distinct terms of the sequence if (count == 2) { // i is ulam number arr.Add(i); s.Add(i); } } } // Driver code public static void Main(String[] args) { // pre compute Ulam Number sequence ulam(); int n = 9; // print nth Ulam number Console.WriteLine(arr[n - 1]); }} // This code is contributed by Rajput-Ji", "e": 15514, "s": 13631, "text": null }, { "code": null, "e": 15517, "s": 15514, "text": "16" }, { "code": null, "e": 15532, "s": 15519, "text": "rituraj_jain" }, { "code": null, "e": 15542, "s": 15532, "text": "Rajput-Ji" }, { "code": null, "e": 15552, "s": 15542, "text": "rutvik_56" }, { "code": null, "e": 15561, "s": 15552, "text": "noob2000" }, { "code": null, "e": 15581, "s": 15561, "text": "abhishek0719kadiyan" }, { "code": null, "e": 15598, "s": 15581, "text": "surinderdawra388" }, { "code": null, "e": 15612, "s": 15598, "text": "number-theory" }, { "code": null, "e": 15625, "s": 15612, "text": "Mathematical" }, { "code": null, "e": 15639, "s": 15625, "text": "number-theory" }, { "code": null, "e": 15652, "s": 15639, "text": "Mathematical" }, { "code": null, "e": 15750, "s": 15652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15774, "s": 15750, "text": "Merge two sorted arrays" }, { "code": null, "e": 15795, "s": 15774, "text": "Operators in C / C++" }, { "code": null, "e": 15809, "s": 15795, "text": "Prime Numbers" }, { "code": null, "e": 15862, "s": 15809, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 15894, "s": 15862, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 15931, "s": 15894, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 15958, "s": 15931, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 16001, "s": 15958, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 16044, "s": 16001, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
ML | Matrix plots in Seaborn
01 Feb, 2022 Seaborn is a wonderful visualization library provided by python. It has several kinds of plots through which it provides the amazing visualization capabilities. Some of them include count plot, scatter plot, pair plots, regression plots, matrix plots and much more. This article deals with the matrix plots in seaborn. Example 1: Heatmaps Heatmap is a way to show some sort of matrix plot. To use a heatmap the data should be in a matrix form. By matrix we mean that the index name and the column name must match in some way so that the data that we fill inside the cells are relevant. Lets look at an example to understand this better.Code : Python program Python3 # import the necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the tips datasetdataset = sns.load_dataset('tips') # first five entries of the tips datasetdataset.head() # correlation between the different parameterstc = dataset.corr() # plot a heatmap of the correlated datasns.heatmap(tc) The first five entries of the dataset The correlation matrix Heatmap of the correlated matrix Inorder to obtain a better visualization with the heatmap, we can add the parameters such as annot, linewidth and line colour. Python3 # import the necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the tips datasetdataset = sns.load_dataset('tips') # first five entries of the tips datasetdataset.head() # correlation between the different parameterstc = dataset.corr()sns.heatmap(tc, annot = True, cmap ='plasma', linecolor ='black', linewidths = 1) Explanation annot is used to annotate the actual value that belongs to these cells cmap is used for the colour mapping you want like coolwarm, plasma, magma etc. linewidth is used to set the width of the lines separating the cells. linecolor is used to set the colour of the lines separating the cells. Here is a plot that shows those attributes. So we can say that all a heatmap does is color the cells based on the gradient and uses some parameters to increase the data visualization. Example 2: Cluster maps Cluster maps use hierarchical clustering. It performs the clustering based on the similarity of the rows and columns. Python3 # import the necessary librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the flights datasetfd = sns.load_dataset('flights') # make a dataframe of the datadf = pd.pivot_table(values ='passengers', index ='month', columns ='year', data = fd) # first five entries of the datasetdf.head() # make a clustermap from the datasetsns.clustermap(df, cmap ='plasma') The first five entries of the dataset The matrix created using the pivot table(first five entries) Clustermap from the given data We can also change the scale of the color bar by using the standard_scale parameter. Python3 # import the necessary librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the flights datasetfd = sns.load_dataset('flights') # make a dataframe of the datadf = pd.pivot_table(values ='passengers', index ='month', columns ='year', data = fd) # first five entries of the datasetdf.head() # make a clustermap from the datasetsns.clustermap(df, cmap ='plasma', standard_scale = 1) Clustermap after using standard scaling standard_scale = 1 normalizes the data from 0 to 1 range. We can see that the months as well as years are no longer in order as they are clustered according to the similarity in case of clustermaps. So we can conclude that a heatmap will display things in the order we give whereas the cluster map clusters the data based on similarity. singghakshay gulshankumarar231 germanshephered48 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Types of Environments in AI Principal Component Analysis with Python Intuition of Adam Optimizer
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2022" }, { "code": null, "e": 688, "s": 28, "text": "Seaborn is a wonderful visualization library provided by python. It has several kinds of plots through which it provides the amazing visualization capabilities. Some of them include count plot, scatter plot, pair plots, regression plots, matrix plots and much more. This article deals with the matrix plots in seaborn. Example 1: Heatmaps Heatmap is a way to show some sort of matrix plot. To use a heatmap the data should be in a matrix form. By matrix we mean that the index name and the column name must match in some way so that the data that we fill inside the cells are relevant. Lets look at an example to understand this better.Code : Python program " }, { "code": null, "e": 696, "s": 688, "text": "Python3" }, { "code": "# import the necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the tips datasetdataset = sns.load_dataset('tips') # first five entries of the tips datasetdataset.head() # correlation between the different parameterstc = dataset.corr() # plot a heatmap of the correlated datasns.heatmap(tc)", "e": 1035, "s": 696, "text": null }, { "code": null, "e": 1075, "s": 1035, "text": "The first five entries of the dataset " }, { "code": null, "e": 1100, "s": 1075, "text": "The correlation matrix " }, { "code": null, "e": 1262, "s": 1100, "text": "Heatmap of the correlated matrix Inorder to obtain a better visualization with the heatmap, we can add the parameters such as annot, linewidth and line colour. " }, { "code": null, "e": 1270, "s": 1262, "text": "Python3" }, { "code": "# import the necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the tips datasetdataset = sns.load_dataset('tips') # first five entries of the tips datasetdataset.head() # correlation between the different parameterstc = dataset.corr()sns.heatmap(tc, annot = True, cmap ='plasma', linecolor ='black', linewidths = 1)", "e": 1646, "s": 1270, "text": null }, { "code": null, "e": 1660, "s": 1646, "text": "Explanation " }, { "code": null, "e": 1731, "s": 1660, "text": "annot is used to annotate the actual value that belongs to these cells" }, { "code": null, "e": 1810, "s": 1731, "text": "cmap is used for the colour mapping you want like coolwarm, plasma, magma etc." }, { "code": null, "e": 1880, "s": 1810, "text": "linewidth is used to set the width of the lines separating the cells." }, { "code": null, "e": 1951, "s": 1880, "text": "linecolor is used to set the colour of the lines separating the cells." }, { "code": null, "e": 1997, "s": 1951, "text": "Here is a plot that shows those attributes. " }, { "code": null, "e": 2281, "s": 1997, "text": "So we can say that all a heatmap does is color the cells based on the gradient and uses some parameters to increase the data visualization. Example 2: Cluster maps Cluster maps use hierarchical clustering. It performs the clustering based on the similarity of the rows and columns. " }, { "code": null, "e": 2289, "s": 2281, "text": "Python3" }, { "code": "# import the necessary librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the flights datasetfd = sns.load_dataset('flights') # make a dataframe of the datadf = pd.pivot_table(values ='passengers', index ='month', columns ='year', data = fd) # first five entries of the datasetdf.head() # make a clustermap from the datasetsns.clustermap(df, cmap ='plasma')", "e": 2723, "s": 2289, "text": null }, { "code": null, "e": 2763, "s": 2723, "text": "The first five entries of the dataset " }, { "code": null, "e": 2826, "s": 2763, "text": "The matrix created using the pivot table(first five entries) " }, { "code": null, "e": 2944, "s": 2826, "text": "Clustermap from the given data We can also change the scale of the color bar by using the standard_scale parameter. " }, { "code": null, "e": 2952, "s": 2944, "text": "Python3" }, { "code": "# import the necessary librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # load the flights datasetfd = sns.load_dataset('flights') # make a dataframe of the datadf = pd.pivot_table(values ='passengers', index ='month', columns ='year', data = fd) # first five entries of the datasetdf.head() # make a clustermap from the datasetsns.clustermap(df, cmap ='plasma', standard_scale = 1)", "e": 3406, "s": 2952, "text": null }, { "code": null, "e": 3784, "s": 3406, "text": "Clustermap after using standard scaling standard_scale = 1 normalizes the data from 0 to 1 range. We can see that the months as well as years are no longer in order as they are clustered according to the similarity in case of clustermaps. So we can conclude that a heatmap will display things in the order we give whereas the cluster map clusters the data based on similarity. " }, { "code": null, "e": 3797, "s": 3784, "text": "singghakshay" }, { "code": null, "e": 3815, "s": 3797, "text": "gulshankumarar231" }, { "code": null, "e": 3833, "s": 3815, "text": "germanshephered48" }, { "code": null, "e": 3850, "s": 3833, "text": "Machine Learning" }, { "code": null, "e": 3867, "s": 3850, "text": "Machine Learning" }, { "code": null, "e": 3965, "s": 3867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4006, "s": 3965, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4042, "s": 4006, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4066, "s": 4042, "text": "Markov Decision Process" }, { "code": null, "e": 4099, "s": 4066, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4150, "s": 4099, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 4183, "s": 4150, "text": "Normalization vs Standardization" }, { "code": null, "e": 4223, "s": 4183, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 4251, "s": 4223, "text": "Types of Environments in AI" }, { "code": null, "e": 4292, "s": 4251, "text": "Principal Component Analysis with Python" } ]
How to remove a subset from a DataFrame in R ?
23 May, 2021 A subset is a combination of cells that form a smaller data frame formed out from the original data frame. A set of rows and columns can be removed from the original data frame to reduce a part of the data frame. The subset removal can be based on constraints to which rows and columns are subjected to. In this article, we will see how to remove subset from a DataFrame in R Programming Language. Method 1: Using anti_join() method. anti_join() method in this package is used to return all the rows from the first data frame with no matching values in y, keeping just columns from the first data frame. It is basically a selection and filter tool. The row numbers of the original data frame are not retained in the result returned. Syntax: anti_join ( x , y , by = c(..)) Arguments : x : The first data frame y : The second data frame by (Optional ) : To consider which column as the key for filtering data. Returns : The first data frame rows that are not in second data frame. Code: R # loading the librarylibrary("dplyr") # declaring data framedata_frame <- data.frame(col1 = c(2, 4, 6, 10), col2 = c(4, 6, 8, 5), col3 = c(8, 10, 12, 20), col4 = letters[1 : 4]) print ("Original Dataframe")print (data_frame) # creating subset dataframesubset <- data.frame(col1 = c(2 , 6), col2 = c(4 , 8)) # removing subset data framedata_frame_mod <- anti_join(data_frame,subset)print ("Modified Dataframe")print (data_frame_mod) Output: [1] "Original Dataframe" col1 col2 col3 col4 1 2 4 8 a 2 4 6 10 b 3 6 8 12 c 4 10 5 20 d [1] "Modified Dataframe" col1 col2 col3 col4 1 4 6 10 b 2 10 5 20 d In case, the second data frame columns belong to different rows of the first data frame, we can specify the column values to take, using the “by” argument in the anti_join() method. R library("dplyr") # declaring data framedata_frame <- data.frame(col1 = c(2, 4, 6, 10), col2 = c(4, 6, 8, 5), col3 = c(8, 10, 12, 20), col4 = letters[1 : 4])print ("Original Dataframe")print (data_frame)subset <- data.frame(col1 = c(2 , 4), col4 = c("a" , "d") )data_frame_mod <- anti_join(data_frame, subset, by = "col4")print ("Modified Dataframe")print (data_frame_mod) Output: [1] "Original Dataframe" col1 col2 col3 col4 1 2 4 8 a 2 4 6 10 b 3 6 8 12 c 4 10 5 20 d [1] "Modified Dataframe" col1 col2 col3 col4 1 4 6 10 b 2 6 8 12 c Method 2: Using %in% operator The %in% operator is used to check for the existence of a value in the vector. It returns a logical value, in case the value is present, else False. val %in% vec The particular column of the first data frame is checked for values in the second data frame, and the rows are returned which are not present in the second data frame. The row numbers of the original data frame are retained during the application of this operator. R library("dplyr") # declaring data framedata_frame <- data.frame(col1 = c(2, 4, 6, 10), col2 = c(4, 6, 8, 5), col3 = c(8, 10, 12, 20), col4 = letters[1 : 4]) print ("Original Dataframe")print (data_frame) # creating second data framesubset <- data.frame(col1 = c(2 , 4), col2 = c("a" , "d"))data_frame_mod <- data_frame[data_frame$col4 %in% subset$col2, ]print ("Modified Dataframe")print (data_frame_mod) Output: [1] "Original Dataframe" col1 col2 col3 col4 1 2 4 8 a 2 4 6 10 b 3 6 8 12 c 4 10 5 20 d [1] "Modified Dataframe" col1 col2 col3 col4 2 4 6 10 b 3 6 8 12 c Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2021" }, { "code": null, "e": 426, "s": 28, "text": "A subset is a combination of cells that form a smaller data frame formed out from the original data frame. A set of rows and columns can be removed from the original data frame to reduce a part of the data frame. The subset removal can be based on constraints to which rows and columns are subjected to. In this article, we will see how to remove subset from a DataFrame in R Programming Language." }, { "code": null, "e": 462, "s": 426, "text": "Method 1: Using anti_join() method." }, { "code": null, "e": 762, "s": 462, "text": "anti_join() method in this package is used to return all the rows from the first data frame with no matching values in y, keeping just columns from the first data frame. It is basically a selection and filter tool. The row numbers of the original data frame are not retained in the result returned. " }, { "code": null, "e": 802, "s": 762, "text": "Syntax: anti_join ( x , y , by = c(..))" }, { "code": null, "e": 815, "s": 802, "text": "Arguments : " }, { "code": null, "e": 840, "s": 815, "text": "x : The first data frame" }, { "code": null, "e": 866, "s": 840, "text": "y : The second data frame" }, { "code": null, "e": 939, "s": 866, "text": "by (Optional ) : To consider which column as the key for filtering data." }, { "code": null, "e": 1011, "s": 939, "text": "Returns : The first data frame rows that are not in second data frame. " }, { "code": null, "e": 1017, "s": 1011, "text": "Code:" }, { "code": null, "e": 1019, "s": 1017, "text": "R" }, { "code": "# loading the librarylibrary(\"dplyr\") # declaring data framedata_frame <- data.frame(col1 = c(2, 4, 6, 10), col2 = c(4, 6, 8, 5), col3 = c(8, 10, 12, 20), col4 = letters[1 : 4]) print (\"Original Dataframe\")print (data_frame) # creating subset dataframesubset <- data.frame(col1 = c(2 , 6), col2 = c(4 , 8)) # removing subset data framedata_frame_mod <- anti_join(data_frame,subset)print (\"Modified Dataframe\")print (data_frame_mod)", "e": 1547, "s": 1019, "text": null }, { "code": null, "e": 1555, "s": 1547, "text": "Output:" }, { "code": null, "e": 1786, "s": 1555, "text": "[1] \"Original Dataframe\" \ncol1 col2 col3 col4 \n1 2 4 8 a \n2 4 6 10 b \n3 6 8 12 c \n4 10 5 20 d \n[1] \"Modified Dataframe\" \ncol1 col2 col3 col4 \n1 4 6 10 b \n2 10 5 20 d" }, { "code": null, "e": 1969, "s": 1786, "text": "In case, the second data frame columns belong to different rows of the first data frame, we can specify the column values to take, using the “by” argument in the anti_join() method. " }, { "code": null, "e": 1971, "s": 1969, "text": "R" }, { "code": "library(\"dplyr\") # declaring data framedata_frame <- data.frame(col1 = c(2, 4, 6, 10), col2 = c(4, 6, 8, 5), col3 = c(8, 10, 12, 20), col4 = letters[1 : 4])print (\"Original Dataframe\")print (data_frame)subset <- data.frame(col1 = c(2 , 4), col4 = c(\"a\" , \"d\") )data_frame_mod <- anti_join(data_frame, subset, by = \"col4\")print (\"Modified Dataframe\")print (data_frame_mod)", "e": 2463, "s": 1971, "text": null }, { "code": null, "e": 2471, "s": 2463, "text": "Output:" }, { "code": null, "e": 2703, "s": 2471, "text": "[1] \"Original Dataframe\" \ncol1 col2 col3 col4 \n1 2 4 8 a \n2 4 6 10 b \n3 6 8 12 c \n4 10 5 20 d \n[1] \"Modified Dataframe\" \ncol1 col2 col3 col4 \n1 4 6 10 b \n2 6 8 12 c " }, { "code": null, "e": 2733, "s": 2703, "text": "Method 2: Using %in% operator" }, { "code": null, "e": 2883, "s": 2733, "text": "The %in% operator is used to check for the existence of a value in the vector. It returns a logical value, in case the value is present, else False. " }, { "code": null, "e": 2896, "s": 2883, "text": "val %in% vec" }, { "code": null, "e": 3162, "s": 2896, "text": "The particular column of the first data frame is checked for values in the second data frame, and the rows are returned which are not present in the second data frame. The row numbers of the original data frame are retained during the application of this operator. " }, { "code": null, "e": 3164, "s": 3162, "text": "R" }, { "code": "library(\"dplyr\") # declaring data framedata_frame <- data.frame(col1 = c(2, 4, 6, 10), col2 = c(4, 6, 8, 5), col3 = c(8, 10, 12, 20), col4 = letters[1 : 4]) print (\"Original Dataframe\")print (data_frame) # creating second data framesubset <- data.frame(col1 = c(2 , 4), col2 = c(\"a\" , \"d\"))data_frame_mod <- data_frame[data_frame$col4 %in% subset$col2, ]print (\"Modified Dataframe\")print (data_frame_mod)", "e": 3664, "s": 3164, "text": null }, { "code": null, "e": 3672, "s": 3664, "text": "Output:" }, { "code": null, "e": 3897, "s": 3672, "text": "[1] \"Original Dataframe\"\n col1 col2 col3 col4\n1 2 4 8 a\n2 4 6 10 b\n3 6 8 12 c\n4 10 5 20 d\n[1] \"Modified Dataframe\"\n col1 col2 col3 col4\n2 4 6 10 b\n3 6 8 12 c " }, { "code": null, "e": 3904, "s": 3897, "text": "Picked" }, { "code": null, "e": 3925, "s": 3904, "text": "R DataFrame-Programs" }, { "code": null, "e": 3937, "s": 3925, "text": "R-DataFrame" }, { "code": null, "e": 3948, "s": 3937, "text": "R Language" }, { "code": null, "e": 3959, "s": 3948, "text": "R Programs" }, { "code": null, "e": 4057, "s": 3959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4109, "s": 4057, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 4167, "s": 4109, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4202, "s": 4167, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4240, "s": 4202, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 4257, "s": 4240, "text": "R - if statement" }, { "code": null, "e": 4315, "s": 4257, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4364, "s": 4315, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 4407, "s": 4364, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 4445, "s": 4407, "text": "Merge DataFrames by Column Names in R" } ]
Write a URL in a C++ program
21 Jun, 2022 Writing URLs in programming code doesn’t affect the program and the compiler will not throw any error. Here, we will how to use Url in various languages without any errors. The full form of URL is Uniform Resource Locators. URLs are unique they store the address of a particular web application. C++ Java PHP C# Javascript // C++ program to demonstrate URL in code#include <iostream>using namespace std; int main(){ https://www.geeksforgeeks.org/ for (int i = 0; i < 5; i++) { cout << "This code is error free" << endl ; // Uncommenting below goto statement causes // infinite loop // goto http; } return 0;} /*package whatever //do not write package name here */import java.io.*; class GFG { public static void main (String[] args) { https://www.geeksforgeeks.org/ for(int i = 0; i < 5; i++){ System.out.println("This code is error free"); } }} <?php// PHP program to demonstrate// URL in code https://www.geeksforgeeks.org/ for ($i = 0; $i < 5; $i++){ echo "This code is error " . "free" , "\n" ; // Uncommenting below // goto statement causes // infinite loop // goto https;} // This code is contributed// by m_kit?> using System;class Demo { static void Main() { string input = "https://www.geeksforgeeks.org"; // See if input matches one of these starts. for (int i = 0; i < 5; i++) Console.WriteLine("This code is error"); }} // This code is contributed by aayushcoding100. <script>//new URL(url, [base])let mainUrl = new URL('https://www.geeksforgeeks.org');alert(mainUrl);for (let i = 0; i < 5; i++) { document.write("This code is error");} // This code is contributed by aayushcoding100.</script> Output: Explanation: Any identifier followed by a : becomes a (goto) labels in a Program.A single line comment begins with a // and so in https://www.geeksforgeeks.org/ and so it is a comment. And therefore: Any identifier followed by a : becomes a (goto) labels in a Program. A single line comment begins with a // and so in https://www.geeksforgeeks.org/ and so it is a comment. And therefore: label- http: comment- www.geeksforgeeks.org/ Time complexity : O(1) Auxiliary Space : O(1) jit_t akshitsaxenaa09 ayushcoding100 sagartomar9927 mahendrabagul569 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++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 227, "s": 54, "text": "Writing URLs in programming code doesn’t affect the program and the compiler will not throw any error. Here, we will how to use Url in various languages without any errors." }, { "code": null, "e": 351, "s": 227, "text": "The full form of URL is Uniform Resource Locators. URLs are unique they store the address of a particular web application." }, { "code": null, "e": 355, "s": 351, "text": "C++" }, { "code": null, "e": 360, "s": 355, "text": "Java" }, { "code": null, "e": 364, "s": 360, "text": "PHP" }, { "code": null, "e": 367, "s": 364, "text": "C#" }, { "code": null, "e": 378, "s": 367, "text": "Javascript" }, { "code": "// C++ program to demonstrate URL in code#include <iostream>using namespace std; int main(){ https://www.geeksforgeeks.org/ for (int i = 0; i < 5; i++) { cout << \"This code is error free\" << endl ; // Uncommenting below goto statement causes // infinite loop // goto http; } return 0;}", "e": 710, "s": 378, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*; class GFG { public static void main (String[] args) { https://www.geeksforgeeks.org/ for(int i = 0; i < 5; i++){ System.out.println(\"This code is error free\"); } }}", "e": 990, "s": 710, "text": null }, { "code": "<?php// PHP program to demonstrate// URL in code https://www.geeksforgeeks.org/ for ($i = 0; $i < 5; $i++){ echo \"This code is error \" . \"free\" , \"\\n\" ; // Uncommenting below // goto statement causes // infinite loop // goto https;} // This code is contributed// by m_kit?>", "e": 1301, "s": 990, "text": null }, { "code": "using System;class Demo { static void Main() { string input = \"https://www.geeksforgeeks.org\"; // See if input matches one of these starts. for (int i = 0; i < 5; i++) Console.WriteLine(\"This code is error\"); }} // This code is contributed by aayushcoding100.", "e": 1583, "s": 1301, "text": null }, { "code": "<script>//new URL(url, [base])let mainUrl = new URL('https://www.geeksforgeeks.org');alert(mainUrl);for (let i = 0; i < 5; i++) { document.write(\"This code is error\");} // This code is contributed by aayushcoding100.</script>", "e": 1816, "s": 1583, "text": null }, { "code": null, "e": 1826, "s": 1816, "text": "Output: " }, { "code": null, "e": 1843, "s": 1828, "text": "Explanation: " }, { "code": null, "e": 2030, "s": 1843, "text": "Any identifier followed by a : becomes a (goto) labels in a Program.A single line comment begins with a // and so in https://www.geeksforgeeks.org/ and so it is a comment. And therefore:" }, { "code": null, "e": 2099, "s": 2030, "text": "Any identifier followed by a : becomes a (goto) labels in a Program." }, { "code": null, "e": 2218, "s": 2099, "text": "A single line comment begins with a // and so in https://www.geeksforgeeks.org/ and so it is a comment. And therefore:" }, { "code": null, "e": 2264, "s": 2218, "text": "label- http: \ncomment- www.geeksforgeeks.org/" }, { "code": null, "e": 2310, "s": 2264, "text": "Time complexity : O(1) Auxiliary Space : O(1)" }, { "code": null, "e": 2316, "s": 2310, "text": "jit_t" }, { "code": null, "e": 2332, "s": 2316, "text": "akshitsaxenaa09" }, { "code": null, "e": 2347, "s": 2332, "text": "ayushcoding100" }, { "code": null, "e": 2362, "s": 2347, "text": "sagartomar9927" }, { "code": null, "e": 2379, "s": 2362, "text": "mahendrabagul569" }, { "code": null, "e": 2390, "s": 2379, "text": "cpp-puzzle" }, { "code": null, "e": 2394, "s": 2390, "text": "C++" }, { "code": null, "e": 2398, "s": 2394, "text": "CPP" }, { "code": null, "e": 2496, "s": 2398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2520, "s": 2496, "text": "Sorting a vector in C++" }, { "code": null, "e": 2540, "s": 2520, "text": "Polymorphism in C++" }, { "code": null, "e": 2573, "s": 2540, "text": "Friend class and function in C++" }, { "code": null, "e": 2617, "s": 2573, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 2642, "s": 2617, "text": "std::string class in C++" }, { "code": null, "e": 2687, "s": 2642, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2735, "s": 2687, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2752, "s": 2735, "text": "std::find in C++" }, { "code": null, "e": 2796, "s": 2752, "text": "List in C++ Standard Template Library (STL)" } ]
Maximum Possible Rating of a Coding Contest
27 Jul, 2020 Given two arrays of positive integer Point[], Upvote[] of size N and a value K (1 <= K <= N). The task is to choose atleast K elements(Problems) such that the rating of the coding contest is maximum.Rating of contest: Rating of a contest is defined as total points of all problems in the contest multiplied by the minimum upvotes among all problems in the contest Hence, Rating = sum of points of contest problems * minimum upvotes among contest problems. Examples: Input: Point[] = {2, 10, 3, 1, 5, 8}, Upvote[] = {5, 4, 3, 9, 7, 2}, K = 2Output: 60Explanation:Here we select 2nd and 5th problem to get the maximum rating of the contest.So maximum rating is (10 + 5) * min(4, 7) = 60 Input: Point[] = {2, 10, 3, 1, 5, 8}, Upvote[] = {5, 4, 3, 9, 7, 2}, K = 3Output: 68Explanation:Here we select 1st, 2nd and 5th problem to get the maximum rating of the contest.So maximum rating is (2 + 10 + 5) * min(5, 4, 7) = 68 Input: Point[] = {2, 20, 3, 1, 5, 8}, Upvote[] = {5, 10, 3, 9, 7, 2}, K = 4Output: 200Explanation:Here we select only 2nd problem to get maximum rating of the contest.A further selection of any problems decreases the rating.So maximum rating is 20 * 10 = 200 Approach : Try the value of every upvote from highest to lowest and at the same time maintain an as large as possible points group, keep adding points to total points, if the number of problems in the contest exceeds K, lay off the problem with lowest points. This includes three steps.Sort problems by their upvotes value in decreasing order.For index i = 0, 1, ..., K-1, we push the points into the min_heap and calculate the rating. We only need to record the maximum rating. We use min_heap to track the problem with minimum points.For an index i = K, K+1, ..., N-1, if the point of the current problem is greater than the top of the min_heap, we pop the existing element and push the current element in the min_heap and update the maximum rating.In this way, calculate the maximum rating with respect to the problem with i-th largest upvotes since we have the problems with the K largest points in the min_heap. Sort problems by their upvotes value in decreasing order.For index i = 0, 1, ..., K-1, we push the points into the min_heap and calculate the rating. We only need to record the maximum rating. We use min_heap to track the problem with minimum points.For an index i = K, K+1, ..., N-1, if the point of the current problem is greater than the top of the min_heap, we pop the existing element and push the current element in the min_heap and update the maximum rating.In this way, calculate the maximum rating with respect to the problem with i-th largest upvotes since we have the problems with the K largest points in the min_heap. Sort problems by their upvotes value in decreasing order. For index i = 0, 1, ..., K-1, we push the points into the min_heap and calculate the rating. We only need to record the maximum rating. We use min_heap to track the problem with minimum points. For an index i = K, K+1, ..., N-1, if the point of the current problem is greater than the top of the min_heap, we pop the existing element and push the current element in the min_heap and update the maximum rating.In this way, calculate the maximum rating with respect to the problem with i-th largest upvotes since we have the problems with the K largest points in the min_heap. Below is the implementation of the above approach. C++ Python3 // C++ program to find the Maximum // Possible Rating of a Coding Contest#include <bits/stdc++.h>using namespace std; // Function to sort all problems// descending to upvotesbool Comparator(pair<int, int> p1, pair<int, int> p2){ return p1.second > p2.second;} // Function to return maximum// ratingint FindMaxRating(int N, int Point[], int Upvote[], int K){ // Declaring vector of pairs vector<pair<int, int> > vec; // Each pair represents a problem // with its points and upvotes for (int i = 0; i < N; i++) { vec.push_back(make_pair(Point[i], Upvote[i])); } // Step (1) - Sort problems by their // upvotes value in decreasing order sort(vec.begin(), vec.end(), Comparator); // Declaring min_heap or priority queue // to track of the problem with // minimum points. priority_queue<int, vector<int>, greater<int> > pq; int total_points = 0, max_rating = 0; // Step (2) - Loop for i = 0 to K - 1 and // do accordingly for (int i = 0; i < K; i++) { total_points = total_points + vec[i].first; max_rating = max(max_rating, total_points * vec[i].second); pq.push(vec[i].first); } // Step (3) - Loop for i = K to N - 1 // and do accordingly for (int i = K; i < N; i++) { if (pq.top() < vec[i].first) { total_points = total_points - pq.top() + vec[i].first; max_rating = max(max_rating, total_points * vec[i].second); pq.pop(); pq.push(vec[i].first); } } return max_rating;} // Driver codeint main(){ int Point[] = { 2, 10, 3, 1, 5, 8 }; int Upvote[] = { 5, 4, 3, 9, 7, 2 }; int N = sizeof(Point) / sizeof(Point[0]); int K = 2; cout << "Maximum Rating of Coding Contest is: " << FindMaxRating(N, Point, Upvote, K); return 0;} # Python3 program to find the Maximum # Possible Rating of a Coding Contest import heapq # Function to sort all problems # descending to upvotesdef Comparator(p1): return p1[1] # Function to return maximum # rating def FindMaxRating(N, Point, Upvote, K): # Declaring vector of pairs vec = [] # Each pair represents a problem # with its points and upvotes for i in range(N): vec.append([Point[i], Upvote[i]]) # Step (1) - Sort problems by their # upvotes value in decreasing order vec.sort(reverse = True, key = Comparator) # Declaring min_heap or priority queue # to track of the problem with # minimum points. pq = [] heapq.heapify(pq) total_points, max_rating = 0, 0 # Step (2) - Loop for i = 0 to K - 1 and # do accordingly for i in range(K): total_points = (total_points + vec[i][0]) max_rating = max(max_rating, total_points * vec[i][1]) heapq.heappush(pq, vec[i][0]) # Step (3) - Loop for i = K to N - 1 # and do accordingly for i in range(K, N): if pq[0] < vec[i][0]: total_points = (total_points - pq[0] + vec[i][0]) max_rating = max(max_rating, total_points * vec[i][1]) heapq.heappop(pq) heapq.heappush(pq, vec[i][0]) return max_rating # Driver codePoint = [ 2, 10, 3, 1, 5, 8 ]Upvote = [ 5, 4, 3, 9, 7, 2 ] N = len(Point)K = 2 print("Maximum Rating of Coding Contest is:", FindMaxRating(N, Point, Upvote, K)) # This code is contributed by stutipathak31jan Maximum Rating of Coding Contest is: 60 Time Complexity: O(N * logN)Auxiliary Space: O(N) stutipathak31jan Algorithms Arrays Data Structures Greedy Heap Sorting Data Structures Arrays Greedy Sorting Heap Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar CPU Scheduling in Operating Systems A* Search Algorithm Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Count of subarrays with average K Program for array rotation
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jul, 2020" }, { "code": null, "e": 418, "s": 54, "text": "Given two arrays of positive integer Point[], Upvote[] of size N and a value K (1 <= K <= N). The task is to choose atleast K elements(Problems) such that the rating of the coding contest is maximum.Rating of contest: Rating of a contest is defined as total points of all problems in the contest multiplied by the minimum upvotes among all problems in the contest" }, { "code": null, "e": 510, "s": 418, "text": "Hence, Rating = sum of points of contest problems * minimum upvotes among contest problems." }, { "code": null, "e": 520, "s": 510, "text": "Examples:" }, { "code": null, "e": 739, "s": 520, "text": "Input: Point[] = {2, 10, 3, 1, 5, 8}, Upvote[] = {5, 4, 3, 9, 7, 2}, K = 2Output: 60Explanation:Here we select 2nd and 5th problem to get the maximum rating of the contest.So maximum rating is (10 + 5) * min(4, 7) = 60" }, { "code": null, "e": 970, "s": 739, "text": "Input: Point[] = {2, 10, 3, 1, 5, 8}, Upvote[] = {5, 4, 3, 9, 7, 2}, K = 3Output: 68Explanation:Here we select 1st, 2nd and 5th problem to get the maximum rating of the contest.So maximum rating is (2 + 10 + 5) * min(5, 4, 7) = 68" }, { "code": null, "e": 1229, "s": 970, "text": "Input: Point[] = {2, 20, 3, 1, 5, 8}, Upvote[] = {5, 10, 3, 9, 7, 2}, K = 4Output: 200Explanation:Here we select only 2nd problem to get maximum rating of the contest.A further selection of any problems decreases the rating.So maximum rating is 20 * 10 = 200" }, { "code": null, "e": 1240, "s": 1229, "text": "Approach :" }, { "code": null, "e": 2146, "s": 1240, "text": "Try the value of every upvote from highest to lowest and at the same time maintain an as large as possible points group, keep adding points to total points, if the number of problems in the contest exceeds K, lay off the problem with lowest points. This includes three steps.Sort problems by their upvotes value in decreasing order.For index i = 0, 1, ..., K-1, we push the points into the min_heap and calculate the rating. We only need to record the maximum rating. We use min_heap to track the problem with minimum points.For an index i = K, K+1, ..., N-1, if the point of the current problem is greater than the top of the min_heap, we pop the existing element and push the current element in the min_heap and update the maximum rating.In this way, calculate the maximum rating with respect to the problem with i-th largest upvotes since we have the problems with the K largest points in the min_heap." }, { "code": null, "e": 2777, "s": 2146, "text": "Sort problems by their upvotes value in decreasing order.For index i = 0, 1, ..., K-1, we push the points into the min_heap and calculate the rating. We only need to record the maximum rating. We use min_heap to track the problem with minimum points.For an index i = K, K+1, ..., N-1, if the point of the current problem is greater than the top of the min_heap, we pop the existing element and push the current element in the min_heap and update the maximum rating.In this way, calculate the maximum rating with respect to the problem with i-th largest upvotes since we have the problems with the K largest points in the min_heap." }, { "code": null, "e": 2835, "s": 2777, "text": "Sort problems by their upvotes value in decreasing order." }, { "code": null, "e": 3029, "s": 2835, "text": "For index i = 0, 1, ..., K-1, we push the points into the min_heap and calculate the rating. We only need to record the maximum rating. We use min_heap to track the problem with minimum points." }, { "code": null, "e": 3410, "s": 3029, "text": "For an index i = K, K+1, ..., N-1, if the point of the current problem is greater than the top of the min_heap, we pop the existing element and push the current element in the min_heap and update the maximum rating.In this way, calculate the maximum rating with respect to the problem with i-th largest upvotes since we have the problems with the K largest points in the min_heap." }, { "code": null, "e": 3461, "s": 3410, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 3465, "s": 3461, "text": "C++" }, { "code": null, "e": 3473, "s": 3465, "text": "Python3" }, { "code": "// C++ program to find the Maximum // Possible Rating of a Coding Contest#include <bits/stdc++.h>using namespace std; // Function to sort all problems// descending to upvotesbool Comparator(pair<int, int> p1, pair<int, int> p2){ return p1.second > p2.second;} // Function to return maximum// ratingint FindMaxRating(int N, int Point[], int Upvote[], int K){ // Declaring vector of pairs vector<pair<int, int> > vec; // Each pair represents a problem // with its points and upvotes for (int i = 0; i < N; i++) { vec.push_back(make_pair(Point[i], Upvote[i])); } // Step (1) - Sort problems by their // upvotes value in decreasing order sort(vec.begin(), vec.end(), Comparator); // Declaring min_heap or priority queue // to track of the problem with // minimum points. priority_queue<int, vector<int>, greater<int> > pq; int total_points = 0, max_rating = 0; // Step (2) - Loop for i = 0 to K - 1 and // do accordingly for (int i = 0; i < K; i++) { total_points = total_points + vec[i].first; max_rating = max(max_rating, total_points * vec[i].second); pq.push(vec[i].first); } // Step (3) - Loop for i = K to N - 1 // and do accordingly for (int i = K; i < N; i++) { if (pq.top() < vec[i].first) { total_points = total_points - pq.top() + vec[i].first; max_rating = max(max_rating, total_points * vec[i].second); pq.pop(); pq.push(vec[i].first); } } return max_rating;} // Driver codeint main(){ int Point[] = { 2, 10, 3, 1, 5, 8 }; int Upvote[] = { 5, 4, 3, 9, 7, 2 }; int N = sizeof(Point) / sizeof(Point[0]); int K = 2; cout << \"Maximum Rating of Coding Contest is: \" << FindMaxRating(N, Point, Upvote, K); return 0;}", "e": 5614, "s": 3473, "text": null }, { "code": "# Python3 program to find the Maximum # Possible Rating of a Coding Contest import heapq # Function to sort all problems # descending to upvotesdef Comparator(p1): return p1[1] # Function to return maximum # rating def FindMaxRating(N, Point, Upvote, K): # Declaring vector of pairs vec = [] # Each pair represents a problem # with its points and upvotes for i in range(N): vec.append([Point[i], Upvote[i]]) # Step (1) - Sort problems by their # upvotes value in decreasing order vec.sort(reverse = True, key = Comparator) # Declaring min_heap or priority queue # to track of the problem with # minimum points. pq = [] heapq.heapify(pq) total_points, max_rating = 0, 0 # Step (2) - Loop for i = 0 to K - 1 and # do accordingly for i in range(K): total_points = (total_points + vec[i][0]) max_rating = max(max_rating, total_points * vec[i][1]) heapq.heappush(pq, vec[i][0]) # Step (3) - Loop for i = K to N - 1 # and do accordingly for i in range(K, N): if pq[0] < vec[i][0]: total_points = (total_points - pq[0] + vec[i][0]) max_rating = max(max_rating, total_points * vec[i][1]) heapq.heappop(pq) heapq.heappush(pq, vec[i][0]) return max_rating # Driver codePoint = [ 2, 10, 3, 1, 5, 8 ]Upvote = [ 5, 4, 3, 9, 7, 2 ] N = len(Point)K = 2 print(\"Maximum Rating of Coding Contest is:\", FindMaxRating(N, Point, Upvote, K)) # This code is contributed by stutipathak31jan", "e": 7456, "s": 5614, "text": null }, { "code": null, "e": 7497, "s": 7456, "text": "Maximum Rating of Coding Contest is: 60\n" }, { "code": null, "e": 7547, "s": 7497, "text": "Time Complexity: O(N * logN)Auxiliary Space: O(N)" }, { "code": null, "e": 7564, "s": 7547, "text": "stutipathak31jan" }, { "code": null, "e": 7575, "s": 7564, "text": "Algorithms" }, { "code": null, "e": 7582, "s": 7575, "text": "Arrays" }, { "code": null, "e": 7598, "s": 7582, "text": "Data Structures" }, { "code": null, "e": 7605, "s": 7598, "text": "Greedy" }, { "code": null, "e": 7610, "s": 7605, "text": "Heap" }, { "code": null, "e": 7618, "s": 7610, "text": "Sorting" }, { "code": null, "e": 7634, "s": 7618, "text": "Data Structures" }, { "code": null, "e": 7641, "s": 7634, "text": "Arrays" }, { "code": null, "e": 7648, "s": 7641, "text": "Greedy" }, { "code": null, "e": 7656, "s": 7648, "text": "Sorting" }, { "code": null, "e": 7661, "s": 7656, "text": "Heap" }, { "code": null, "e": 7672, "s": 7661, "text": "Algorithms" }, { "code": null, "e": 7770, "s": 7672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7819, "s": 7770, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 7844, "s": 7819, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 7880, "s": 7844, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 7900, "s": 7880, "text": "A* Search Algorithm" }, { "code": null, "e": 7967, "s": 7900, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 7982, "s": 7967, "text": "Arrays in Java" }, { "code": null, "e": 8028, "s": 7982, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 8096, "s": 8028, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 8130, "s": 8096, "text": "Count of subarrays with average K" } ]
Convert PyMongo Cursor to Dataframe
26 May, 2020 Prerequisites: MongoDB Python Basics This article is about converting the PyMongo Cursor to Pandas Dataframe. Functions like find() and find_one() returns the Cursor instance. Let’s begin: Importing Required Modules: Import the required module using the command:from pymongo import MongoClient from pandas import DataFrameIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonIf pandas not install you can install it using pip and if you are using Python3 then use pip3 instead of pip to install the required modules.pip install pandas Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseAccessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collectionGetting the documents: Getting all the documents from the collection using find() method. It returns the instance of the Cursor.cursor = collection_name.find() Converting the Cursor to Dataframe: Converting the Cursor to the Pandas Dataframe.First, we convert the cursor to the list of dictionary.list_cur = list(cursor) Now, converting the list to the Dataframedf = DataFrame(list_cur) Importing Required Modules: Import the required module using the command:from pymongo import MongoClient from pandas import DataFrameIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonIf pandas not install you can install it using pip and if you are using Python3 then use pip3 instead of pip to install the required modules.pip install pandas from pymongo import MongoClient from pandas import DataFrame If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python If pandas not install you can install it using pip and if you are using Python3 then use pip3 instead of pip to install the required modules. pip install pandas Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017) client = MongoClient(‘localhost’, 27017) Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_database mydatabase = client.name_of_the_database Accessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collection collection_name = mydatabase.name_of_collection Getting the documents: Getting all the documents from the collection using find() method. It returns the instance of the Cursor.cursor = collection_name.find() cursor = collection_name.find() Converting the Cursor to Dataframe: Converting the Cursor to the Pandas Dataframe.First, we convert the cursor to the list of dictionary.list_cur = list(cursor) Now, converting the list to the Dataframedf = DataFrame(list_cur) list_cur = list(cursor) Now, converting the list to the Dataframe df = DataFrame(list_cur) Below is the implementation. Sample Database: # Python Program for demonstrating the # PyMongo Cursor to Pandas DataFrame # Importing required modulesfrom pymongo import MongoClientfrom pandas import DataFrame # Connecting to MongoDB server# client = MongoClient('host_name',# 'port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.College # Now creating a Cursor instance# using find() functioncursor = mycollection.find()print('Type of cursor:',type(cursor)) # Converting cursor to the list of # dictionarieslist_cur = list(cursor) # Converting to the DataFramedf = DataFrame(list_cur)print('Type of df:',type(df)) # Printing the df to consoleprint()print(df.head()) Output: Type of cursor: <class 'pymongo.cursor.Cursor'> Type of df: <class 'pandas.core.frame.DataFrame'> _id name Roll No Branch 0 1 Vishwash 1001 CSE 1 2 Vishesh 1002 IT 2 3 Shivam 1003 ME 3 4 Yash 1004 ECE 4 5 Raju 1005 CSE Python-mongoDB 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": "\n26 May, 2020" }, { "code": null, "e": 65, "s": 28, "text": "Prerequisites: MongoDB Python Basics" }, { "code": null, "e": 204, "s": 65, "text": "This article is about converting the PyMongo Cursor to Pandas Dataframe. Functions like find() and find_one() returns the Cursor instance." }, { "code": null, "e": 217, "s": 204, "text": "Let’s begin:" }, { "code": null, "e": 1573, "s": 217, "text": "Importing Required Modules: Import the required module using the command:from pymongo import MongoClient\nfrom pandas import DataFrameIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonIf pandas not install you can install it using pip and if you are using Python3 then use pip3 instead of pip to install the required modules.pip install pandas\nCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseAccessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collectionGetting the documents: Getting all the documents from the collection using find() method. It returns the instance of the Cursor.cursor = collection_name.find()\nConverting the Cursor to Dataframe: Converting the Cursor to the Pandas Dataframe.First, we convert the cursor to the list of dictionary.list_cur = list(cursor)\nNow, converting the list to the Dataframedf = DataFrame(list_cur)\n" }, { "code": null, "e": 1983, "s": 1573, "text": "Importing Required Modules: Import the required module using the command:from pymongo import MongoClient\nfrom pandas import DataFrameIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonIf pandas not install you can install it using pip and if you are using Python3 then use pip3 instead of pip to install the required modules.pip install pandas\n" }, { "code": null, "e": 2044, "s": 1983, "text": "from pymongo import MongoClient\nfrom pandas import DataFrame" }, { "code": null, "e": 2161, "s": 2044, "text": "If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python" }, { "code": null, "e": 2303, "s": 2161, "text": "If pandas not install you can install it using pip and if you are using Python3 then use pip3 instead of pip to install the required modules." }, { "code": null, "e": 2323, "s": 2303, "text": "pip install pandas\n" }, { "code": null, "e": 2566, "s": 2323, "text": "Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)" }, { "code": null, "e": 2607, "s": 2566, "text": "client = MongoClient(‘localhost’, 27017)" }, { "code": null, "e": 2778, "s": 2607, "text": "Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_database" }, { "code": null, "e": 2819, "s": 2778, "text": "mydatabase = client.name_of_the_database" }, { "code": null, "e": 2967, "s": 2819, "text": "Accessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collection" }, { "code": null, "e": 3015, "s": 2967, "text": "collection_name = mydatabase.name_of_collection" }, { "code": null, "e": 3176, "s": 3015, "text": "Getting the documents: Getting all the documents from the collection using find() method. It returns the instance of the Cursor.cursor = collection_name.find()\n" }, { "code": null, "e": 3209, "s": 3176, "text": "cursor = collection_name.find()\n" }, { "code": null, "e": 3437, "s": 3209, "text": "Converting the Cursor to Dataframe: Converting the Cursor to the Pandas Dataframe.First, we convert the cursor to the list of dictionary.list_cur = list(cursor)\nNow, converting the list to the Dataframedf = DataFrame(list_cur)\n" }, { "code": null, "e": 3462, "s": 3437, "text": "list_cur = list(cursor)\n" }, { "code": null, "e": 3504, "s": 3462, "text": "Now, converting the list to the Dataframe" }, { "code": null, "e": 3530, "s": 3504, "text": "df = DataFrame(list_cur)\n" }, { "code": null, "e": 3559, "s": 3530, "text": "Below is the implementation." }, { "code": null, "e": 3576, "s": 3559, "text": "Sample Database:" }, { "code": "# Python Program for demonstrating the # PyMongo Cursor to Pandas DataFrame # Importing required modulesfrom pymongo import MongoClientfrom pandas import DataFrame # Connecting to MongoDB server# client = MongoClient('host_name',# 'port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.College # Now creating a Cursor instance# using find() functioncursor = mycollection.find()print('Type of cursor:',type(cursor)) # Converting cursor to the list of # dictionarieslist_cur = list(cursor) # Converting to the DataFramedf = DataFrame(list_cur)print('Type of df:',type(df)) # Printing the df to consoleprint()print(df.head())", "e": 4351, "s": 3576, "text": null }, { "code": null, "e": 4359, "s": 4351, "text": "Output:" }, { "code": null, "e": 4650, "s": 4359, "text": "Type of cursor: <class 'pymongo.cursor.Cursor'>\nType of df: <class 'pandas.core.frame.DataFrame'>\n\n _id name Roll No Branch\n0 1 Vishwash 1001 CSE\n1 2 Vishesh 1002 IT\n2 3 Shivam 1003 ME\n3 4 Yash 1004 ECE\n4 5 Raju 1005 CSE" }, { "code": null, "e": 4665, "s": 4650, "text": "Python-mongoDB" }, { "code": null, "e": 4672, "s": 4665, "text": "Python" }, { "code": null, "e": 4770, "s": 4672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4788, "s": 4770, "text": "Python Dictionary" }, { "code": null, "e": 4830, "s": 4788, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4852, "s": 4830, "text": "Enumerate() in Python" }, { "code": null, "e": 4887, "s": 4852, "text": "Read a file line by line in Python" }, { "code": null, "e": 4913, "s": 4887, "text": "Python String | replace()" }, { "code": null, "e": 4945, "s": 4913, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4974, "s": 4945, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5004, "s": 4974, "text": "Iterate over a list in Python" }, { "code": null, "e": 5031, "s": 5004, "text": "Python Classes and Objects" } ]
How to use while True in Python
22 Nov, 2021 In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Python3 # Python program to demonstrate# while loop with True while True: pass If we run the above code then this loop will run infinite number of times. To come out of this loop we will use the break statement explicitly. Let’s consider the below example, where we want to find the sum of the first N numbers. Let’s see the below code for better understanding. Python3 # Python program to demonstrate# while loop with True N = 10Sum = 0 # This loop will run foreverwhile True: Sum += N N -= 1 # the below condition will tell # the loop to stop if N == 0: break print(f"Sum of First 10 Numbers is {Sum}") Sum of First 10 Numbers is 55 In the above example, we have used the while True statement to run the while loop and we have added an if statement that will stop the execution of the loop when the value of N becomes 0 If we do not write this if statement then the loop will run forever and will start adding the negative values of N to the sum. prachisoda1234 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 How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 94, "s": 28, "text": "In this article, we will discuss how to use while True in Python." }, { "code": null, "e": 256, "s": 94, "text": "While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever." }, { "code": null, "e": 264, "s": 256, "text": "Python3" }, { "code": "# Python program to demonstrate# while loop with True while True: pass", "e": 339, "s": 264, "text": null }, { "code": null, "e": 483, "s": 339, "text": "If we run the above code then this loop will run infinite number of times. To come out of this loop we will use the break statement explicitly." }, { "code": null, "e": 622, "s": 483, "text": "Let’s consider the below example, where we want to find the sum of the first N numbers. Let’s see the below code for better understanding." }, { "code": null, "e": 630, "s": 622, "text": "Python3" }, { "code": "# Python program to demonstrate# while loop with True N = 10Sum = 0 # This loop will run foreverwhile True: Sum += N N -= 1 # the below condition will tell # the loop to stop if N == 0: break print(f\"Sum of First 10 Numbers is {Sum}\")", "e": 904, "s": 630, "text": null }, { "code": null, "e": 934, "s": 904, "text": "Sum of First 10 Numbers is 55" }, { "code": null, "e": 1248, "s": 934, "text": "In the above example, we have used the while True statement to run the while loop and we have added an if statement that will stop the execution of the loop when the value of N becomes 0 If we do not write this if statement then the loop will run forever and will start adding the negative values of N to the sum." }, { "code": null, "e": 1263, "s": 1248, "text": "prachisoda1234" }, { "code": null, "e": 1270, "s": 1263, "text": "Python" }, { "code": null, "e": 1368, "s": 1270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1400, "s": 1368, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1427, "s": 1400, "text": "Python Classes and Objects" }, { "code": null, "e": 1458, "s": 1427, "text": "Python | os.path.join() method" }, { "code": null, "e": 1479, "s": 1458, "text": "Python OOPs Concepts" }, { "code": null, "e": 1535, "s": 1479, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1558, "s": 1535, "text": "Introduction To PYTHON" }, { "code": null, "e": 1600, "s": 1558, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1642, "s": 1600, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1681, "s": 1642, "text": "Python | datetime.timedelta() function" } ]
Python – Filter all uppercase characters Tuples from given list of tuples
02 Sep, 2020 Given a Tuple list, filter tuples which contains all uppercase characters. Input : test_list = [(“GFG”, “IS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)]Output : [(‘GFG’, ‘IS’, ‘BEST’)]Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [(“GFG”, “iS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)]Output : []Explanation : No has all uppercase Strings. Method #1 : Using loop In this, we iterate for each tuple, and check if every string is uppercase, if no, that tuple is omitted from new tuple. Python3 # Python3 code to demonstrate working of # Filter uppercase characters Tuples# Using loop # initializing listtest_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")] # printing original listprint("The original list is : " + str(test_list)) res_list = []for sub in test_list: res = True for ele in sub: # checking for uppercase if not ele.isupper(): res = False break if res: res_list.append(sub) # printing resultsprint("Filtered Tuples : " + str(res_list)) The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')] Filtered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )] Method #2 : Using list comprehension + all() + isupper() In this, we check for all strings uppercase using all(), and list comprehension provides compact solution of problem. isupper() is used to check for uppercase. Python3 # Python3 code to demonstrate working of # Filter uppercase characters Tuples# Using list comprehension + all() + isupper() # initializing listtest_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")] # printing original listprint("The original list is : " + str(test_list)) # all() returns true only when all strings are uppercaseres = [sub for sub in test_list if all(ele.isupper() for ele in sub)] # printing resultsprint("Filtered Tuples : " + str(res)) The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')] Filtered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON 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 Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 103, "s": 28, "text": "Given a Tuple list, filter tuples which contains all uppercase characters." }, { "code": null, "e": 278, "s": 103, "text": "Input : test_list = [(“GFG”, “IS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)]Output : [(‘GFG’, ‘IS’, ‘BEST’)]Explanation : Only 1 tuple has all uppercase Strings." }, { "code": null, "e": 422, "s": 278, "text": "Input : test_list = [(“GFG”, “iS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)]Output : []Explanation : No has all uppercase Strings." }, { "code": null, "e": 445, "s": 422, "text": "Method #1 : Using loop" }, { "code": null, "e": 567, "s": 445, "text": "In this, we iterate for each tuple, and check if every string is uppercase, if no, that tuple is omitted from new tuple. " }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Filter uppercase characters Tuples# Using loop # initializing listtest_list = [(\"GFG\", \"IS\", \"BEST\"), (\"GFg\", \"AVERAGE\"), (\"GFG\", ), (\"Gfg\", \"CS\")] # printing original listprint(\"The original list is : \" + str(test_list)) res_list = []for sub in test_list: res = True for ele in sub: # checking for uppercase if not ele.isupper(): res = False break if res: res_list.append(sub) # printing resultsprint(\"Filtered Tuples : \" + str(res_list))", "e": 1126, "s": 575, "text": null }, { "code": null, "e": 1273, "s": 1126, "text": "The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')]\nFiltered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )]\n" }, { "code": null, "e": 1330, "s": 1273, "text": "Method #2 : Using list comprehension + all() + isupper()" }, { "code": null, "e": 1490, "s": 1330, "text": "In this, we check for all strings uppercase using all(), and list comprehension provides compact solution of problem. isupper() is used to check for uppercase." }, { "code": null, "e": 1498, "s": 1490, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Filter uppercase characters Tuples# Using list comprehension + all() + isupper() # initializing listtest_list = [(\"GFG\", \"IS\", \"BEST\"), (\"GFg\", \"AVERAGE\"), (\"GFG\", ), (\"Gfg\", \"CS\")] # printing original listprint(\"The original list is : \" + str(test_list)) # all() returns true only when all strings are uppercaseres = [sub for sub in test_list if all(ele.isupper() for ele in sub)] # printing resultsprint(\"Filtered Tuples : \" + str(res))", "e": 1984, "s": 1498, "text": null }, { "code": null, "e": 2131, "s": 1984, "text": "The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')]\nFiltered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )]\n" }, { "code": null, "e": 2152, "s": 2131, "text": "Python list-programs" }, { "code": null, "e": 2159, "s": 2152, "text": "Python" }, { "code": null, "e": 2175, "s": 2159, "text": "Python Programs" }, { "code": null, "e": 2273, "s": 2175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2305, "s": 2273, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2332, "s": 2305, "text": "Python Classes and Objects" }, { "code": null, "e": 2353, "s": 2332, "text": "Python OOPs Concepts" }, { "code": null, "e": 2376, "s": 2353, "text": "Introduction To PYTHON" }, { "code": null, "e": 2432, "s": 2376, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2454, "s": 2432, "text": "Defaultdict in Python" }, { "code": null, "e": 2493, "s": 2454, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2531, "s": 2493, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2568, "s": 2531, "text": "Python Program for Fibonacci numbers" } ]
Python sympy | Matrix.rref() method
13 Aug, 2019 With the help of sympy.Matrix().rref() method, we can put a matrix into reduced Row echelon form. Matrix().rref() returns a tuple of two elements. The first is the reduced row echelon form, and the second is a tuple of indices of the pivot columns. Syntax: Matrix().rref() Returns: Returns a tuple of which first element is of type Matrix and second one is of type tuple. Example #1: # import sympy from sympy import * M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])print("Matrix : {} ".format(M)) # Use sympy.rref() method M_rref = M.rref() print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref)) Output: Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]]) The Row echelon form of matrix M and the pivot columns : (Matrix([ [1, 0, 1, 3], [0, 1, 2/3, 1/3], [0, 0, 0, 0]]), (0, 1)) Example #2: # import sympy from sympy import * M = Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])print("Matrix : {} ".format(M)) # Use sympy.rref() method M_rref = M.rref() print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref)) Output: Matrix : Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]]) The Row echelon form of matrix M and the pivot columns : (Matrix([ [1, 0, 0, 1405/4254], [0, 1, 0, 10/709], [0, 0, 1, -314/2127]]), (0, 1, 2)) SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Aug, 2019" }, { "code": null, "e": 301, "s": 52, "text": "With the help of sympy.Matrix().rref() method, we can put a matrix into reduced Row echelon form. Matrix().rref() returns a tuple of two elements. The first is the reduced row echelon form, and the second is a tuple of indices of the pivot columns." }, { "code": null, "e": 325, "s": 301, "text": "Syntax: Matrix().rref()" }, { "code": null, "e": 424, "s": 325, "text": "Returns: Returns a tuple of which first element is of type Matrix and second one is of type tuple." }, { "code": null, "e": 436, "s": 424, "text": "Example #1:" }, { "code": "# import sympy from sympy import * M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])print(\"Matrix : {} \".format(M)) # Use sympy.rref() method M_rref = M.rref() print(\"The Row echelon form of matrix M and the pivot columns : {}\".format(M_rref)) ", "e": 702, "s": 436, "text": null }, { "code": null, "e": 710, "s": 702, "text": "Output:" }, { "code": null, "e": 907, "s": 710, "text": "Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]]) \nThe Row echelon form of matrix M and the pivot columns : (Matrix([\n[1, 0, 1, 3],\n[0, 1, 2/3, 1/3],\n[0, 0, 0, 0]]), (0, 1))\n" }, { "code": null, "e": 919, "s": 907, "text": "Example #2:" }, { "code": "# import sympy from sympy import * M = Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])print(\"Matrix : {} \".format(M)) # Use sympy.rref() method M_rref = M.rref() print(\"The Row echelon form of matrix M and the pivot columns : {}\".format(M_rref)) ", "e": 1191, "s": 919, "text": null }, { "code": null, "e": 1199, "s": 1191, "text": "Output:" }, { "code": null, "e": 1417, "s": 1199, "text": "Matrix : Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]]) \nThe Row echelon form of matrix M and the pivot columns : (Matrix([\n[1, 0, 0, 1405/4254],\n[0, 1, 0, 10/709],\n[0, 0, 1, -314/2127]]), (0, 1, 2))\n" }, { "code": null, "e": 1423, "s": 1417, "text": "SymPy" }, { "code": null, "e": 1430, "s": 1423, "text": "Python" } ]
How to calculate the number of occurrences of a character in each row of R DataFrame ?
18 Apr, 2022 In this article, we will discuss how to calculate the number of occurrences of a given character in each row in DataFrame in R Programming Language. The stringr package in R programming language can be used to perform string manipulations and extraction, which can be installed into the working space. The str_count() method is used to return the matching of the specified pattern in the vector of strings. It returns an integer vector of the number of instances of the pattern found in the input argument vector. The str_count() method is case-sensitive. Syntax: str_count(str, pattern = “”) Parameter : str – The vector of strings or a single string to search for the pattern pattern – The pattern to be searched for. Usually a regular expression. The pattern may be a single character or a group of characters stacked together. It may even contain special symbols or digits. In case, the pattern is not found, an integer value of 0 is returned. Example: R # loading the reqd librarylibrary ("stringr") # creating a data framedata_frame <- data.frame( col1 = c(1:5), col2 = c("Geeks","for","geeks","CSE","portal")) # character to search forch <- "e" # counting the occurrences of charactercount <- str_count(data_frame$col2, ch)print ("Count of e :")print (count) Output [1] “Count of e :” [1] 2 0 2 0 0 The gregexpr() method of base R is used to indicate where a pattern is located within a specified character vector. It is used to return a vector of vectors of the starting positions of the matching w.r.t each component of the input character array. The returned vector’s length is equivalent to the length of the original string vector. Syntax: gregexpr(pattern, str, ignore.case=FALSE) Parameter : str – The vector of strings or a single string to search for the pattern pattern – The pattern to be searched for. Usually a regular expression. ignore.case – Indicator to ignore case or not Here, the pattern is the character to search for and the str is the column of strings to look the pattern in. The regmatches() method is applied over the output of this function, which is used to extract or replace the matched substrings from the matched data. In case, no match of the substring pattern is found, empty string is returned. Syntax: regmatches(str, m) Parameter : m – The output vector from the matched data. This is followed by the application of lengths() method, which returns the length of each substring component from the regmatches() vector. Example: R # creating a data framedata_frame <- data.frame( col1 = c(1:5), col2 = c("!?contains","do!es!nt", "Contain","cs!!!e","circus?")) print ("Original DataFrame")print (data_frame) # character to search forch <- "!"count <- regmatches( data_frame$col2, gregexpr(ch, data_frame$col2)) print ("Count of !") # returning the number of occurrenceslengths(count) Output [1] “Original DataFrame” col1 col2 1 1 !?contains 2 2 do!es!nt 3 3 Contain 4 4 cs!!!e 5 5 circus? [1] “Count of !” [1] 1 2 0 3 0 The sapply() method in R is used to apply a user-defined function over the specified input vector taken as the first argument. The user-defined function, in this case, consists of a sequence of steps : Syntax: sapply ( x , fun) strsplit() method is applied to split each component of the input vector into components based on ” ” delimiter. It is useful in case a string consists of multiple words. It returns an array of words in each element of the column. The unlist() method is then applied to each word in a vector of letters, and check if each letter is equivalent to the character we wish to search for. The sum() method is then applied to increment the count each time a match is found. Syntax: sum ( unlist( str) == ch) Example: R # creating a data framedata_frame <- data.frame( col1 = c(1:5), col2 = c("!?contains","do!es!nt", "Contain","cs!!!e","circus?")) print ("Original DataFrame")print (data_frame) # character to search forch <- "!"count <- sapply(as.character(data_frame$col2), function(x, letter = ch){ str <- strsplit(x, split = "") sum(unlist(str) == letter)})print ("Count of !") # returning the number of occurrencesprint(count) Output [1] “Original DataFrame” col1 col2 1 1 !?contains 2 2 do!es!nt 3 3 Contain 4 4 cs!!!e 5 5 circus? [1] “Count of !” !?contains do!es!nt Contain cs!!!e circus? 1 2 0 3 0 sweetyty Picked R DataFrame-Programs R String-Programs R-DataFrame R-strings R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Apr, 2022" }, { "code": null, "e": 177, "s": 28, "text": "In this article, we will discuss how to calculate the number of occurrences of a given character in each row in DataFrame in R Programming Language." }, { "code": null, "e": 330, "s": 177, "text": "The stringr package in R programming language can be used to perform string manipulations and extraction, which can be installed into the working space." }, { "code": null, "e": 585, "s": 330, "text": "The str_count() method is used to return the matching of the specified pattern in the vector of strings. It returns an integer vector of the number of instances of the pattern found in the input argument vector. The str_count() method is case-sensitive. " }, { "code": null, "e": 593, "s": 585, "text": "Syntax:" }, { "code": null, "e": 622, "s": 593, "text": "str_count(str, pattern = “”)" }, { "code": null, "e": 635, "s": 622, "text": "Parameter : " }, { "code": null, "e": 708, "s": 635, "text": "str – The vector of strings or a single string to search for the pattern" }, { "code": null, "e": 780, "s": 708, "text": "pattern – The pattern to be searched for. Usually a regular expression." }, { "code": null, "e": 979, "s": 780, "text": "The pattern may be a single character or a group of characters stacked together. It may even contain special symbols or digits. In case, the pattern is not found, an integer value of 0 is returned. " }, { "code": null, "e": 988, "s": 979, "text": "Example:" }, { "code": null, "e": 990, "s": 988, "text": "R" }, { "code": "# loading the reqd librarylibrary (\"stringr\") # creating a data framedata_frame <- data.frame( col1 = c(1:5), col2 = c(\"Geeks\",\"for\",\"geeks\",\"CSE\",\"portal\")) # character to search forch <- \"e\" # counting the occurrences of charactercount <- str_count(data_frame$col2, ch)print (\"Count of e :\")print (count)", "e": 1298, "s": 990, "text": null }, { "code": null, "e": 1305, "s": 1298, "text": "Output" }, { "code": null, "e": 1325, "s": 1305, "text": "[1] “Count of e :” " }, { "code": null, "e": 1339, "s": 1325, "text": "[1] 2 0 2 0 0" }, { "code": null, "e": 1678, "s": 1339, "text": "The gregexpr() method of base R is used to indicate where a pattern is located within a specified character vector. It is used to return a vector of vectors of the starting positions of the matching w.r.t each component of the input character array. The returned vector’s length is equivalent to the length of the original string vector. " }, { "code": null, "e": 1686, "s": 1678, "text": "Syntax:" }, { "code": null, "e": 1728, "s": 1686, "text": "gregexpr(pattern, str, ignore.case=FALSE)" }, { "code": null, "e": 1740, "s": 1728, "text": "Parameter :" }, { "code": null, "e": 1813, "s": 1740, "text": "str – The vector of strings or a single string to search for the pattern" }, { "code": null, "e": 1885, "s": 1813, "text": "pattern – The pattern to be searched for. Usually a regular expression." }, { "code": null, "e": 1931, "s": 1885, "text": "ignore.case – Indicator to ignore case or not" }, { "code": null, "e": 2273, "s": 1931, "text": "Here, the pattern is the character to search for and the str is the column of strings to look the pattern in. The regmatches() method is applied over the output of this function, which is used to extract or replace the matched substrings from the matched data. In case, no match of the substring pattern is found, empty string is returned. " }, { "code": null, "e": 2281, "s": 2273, "text": "Syntax:" }, { "code": null, "e": 2300, "s": 2281, "text": "regmatches(str, m)" }, { "code": null, "e": 2313, "s": 2300, "text": "Parameter : " }, { "code": null, "e": 2359, "s": 2313, "text": "m – The output vector from the matched data. " }, { "code": null, "e": 2500, "s": 2359, "text": "This is followed by the application of lengths() method, which returns the length of each substring component from the regmatches() vector. " }, { "code": null, "e": 2509, "s": 2500, "text": "Example:" }, { "code": null, "e": 2511, "s": 2509, "text": "R" }, { "code": "# creating a data framedata_frame <- data.frame( col1 = c(1:5), col2 = c(\"!?contains\",\"do!es!nt\", \"Contain\",\"cs!!!e\",\"circus?\")) print (\"Original DataFrame\")print (data_frame) # character to search forch <- \"!\"count <- regmatches( data_frame$col2, gregexpr(ch, data_frame$col2)) print (\"Count of !\") # returning the number of occurrenceslengths(count)", "e": 2890, "s": 2511, "text": null }, { "code": null, "e": 2897, "s": 2890, "text": "Output" }, { "code": null, "e": 2923, "s": 2897, "text": "[1] “Original DataFrame” " }, { "code": null, "e": 2944, "s": 2923, "text": " col1 col2 " }, { "code": null, "e": 2963, "s": 2944, "text": "1 1 !?contains " }, { "code": null, "e": 2982, "s": 2963, "text": "2 2 do!es!nt " }, { "code": null, "e": 3001, "s": 2982, "text": "3 3 Contain " }, { "code": null, "e": 3020, "s": 3001, "text": "4 4 cs!!!e " }, { "code": null, "e": 3039, "s": 3020, "text": "5 5 circus? " }, { "code": null, "e": 3057, "s": 3039, "text": "[1] “Count of !” " }, { "code": null, "e": 3071, "s": 3057, "text": "[1] 1 2 0 3 0" }, { "code": null, "e": 3273, "s": 3071, "text": "The sapply() method in R is used to apply a user-defined function over the specified input vector taken as the first argument. The user-defined function, in this case, consists of a sequence of steps :" }, { "code": null, "e": 3281, "s": 3273, "text": "Syntax:" }, { "code": null, "e": 3299, "s": 3281, "text": "sapply ( x , fun)" }, { "code": null, "e": 3530, "s": 3299, "text": "strsplit() method is applied to split each component of the input vector into components based on ” ” delimiter. It is useful in case a string consists of multiple words. It returns an array of words in each element of the column." }, { "code": null, "e": 3766, "s": 3530, "text": "The unlist() method is then applied to each word in a vector of letters, and check if each letter is equivalent to the character we wish to search for. The sum() method is then applied to increment the count each time a match is found." }, { "code": null, "e": 3774, "s": 3766, "text": "Syntax:" }, { "code": null, "e": 3800, "s": 3774, "text": "sum ( unlist( str) == ch)" }, { "code": null, "e": 3809, "s": 3800, "text": "Example:" }, { "code": null, "e": 3811, "s": 3809, "text": "R" }, { "code": "# creating a data framedata_frame <- data.frame( col1 = c(1:5), col2 = c(\"!?contains\",\"do!es!nt\", \"Contain\",\"cs!!!e\",\"circus?\")) print (\"Original DataFrame\")print (data_frame) # character to search forch <- \"!\"count <- sapply(as.character(data_frame$col2), function(x, letter = ch){ str <- strsplit(x, split = \"\") sum(unlist(str) == letter)})print (\"Count of !\") # returning the number of occurrencesprint(count)", "e": 4267, "s": 3811, "text": null }, { "code": null, "e": 4274, "s": 4267, "text": "Output" }, { "code": null, "e": 4300, "s": 4274, "text": "[1] “Original DataFrame” " }, { "code": null, "e": 4321, "s": 4300, "text": " col1 col2 " }, { "code": null, "e": 4340, "s": 4321, "text": "1 1 !?contains " }, { "code": null, "e": 4359, "s": 4340, "text": "2 2 do!es!nt " }, { "code": null, "e": 4378, "s": 4359, "text": "3 3 Contain " }, { "code": null, "e": 4397, "s": 4378, "text": "4 4 cs!!!e " }, { "code": null, "e": 4415, "s": 4397, "text": "5 5 circus?" }, { "code": null, "e": 4433, "s": 4415, "text": "[1] “Count of !” " }, { "code": null, "e": 4499, "s": 4433, "text": "!?contains do!es!nt Contain cs!!!e circus? " }, { "code": null, "e": 4555, "s": 4499, "text": " 1 2 0 3 0 " }, { "code": null, "e": 4564, "s": 4555, "text": "sweetyty" }, { "code": null, "e": 4571, "s": 4564, "text": "Picked" }, { "code": null, "e": 4592, "s": 4571, "text": "R DataFrame-Programs" }, { "code": null, "e": 4610, "s": 4592, "text": "R String-Programs" }, { "code": null, "e": 4622, "s": 4610, "text": "R-DataFrame" }, { "code": null, "e": 4632, "s": 4622, "text": "R-strings" }, { "code": null, "e": 4643, "s": 4632, "text": "R Language" }, { "code": null, "e": 4654, "s": 4643, "text": "R Programs" }, { "code": null, "e": 4752, "s": 4654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4804, "s": 4752, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 4862, "s": 4804, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4897, "s": 4862, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4935, "s": 4897, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 4984, "s": 4935, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 5042, "s": 4984, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5091, "s": 5042, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 5134, "s": 5091, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 5172, "s": 5134, "text": "Merge DataFrames by Column Names in R" } ]
Making Calls in Flutter
13 Jun, 2022 In this online world, customer care is playing a major role in the success of a company. Users are quite satisfied when they converse with the executives through calls. This has forced companies to add phone numbers to their apps for their customers to contact them easily. But, dialing those numbers from the app into the default phone app makes it quite cumbersome. So, in order to improve the user experience, Flutter has come up with a feature where the user can call the other, just with a click. This can be achieved by using the “url_launcher” plugin. In Flutter, everything is a widget and in the same way, Flutter also uses a lot of plugins or dependencies in order to make the app work faster and easier. In this case, the “url_launcher” plugin can be used to make a call in a mobile application. The steps for adding the plugin to the Flutter app are as follows: 1. Open “pubspec.yaml” file from the project folder. 2. In the pubspec.yaml file, type “url_launcher:” under dependencies. After that, the code looks like this: Dart dependencies: flutter: sdk: flutter url_launcher: 3. Now click “Pub Get” button at the top of the application (Android Studio). 4. The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully. 5. Now import the plugin or package by adding the “import ‘package:url_launcher/url_launcher.dart’;” code to the top of the “main.dart” file. Now, let’s create a function that can be called, whenever the user clicks a button, that’s linked to a phone number, to make a call. Dart _makingPhoneCall() async { var url = Uri.parse("tel:9776765434"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} The function is named here as “_makingPhoneCall” and the function is declared as “async”, so that it returns a promise.The “url” variable is assigned with the required phone number, as a string. The “tel:” syntax here before the phone number, makes Flutter realize that the following number is a phone number that has to be opened in the default Phone App. It is declared as a “const”, so that the variable is not changed under any circumstance.If there is a possibility to launch the URL, only then the URL is launched by calling the launch() function with the URL variable as an attribute.Else, it will throw/print a text with the URL value, as an error message. The function is named here as “_makingPhoneCall” and the function is declared as “async”, so that it returns a promise. The “url” variable is assigned with the required phone number, as a string. The “tel:” syntax here before the phone number, makes Flutter realize that the following number is a phone number that has to be opened in the default Phone App. It is declared as a “const”, so that the variable is not changed under any circumstance. If there is a possibility to launch the URL, only then the URL is launched by calling the launch() function with the URL variable as an attribute. Else, it will throw/print a text with the URL value, as an error message. The above function can be called when needed inside the program, by calling the name of the functions as it is. The example is as follows: Dart ElevatedButton( onPressed: _makingPhoneCall, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), child: const Text('Here'), ), // ElevatedButton // DEPRECATED // RaisedButton( // onPressed: _makingPhoneCall, // child: Text('Call'), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), // ), This creates a raised button having the text “Call” on it.For the onPressed attribute, we are calling “_makingPhoneCall” so that, when the button is pressed, the default Phone app is opened and the phone number in the URL variable is dialed automatically, making it easier for the user. This creates a raised button having the text “Call” on it. For the onPressed attribute, we are calling “_makingPhoneCall” so that, when the button is pressed, the default Phone app is opened and the phone number in the URL variable is dialed automatically, making it easier for the user. Complete Source Code: Dart // importing dependenciesimport 'package:flutter/material.dart';// cupertino package was unusesimport 'package:url_launcher/url_launcher.dart'; // function to trigger the app buildvoid main() => runApp(const MyApp()); _makingPhoneCall() async { var url = Uri.parse("tel:9776765434"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), // AppBar body: SafeArea( child: Center( child: Column( children: [ Container( height: 250.0, ),//Container const Text( 'Welcome to GFG!', style: TextStyle( fontSize: 30.0, color: Colors.green, fontWeight: FontWeight.bold, ),//TextStyle ),//Text Container( height: 20.0, ), const Text( 'For further Updates', style: TextStyle( fontSize: 20.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), Container( height: 20.0, ), ElevatedButton( onPressed: _makingPhoneCall, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), child: const Text('Here'), ), // ElevatedButton // DEPRECATED // RaisedButton( // onPressed: _makingPhoneCall, // child: Text('Call'), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), // ), ], ), ), ), ), ); }} Output: ankit_kumar_ Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android Architecture MVVM (Model View ViewModel) Architecture Pattern in Android Services in Android with Example Android Tutorial Bottom Navigation Bar in Android Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 587, "s": 28, "text": "In this online world, customer care is playing a major role in the success of a company. Users are quite satisfied when they converse with the executives through calls. This has forced companies to add phone numbers to their apps for their customers to contact them easily. But, dialing those numbers from the app into the default phone app makes it quite cumbersome. So, in order to improve the user experience, Flutter has come up with a feature where the user can call the other, just with a click. This can be achieved by using the “url_launcher” plugin." }, { "code": null, "e": 902, "s": 587, "text": "In Flutter, everything is a widget and in the same way, Flutter also uses a lot of plugins or dependencies in order to make the app work faster and easier. In this case, the “url_launcher” plugin can be used to make a call in a mobile application. The steps for adding the plugin to the Flutter app are as follows:" }, { "code": null, "e": 955, "s": 902, "text": "1. Open “pubspec.yaml” file from the project folder." }, { "code": null, "e": 1025, "s": 955, "text": "2. In the pubspec.yaml file, type “url_launcher:” under dependencies." }, { "code": null, "e": 1063, "s": 1025, "text": "After that, the code looks like this:" }, { "code": null, "e": 1068, "s": 1063, "text": "Dart" }, { "code": "dependencies: flutter: sdk: flutter url_launcher:", "e": 1120, "s": 1068, "text": null }, { "code": null, "e": 1198, "s": 1120, "text": "3. Now click “Pub Get” button at the top of the application (Android Studio)." }, { "code": null, "e": 1310, "s": 1198, "text": "4. The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully." }, { "code": null, "e": 1452, "s": 1310, "text": "5. Now import the plugin or package by adding the “import ‘package:url_launcher/url_launcher.dart’;” code to the top of the “main.dart” file." }, { "code": null, "e": 1585, "s": 1452, "text": "Now, let’s create a function that can be called, whenever the user clicks a button, that’s linked to a phone number, to make a call." }, { "code": null, "e": 1590, "s": 1585, "text": "Dart" }, { "code": "_makingPhoneCall() async { var url = Uri.parse(\"tel:9776765434\"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }}", "e": 1762, "s": 1590, "text": null }, { "code": null, "e": 2427, "s": 1762, "text": "The function is named here as “_makingPhoneCall” and the function is declared as “async”, so that it returns a promise.The “url” variable is assigned with the required phone number, as a string. The “tel:” syntax here before the phone number, makes Flutter realize that the following number is a phone number that has to be opened in the default Phone App. It is declared as a “const”, so that the variable is not changed under any circumstance.If there is a possibility to launch the URL, only then the URL is launched by calling the launch() function with the URL variable as an attribute.Else, it will throw/print a text with the URL value, as an error message." }, { "code": null, "e": 2547, "s": 2427, "text": "The function is named here as “_makingPhoneCall” and the function is declared as “async”, so that it returns a promise." }, { "code": null, "e": 2874, "s": 2547, "text": "The “url” variable is assigned with the required phone number, as a string. The “tel:” syntax here before the phone number, makes Flutter realize that the following number is a phone number that has to be opened in the default Phone App. It is declared as a “const”, so that the variable is not changed under any circumstance." }, { "code": null, "e": 3021, "s": 2874, "text": "If there is a possibility to launch the URL, only then the URL is launched by calling the launch() function with the URL variable as an attribute." }, { "code": null, "e": 3095, "s": 3021, "text": "Else, it will throw/print a text with the URL value, as an error message." }, { "code": null, "e": 3234, "s": 3095, "text": "The above function can be called when needed inside the program, by calling the name of the functions as it is. The example is as follows:" }, { "code": null, "e": 3239, "s": 3234, "text": "Dart" }, { "code": " ElevatedButton( onPressed: _makingPhoneCall, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), child: const Text('Here'), ), // ElevatedButton // DEPRECATED // RaisedButton( // onPressed: _makingPhoneCall, // child: Text('Call'), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), // ),", "e": 3754, "s": 3239, "text": null }, { "code": null, "e": 4041, "s": 3754, "text": "This creates a raised button having the text “Call” on it.For the onPressed attribute, we are calling “_makingPhoneCall” so that, when the button is pressed, the default Phone app is opened and the phone number in the URL variable is dialed automatically, making it easier for the user." }, { "code": null, "e": 4100, "s": 4041, "text": "This creates a raised button having the text “Call” on it." }, { "code": null, "e": 4329, "s": 4100, "text": "For the onPressed attribute, we are calling “_makingPhoneCall” so that, when the button is pressed, the default Phone app is opened and the phone number in the URL variable is dialed automatically, making it easier for the user." }, { "code": null, "e": 4351, "s": 4329, "text": "Complete Source Code:" }, { "code": null, "e": 4356, "s": 4351, "text": "Dart" }, { "code": "// importing dependenciesimport 'package:flutter/material.dart';// cupertino package was unusesimport 'package:url_launcher/url_launcher.dart'; // function to trigger the app buildvoid main() => runApp(const MyApp()); _makingPhoneCall() async { var url = Uri.parse(\"tel:9776765434\"); if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; }} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), // AppBar body: SafeArea( child: Center( child: Column( children: [ Container( height: 250.0, ),//Container const Text( 'Welcome to GFG!', style: TextStyle( fontSize: 30.0, color: Colors.green, fontWeight: FontWeight.bold, ),//TextStyle ),//Text Container( height: 20.0, ), const Text( 'For further Updates', style: TextStyle( fontSize: 20.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), Container( height: 20.0, ), ElevatedButton( onPressed: _makingPhoneCall, style: ButtonStyle( padding: MaterialStateProperty.all(const EdgeInsets.all(5.0)), textStyle: MaterialStateProperty.all( const TextStyle(color: Colors.black), ), ), child: const Text('Here'), ), // ElevatedButton // DEPRECATED // RaisedButton( // onPressed: _makingPhoneCall, // child: Text('Call'), // textColor: Colors.black, // padding: const EdgeInsets.all(5.0), // ), ], ), ), ), ), ); }}", "e": 6723, "s": 4356, "text": null }, { "code": null, "e": 6731, "s": 6723, "text": "Output:" }, { "code": null, "e": 6744, "s": 6731, "text": "ankit_kumar_" }, { "code": null, "e": 6752, "s": 6744, "text": "Android" }, { "code": null, "e": 6757, "s": 6752, "text": "Dart" }, { "code": null, "e": 6765, "s": 6757, "text": "Flutter" }, { "code": null, "e": 6773, "s": 6765, "text": "Android" }, { "code": null, "e": 6871, "s": 6773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6892, "s": 6871, "text": "Android Architecture" }, { "code": null, "e": 6952, "s": 6892, "text": "MVVM (Model View ViewModel) Architecture Pattern in Android" }, { "code": null, "e": 6985, "s": 6952, "text": "Services in Android with Example" }, { "code": null, "e": 7002, "s": 6985, "text": "Android Tutorial" }, { "code": null, "e": 7035, "s": 7002, "text": "Bottom Navigation Bar in Android" }, { "code": null, "e": 7067, "s": 7035, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 7095, "s": 7067, "text": "Listview.builder in Flutter" }, { "code": null, "e": 7134, "s": 7095, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 7159, "s": 7134, "text": "Splash Screen in Flutter" } ]
Python | How to shorten long URLs using Bitly API
22 Oct, 2018 Bitly is used to shorten, brand, share, or retrieve data from links programmatically. In this article, we’ll see how to shorten URLs using Bitly API. Below is a working example to shorten a URL using Bitly API. Step #1: Install Bitly API using gitgit clone https://github.com/bitly/bitly-api-python.git Go inside the folder using:cd bitly-api-python Note: In case installation with pip command is not working: File "/usr/local/lib/python3.5/dist-packages/bitly_api/__init__.py", line 1, in from bitly_api import Connection, BitlyError, Error ImportError: cannot import name 'Connection' Uninstall bitly-api in case already installed using pip: pip uninstall bitly_api Step #2: Install in Python’s folder for modules: python setup.py install Note: Delete the source code using (since we don’t need it for now) : cd../ rmdir bitly-api-python-master Step #3: To get “Bitly username and API Key” login to account on bit.ly and then go here and get it. In case of further assistance, one can go here. Step #4: Now create a file shorturl.py and write this code: import bitly_api API_USER = "your_username"API_KEY = "your_API_Key" b = bitly_api.Connection(API_USER, API_KEY) # Replace this with your Long URL Herelongurl = www.google.com response = b.shorten(uri = longurl) # Now let us print the Bitly URLprint(response) Step #5: Run the file ‘shorturl.py’. Reference: https://dev.bitly.com/v4_documentation.html Technical Scripter 2018 Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU. How to setup cron jobs in Ubuntu Top Programming Languages for Android App Development How to Add External JAR File to an IntelliJ IDEA Project? 'dd' command in Linux How to Delete Temporary Files in Windows 10?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2018" }, { "code": null, "e": 114, "s": 28, "text": "Bitly is used to shorten, brand, share, or retrieve data from links programmatically." }, { "code": null, "e": 239, "s": 114, "text": "In this article, we’ll see how to shorten URLs using Bitly API. Below is a working example to shorten a URL using Bitly API." }, { "code": null, "e": 331, "s": 239, "text": "Step #1: Install Bitly API using gitgit clone https://github.com/bitly/bitly-api-python.git" }, { "code": null, "e": 378, "s": 331, "text": "Go inside the folder using:cd bitly-api-python" }, { "code": null, "e": 438, "s": 378, "text": "Note: In case installation with pip command is not working:" }, { "code": "File \"/usr/local/lib/python3.5/dist-packages/bitly_api/__init__.py\", line 1, in from bitly_api import Connection, BitlyError, Error ImportError: cannot import name 'Connection'", "e": 616, "s": 438, "text": null }, { "code": null, "e": 673, "s": 616, "text": "Uninstall bitly-api in case already installed using pip:" }, { "code": null, "e": 697, "s": 673, "text": "pip uninstall bitly_api" }, { "code": null, "e": 748, "s": 699, "text": "Step #2: Install in Python’s folder for modules:" }, { "code": null, "e": 772, "s": 748, "text": "python setup.py install" }, { "code": null, "e": 842, "s": 772, "text": "Note: Delete the source code using (since we don’t need it for now) :" }, { "code": null, "e": 878, "s": 842, "text": "cd../\nrmdir bitly-api-python-master" }, { "code": null, "e": 1028, "s": 878, "text": " Step #3: To get “Bitly username and API Key” login to account on bit.ly and then go here and get it. In case of further assistance, one can go here." }, { "code": null, "e": 1089, "s": 1028, "text": " Step #4: Now create a file shorturl.py and write this code:" }, { "code": "import bitly_api API_USER = \"your_username\"API_KEY = \"your_API_Key\" b = bitly_api.Connection(API_USER, API_KEY) # Replace this with your Long URL Herelongurl = www.google.com response = b.shorten(uri = longurl) # Now let us print the Bitly URLprint(response)", "e": 1355, "s": 1089, "text": null }, { "code": null, "e": 1392, "s": 1355, "text": "Step #5: Run the file ‘shorturl.py’." }, { "code": null, "e": 1448, "s": 1392, "text": " Reference: https://dev.bitly.com/v4_documentation.html" }, { "code": null, "e": 1472, "s": 1448, "text": "Technical Scripter 2018" }, { "code": null, "e": 1491, "s": 1472, "text": "Technical Scripter" }, { "code": null, "e": 1500, "s": 1491, "text": "TechTips" }, { "code": null, "e": 1598, "s": 1500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1651, "s": 1598, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 1677, "s": 1651, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1712, "s": 1677, "text": "Setting up the environment in Java" }, { "code": null, "e": 1753, "s": 1712, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 1783, "s": 1753, "text": "Running Python script on GPU." }, { "code": null, "e": 1816, "s": 1783, "text": "How to setup cron jobs in Ubuntu" }, { "code": null, "e": 1870, "s": 1816, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 1928, "s": 1870, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 1950, "s": 1928, "text": "'dd' command in Linux" } ]
Find XOR of numbers from the range [L, R]
13 Jun, 2022 Given two integers L and R, the task is to find the XOR of elements of the range [L, R]. Examples: Input: L = 4, R = 8 Output: 8 4 ^ 5 ^ 6 ^ 7 ^ 8 = 8 Input: L = 3, R = 7 Output: 3 Naive Approach: Initialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer. This would take O(N) time. C++ Java C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the XOR of elements// from the range [l, r]int findXOR(int l, int r){ int ans = 0; for (int i = l; i <= r; i++) { ans = ans ^ i; } return ans;} // Driver codeint main(){ int l = 4, r = 8; cout << findXOR(l, r); return 0;} // this code is contributed by devendra solunke /*package whatever //do not write package name here */ import java.io.*; class GFG { // Function to return the XOR of elements // from the range [l, r] public static int findXOR(int l, int r) { int ans = 0; for (int i = l; i <= r; i++) { ans = ans ^ i; } return ans; } // Driver code public static void main(String[] args) { int l = 4; int r = 8; System.out.println(findXOR(l, r)); }}// this code is contributed by devendra solunke // c# implementation of find xor between given rangeusing System; public class GFG { // Function to return the XOR of elements // from the range [l, r] static int findXOR(int l, int r) { int ans = 0; for (int i = l; i <= r; i++) { ans = ans ^ i; } return ans; } // Driver code static void Main(String[] args) { int l = 4; int r = 8; Console.WriteLine(findXOR(l, r)); }} // this code is contributed by devendra saunke // Javascript code to find xor of given range<script> var l = 4; var r = 8; var ans = 0; var(int i = l; i <= r; i++) { ans = ans ^ i; } document.write(ans);</script>// this code is contributed by devendra solunke 8 Time complexity: O(N)Auxiliary Space: O(1) Efficient Approach: By following the approach discussed here, we can find the XOR of elements from the range [1, N] in O(1) time. Using this approach, we have to find xor of elements from the range [1, L – 1] and from the range [1, R] and then xor the respective answers again to get the xor of the elements from the range [L, R]. This is because every element from the range [1, L – 1] will get XORed twice in the result resulting in a 0 which when XORed with the elements of the range [L, R] will give the result.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the XOR of elements// from the range [1, n]int findXOR(int n){ int mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0;} // Function to return the XOR of elements// from the range [l, r]int findXOR(int l, int r){ return (findXOR(l - 1) ^ findXOR(r));} // Driver codeint main(){ int l = 4, r = 8; cout << findXOR(l, r); return 0;} // Java implementation of the approachclass GFG{ // Function to return the XOR of elements // from the range [1, n] static int findXOR(int n) { int mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0; return 0; } // Function to return the XOR of elements // from the range [l, r] static int findXOR(int l, int r) { return (findXOR(l - 1) ^ findXOR(r)); } // Driver code public static void main(String[] args) { int l = 4, r = 8; System.out.println(findXOR(l, r)); }} // This code contributed by Rajput-Ji # Python3 implementation of the approachfrom operator import xor # Function to return the XOR of elements# from the range [1, n]def findXOR(n): mod = n % 4; # If n is a multiple of 4 if (mod == 0): return n; # If n % 4 gives remainder 1 elif (mod == 1): return 1; # If n % 4 gives remainder 2 elif (mod == 2): return n + 1; # If n % 4 gives remainder 3 elif (mod == 3): return 0; # Function to return the XOR of elements# from the range [l, r]def findXORFun(l, r): return (xor(findXOR(l - 1) , findXOR(r))); # Driver codel = 4; r = 8; print(findXORFun(l, r)); # This code is contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Function to return the XOR of elements // from the range [1, n] static int findXOR(int n) { int mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0; return 0; } // Function to return the XOR of elements // from the range [l, r] static int findXOR(int l, int r) { return (findXOR(l - 1) ^ findXOR(r)); } // Driver code public static void Main() { int l = 4, r = 8; Console.WriteLine(findXOR(l, r)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the approach // Function to return the XOR of elements // from the range [1, n] function findxOR(n) { let mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0; } // Function to return the XOR of elements // from the range [l, r] function findXOR(l, r) { return (findxOR(l - 1) ^ findxOR(r)); } let l = 4, r = 8; document.write(findXOR(l, r)); </script> 8 Time Complexity: O(1)Auxiliary Space: O(1) Rajput-Ji ankthon princiraj1992 divyesh072019 adnanirshad158 subhamkumarm348 devendrasalunke Bitwise-XOR Arrays Bit Magic Mathematical Arrays Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) How to swap two numbers without using a temporary variable? Little and Big Endian Mystery Program to find whether a given number is power of 2
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 152, "s": 53, "text": "Given two integers L and R, the task is to find the XOR of elements of the range [L, R]. Examples:" }, { "code": null, "e": 204, "s": 152, "text": "Input: L = 4, R = 8 Output: 8 4 ^ 5 ^ 6 ^ 7 ^ 8 = 8" }, { "code": null, "e": 236, "s": 204, "text": "Input: L = 3, R = 7 Output: 3 " }, { "code": null, "e": 398, "s": 236, "text": "Naive Approach: Initialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer. This would take O(N) time." }, { "code": null, "e": 402, "s": 398, "text": "C++" }, { "code": null, "e": 407, "s": 402, "text": "Java" }, { "code": null, "e": 410, "s": 407, "text": "C#" }, { "code": null, "e": 421, "s": 410, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the XOR of elements// from the range [l, r]int findXOR(int l, int r){ int ans = 0; for (int i = l; i <= r; i++) { ans = ans ^ i; } return ans;} // Driver codeint main(){ int l = 4, r = 8; cout << findXOR(l, r); return 0;} // this code is contributed by devendra solunke", "e": 825, "s": 421, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { // Function to return the XOR of elements // from the range [l, r] public static int findXOR(int l, int r) { int ans = 0; for (int i = l; i <= r; i++) { ans = ans ^ i; } return ans; } // Driver code public static void main(String[] args) { int l = 4; int r = 8; System.out.println(findXOR(l, r)); }}// this code is contributed by devendra solunke", "e": 1346, "s": 825, "text": null }, { "code": "// c# implementation of find xor between given rangeusing System; public class GFG { // Function to return the XOR of elements // from the range [l, r] static int findXOR(int l, int r) { int ans = 0; for (int i = l; i <= r; i++) { ans = ans ^ i; } return ans; } // Driver code static void Main(String[] args) { int l = 4; int r = 8; Console.WriteLine(findXOR(l, r)); }} // this code is contributed by devendra saunke", "e": 1853, "s": 1346, "text": null }, { "code": "// Javascript code to find xor of given range<script> var l = 4; var r = 8; var ans = 0; var(int i = l; i <= r; i++) { ans = ans ^ i; } document.write(ans);</script>// this code is contributed by devendra solunke", "e": 2114, "s": 1853, "text": null }, { "code": null, "e": 2116, "s": 2114, "text": "8" }, { "code": null, "e": 2159, "s": 2116, "text": "Time complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 2727, "s": 2159, "text": "Efficient Approach: By following the approach discussed here, we can find the XOR of elements from the range [1, N] in O(1) time. Using this approach, we have to find xor of elements from the range [1, L – 1] and from the range [1, R] and then xor the respective answers again to get the xor of the elements from the range [L, R]. This is because every element from the range [1, L – 1] will get XORed twice in the result resulting in a 0 which when XORed with the elements of the range [L, R] will give the result.Below is the implementation of the above approach: " }, { "code": null, "e": 2731, "s": 2727, "text": "C++" }, { "code": null, "e": 2736, "s": 2731, "text": "Java" }, { "code": null, "e": 2744, "s": 2736, "text": "Python3" }, { "code": null, "e": 2747, "s": 2744, "text": "C#" }, { "code": null, "e": 2758, "s": 2747, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the XOR of elements// from the range [1, n]int findXOR(int n){ int mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0;} // Function to return the XOR of elements// from the range [l, r]int findXOR(int l, int r){ return (findXOR(l - 1) ^ findXOR(r));} // Driver codeint main(){ int l = 4, r = 8; cout << findXOR(l, r); return 0;}", "e": 3457, "s": 2758, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the XOR of elements // from the range [1, n] static int findXOR(int n) { int mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0; return 0; } // Function to return the XOR of elements // from the range [l, r] static int findXOR(int l, int r) { return (findXOR(l - 1) ^ findXOR(r)); } // Driver code public static void main(String[] args) { int l = 4, r = 8; System.out.println(findXOR(l, r)); }} // This code contributed by Rajput-Ji", "e": 4343, "s": 3457, "text": null }, { "code": "# Python3 implementation of the approachfrom operator import xor # Function to return the XOR of elements# from the range [1, n]def findXOR(n): mod = n % 4; # If n is a multiple of 4 if (mod == 0): return n; # If n % 4 gives remainder 1 elif (mod == 1): return 1; # If n % 4 gives remainder 2 elif (mod == 2): return n + 1; # If n % 4 gives remainder 3 elif (mod == 3): return 0; # Function to return the XOR of elements# from the range [l, r]def findXORFun(l, r): return (xor(findXOR(l - 1) , findXOR(r))); # Driver codel = 4; r = 8; print(findXORFun(l, r)); # This code is contributed by PrinciRaj1992", "e": 5009, "s": 4343, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the XOR of elements // from the range [1, n] static int findXOR(int n) { int mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0; return 0; } // Function to return the XOR of elements // from the range [l, r] static int findXOR(int l, int r) { return (findXOR(l - 1) ^ findXOR(r)); } // Driver code public static void Main() { int l = 4, r = 8; Console.WriteLine(findXOR(l, r)); }} // This code is contributed by AnkitRai01", "e": 5897, "s": 5009, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the XOR of elements // from the range [1, n] function findxOR(n) { let mod = n % 4; // If n is a multiple of 4 if (mod == 0) return n; // If n % 4 gives remainder 1 else if (mod == 1) return 1; // If n % 4 gives remainder 2 else if (mod == 2) return n + 1; // If n % 4 gives remainder 3 else if (mod == 3) return 0; } // Function to return the XOR of elements // from the range [l, r] function findXOR(l, r) { return (findxOR(l - 1) ^ findxOR(r)); } let l = 4, r = 8; document.write(findXOR(l, r)); </script>", "e": 6681, "s": 5897, "text": null }, { "code": null, "e": 6683, "s": 6681, "text": "8" }, { "code": null, "e": 6726, "s": 6683, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 6736, "s": 6726, "text": "Rajput-Ji" }, { "code": null, "e": 6744, "s": 6736, "text": "ankthon" }, { "code": null, "e": 6758, "s": 6744, "text": "princiraj1992" }, { "code": null, "e": 6772, "s": 6758, "text": "divyesh072019" }, { "code": null, "e": 6787, "s": 6772, "text": "adnanirshad158" }, { "code": null, "e": 6803, "s": 6787, "text": "subhamkumarm348" }, { "code": null, "e": 6819, "s": 6803, "text": "devendrasalunke" }, { "code": null, "e": 6831, "s": 6819, "text": "Bitwise-XOR" }, { "code": null, "e": 6838, "s": 6831, "text": "Arrays" }, { "code": null, "e": 6848, "s": 6838, "text": "Bit Magic" }, { "code": null, "e": 6861, "s": 6848, "text": "Mathematical" }, { "code": null, "e": 6868, "s": 6861, "text": "Arrays" }, { "code": null, "e": 6881, "s": 6868, "text": "Mathematical" }, { "code": null, "e": 6891, "s": 6881, "text": "Bit Magic" }, { "code": null, "e": 6989, "s": 6891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7057, "s": 6989, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7101, "s": 7057, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7133, "s": 7101, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7181, "s": 7133, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 7195, "s": 7181, "text": "Linear Search" }, { "code": null, "e": 7241, "s": 7195, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 7309, "s": 7241, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 7369, "s": 7309, "text": "How to swap two numbers without using a temporary variable?" }, { "code": null, "e": 7399, "s": 7369, "text": "Little and Big Endian Mystery" } ]
Programming Language For Placement – C++, Java or Python?
12 Dec, 2020 Many times we’ve seen students struggling with the dilemma of choosing a worthwhile Programming Language for the sake of placements. Though this situation is somewhat justifiable as among the numerous Programming Language available across the world, to pick out the one that can help you to get your DREAM JOB is not an easy job. But wait...do you know that it is not that difficult to make a worthwhile choice in such a situation – yes, all you need to do is follow a strategical approach and perform several assessment practices. And with a similar concern, in this article, we’ll discuss those approaches and assessment practices that will help you to make the right choice for placements among these three renowned programming languages – C++, Java, and Python!! Before moving further, you need to know that having sound knowledge of the particular programming language is reasonably important while going out for the tech interviews as recruiters emphasize assessing your programming knowledge and skills during multiple phases like in coding round, technical interview rounds,, etc. That means, whichever language you’re working upon, you need to get your programming fundamentals clear with it. Now let’s take a brief look at the details of all these three programming languages: It is a general-purpose programming language that supports object-oriented programming paradigms. The language acts as a mid-level language as it can be used for both – system programming and large-scale user applications. It can be considered as the advanced version of the C Language and the basic syntax of both languages is somewhat similar. Moreover, C++ provides you with rich library support in the form of Standard Template Library. Indeed, C++ has been among one of the top programming languages for a long time and the language has a wide range of applications such as Operating Systems, Cloud/Distributed Systems, Web Browsers, and many more. Java is an object-oriented programming language that works on Write Once, Run Anywhere principle which means the compiled JAVA code can execute on each platform that supports JAVA without doing recompilation. The language offers you various remarkable features such as portability, robustness, multithreading, security & platform-independency, and many more. Though in the last year’s index report, JAVA has seen a decline in its demand and popularity. But the language is still having much occupancy in the tech world. If we look at the numbers, there are around nearly 8-9 million JAVA Developers across the world and the language has its wide use in the development of enterprise-scale web applications and Android applications. Python is undeniably one of the most favorable languages for young developers, more specifically students. Most probably, the reason behind it is its simple syntax and easy to learn nature. It is a high-level, general-purpose programming language that supports multiple programming paradigms like structured, functional, and object-oriented programming. Python comes up with various worthwhile features such as extensive library support, easy integration with other languages, automatic garbage collection support, and many more. The language is being used by nearly every IT giant whether it be Google, Amazon, Facebook, or any other and it is widely used in domains like Web Development, Machine Learning, Web scraping, etc. As of now, you must have known about these 3 languages and so you would’ve also been familiar with the fact that each programming language has its own features & use cases. Now, it’d be easier for you to make a choice among these 3 programming languages for the placement concerns based on the below-mentioned parameters: You’re recommended to start your decision-making process with this basic yet most under-rated parameter of the programming languages. The reason behind taking this factor into account is that a faster programming language is always preferred in the tech industry as it optimizes the development cost for any organization. Though, you need to remember that here faster programming language is concerned with the running time of the program rather than of developers coding time (however it saves a lot of your coding time as well through STL). Moreover, if we take the scenario of these 3 programming languages – C++, Java, and Python – JAVA is relatively faster than Python in terms of speed and C++ is comparatively faster than the other two languages. Everyone knows that Competitive Programming plays a pivotal process during the recruitment process as it adds much-needed value to your resume and sharpens your programming skills also. Hence, you need to pick out a programming language that can fulfill all the requirements for competitive programming efficiently. And, C++ is the most recommended programming language for competitive programming primarily because of the availability of a rich library known as Standard Template Library that allows you to deal with various data structures such as lists, graphs, stacks, arrays, trees, and others effectively. Also, as C++ supports Object-Oriented Programming methods, it helps you to solve real-time problems in coding contests. This is a bit tricky parameter. During the recruitment process, particularly in the technical interview round, the interviewer often asks you several questions related to programming functionalities. So, you need to be proficient with these programming fundamentals and concepts to do well during placements. For example – you may be asked questions based on pointers, structures & unions, etc. However, like C++, Java & Python does not come up with these low-level programming functionalities and underlying mechanisms. And apart from this low-level programming knowledge, as C++ also provides you with the knowledge of OOPs concepts, it is surely having an upper hand in this particular parameter. NOTE: This is indeed the most important parameter of all. WHY... ?? Because every programming language has its own area of expertise and applications. Okay, let us understand it with a scenario – suppose you’re looking forward to making a career in Android Development then the comparison between Java and Kotlin will be more worthwhile. Similarly, if your end goal is to get into Game Development, you can go with C++ without giving a second thought or if you’re fascinated with having a career in trending technologies like Machine Learning Artificial Intelligence, etc. – you can consider Python for that. In short, once you’ll get clear with your end-goal, it will become easier for you to understand which language is the best fit for your requirements. Also, you need to know that once you’ll command over any low-level language like C or C++, it will hardly take you 3-4 weeks to learn other languages like Java, Python, etc. Hence, you’re strongly recommended to learn and master one language first instead of unnecessarily keep switching the languages. So, these are several parameters based on which you can decide a particular programming language for your placement and career goals. Apart from these above-mentioned parameters, several other parameters that can also be taken into consideration are demand & popularity of the language, job opportunities, etc. Again, you must ensure to identify your requirements and area of interest before opting for any of the programming languages. In the end, whichever programming language you would choose, you must be confident and efficient with that to get success!! GBlog Placements Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? SDE SHEET - A Complete Guide for SDE Preparation Numbers TCS Placement Paper | MCQ 1 Top 20 Puzzles Commonly Asked During SDE Interviews Must Do Questions for Companies like TCS, CTS, HCL, IBM ...
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Dec, 2020" }, { "code": null, "e": 383, "s": 53, "text": "Many times we’ve seen students struggling with the dilemma of choosing a worthwhile Programming Language for the sake of placements. Though this situation is somewhat justifiable as among the numerous Programming Language available across the world, to pick out the one that can help you to get your DREAM JOB is not an easy job." }, { "code": null, "e": 820, "s": 383, "text": "But wait...do you know that it is not that difficult to make a worthwhile choice in such a situation – yes, all you need to do is follow a strategical approach and perform several assessment practices. And with a similar concern, in this article, we’ll discuss those approaches and assessment practices that will help you to make the right choice for placements among these three renowned programming languages – C++, Java, and Python!!" }, { "code": null, "e": 1255, "s": 820, "text": "Before moving further, you need to know that having sound knowledge of the particular programming language is reasonably important while going out for the tech interviews as recruiters emphasize assessing your programming knowledge and skills during multiple phases like in coding round, technical interview rounds,, etc. That means, whichever language you’re working upon, you need to get your programming fundamentals clear with it." }, { "code": null, "e": 1340, "s": 1255, "text": "Now let’s take a brief look at the details of all these three programming languages:" }, { "code": null, "e": 1996, "s": 1340, "text": "It is a general-purpose programming language that supports object-oriented programming paradigms. The language acts as a mid-level language as it can be used for both – system programming and large-scale user applications. It can be considered as the advanced version of the C Language and the basic syntax of both languages is somewhat similar. Moreover, C++ provides you with rich library support in the form of Standard Template Library. Indeed, C++ has been among one of the top programming languages for a long time and the language has a wide range of applications such as Operating Systems, Cloud/Distributed Systems, Web Browsers, and many more. " }, { "code": null, "e": 2728, "s": 1996, "text": "Java is an object-oriented programming language that works on Write Once, Run Anywhere principle which means the compiled JAVA code can execute on each platform that supports JAVA without doing recompilation. The language offers you various remarkable features such as portability, robustness, multithreading, security & platform-independency, and many more. Though in the last year’s index report, JAVA has seen a decline in its demand and popularity. But the language is still having much occupancy in the tech world. If we look at the numbers, there are around nearly 8-9 million JAVA Developers across the world and the language has its wide use in the development of enterprise-scale web applications and Android applications." }, { "code": null, "e": 3455, "s": 2728, "text": "Python is undeniably one of the most favorable languages for young developers, more specifically students. Most probably, the reason behind it is its simple syntax and easy to learn nature. It is a high-level, general-purpose programming language that supports multiple programming paradigms like structured, functional, and object-oriented programming. Python comes up with various worthwhile features such as extensive library support, easy integration with other languages, automatic garbage collection support, and many more. The language is being used by nearly every IT giant whether it be Google, Amazon, Facebook, or any other and it is widely used in domains like Web Development, Machine Learning, Web scraping, etc." }, { "code": null, "e": 3777, "s": 3455, "text": "As of now, you must have known about these 3 languages and so you would’ve also been familiar with the fact that each programming language has its own features & use cases. Now, it’d be easier for you to make a choice among these 3 programming languages for the placement concerns based on the below-mentioned parameters:" }, { "code": null, "e": 4320, "s": 3777, "text": "You’re recommended to start your decision-making process with this basic yet most under-rated parameter of the programming languages. The reason behind taking this factor into account is that a faster programming language is always preferred in the tech industry as it optimizes the development cost for any organization. Though, you need to remember that here faster programming language is concerned with the running time of the program rather than of developers coding time (however it saves a lot of your coding time as well through STL)." }, { "code": null, "e": 4531, "s": 4320, "text": "Moreover, if we take the scenario of these 3 programming languages – C++, Java, and Python – JAVA is relatively faster than Python in terms of speed and C++ is comparatively faster than the other two languages." }, { "code": null, "e": 5263, "s": 4531, "text": "Everyone knows that Competitive Programming plays a pivotal process during the recruitment process as it adds much-needed value to your resume and sharpens your programming skills also. Hence, you need to pick out a programming language that can fulfill all the requirements for competitive programming efficiently. And, C++ is the most recommended programming language for competitive programming primarily because of the availability of a rich library known as Standard Template Library that allows you to deal with various data structures such as lists, graphs, stacks, arrays, trees, and others effectively. Also, as C++ supports Object-Oriented Programming methods, it helps you to solve real-time problems in coding contests." }, { "code": null, "e": 5963, "s": 5263, "text": "This is a bit tricky parameter. During the recruitment process, particularly in the technical interview round, the interviewer often asks you several questions related to programming functionalities. So, you need to be proficient with these programming fundamentals and concepts to do well during placements. For example – you may be asked questions based on pointers, structures & unions, etc. However, like C++, Java & Python does not come up with these low-level programming functionalities and underlying mechanisms. And apart from this low-level programming knowledge, as C++ also provides you with the knowledge of OOPs concepts, it is surely having an upper hand in this particular parameter." }, { "code": null, "e": 6021, "s": 5963, "text": "NOTE: This is indeed the most important parameter of all." }, { "code": null, "e": 6722, "s": 6021, "text": "WHY... ?? Because every programming language has its own area of expertise and applications. Okay, let us understand it with a scenario – suppose you’re looking forward to making a career in Android Development then the comparison between Java and Kotlin will be more worthwhile. Similarly, if your end goal is to get into Game Development, you can go with C++ without giving a second thought or if you’re fascinated with having a career in trending technologies like Machine Learning Artificial Intelligence, etc. – you can consider Python for that. In short, once you’ll get clear with your end-goal, it will become easier for you to understand which language is the best fit for your requirements." }, { "code": null, "e": 7025, "s": 6722, "text": "Also, you need to know that once you’ll command over any low-level language like C or C++, it will hardly take you 3-4 weeks to learn other languages like Java, Python, etc. Hence, you’re strongly recommended to learn and master one language first instead of unnecessarily keep switching the languages." }, { "code": null, "e": 7462, "s": 7025, "text": "So, these are several parameters based on which you can decide a particular programming language for your placement and career goals. Apart from these above-mentioned parameters, several other parameters that can also be taken into consideration are demand & popularity of the language, job opportunities, etc. Again, you must ensure to identify your requirements and area of interest before opting for any of the programming languages." }, { "code": null, "e": 7586, "s": 7462, "text": "In the end, whichever programming language you would choose, you must be confident and efficient with that to get success!!" }, { "code": null, "e": 7592, "s": 7586, "text": "GBlog" }, { "code": null, "e": 7603, "s": 7592, "text": "Placements" }, { "code": null, "e": 7701, "s": 7603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7726, "s": 7701, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 7781, "s": 7726, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 7818, "s": 7781, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 7856, "s": 7818, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 7922, "s": 7856, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 7971, "s": 7922, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 7979, "s": 7971, "text": "Numbers" }, { "code": null, "e": 8007, "s": 7979, "text": "TCS Placement Paper | MCQ 1" }, { "code": null, "e": 8059, "s": 8007, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" } ]