title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Running previous command with sudo - GeeksforGeeks
19 Nov, 2018 Very often in linux, we execute a command only to see an error displaying ‘Permission denied.’ Then we realize that we had forgotten sudo before the command and we write the command again, this time with a sudo infront. Examples: rohan@Rohan-PC:~$ apt-get update Reading package lists... Done W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted) E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied) E: Unable to lock directory /var/lib/apt/lists/ W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied) W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied) rohan@Rohan-PC:~$ sudo apt-get update [sudo] password for rohan: Get:1 http://packages.microsoft.com/repos/vscode stable InRelease [2, 802 B] Hit:2 http://archive.ubuntu.com/ubuntu xenial InRelease Hit:3 http://ppa.launchpad.net/ansible/ansible/ubuntu xenial InRelease Ign:4 http://dl.google.com/linux/chrome/deb stable InRelease Get:5 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Hit:6 https://deb.nodesource.com/node_8.x xenial InRelease Hit:7 http://ppa.launchpad.net/hanipouspilot/rtlwifi/ubuntu xenial InRelease Hit:8 http://dl.google.com/linux/chrome/deb stable Release Get:9 http://packages.microsoft.com/repos/vscode stable/main amd64 Packages [77.9 kB] Hit:10 http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu xenial InRelease Get:12 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Hit:13 https://download.sublimetext.com apt/stable/ InRelease Hit:14 http://ppa.launchpad.net/noobslab/apps/ubuntu xenial InRelease Get:15 http://archive.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Hit:16 http://ppa.launchpad.net/noobslab/macbuntu/ubuntu xenial InRelease Hit:17 http://packages.treasuredata.com/3/ubuntu/xenial xenial InRelease Get:18 http://nginx.org/packages/ubuntu xenial InRelease [4, 339 B] Ign:18 http://nginx.org/packages/ubuntu xenial InRelease Hit:19 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease Hit:20 http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu xenial InRelease Hit:21 http://ppa.launchpad.net/videolan/master-daily/ubuntu xenial InRelease Hit:22 https://dl.winehq.org/wine-builds/ubuntu xenial InRelease Hit:23 https://download.docker.com/linux/ubuntu xenial InRelease Hit:24 http://ppa.launchpad.net/webupd8team/java/ubuntu xenial InRelease Fetched 408 kB in 3s (117 kB/s) Reading package lists... Done The situation becomes frustrating when the command is a long one which you have typed. You certainly wouldn’t want to retype that long command. To solve this problem, the following cool linux hack is presented: Command : sudo !! This command repeats the previous command with sudo infront. It certainly saves a lot of time and effort and prevents frustration among geeks. Example: rohan@Rohan-PC:~$ apt-get update Reading package lists... Done W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted) E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied) E: Unable to lock directory /var/lib/apt/lists/ W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied) W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied) rohan@Rohan-PC:~$ sudo !! sudo apt-get update Hit:1 http://packages.treasuredata.com/3/ubuntu/xenial xenial InRelease Ign:2 http://dl.google.com/linux/chrome/deb stable InRelease Hit:3 http://ppa.launchpad.net/ansible/ansible/ubuntu xenial InRelease Hit:4 http://archive.ubuntu.com/ubuntu xenial InRelease Hit:5 http://dl.google.com/linux/chrome/deb stable Release Get:6 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Get:8 http://nginx.org/packages/ubuntu xenial InRelease [4, 339 B] Hit:9 https://dl.winehq.org/wine-builds/ubuntu xenial InRelease Ign:8 http://nginx.org/packages/ubuntu xenial InRelease Hit:10 http://ppa.launchpad.net/hanipouspilot/rtlwifi/ubuntu xenial InRelease Hit:11 https://download.sublimetext.com apt/stable/ InRelease Hit:12 http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu xenial InRelease Get:13 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Hit:14 http://ppa.launchpad.net/noobslab/apps/ubuntu xenial InRelease Get:15 http://archive.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Hit:16 https://deb.nodesource.com/node_8.x xenial InRelease Hit:17 https://download.docker.com/linux/ubuntu xenial InRelease Hit:18 http://ppa.launchpad.net/noobslab/macbuntu/ubuntu xenial InRelease Hit:19 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease Hit:20 http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu xenial InRelease Hit:21 http://ppa.launchpad.net/videolan/master-daily/ubuntu xenial InRelease Get:22 http://packages.microsoft.com/repos/vscode stable InRelease [2, 802 B] Hit:23 http://ppa.launchpad.net/webupd8team/java/ubuntu xenial InRelease Fetched 330 kB in 3s (103 kB/s) Reading package lists... Done linux-command Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ mv command in Linux with examples nohup Command in Linux with Examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n19 Nov, 2018" }, { "code": null, "e": 24235, "s": 24015, "text": "Very often in linux, we execute a command only to see an error displaying ‘Permission denied.’ Then we realize that we had forgotten sudo before the command and we write the command again, this time with a sudo infront." }, { "code": null, "e": 24245, "s": 24235, "text": "Examples:" }, { "code": null, "e": 26681, "s": 24245, "text": "rohan@Rohan-PC:~$ apt-get update\nReading package lists... Done\nW: chmod 0700 of directory /var/lib/apt/lists/partial failed - \nSetupAPTPartialDirectory (1: Operation not permitted)\nE: Could not open lock file /var/lib/apt/lists/lock - open \n(13: Permission denied)\nE: Unable to lock directory /var/lib/apt/lists/\nW: Problem unlinking the file /var/cache/apt/pkgcache.bin - \nRemoveCaches (13: Permission denied)\nW: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - \nRemoveCaches (13: Permission denied)\n\nrohan@Rohan-PC:~$ sudo apt-get update\n[sudo] password for rohan: \nGet:1 http://packages.microsoft.com/repos/vscode stable InRelease [2, 802 B]\nHit:2 http://archive.ubuntu.com/ubuntu xenial InRelease \nHit:3 http://ppa.launchpad.net/ansible/ansible/ubuntu xenial InRelease \nIgn:4 http://dl.google.com/linux/chrome/deb stable InRelease \nGet:5 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB]\nHit:6 https://deb.nodesource.com/node_8.x xenial InRelease \nHit:7 http://ppa.launchpad.net/hanipouspilot/rtlwifi/ubuntu xenial InRelease\nHit:8 http://dl.google.com/linux/chrome/deb stable Release \nGet:9 http://packages.microsoft.com/repos/vscode stable/main amd64 Packages [77.9 kB]\nHit:10 http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu xenial InRelease\nGet:12 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB]\nHit:13 https://download.sublimetext.com apt/stable/ InRelease \nHit:14 http://ppa.launchpad.net/noobslab/apps/ubuntu xenial InRelease \nGet:15 http://archive.ubuntu.com/ubuntu xenial-security InRelease [107 kB]\nHit:16 http://ppa.launchpad.net/noobslab/macbuntu/ubuntu xenial InRelease\nHit:17 http://packages.treasuredata.com/3/ubuntu/xenial xenial InRelease\nGet:18 http://nginx.org/packages/ubuntu xenial InRelease [4, 339 B] \nIgn:18 http://nginx.org/packages/ubuntu xenial InRelease \nHit:19 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease\nHit:20 http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu xenial InRelease\nHit:21 http://ppa.launchpad.net/videolan/master-daily/ubuntu xenial InRelease\nHit:22 https://dl.winehq.org/wine-builds/ubuntu xenial InRelease\nHit:23 https://download.docker.com/linux/ubuntu xenial InRelease\nHit:24 http://ppa.launchpad.net/webupd8team/java/ubuntu xenial InRelease\nFetched 408 kB in 3s (117 kB/s) \nReading package lists... Done\n" }, { "code": null, "e": 26892, "s": 26681, "text": "The situation becomes frustrating when the command is a long one which you have typed. You certainly wouldn’t want to retype that long command. To solve this problem, the following cool linux hack is presented:" }, { "code": null, "e": 26911, "s": 26892, "text": "Command : sudo !!\n" }, { "code": null, "e": 27054, "s": 26911, "text": "This command repeats the previous command with sudo infront. It certainly saves a lot of time and effort and prevents frustration among geeks." }, { "code": null, "e": 29421, "s": 27054, "text": "Example:\nrohan@Rohan-PC:~$ apt-get update\nReading package lists... Done\nW: chmod 0700 of directory /var/lib/apt/lists/partial failed - \nSetupAPTPartialDirectory (1: Operation not permitted)\nE: Could not open lock file /var/lib/apt/lists/lock - open \n(13: Permission denied)\nE: Unable to lock directory /var/lib/apt/lists/\nW: Problem unlinking the file /var/cache/apt/pkgcache.bin - \nRemoveCaches (13: Permission denied)\nW: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - \nRemoveCaches (13: Permission denied)\n\nrohan@Rohan-PC:~$ sudo !!\nsudo apt-get update\nHit:1 http://packages.treasuredata.com/3/ubuntu/xenial xenial InRelease\nIgn:2 http://dl.google.com/linux/chrome/deb stable InRelease \nHit:3 http://ppa.launchpad.net/ansible/ansible/ubuntu xenial InRelease \nHit:4 http://archive.ubuntu.com/ubuntu xenial InRelease \nHit:5 http://dl.google.com/linux/chrome/deb stable Release \nGet:6 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB]\nGet:8 http://nginx.org/packages/ubuntu xenial InRelease [4, 339 B] \nHit:9 https://dl.winehq.org/wine-builds/ubuntu xenial InRelease \nIgn:8 http://nginx.org/packages/ubuntu xenial InRelease \nHit:10 http://ppa.launchpad.net/hanipouspilot/rtlwifi/ubuntu xenial InRelease\nHit:11 https://download.sublimetext.com apt/stable/ InRelease \nHit:12 http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu xenial \nInRelease\nGet:13 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB]\nHit:14 http://ppa.launchpad.net/noobslab/apps/ubuntu xenial InRelease \nGet:15 http://archive.ubuntu.com/ubuntu xenial-security InRelease [107 kB]\nHit:16 https://deb.nodesource.com/node_8.x xenial InRelease \nHit:17 https://download.docker.com/linux/ubuntu xenial InRelease \nHit:18 http://ppa.launchpad.net/noobslab/macbuntu/ubuntu xenial InRelease\nHit:19 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease\nHit:20 http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu xenial InRelease\nHit:21 http://ppa.launchpad.net/videolan/master-daily/ubuntu xenial InRelease\nGet:22 http://packages.microsoft.com/repos/vscode stable InRelease [2, 802 B]\nHit:23 http://ppa.launchpad.net/webupd8team/java/ubuntu xenial InRelease\nFetched 330 kB in 3s (103 kB/s) \nReading package lists... Done\n\n" }, { "code": null, "e": 29435, "s": 29421, "text": "linux-command" }, { "code": null, "e": 29459, "s": 29435, "text": "Technical Scripter 2018" }, { "code": null, "e": 29470, "s": 29459, "text": "Linux-Unix" }, { "code": null, "e": 29489, "s": 29470, "text": "Technical Scripter" }, { "code": null, "e": 29587, "s": 29489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29596, "s": 29587, "text": "Comments" }, { "code": null, "e": 29609, "s": 29596, "text": "Old Comments" }, { "code": null, "e": 29635, "s": 29609, "text": "Thread functions in C/C++" }, { "code": null, "e": 29669, "s": 29635, "text": "mv command in Linux with examples" }, { "code": null, "e": 29706, "s": 29669, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29741, "s": 29706, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29767, "s": 29741, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29804, "s": 29767, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29844, "s": 29804, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 29873, "s": 29844, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29915, "s": 29873, "text": "Named Pipe or FIFO with example C program" } ]
Print string of odd length in 'X' format - GeeksforGeeks
25 Nov, 2021 Given a string of odd length, print the string X format.Examples : Input: 12345 Output: 1 5 2 4 3 2 4 1 5 Input: geeksforgeeks Output: g s e k e e k e s g f r o f r s g k e e e e k g s We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two variables in a single loop, the first variable ‘i’ goes from left to right and second variable ‘j’ goes from right to left. The upper part of Cross (or X) is printed before they meet. The central character is printed when they meet and lower parted is printed after they cross each other. In the upper part str[i] is printed before str[j] and in the lower part, str[j] is printed before str[i].Below is the implementation of above idea. C Java Python3 C# PHP Javascript // C++ program to print Cross pattern#include<iostream>using namespace std; // Function to print given string in cross pattern// Length of string must be oddvoid printPattern(string str){ int len = str.length(); // i goes from 0 to len and j goes from len-1 to 0 for (int i=0,j=len-1; i<=len,j>=0; i++,j--) { // To print the upper part. This loop runs // till middle point of string (i and j become // same if (i<j) { // Print i spaces for (int x=0; x<i; x++) cout << " "; // Print i'th character cout << str[i]; // Print j-i-1 spaces for (int x=0; x<j-i-1; x++) cout << " "; // Print j'th character cout << str[j] << endl; } // To print center point if (i==j) { // Print i spaces for (int x=0; x<i; x++) cout << " "; // Print middle character cout << str[i] << endl; } // To print lower part else if (i>j) { // Print j spaces for (int x = j-1; x>=0; x--) cout << " "; // Print j'th character cout << str[j]; // Print i-j-1 spaces for (int x=0; x<i-j-1; x++) cout << " "; // Print i'h character cout << str[i] << endl; } }} // Driver programint main(){ printPattern("geeksforgeeks"); return 0;} // Java program to// print cross patternclass GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes // of characters to be // displayed in the ith // iteration i = 0 initially // and go upto length of string // j = length of string initially // in each iteration of i, // we increment i and decrement j, // we print character only // of k==i or k==j for (int i = 0; i < len; i++) { int j = len - 1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) System.out.print(str.charAt(k)); else System.out.print(" "); } System.out.println(""); }} // Driver codepublic static void main (String[] args){ String str = "geeksforgeeks"; int len = str.length(); pattern(str, len); }} // This code is contributed// by Smitha # Python 3 program to# print cross pattern # Function to print given# string in cross patterndef pattern(str, len): # i and j are the indexes # of characters to be # displayed in the ith # iteration i = 0 initially # and go upto length of string # j = length of string initially # in each iteration of i, we # increment i and decrement j, # we print character only of # k==i or k==j for i in range(0, len): j = len -1 - i for k in range(0, len): if (k == i or k == j): print(str[k], end = "") else: print(end = " ") print(" ") # Driver codestr = "geeksforgeeks"len = len(str)pattern(str, len) # This code is contributed# by Smitha // C# program to print// cross patternusing System; class GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes // of characters to be // displayed in the ith // iteration i = 0 initially // and go upto length of string // j = length of string initially // in each iteration of i, we // increment i and decrement j, // we print character only of // k==i or k==j for (int i = 0; i < len; i++) { int j = len - 1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) Console.Write(str[k]); else Console.Write(" "); } Console.Write("\n"); }} // Driver codepublic static void Main (){ String str = "geeksforgeeks"; int len = str.Length; pattern(str, len);}} // This code is contributed by Smitha <?php// PHP program to print// Cross pattern // Function to print given// string in cross pattern,// Length of string must be oddfunction printPattern($str){ $len = strlen($str); // i goes from 0 to len and // j goes from len-1 to 0 for ($i = 0, $j = $len - 1; $i <= $len, $j >= 0; $i++, $j--) { // To print the upper part. // This loop runs till middle point // of string i and j become same if ($i < $j) { // Print i spaces for ($x = 0; $x < $i; $x++) echo " "; // Print i'th character echo $str[$i]; // Print j-i-1 spaces for ( $x = 0; $x < $j - $i - 1; $x++) echo " "; // Print j'th character echo $str[$j]."\n"; } // To print center point if ($i == $j) { // Print i spaces for ($x = 0; $x < $i; $x++) echo " "; // Print middle character echo $str[$i]."\n"; } // To print lower part else if ($i > $j) { // Print j spaces for ($x = $j - 1; $x >= 0; $x--) echo " "; // Print j'th character echo $str[$j]; // Print i-j-1 spaces for ( $x = 0; $x < $i - $j - 1; $x++) echo " "; // Print i'h character echo $str[$i]."\n"; } }} // Driver codeprintPattern("geeksforgeeks"); // This code is contributed by mits?> <script> // javascript program to// print cross pattern // Function to print given// string in cross patternfunction pattern(str,len){ // i and j are the indexes // of characters to be // displayed in the ith // iteration i = 0 initially // and go upto length of string // j = length of string initially // in each iteration of i, // we increment i and decrement j, // we print character only // of k==i or k==j for (i = 0; i < len; i++) { var j = len - 1 - i; for (k = 0; k < len; k++) { if (k == i || k == j) document.write(str.charAt(k)); else document.write(" "); } document.write("<br>"); }} // Driver codestr = "geeksforgeeks";var len = str.length;pattern(str, len); // This code is contributed by Amit Katiyar</script> Output : g s e k e e k e s g f r o f r s g k e e e e k g s Alternative Solution : C++ Java Python3 C# PHP Javascript // CPP program to print cross pattern#include<bits/stdc++.h>using namespace std; // Function to print given string in// cross patternvoid pattern(string str, int len){ // i and j are the indexes of characters // to be displayed in the ith iteration // i = 0 initially and go upto length of // string // j = length of string initially // in each iteration of i, we increment // i and decrement j, we print character // only of k==i or k==j for (int i = 0; i < len; i++) { int j = len -1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) cout << str[k]; else cout << " "; } cout << endl; }} // driver codeint main (){ string str = "geeksforgeeks"; int len = str.size(); pattern(str, len); return 0;}// This code is contributed by Satinder Kaur // Java program to print cross pattern class GFG{ // Function to print given // string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length // of string j = length of string // initially in each iteration // of i, we increment i and decrement // j, we print character only // of k==i or k==j for (int i = 0; i < len; i++) { int j = len -1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) System.out.print(str.charAt(k)); else System.out.print(" "); } System.out.println(""); }} // driver codepublic static void main(String[] args){ String str = "geeksforgeeks"; int len = str.length(); pattern(str, len);}} // This code is contributed by 29AjayKumar # Python 3 program to print cross pattern # Function to print given string in# cross patterndef pattern(st, length): # i and j are the indexes of characters # to be displayed in the ith iteration # i = 0 initially and go upto length of # string # j = length of string initially # in each iteration of i, we increment # i and decrement j, we print character # only of k==i or k==j for i in range(length): j = length -1 - i for k in range(length): if (k == i or k == j): print(st[k],end="") else: print(" ",end="") print() # driver codeif __name__ == "__main__": st = "geeksforgeeks" length = len(st) pattern(st, length) // C# program to print cross patternusing System; class GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length // of string j = length of string // initially in each iteration // of i, we increment i and decrement // j, we print character only // of k==i or k==j for (int i = 0; i < len; i++) { int j = len -1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) Console.Write(str[k]); else Console.Write(" "); } Console.WriteLine(""); }} // Driver codepublic static void Main(String[] args){ String str = "geeksforgeeks"; int len = str.Length; pattern(str, len);}} // This code is contributed by Rajput-Ji <?php// PHP program to print// cross pattern // Function to print given// string in cross patternfunction pattern($str, $len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length of // string // j = length of string initially // in each iteration of i, we // increment i and decrement j, we // print character only of k==i or k==j for ($i = 0; $i < $len; $i++) { $j = $len -1 - $i; for ($k = 0; $k < $len; $k++) { if ($k == $i || $k == $j) echo $str[$k]; else echo " "; } echo "\n"; }} // Driver code$str = "geeksforgeeks";$len = strlen($str);pattern($str, $len); // This code is contributed by mits?> <script> // Javascript program to print cross pattern // Function to print given // string in cross patternfunction pattern(str , len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length // of string j = length of string // initially in each iteration // of i, we increment i and decrement // j, we print character only // of k==i or k==j for (var i = 0; i < len; i++) { var j = len -1 - i; for (var k = 0; k < len; k++) { if (k == i || k == j) document.write(str.charAt(k)); else document.write(" "); } document.write('<br>'); }} // driver codevar str = "geeksforgeeks";var len = str.length;pattern(str, len); // This code is contributed by 29AjayKumar </script> Output : g s e k e e k e s g f r o f r s g k e e e e k g s Solution 3: This problem can also be solved by observing that the characters are printed along the left and right diagonals only if we enclose the pattern within a matrix. Now, if the length of the string is len then the pattern can be enclosed within a square matrix of order len. The elements along the left diagonal can be accessed by the condition ( i==j ) where i and j are the row and column numbers respectively. The elements along the right diagonal can be accessed by the condition (i+j == len-1). So, run a nested loop of order len and fill the positions satisfying at the above two conditions with respective characters and the rest of the positions with blank spaces.Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to print the given pattern #include<bits/stdc++.h>using namespace std; // Function to print the given// string in respective patternvoid printPattern(string str, int len){ for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len-1)) cout<<str[j]; // Print blank space at rest of places else cout<<" "; } cout<<endl; }} // Driver Codeint main(){ string str = "geeksforgeeks"; int len = str.size(); printPattern(str, len); return 0;} // This code and Approach is contributed by// Aravind Kimonn // Java program to print the given patternimport java.io.*;class GFG{ // Function to print the given // string in respective pattern static void printPattern(String str, int len) { for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len - 1)) System.out.print(str.charAt(j)); // Print blank space at rest of places else System.out.print(" "); } System.out.println(); } } // Driver code public static void main (String[] args) { String str = "geeksforgeeks"; int len = str.length(); printPattern(str, len); }} // This code is contributed by rag2127. # Python3 program to print the given pattern # Function to print the given# string in respective patterndef printPattern (Str, Len) : for i in range(Len) : for j in range(Len) : # Print characters at corresponding # places satisfying the two conditions if ((i == j) or (i + j == Len - 1)) : print(Str[j], end = "") # Print blank space at rest of places else : print(" ", end = "") print() Str = "geeksforgeeks"Len = len(Str)printPattern(Str, Len) # This code is contributed by divyeshrabadiya07. // C# program to print the given patternusing System;public class GFG{ // Function to print the given // string in respective pattern static void printPattern(string str, int len) { for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len - 1)) Console.Write(str[j]); // Print blank space at rest of places else Console.Write(" "); } Console.WriteLine(); } } // Driver code static public void Main () { String str = "geeksforgeeks"; int len = str.Length; printPattern(str, len); }} // This code is contributed by avanitrachhadiya2155 <script>// javascript program to print the given pattern // Function to print the given // string in respective pattern function printPattern(str , len) { for(var i = 0; i < len; i++) { for(var j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len - 1)) document.write(str.charAt(j)); // Print blank space at rest of places else document.write(" "); } document.write('<br>'); } } // Driver code var str = "geeksforgeeks"; var len = str.length; printPattern(str, len); // This code is contributed by 29AjayKumar</script> Output : g s e k e e k e s g f r o f r s g k e e e e k g s https://youtu.be/7gyjMrezEos This article is contributed by Dinesh T.P.D. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar Smitha Dinesh Semwal 29AjayKumar Rajput-Ji Akanksha_Rai ManasChhabra2 ukasp kavinkumar999 rag2127 avanitrachhadiya2155 divyeshrabadiya07 amit143katiyar simranarora5sos surinderdawra388 pattern-printing Zoho Strings Zoho Strings pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack Different methods to reverse a string in C/C++ KMP Algorithm for Pattern Searching Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Reverse words in a given string Check whether two strings are anagram of each other
[ { "code": null, "e": 24379, "s": 24351, "text": "\n25 Nov, 2021" }, { "code": null, "e": 24447, "s": 24379, "text": "Given a string of odd length, print the string X format.Examples : " }, { "code": null, "e": 24836, "s": 24447, "text": "Input: 12345\nOutput:\n1 5\n 2 4\n 3\n 2 4\n1 5 \n\nInput: geeksforgeeks\nOutput:\ng s\n e k\n e e\n k e\n s g\n f r\n o\n f r\n s g\n k e\n e e\n e k\ng s " }, { "code": null, "e": 25377, "s": 24836, "text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two variables in a single loop, the first variable ‘i’ goes from left to right and second variable ‘j’ goes from right to left. The upper part of Cross (or X) is printed before they meet. The central character is printed when they meet and lower parted is printed after they cross each other. In the upper part str[i] is printed before str[j] and in the lower part, str[j] is printed before str[i].Below is the implementation of above idea. " }, { "code": null, "e": 25379, "s": 25377, "text": "C" }, { "code": null, "e": 25384, "s": 25379, "text": "Java" }, { "code": null, "e": 25392, "s": 25384, "text": "Python3" }, { "code": null, "e": 25395, "s": 25392, "text": "C#" }, { "code": null, "e": 25399, "s": 25395, "text": "PHP" }, { "code": null, "e": 25410, "s": 25399, "text": "Javascript" }, { "code": "// C++ program to print Cross pattern#include<iostream>using namespace std; // Function to print given string in cross pattern// Length of string must be oddvoid printPattern(string str){ int len = str.length(); // i goes from 0 to len and j goes from len-1 to 0 for (int i=0,j=len-1; i<=len,j>=0; i++,j--) { // To print the upper part. This loop runs // till middle point of string (i and j become // same if (i<j) { // Print i spaces for (int x=0; x<i; x++) cout << \" \"; // Print i'th character cout << str[i]; // Print j-i-1 spaces for (int x=0; x<j-i-1; x++) cout << \" \"; // Print j'th character cout << str[j] << endl; } // To print center point if (i==j) { // Print i spaces for (int x=0; x<i; x++) cout << \" \"; // Print middle character cout << str[i] << endl; } // To print lower part else if (i>j) { // Print j spaces for (int x = j-1; x>=0; x--) cout << \" \"; // Print j'th character cout << str[j]; // Print i-j-1 spaces for (int x=0; x<i-j-1; x++) cout << \" \"; // Print i'h character cout << str[i] << endl; } }} // Driver programint main(){ printPattern(\"geeksforgeeks\"); return 0;}", "e": 26929, "s": 25410, "text": null }, { "code": "// Java program to// print cross patternclass GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes // of characters to be // displayed in the ith // iteration i = 0 initially // and go upto length of string // j = length of string initially // in each iteration of i, // we increment i and decrement j, // we print character only // of k==i or k==j for (int i = 0; i < len; i++) { int j = len - 1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) System.out.print(str.charAt(k)); else System.out.print(\" \"); } System.out.println(\"\"); }} // Driver codepublic static void main (String[] args){ String str = \"geeksforgeeks\"; int len = str.length(); pattern(str, len); }} // This code is contributed// by Smitha", "e": 27878, "s": 26929, "text": null }, { "code": "# Python 3 program to# print cross pattern # Function to print given# string in cross patterndef pattern(str, len): # i and j are the indexes # of characters to be # displayed in the ith # iteration i = 0 initially # and go upto length of string # j = length of string initially # in each iteration of i, we # increment i and decrement j, # we print character only of # k==i or k==j for i in range(0, len): j = len -1 - i for k in range(0, len): if (k == i or k == j): print(str[k], end = \"\") else: print(end = \" \") print(\" \") # Driver codestr = \"geeksforgeeks\"len = len(str)pattern(str, len) # This code is contributed# by Smitha", "e": 28664, "s": 27878, "text": null }, { "code": "// C# program to print// cross patternusing System; class GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes // of characters to be // displayed in the ith // iteration i = 0 initially // and go upto length of string // j = length of string initially // in each iteration of i, we // increment i and decrement j, // we print character only of // k==i or k==j for (int i = 0; i < len; i++) { int j = len - 1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) Console.Write(str[k]); else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Driver codepublic static void Main (){ String str = \"geeksforgeeks\"; int len = str.Length; pattern(str, len);}} // This code is contributed by Smitha", "e": 29591, "s": 28664, "text": null }, { "code": "<?php// PHP program to print// Cross pattern // Function to print given// string in cross pattern,// Length of string must be oddfunction printPattern($str){ $len = strlen($str); // i goes from 0 to len and // j goes from len-1 to 0 for ($i = 0, $j = $len - 1; $i <= $len, $j >= 0; $i++, $j--) { // To print the upper part. // This loop runs till middle point // of string i and j become same if ($i < $j) { // Print i spaces for ($x = 0; $x < $i; $x++) echo \" \"; // Print i'th character echo $str[$i]; // Print j-i-1 spaces for ( $x = 0; $x < $j - $i - 1; $x++) echo \" \"; // Print j'th character echo $str[$j].\"\\n\"; } // To print center point if ($i == $j) { // Print i spaces for ($x = 0; $x < $i; $x++) echo \" \"; // Print middle character echo $str[$i].\"\\n\"; } // To print lower part else if ($i > $j) { // Print j spaces for ($x = $j - 1; $x >= 0; $x--) echo \" \"; // Print j'th character echo $str[$j]; // Print i-j-1 spaces for ( $x = 0; $x < $i - $j - 1; $x++) echo \" \"; // Print i'h character echo $str[$i].\"\\n\"; } }} // Driver codeprintPattern(\"geeksforgeeks\"); // This code is contributed by mits?>", "e": 31242, "s": 29591, "text": null }, { "code": "<script> // javascript program to// print cross pattern // Function to print given// string in cross patternfunction pattern(str,len){ // i and j are the indexes // of characters to be // displayed in the ith // iteration i = 0 initially // and go upto length of string // j = length of string initially // in each iteration of i, // we increment i and decrement j, // we print character only // of k==i or k==j for (i = 0; i < len; i++) { var j = len - 1 - i; for (k = 0; k < len; k++) { if (k == i || k == j) document.write(str.charAt(k)); else document.write(\" \"); } document.write(\"<br>\"); }} // Driver codestr = \"geeksforgeeks\";var len = str.length;pattern(str, len); // This code is contributed by Amit Katiyar</script>", "e": 32099, "s": 31242, "text": null }, { "code": null, "e": 32109, "s": 32099, "text": "Output : " }, { "code": null, "e": 32255, "s": 32109, "text": "g s\n e k\n e e\n k e\n s g\n f r\n o\n f r\n s g\n k e\n e e\n e k\ng s" }, { "code": null, "e": 32280, "s": 32255, "text": "Alternative Solution : " }, { "code": null, "e": 32284, "s": 32280, "text": "C++" }, { "code": null, "e": 32289, "s": 32284, "text": "Java" }, { "code": null, "e": 32297, "s": 32289, "text": "Python3" }, { "code": null, "e": 32300, "s": 32297, "text": "C#" }, { "code": null, "e": 32304, "s": 32300, "text": "PHP" }, { "code": null, "e": 32315, "s": 32304, "text": "Javascript" }, { "code": "// CPP program to print cross pattern#include<bits/stdc++.h>using namespace std; // Function to print given string in// cross patternvoid pattern(string str, int len){ // i and j are the indexes of characters // to be displayed in the ith iteration // i = 0 initially and go upto length of // string // j = length of string initially // in each iteration of i, we increment // i and decrement j, we print character // only of k==i or k==j for (int i = 0; i < len; i++) { int j = len -1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) cout << str[k]; else cout << \" \"; } cout << endl; }} // driver codeint main (){ string str = \"geeksforgeeks\"; int len = str.size(); pattern(str, len); return 0;}// This code is contributed by Satinder Kaur", "e": 33210, "s": 32315, "text": null }, { "code": "// Java program to print cross pattern class GFG{ // Function to print given // string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length // of string j = length of string // initially in each iteration // of i, we increment i and decrement // j, we print character only // of k==i or k==j for (int i = 0; i < len; i++) { int j = len -1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) System.out.print(str.charAt(k)); else System.out.print(\" \"); } System.out.println(\"\"); }} // driver codepublic static void main(String[] args){ String str = \"geeksforgeeks\"; int len = str.length(); pattern(str, len);}} // This code is contributed by 29AjayKumar", "e": 34157, "s": 33210, "text": null }, { "code": "# Python 3 program to print cross pattern # Function to print given string in# cross patterndef pattern(st, length): # i and j are the indexes of characters # to be displayed in the ith iteration # i = 0 initially and go upto length of # string # j = length of string initially # in each iteration of i, we increment # i and decrement j, we print character # only of k==i or k==j for i in range(length): j = length -1 - i for k in range(length): if (k == i or k == j): print(st[k],end=\"\") else: print(\" \",end=\"\") print() # driver codeif __name__ == \"__main__\": st = \"geeksforgeeks\" length = len(st) pattern(st, length)", "e": 34893, "s": 34157, "text": null }, { "code": "// C# program to print cross patternusing System; class GFG{ // Function to print given// string in cross patternstatic void pattern(String str, int len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length // of string j = length of string // initially in each iteration // of i, we increment i and decrement // j, we print character only // of k==i or k==j for (int i = 0; i < len; i++) { int j = len -1 - i; for (int k = 0; k < len; k++) { if (k == i || k == j) Console.Write(str[k]); else Console.Write(\" \"); } Console.WriteLine(\"\"); }} // Driver codepublic static void Main(String[] args){ String str = \"geeksforgeeks\"; int len = str.Length; pattern(str, len);}} // This code is contributed by Rajput-Ji", "e": 35830, "s": 34893, "text": null }, { "code": "<?php// PHP program to print// cross pattern // Function to print given// string in cross patternfunction pattern($str, $len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length of // string // j = length of string initially // in each iteration of i, we // increment i and decrement j, we // print character only of k==i or k==j for ($i = 0; $i < $len; $i++) { $j = $len -1 - $i; for ($k = 0; $k < $len; $k++) { if ($k == $i || $k == $j) echo $str[$k]; else echo \" \"; } echo \"\\n\"; }} // Driver code$str = \"geeksforgeeks\";$len = strlen($str);pattern($str, $len); // This code is contributed by mits?>", "e": 36631, "s": 35830, "text": null }, { "code": "<script> // Javascript program to print cross pattern // Function to print given // string in cross patternfunction pattern(str , len){ // i and j are the indexes of // characters to be displayed // in the ith iteration i = 0 // initially and go upto length // of string j = length of string // initially in each iteration // of i, we increment i and decrement // j, we print character only // of k==i or k==j for (var i = 0; i < len; i++) { var j = len -1 - i; for (var k = 0; k < len; k++) { if (k == i || k == j) document.write(str.charAt(k)); else document.write(\" \"); } document.write('<br>'); }} // driver codevar str = \"geeksforgeeks\";var len = str.length;pattern(str, len); // This code is contributed by 29AjayKumar </script>", "e": 37518, "s": 36631, "text": null }, { "code": null, "e": 37528, "s": 37518, "text": "Output : " }, { "code": null, "e": 37674, "s": 37528, "text": "g s\n e k\n e e\n k e\n s g\n f r\n o\n f r\n s g\n k e\n e e\n e k\ng s" }, { "code": null, "e": 37958, "s": 37674, "text": "Solution 3: This problem can also be solved by observing that the characters are printed along the left and right diagonals only if we enclose the pattern within a matrix. Now, if the length of the string is len then the pattern can be enclosed within a square matrix of order len. " }, { "code": null, "e": 38096, "s": 37958, "text": "The elements along the left diagonal can be accessed by the condition ( i==j ) where i and j are the row and column numbers respectively." }, { "code": null, "e": 38183, "s": 38096, "text": "The elements along the right diagonal can be accessed by the condition (i+j == len-1)." }, { "code": null, "e": 38408, "s": 38183, "text": "So, run a nested loop of order len and fill the positions satisfying at the above two conditions with respective characters and the rest of the positions with blank spaces.Below is the implementation of the above approach: " }, { "code": null, "e": 38412, "s": 38408, "text": "CPP" }, { "code": null, "e": 38417, "s": 38412, "text": "Java" }, { "code": null, "e": 38425, "s": 38417, "text": "Python3" }, { "code": null, "e": 38428, "s": 38425, "text": "C#" }, { "code": null, "e": 38439, "s": 38428, "text": "Javascript" }, { "code": "// C++ program to print the given pattern #include<bits/stdc++.h>using namespace std; // Function to print the given// string in respective patternvoid printPattern(string str, int len){ for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len-1)) cout<<str[j]; // Print blank space at rest of places else cout<<\" \"; } cout<<endl; }} // Driver Codeint main(){ string str = \"geeksforgeeks\"; int len = str.size(); printPattern(str, len); return 0;} // This code and Approach is contributed by// Aravind Kimonn", "e": 39220, "s": 38439, "text": null }, { "code": "// Java program to print the given patternimport java.io.*;class GFG{ // Function to print the given // string in respective pattern static void printPattern(String str, int len) { for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len - 1)) System.out.print(str.charAt(j)); // Print blank space at rest of places else System.out.print(\" \"); } System.out.println(); } } // Driver code public static void main (String[] args) { String str = \"geeksforgeeks\"; int len = str.length(); printPattern(str, len); }} // This code is contributed by rag2127.", "e": 39991, "s": 39220, "text": null }, { "code": "# Python3 program to print the given pattern # Function to print the given# string in respective patterndef printPattern (Str, Len) : for i in range(Len) : for j in range(Len) : # Print characters at corresponding # places satisfying the two conditions if ((i == j) or (i + j == Len - 1)) : print(Str[j], end = \"\") # Print blank space at rest of places else : print(\" \", end = \"\") print() Str = \"geeksforgeeks\"Len = len(Str)printPattern(Str, Len) # This code is contributed by divyeshrabadiya07.", "e": 40636, "s": 39991, "text": null }, { "code": "// C# program to print the given patternusing System;public class GFG{ // Function to print the given // string in respective pattern static void printPattern(string str, int len) { for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len - 1)) Console.Write(str[j]); // Print blank space at rest of places else Console.Write(\" \"); } Console.WriteLine(); } } // Driver code static public void Main () { String str = \"geeksforgeeks\"; int len = str.Length; printPattern(str, len); }} // This code is contributed by avanitrachhadiya2155", "e": 41389, "s": 40636, "text": null }, { "code": "<script>// javascript program to print the given pattern // Function to print the given // string in respective pattern function printPattern(str , len) { for(var i = 0; i < len; i++) { for(var j = 0; j < len; j++) { // Print characters at corresponding // places satisfying the two conditions if((i == j) || (i + j == len - 1)) document.write(str.charAt(j)); // Print blank space at rest of places else document.write(\" \"); } document.write('<br>'); } } // Driver code var str = \"geeksforgeeks\"; var len = str.length; printPattern(str, len); // This code is contributed by 29AjayKumar</script>", "e": 42080, "s": 41389, "text": null }, { "code": null, "e": 42090, "s": 42080, "text": "Output : " }, { "code": null, "e": 42236, "s": 42090, "text": "g s\n e k\n e e\n k e\n s g\n f r\n o\n f r\n s g\n k e\n e e\n e k\ng s" }, { "code": null, "e": 42267, "s": 42236, "text": "https://youtu.be/7gyjMrezEos " }, { "code": null, "e": 42437, "s": 42267, "text": "This article is contributed by Dinesh T.P.D. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 42452, "s": 42439, "text": "Mithun Kumar" }, { "code": null, "e": 42473, "s": 42452, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 42485, "s": 42473, "text": "29AjayKumar" }, { "code": null, "e": 42495, "s": 42485, "text": "Rajput-Ji" }, { "code": null, "e": 42508, "s": 42495, "text": "Akanksha_Rai" }, { "code": null, "e": 42522, "s": 42508, "text": "ManasChhabra2" }, { "code": null, "e": 42528, "s": 42522, "text": "ukasp" }, { "code": null, "e": 42542, "s": 42528, "text": "kavinkumar999" }, { "code": null, "e": 42550, "s": 42542, "text": "rag2127" }, { "code": null, "e": 42571, "s": 42550, "text": "avanitrachhadiya2155" }, { "code": null, "e": 42589, "s": 42571, "text": "divyeshrabadiya07" }, { "code": null, "e": 42604, "s": 42589, "text": "amit143katiyar" }, { "code": null, "e": 42620, "s": 42604, "text": "simranarora5sos" }, { "code": null, "e": 42637, "s": 42620, "text": "surinderdawra388" }, { "code": null, "e": 42654, "s": 42637, "text": "pattern-printing" }, { "code": null, "e": 42659, "s": 42654, "text": "Zoho" }, { "code": null, "e": 42667, "s": 42659, "text": "Strings" }, { "code": null, "e": 42672, "s": 42667, "text": "Zoho" }, { "code": null, "e": 42680, "s": 42672, "text": "Strings" }, { "code": null, "e": 42697, "s": 42680, "text": "pattern-printing" }, { "code": null, "e": 42795, "s": 42697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42804, "s": 42795, "text": "Comments" }, { "code": null, "e": 42817, "s": 42804, "text": "Old Comments" }, { "code": null, "e": 42874, "s": 42817, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 42949, "s": 42874, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 42996, "s": 42949, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 43032, "s": 42996, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 43068, "s": 43032, "text": "Convert string to char array in C++" }, { "code": null, "e": 43121, "s": 43068, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 43159, "s": 43121, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 43189, "s": 43159, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 43221, "s": 43189, "text": "Reverse words in a given string" } ]
F# - while..do Loops
The while...do expression is used to perform iterative execution while a specified test condition is true. while test-expression do body-expression The test-expression is evaluated first; if it is true, the body-expression is executed and the test expression is evaluated again. The body-expression must have type unit, i.e., it should not return any value. If the test expression is false, the iteration ends. let mutable a = 10 while (a < 20) do printfn "value of a: %d" a a <- a + 1 When you compile and execute the program, it yields the following output − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 Print Add Notes Bookmark this page
[ { "code": null, "e": 2268, "s": 2161, "text": "The while...do expression is used to perform iterative execution while a specified test condition is true." }, { "code": null, "e": 2313, "s": 2268, "text": "while test-expression do\n body-expression\n" }, { "code": null, "e": 2576, "s": 2313, "text": "The test-expression is evaluated first; if it is true, the body-expression is executed and the test expression is evaluated again. The body-expression must have type unit, i.e., it should not return any value. If the test expression is false, the iteration ends." }, { "code": null, "e": 2657, "s": 2576, "text": "let mutable a = 10\nwhile (a < 20) do\n printfn \"value of a: %d\" a\n a <- a + 1" }, { "code": null, "e": 2732, "s": 2657, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 2883, "s": 2732, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 2890, "s": 2883, "text": " Print" }, { "code": null, "e": 2901, "s": 2890, "text": " Add Notes" } ]
Creating Synthetic Data for Machine Learning | by Amizorach | Towards Data Science
The training itself is based on Jacob Solawetz Tutorial on Training custom objects with YOLOv5 And so I will be using the YOLOv5 repository by Ultralytics. This tutorial will guide you through the steps needed to create the synthetic data and show how you can then train it with YOLOv5 in order to work on real images. If you would like to access the full script or download the dataset you can find it all in this Git repository. As an example, I will be training the classifier to detect oranges on a tree. In a perfect world data sets would be abundant, and we could go ahead and train our models on real images in order to make better predictions. However in reality most of an ML coder's time will be spent on gathering data and annotating it correctly. Bigger companies such as Google/Facebook/Amazon/Apple and even mid-sized companies that have the resources can go ahead and launch such projects. First, because they have the data itself — in our case the images. And second, because they have the ability to annotate the data in order to create an error-free dataset. But even these companies can not be sure that the data is correctly annotated and so the normal process would be to annotate each image more than once and then look for discrepancies. For a small company or just someone like myself trying to build a ML project from the ground up, this is too large of a task. And so I find myself using one of the datasets available online. There are many great datasets out there and in some instances creating a new dataset is really not needed. But after a while, I started to realize all of my projects were not doing exactly what I want them to do, as they were trained on a different kind of data. For this project, I wanted to count oranges on a tree and could not find a suitable dataset. So I started downloading images and attempted to annotate them. For example, I started with the following image taken from Wikimedia. This is not a full tree and still, it was clear to me very quickly I will not be able to annotate this image. I figured I can try to choose simple images but I was not sure how they would stand up when training the network. Moving on to more complex images such as this one (also from Wikimedia), I understood this was no longer an option and started playing around with different datasets that I could find online. This was not what I wanted to do, and quickly I was getting discouraged. This is when I found myself searching for a different solution and watched Adam Kellys (Immersive Limit) great tutorial where he trained a network to recognize weeds using synthetic data. You can watch his video here AI Weed Detector. Although I was not over-impressed by the results (He seems to be) as I needed better results I realized if I was going to continue the project this was the way to go. So geared with the new keywords I need, I started my search throughout google and came along the following paper by Maryam Rahnemoonfar and Clay Sheppard — Deep Count: Fruit Counting Based on Deep Simulated Learning This paper seemed to be exactly what I was after they went ahead and trained their network on data that was generated without the need to get up and start taking images. And even more, they were trying to do something very similar to what I was doing. They did not provide the dataset and looking at their images I thought I can do better. In general, they proposed the following steps But it seemed to me that they were not taking into account the fact that the fruit may be obstructed by leaves and they also did not compute the bounding boxes. Still, as I was encouraged by the fact that it worked I went out on creating my own synthetic data. I realized I needed to do the following in order for the network to be able to count real data Gather information regarding the backgrounds I may encounter Gather information regarding the backgrounds I may encounter 2. Create a background image that is constructed from these colors 3. Create circles of varying sizes to replace the oranges 4. Create a foreground from leaves colors that will obstruct some of the oranges So to do this I wrote a simple python program that will create the images for me — (The code was simplified so the reader can easily read through it if you want to download the full code check out my Git) from PIL import Image, ImageDrawfrom PIL import ImageFilterfrom PIL import ImageColorfrom pascal import PascalVOC, PascalObject, BndBox, size_blockfrom pathlib import Pathimport cv2import numpy as npimport random We start with some imports I am using PIL (pillow) in order to create the images and pascal (PascalVoc) in order to save the information as annotations. I downloaded a few images of orange trees from the web and started to sample pixels. Their color was then saved into one of three arrays leaves, sky, ground At this point, I did not sample the oranges as I used a different approach for them def prepare_colors(): txt_leaves = ['#608d2a', '#a8b146', '#ccf0bc'] txt_sky = ['#e9e3c3', '#99949e', '#9bb5cf'] txt_ground = ['#3d2c15', '#dfcba6'] bg_colors = [] fg_colors = [] for t in txt_leaves: bg_colors.append(ImageColor.getrgb(t)) fg_colors.append(ImageColor.getrgb(t)) for t in txt_sky: bg_colors.append(ImageColor.getrgb(t)) for t in txt_ground: bg_colors.append(ImageColor.getrgb(t)) return bg_colors, fg_colors This was simple enough but it's worth mentioning I sampled more colors than in the code above (you can find all the colors I sampled in the Git) but I cut back for clarity The next step was to write a function that would randomly place colors on a layer def plot_random_color_blobs(draw, colors, count, mins, maxs): for i in range(count): x = random.randint(0,width) y = random.randint(0,height) w = random.randint(mins,maxs) l = random.randint(mins,maxs) c = bg_colors[random.randint(0,len(colors)-1)] draw.ellipse((x, y, x+w, y+l), fill=c, outline=None) This function receives an ImageDraw.Draw object from PIL and adds count amount of ellipses in random spots The result for a layer may look something like this Assuming we are using the colors red green and blue, and a high number of count (in this case 1500) so now its time to construct the background layer def create_bg(colors, width, height): im_bg = Image.new('RGBA', (width, height), ImageColor.getrgb('#7FCBFDFF')) draw_bg = ImageDraw.Draw(im_bg) plot_random_blobs(draw_bg, colors, 1500, 10, 25) im_bg = im_bg.filter(ImageFilter.MedianFilter(size=9)) return im_bg As you can see the image is created with a light blue background in order to eliminate any areas that were not targeted by the random ellipses. After plotting the blobs I made sure to blur the image using a blur filter so the result was something like this This was starting to look like I was in the correct direction. But I was worried the network would learn how to distinguish between blurry parts of the image and the nonblurred part in our case the fruit, so I dialed it down and moved to a MedianFilter which allowed merging colors but still preserving the overall sharpness of the background. Next, I created the foreground layer — this layer will be placed over the fruit layer in order to mask out some of the fruit def create_fg(colors, width, height): im_fg = Image.new('RGBA', (width, height), (0, 0, 0, 0)) draw_fg = ImageDraw.Draw(im_fg) plot_random_el(draw_fg, colors, 40, 10, 25) im_fg = im_fg.filter(ImageFilter.MedianFilter(size=9)) return im_fg As you can see this function is almost identical except for the fact I set the background to transparent and used a much lower number of blobs (40) to make sure most of the fruit can be seen Last it was time to create the fruit layer def plot_random_fruit(color_range, count, width, height, mins, maxs): im_fruit = Image.new('RGBA', (width, height), (0, 0, 0, 0)) draw_fruit = ImageDraw.Draw(im_fruit) fruit_info = [] for i in range(count): x = random.randint(0,width-10) y = random.randint(0,height-10) w = random.randint(mins,maxs) c = (random.randint(color_range[0][0],color_range[0][1]), random.randint(color_range[1][0], color_range[1][1]), random.randint(color_range[2][0], color_range[2][1])) fruit_info.append([x, y, w, w, c]) draw_fruit.ellipse((x, y, x+w, y+w), fill=c, outline=None) return im_fruit, fruit_info Similar to the other layers this layer plots fruit in random places around the image. However, this layer differs by four points. The plotting is always a circle, as this is the more common shape of the fruit.It uses a range of colors (all orange variants in my case) to choose a color randomly.No filter is assigned to the image.The image stores the bounding boxes of the fruit as well as its color in an array that is returned as fruit info. The plotting is always a circle, as this is the more common shape of the fruit. It uses a range of colors (all orange variants in my case) to choose a color randomly. No filter is assigned to the image. The image stores the bounding boxes of the fruit as well as its color in an array that is returned as fruit info. def create_layered_image(im_bg, im_fruit, im_fg): img = im_bg.copy() img.paste(im_fruit, (0, 0), im_fruit) img.paste(im_fg, (0, 0), im_fg) return img This final function simply pastes the images one on the other And the result would like something like this Clearly, this does not look like a fruit tree but it includes the correct colors and situations the network might need to see in order to be able to train correctly. The next part was to create an annotation file, I decided to use the PascalObject as I was more familiar with it, but any other annotation could have worked. def create_annotation(img, fruit_info, obj_name, img_name ,ann_name): pobjs = [] for i in range(len(fruit_info)): pct = 0 circle = fruit_info[i] color = circle[4] for i in range(circle[2]): if (circle[0]+i >= width): continue; for j in range(circle[3]): if (circle[1]+j >= height): continue; r = img.getpixel((circle[0]+i, circle[1]+j)) if (r[0] == color[0]): pct = pct +1 diffculty = pct/(circle[2]*circle[3]) if (diffculty > 0.1): dif = True if (diffculty > 0.4): dif = False pobjs.append( PascalObject(obj_name, "", truncated=False, difficult=dif, bndbox=BndBox(circle[0], circle[1], circle[0]+circle[2], circle[1]+circle[3]))) pascal_ann = PascalVOC(img_name, size=size_block(width, height, 3), objects=pobjs) pascal_ann.save(ann_name) Before adding the bounding box to the annotation the function checks how much of the fruit is not obstructed by the foreground. This allows the network to decide if a mistake in counting this fruit is critical. However the difficulty parameter in the PascalObject is a boolean so I choose the following 3 cutoffs if less the 10% of the fruit is seen, I simply omit the information, and any fruit that is obstructed by more than 40% is considered difficult. Putting it all together I was now ready to start generating the images def create_training_image(counter, bg_colors, fg_colors, fruit_color_range): fruit_count = random.randint(0, 20) ext = '{}_{}'.format(counter, fruit_count) img_name = '{}/fruit_{}.png'.format(img_path, ext) ann_name = '{}/ann_{}.xml'.format(ann_path, ext) im_bg = create_bg(bg_colors, width, height) im_fg = create_fg(fg_colors, width, height) im_fruit, fruit_info = plot_random_fruit(fruit_color_range, fruit_count, width, height, 10, 25) img = create_layered_image(im_bg, im_fruit, im_fg) #create the anootation File create_annotation(img, fruit_info, 'oranges', img_name, ann_name) img.save(img_name) return img, img_name, ann_name This function should now be self-explanatory and creates a single image and its annotation file. And now for the production of many images, I added def create_training_set(num, start_at=0): bg_colors, fg_colors = prepare_colors() fruit_color_range = [[180,230],[50,130],[0,5]] for i in range(num): create_training_image(num+start_at, bg_colors, fg_colors, fruit_color_range) And the results were Once I had the images and annotations ready I followed Solawetz Tutorial and used Roboflow to turn it into a readable dataset for YOLOv5 — as Roboflow’s max amount of images for free usage was 1000 images I made sure not to create too many images, in the future I will try to overcome this by simply creating the dataset in code, but for now it should do. Following the simple 5 steps in the Roboflow setup, I was able to construct the dataset within minutes. I choose not to create augmentations at this point but ended up using them for zoom purposes later on to allow the network to detect bigger objects. After setting up the environment according to Solawetz’s tutorial training was reduced to a single line of code %%time%cd /content/yolov5/!python train.py --img 416 --batch 16 --epochs 100 --data '../data.yaml' --cfg ./models/custom_yolov5s.yaml --weights '' --name yolov5s_results --cache To train your own model I suggest checking out Roboflow’s notebook. I originally wrote my own notebook that can be found in the Git repository, but after reviewing it, I found that the above notebook is simply written better so Kudos to them :). As I am more accustomed to using Tensorflow and less familiar with PyTorch, and since the object of the training was to test the synthetic data, I opted not to change the training code and not to try to adjust it. In the future, I plan to explore this as well. After only a few minutes (running on a GPU using Collab) and running just 100 epochs, I had the training results with a precision of almost 91%. In fact, the network was able to converge to such precision in less than 40 epochs. Amazing. But of course, this was all on the synthetic data. It was time to test real data. And as always pictures are worth 1000 words. Not all worked perfectly. Images that had large oranges that took a large portion of the screen did not work well, I guessed this was because all oranges in my training set were relatively small. I retrained the dataset using Roboflows Augmentations with the zoom augmentation and got better results. But in further testing, I plan to create images that include a wider range of blob and orange sizes. The colors picked for the background may be crucial — in my first test I did not add any general colors that can appear in images such as skin tone and it picked them up as oranges in some instances. But again after adding some skin tones to the background colors this problem seemed to go away. In conclusion, using synthetic data proved to be useful and easy. I was easily able to run it on a video and as the Yolov5s is so quick it can actually run in real-time. If you want to download the full code and data set you can check out my Git I am now moving on to the next step which will be tracking these oranges through many different frames to allow stronger validation throughout different views and eventually Crop estimation.
[ { "code": null, "e": 267, "s": 172, "text": "The training itself is based on Jacob Solawetz Tutorial on Training custom objects with YOLOv5" }, { "code": null, "e": 328, "s": 267, "text": "And so I will be using the YOLOv5 repository by Ultralytics." }, { "code": null, "e": 491, "s": 328, "text": "This tutorial will guide you through the steps needed to create the synthetic data and show how you can then train it with YOLOv5 in order to work on real images." }, { "code": null, "e": 603, "s": 491, "text": "If you would like to access the full script or download the dataset you can find it all in this Git repository." }, { "code": null, "e": 681, "s": 603, "text": "As an example, I will be training the classifier to detect oranges on a tree." }, { "code": null, "e": 931, "s": 681, "text": "In a perfect world data sets would be abundant, and we could go ahead and train our models on real images in order to make better predictions. However in reality most of an ML coder's time will be spent on gathering data and annotating it correctly." }, { "code": null, "e": 1433, "s": 931, "text": "Bigger companies such as Google/Facebook/Amazon/Apple and even mid-sized companies that have the resources can go ahead and launch such projects. First, because they have the data itself — in our case the images. And second, because they have the ability to annotate the data in order to create an error-free dataset. But even these companies can not be sure that the data is correctly annotated and so the normal process would be to annotate each image more than once and then look for discrepancies." }, { "code": null, "e": 1887, "s": 1433, "text": "For a small company or just someone like myself trying to build a ML project from the ground up, this is too large of a task. And so I find myself using one of the datasets available online. There are many great datasets out there and in some instances creating a new dataset is really not needed. But after a while, I started to realize all of my projects were not doing exactly what I want them to do, as they were trained on a different kind of data." }, { "code": null, "e": 1980, "s": 1887, "text": "For this project, I wanted to count oranges on a tree and could not find a suitable dataset." }, { "code": null, "e": 2044, "s": 1980, "text": "So I started downloading images and attempted to annotate them." }, { "code": null, "e": 2114, "s": 2044, "text": "For example, I started with the following image taken from Wikimedia." }, { "code": null, "e": 2224, "s": 2114, "text": "This is not a full tree and still, it was clear to me very quickly I will not be able to annotate this image." }, { "code": null, "e": 2338, "s": 2224, "text": "I figured I can try to choose simple images but I was not sure how they would stand up when training the network." }, { "code": null, "e": 2530, "s": 2338, "text": "Moving on to more complex images such as this one (also from Wikimedia), I understood this was no longer an option and started playing around with different datasets that I could find online." }, { "code": null, "e": 2603, "s": 2530, "text": "This was not what I wanted to do, and quickly I was getting discouraged." }, { "code": null, "e": 2838, "s": 2603, "text": "This is when I found myself searching for a different solution and watched Adam Kellys (Immersive Limit) great tutorial where he trained a network to recognize weeds using synthetic data. You can watch his video here AI Weed Detector." }, { "code": null, "e": 3005, "s": 2838, "text": "Although I was not over-impressed by the results (He seems to be) as I needed better results I realized if I was going to continue the project this was the way to go." }, { "code": null, "e": 3221, "s": 3005, "text": "So geared with the new keywords I need, I started my search throughout google and came along the following paper by Maryam Rahnemoonfar and Clay Sheppard — Deep Count: Fruit Counting Based on Deep Simulated Learning" }, { "code": null, "e": 3473, "s": 3221, "text": "This paper seemed to be exactly what I was after they went ahead and trained their network on data that was generated without the need to get up and start taking images. And even more, they were trying to do something very similar to what I was doing." }, { "code": null, "e": 3561, "s": 3473, "text": "They did not provide the dataset and looking at their images I thought I can do better." }, { "code": null, "e": 3607, "s": 3561, "text": "In general, they proposed the following steps" }, { "code": null, "e": 3768, "s": 3607, "text": "But it seemed to me that they were not taking into account the fact that the fruit may be obstructed by leaves and they also did not compute the bounding boxes." }, { "code": null, "e": 3868, "s": 3768, "text": "Still, as I was encouraged by the fact that it worked I went out on creating my own synthetic data." }, { "code": null, "e": 3963, "s": 3868, "text": "I realized I needed to do the following in order for the network to be able to count real data" }, { "code": null, "e": 4024, "s": 3963, "text": "Gather information regarding the backgrounds I may encounter" }, { "code": null, "e": 4085, "s": 4024, "text": "Gather information regarding the backgrounds I may encounter" }, { "code": null, "e": 4152, "s": 4085, "text": "2. Create a background image that is constructed from these colors" }, { "code": null, "e": 4210, "s": 4152, "text": "3. Create circles of varying sizes to replace the oranges" }, { "code": null, "e": 4291, "s": 4210, "text": "4. Create a foreground from leaves colors that will obstruct some of the oranges" }, { "code": null, "e": 4496, "s": 4291, "text": "So to do this I wrote a simple python program that will create the images for me — (The code was simplified so the reader can easily read through it if you want to download the full code check out my Git)" }, { "code": null, "e": 4709, "s": 4496, "text": "from PIL import Image, ImageDrawfrom PIL import ImageFilterfrom PIL import ImageColorfrom pascal import PascalVOC, PascalObject, BndBox, size_blockfrom pathlib import Pathimport cv2import numpy as npimport random" }, { "code": null, "e": 4862, "s": 4709, "text": "We start with some imports I am using PIL (pillow) in order to create the images and pascal (PascalVoc) in order to save the information as annotations." }, { "code": null, "e": 4999, "s": 4862, "text": "I downloaded a few images of orange trees from the web and started to sample pixels. Their color was then saved into one of three arrays" }, { "code": null, "e": 5019, "s": 4999, "text": "leaves, sky, ground" }, { "code": null, "e": 5103, "s": 5019, "text": "At this point, I did not sample the oranges as I used a different approach for them" }, { "code": null, "e": 5581, "s": 5103, "text": "def prepare_colors(): txt_leaves = ['#608d2a', '#a8b146', '#ccf0bc'] txt_sky = ['#e9e3c3', '#99949e', '#9bb5cf'] txt_ground = ['#3d2c15', '#dfcba6'] bg_colors = [] fg_colors = [] for t in txt_leaves: bg_colors.append(ImageColor.getrgb(t)) fg_colors.append(ImageColor.getrgb(t)) for t in txt_sky: bg_colors.append(ImageColor.getrgb(t)) for t in txt_ground: bg_colors.append(ImageColor.getrgb(t)) return bg_colors, fg_colors" }, { "code": null, "e": 5753, "s": 5581, "text": "This was simple enough but it's worth mentioning I sampled more colors than in the code above (you can find all the colors I sampled in the Git) but I cut back for clarity" }, { "code": null, "e": 5835, "s": 5753, "text": "The next step was to write a function that would randomly place colors on a layer" }, { "code": null, "e": 6182, "s": 5835, "text": "def plot_random_color_blobs(draw, colors, count, mins, maxs): for i in range(count): x = random.randint(0,width) y = random.randint(0,height) w = random.randint(mins,maxs) l = random.randint(mins,maxs) c = bg_colors[random.randint(0,len(colors)-1)] draw.ellipse((x, y, x+w, y+l), fill=c, outline=None)" }, { "code": null, "e": 6289, "s": 6182, "text": "This function receives an ImageDraw.Draw object from PIL and adds count amount of ellipses in random spots" }, { "code": null, "e": 6441, "s": 6289, "text": "The result for a layer may look something like this Assuming we are using the colors red green and blue, and a high number of count (in this case 1500)" }, { "code": null, "e": 6491, "s": 6441, "text": "so now its time to construct the background layer" }, { "code": null, "e": 6790, "s": 6491, "text": "def create_bg(colors, width, height): im_bg = Image.new('RGBA', (width, height), ImageColor.getrgb('#7FCBFDFF')) draw_bg = ImageDraw.Draw(im_bg) plot_random_blobs(draw_bg, colors, 1500, 10, 25) im_bg = im_bg.filter(ImageFilter.MedianFilter(size=9)) return im_bg" }, { "code": null, "e": 6934, "s": 6790, "text": "As you can see the image is created with a light blue background in order to eliminate any areas that were not targeted by the random ellipses." }, { "code": null, "e": 7047, "s": 6934, "text": "After plotting the blobs I made sure to blur the image using a blur filter so the result was something like this" }, { "code": null, "e": 7110, "s": 7047, "text": "This was starting to look like I was in the correct direction." }, { "code": null, "e": 7391, "s": 7110, "text": "But I was worried the network would learn how to distinguish between blurry parts of the image and the nonblurred part in our case the fruit, so I dialed it down and moved to a MedianFilter which allowed merging colors but still preserving the overall sharpness of the background." }, { "code": null, "e": 7516, "s": 7391, "text": "Next, I created the foreground layer — this layer will be placed over the fruit layer in order to mask out some of the fruit" }, { "code": null, "e": 7770, "s": 7516, "text": "def create_fg(colors, width, height): im_fg = Image.new('RGBA', (width, height), (0, 0, 0, 0)) draw_fg = ImageDraw.Draw(im_fg) plot_random_el(draw_fg, colors, 40, 10, 25) im_fg = im_fg.filter(ImageFilter.MedianFilter(size=9)) return im_fg" }, { "code": null, "e": 7961, "s": 7770, "text": "As you can see this function is almost identical except for the fact I set the background to transparent and used a much lower number of blobs (40) to make sure most of the fruit can be seen" }, { "code": null, "e": 8004, "s": 7961, "text": "Last it was time to create the fruit layer" }, { "code": null, "e": 8696, "s": 8004, "text": "def plot_random_fruit(color_range, count, width, height, mins, maxs): im_fruit = Image.new('RGBA', (width, height), (0, 0, 0, 0)) draw_fruit = ImageDraw.Draw(im_fruit) fruit_info = [] for i in range(count): x = random.randint(0,width-10) y = random.randint(0,height-10) w = random.randint(mins,maxs) c = (random.randint(color_range[0][0],color_range[0][1]), random.randint(color_range[1][0], color_range[1][1]), random.randint(color_range[2][0], color_range[2][1])) fruit_info.append([x, y, w, w, c]) draw_fruit.ellipse((x, y, x+w, y+w), fill=c, outline=None) return im_fruit, fruit_info" }, { "code": null, "e": 8826, "s": 8696, "text": "Similar to the other layers this layer plots fruit in random places around the image. However, this layer differs by four points." }, { "code": null, "e": 9140, "s": 8826, "text": "The plotting is always a circle, as this is the more common shape of the fruit.It uses a range of colors (all orange variants in my case) to choose a color randomly.No filter is assigned to the image.The image stores the bounding boxes of the fruit as well as its color in an array that is returned as fruit info." }, { "code": null, "e": 9220, "s": 9140, "text": "The plotting is always a circle, as this is the more common shape of the fruit." }, { "code": null, "e": 9307, "s": 9220, "text": "It uses a range of colors (all orange variants in my case) to choose a color randomly." }, { "code": null, "e": 9343, "s": 9307, "text": "No filter is assigned to the image." }, { "code": null, "e": 9457, "s": 9343, "text": "The image stores the bounding boxes of the fruit as well as its color in an array that is returned as fruit info." }, { "code": null, "e": 9619, "s": 9457, "text": "def create_layered_image(im_bg, im_fruit, im_fg): img = im_bg.copy() img.paste(im_fruit, (0, 0), im_fruit) img.paste(im_fg, (0, 0), im_fg) return img" }, { "code": null, "e": 9681, "s": 9619, "text": "This final function simply pastes the images one on the other" }, { "code": null, "e": 9727, "s": 9681, "text": "And the result would like something like this" }, { "code": null, "e": 9893, "s": 9727, "text": "Clearly, this does not look like a fruit tree but it includes the correct colors and situations the network might need to see in order to be able to train correctly." }, { "code": null, "e": 10051, "s": 9893, "text": "The next part was to create an annotation file, I decided to use the PascalObject as I was more familiar with it, but any other annotation could have worked." }, { "code": null, "e": 11241, "s": 10051, "text": "def create_annotation(img, fruit_info, obj_name, img_name ,ann_name): pobjs = [] for i in range(len(fruit_info)): pct = 0 circle = fruit_info[i] color = circle[4] for i in range(circle[2]): if (circle[0]+i >= width): continue; for j in range(circle[3]): if (circle[1]+j >= height): continue; r = img.getpixel((circle[0]+i, circle[1]+j)) if (r[0] == color[0]): pct = pct +1 diffculty = pct/(circle[2]*circle[3]) if (diffculty > 0.1): dif = True if (diffculty > 0.4): dif = False pobjs.append( PascalObject(obj_name, \"\", truncated=False, difficult=dif, bndbox=BndBox(circle[0], circle[1], circle[0]+circle[2], circle[1]+circle[3]))) pascal_ann = PascalVOC(img_name, size=size_block(width, height, 3), objects=pobjs) pascal_ann.save(ann_name)" }, { "code": null, "e": 11452, "s": 11241, "text": "Before adding the bounding box to the annotation the function checks how much of the fruit is not obstructed by the foreground. This allows the network to decide if a mistake in counting this fruit is critical." }, { "code": null, "e": 11698, "s": 11452, "text": "However the difficulty parameter in the PascalObject is a boolean so I choose the following 3 cutoffs if less the 10% of the fruit is seen, I simply omit the information, and any fruit that is obstructed by more than 40% is considered difficult." }, { "code": null, "e": 11769, "s": 11698, "text": "Putting it all together I was now ready to start generating the images" }, { "code": null, "e": 12575, "s": 11769, "text": "def create_training_image(counter, bg_colors, fg_colors, fruit_color_range): fruit_count = random.randint(0, 20) ext = '{}_{}'.format(counter, fruit_count) img_name = '{}/fruit_{}.png'.format(img_path, ext) ann_name = '{}/ann_{}.xml'.format(ann_path, ext) im_bg = create_bg(bg_colors, width, height) im_fg = create_fg(fg_colors, width, height) im_fruit, fruit_info = plot_random_fruit(fruit_color_range, fruit_count, width, height, 10, 25) img = create_layered_image(im_bg, im_fruit, im_fg) #create the anootation File create_annotation(img, fruit_info, 'oranges', img_name, ann_name) img.save(img_name) return img, img_name, ann_name" }, { "code": null, "e": 12672, "s": 12575, "text": "This function should now be self-explanatory and creates a single image and its annotation file." }, { "code": null, "e": 12723, "s": 12672, "text": "And now for the production of many images, I added" }, { "code": null, "e": 12995, "s": 12723, "text": "def create_training_set(num, start_at=0): bg_colors, fg_colors = prepare_colors() fruit_color_range = [[180,230],[50,130],[0,5]] for i in range(num): create_training_image(num+start_at, bg_colors, fg_colors, fruit_color_range)" }, { "code": null, "e": 13016, "s": 12995, "text": "And the results were" }, { "code": null, "e": 13372, "s": 13016, "text": "Once I had the images and annotations ready I followed Solawetz Tutorial and used Roboflow to turn it into a readable dataset for YOLOv5 — as Roboflow’s max amount of images for free usage was 1000 images I made sure not to create too many images, in the future I will try to overcome this by simply creating the dataset in code, but for now it should do." }, { "code": null, "e": 13476, "s": 13372, "text": "Following the simple 5 steps in the Roboflow setup, I was able to construct the dataset within minutes." }, { "code": null, "e": 13625, "s": 13476, "text": "I choose not to create augmentations at this point but ended up using them for zoom purposes later on to allow the network to detect bigger objects." }, { "code": null, "e": 13737, "s": 13625, "text": "After setting up the environment according to Solawetz’s tutorial training was reduced to a single line of code" }, { "code": null, "e": 13916, "s": 13737, "text": "%%time%cd /content/yolov5/!python train.py --img 416 --batch 16 --epochs 100 --data '../data.yaml' --cfg ./models/custom_yolov5s.yaml --weights '' --name yolov5s_results --cache" }, { "code": null, "e": 13984, "s": 13916, "text": "To train your own model I suggest checking out Roboflow’s notebook." }, { "code": null, "e": 14162, "s": 13984, "text": "I originally wrote my own notebook that can be found in the Git repository, but after reviewing it, I found that the above notebook is simply written better so Kudos to them :)." }, { "code": null, "e": 14423, "s": 14162, "text": "As I am more accustomed to using Tensorflow and less familiar with PyTorch, and since the object of the training was to test the synthetic data, I opted not to change the training code and not to try to adjust it. In the future, I plan to explore this as well." }, { "code": null, "e": 14661, "s": 14423, "text": "After only a few minutes (running on a GPU using Collab) and running just 100 epochs, I had the training results with a precision of almost 91%. In fact, the network was able to converge to such precision in less than 40 epochs. Amazing." }, { "code": null, "e": 14712, "s": 14661, "text": "But of course, this was all on the synthetic data." }, { "code": null, "e": 14743, "s": 14712, "text": "It was time to test real data." }, { "code": null, "e": 14788, "s": 14743, "text": "And as always pictures are worth 1000 words." }, { "code": null, "e": 14814, "s": 14788, "text": "Not all worked perfectly." }, { "code": null, "e": 15190, "s": 14814, "text": "Images that had large oranges that took a large portion of the screen did not work well, I guessed this was because all oranges in my training set were relatively small. I retrained the dataset using Roboflows Augmentations with the zoom augmentation and got better results. But in further testing, I plan to create images that include a wider range of blob and orange sizes." }, { "code": null, "e": 15486, "s": 15190, "text": "The colors picked for the background may be crucial — in my first test I did not add any general colors that can appear in images such as skin tone and it picked them up as oranges in some instances. But again after adding some skin tones to the background colors this problem seemed to go away." }, { "code": null, "e": 15552, "s": 15486, "text": "In conclusion, using synthetic data proved to be useful and easy." }, { "code": null, "e": 15656, "s": 15552, "text": "I was easily able to run it on a video and as the Yolov5s is so quick it can actually run in real-time." }, { "code": null, "e": 15732, "s": 15656, "text": "If you want to download the full code and data set you can check out my Git" } ]
Compute Cumulative Logistic Density in R Programming - plogis() Function - GeeksforGeeks
25 Jun, 2020 plogis() function in R Language is used to compute logistic cumulative density of the distribution. It also creates a plot of the density of the logistic cumulative distribution. Syntax: plogis(vec) Parameters:vec: Vector of x-values for density Example 1: # R program to calculate # cumulative logistic density # Create a vector of x-valuesx <- seq(-1, 1, by = 0.1) # Calling the plogis() functiony <- plogis(x)y Output: [1] 0.2689414 0.2890505 0.3100255 0.3318122 0.3543437 0.3775407 0.4013123 [8] 0.4255575 0.4501660 0.4750208 0.5000000 0.5249792 0.5498340 0.5744425 [15] 0.5986877 0.6224593 0.6456563 0.6681878 0.6899745 0.7109495 0.7310586 Example 2: # R program to calculate # cumulative logistic density # Create a vector of x-valuesx <- seq(-20, 20, by = 0.1) # Calling the plogis() functiony <- plogis(x) # Plot the graphplot(y) Output: R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming
[ { "code": null, "e": 25043, "s": 25015, "text": "\n25 Jun, 2020" }, { "code": null, "e": 25222, "s": 25043, "text": "plogis() function in R Language is used to compute logistic cumulative density of the distribution. It also creates a plot of the density of the logistic cumulative distribution." }, { "code": null, "e": 25242, "s": 25222, "text": "Syntax: plogis(vec)" }, { "code": null, "e": 25289, "s": 25242, "text": "Parameters:vec: Vector of x-values for density" }, { "code": null, "e": 25300, "s": 25289, "text": "Example 1:" }, { "code": "# R program to calculate # cumulative logistic density # Create a vector of x-valuesx <- seq(-1, 1, by = 0.1) # Calling the plogis() functiony <- plogis(x)y", "e": 25459, "s": 25300, "text": null }, { "code": null, "e": 25467, "s": 25459, "text": "Output:" }, { "code": null, "e": 25693, "s": 25467, "text": " [1] 0.2689414 0.2890505 0.3100255 0.3318122 0.3543437 0.3775407 0.4013123\n [8] 0.4255575 0.4501660 0.4750208 0.5000000 0.5249792 0.5498340 0.5744425\n[15] 0.5986877 0.6224593 0.6456563 0.6681878 0.6899745 0.7109495 0.7310586\n" }, { "code": null, "e": 25704, "s": 25693, "text": "Example 2:" }, { "code": "# R program to calculate # cumulative logistic density # Create a vector of x-valuesx <- seq(-20, 20, by = 0.1) # Calling the plogis() functiony <- plogis(x) # Plot the graphplot(y)", "e": 25889, "s": 25704, "text": null }, { "code": null, "e": 25897, "s": 25889, "text": "Output:" }, { "code": null, "e": 25910, "s": 25897, "text": "R-Statistics" }, { "code": null, "e": 25921, "s": 25910, "text": "R Language" }, { "code": null, "e": 26019, "s": 25921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26028, "s": 26019, "text": "Comments" }, { "code": null, "e": 26041, "s": 26028, "text": "Old Comments" }, { "code": null, "e": 26099, "s": 26041, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26143, "s": 26099, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26195, "s": 26143, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26227, "s": 26195, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26279, "s": 26227, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26311, "s": 26279, "text": "Printing Output of an R Program" }, { "code": null, "e": 26349, "s": 26311, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26384, "s": 26349, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26442, "s": 26384, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
How to Fix: No module named pandas - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss how to fix the No module named pandas error. The error “No module named pandas ” will occur when there is no pandas library in your environment IE the pandas module is either not installed or there is an issue while downloading the module right. Let’s see the error by creating an pandas dataframe. Example: Produce the error Python3 # import pandasimport pandas # create dataframepandas.DataFrame({'a': [1, 2]}) Output: We will discuss how to overcome this error. In python, we will use pip function to install any module Syntax: pip install module_name So we have to specify pandas Example: Installing Pandas Python3 pip install pandas Output: Collecting pandas Downloading pandas-3.2.0.tar.gz (281.3 MB) |████████████████████████████████| 281.3 MB 9.7 kB/s Collecting py4j==0.10.9.2 Downloading py4j-0.10.9.2-py2.py3-none-any.whl (198 kB) |████████████████████████████████| 198 kB 52.8 MB/s Building wheels for collected packages: pandas Building wheel for pandas (setup.py) ... done Created wheel for pandas: filename=pyspark-3.2.0-py2.py3-none-any.whl size=281805912 sha256=c6c9edb963f9a25f31d11d88374ce3be6b3c73ac73ac467ef40b51b5f4eca737 Stored in directory: /root/.cache/pip/wheels/0b/de/d2/9be5d59d7331c6c2a7c1b6d1a4f463ce107332b1ecd4e80718 Successfully built pandas Installing collected packages: py4j, pandas Successfully installed py4j-0.10.9.2 pandas-3.2.0 We can verify by again typing same command then the output will be: Output: Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.1.5) To get the pandas description in our environment we can use the show command. This can help keep track of the module and its installation. Example: Show module description Python3 # display pandas detailspip show pandas Output: Name: pandas Version: 1.1.5 Summary: Powerful data structures for data analysis, time series, and statistics Home-page: https://pandas.pydata.org Author: None Author-email: None License: BSD Location: /usr/local/lib/python3.7/dist-packages Requires: numpy, python-dateutil, pytz Required-by: xarray, vega-datasets, statsmodels, sklearn-pandas, seaborn, pymc3, plotnine, pandas-profiling, pandas-gbq, pandas-datareader, mlxtend, mizani, holoviews, gspread-dataframe, google-colab, fix-yahoo-finance, fbprophet, fastai, cufflinks, cmdstanpy, arviz, altair Upgrading pandas is the best advantage to get error-free in your environment. So, we have to upgrade using the following command. Example: Upgrading Pandas Python3 pip3 install pandas - -upgrade Output: To install a specific version of pandas we have to specify the version in the pip command. Example: Installing a specific version of a module Python3 # install 1.3.4 versionpip3 install pandas == 1.3.4 Output: If we want to find the version then we have to use __version__ Syntax: module_name.__version__ Example: Get pandas version Python3 #import moduleimport pandas as pd # get the versionpd.__version__ Output: 1.1.5 Picked Python How-to-fix Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25633, "s": 25555, "text": "In this article, we will discuss how to fix the No module named pandas error." }, { "code": null, "e": 25834, "s": 25633, "text": "The error “No module named pandas ” will occur when there is no pandas library in your environment IE the pandas module is either not installed or there is an issue while downloading the module right." }, { "code": null, "e": 25887, "s": 25834, "text": "Let’s see the error by creating an pandas dataframe." }, { "code": null, "e": 25914, "s": 25887, "text": "Example: Produce the error" }, { "code": null, "e": 25922, "s": 25914, "text": "Python3" }, { "code": "# import pandasimport pandas # create dataframepandas.DataFrame({'a': [1, 2]})", "e": 26002, "s": 25922, "text": null }, { "code": null, "e": 26010, "s": 26002, "text": "Output:" }, { "code": null, "e": 26112, "s": 26010, "text": "We will discuss how to overcome this error. In python, we will use pip function to install any module" }, { "code": null, "e": 26120, "s": 26112, "text": "Syntax:" }, { "code": null, "e": 26144, "s": 26120, "text": "pip install module_name" }, { "code": null, "e": 26173, "s": 26144, "text": "So we have to specify pandas" }, { "code": null, "e": 26201, "s": 26173, "text": "Example: Installing Pandas " }, { "code": null, "e": 26209, "s": 26201, "text": "Python3" }, { "code": "pip install pandas", "e": 26228, "s": 26209, "text": null }, { "code": null, "e": 26236, "s": 26228, "text": "Output:" }, { "code": null, "e": 26254, "s": 26236, "text": "Collecting pandas" }, { "code": null, "e": 26299, "s": 26254, "text": " Downloading pandas-3.2.0.tar.gz (281.3 MB)" }, { "code": null, "e": 26358, "s": 26299, "text": " |████████████████████████████████| 281.3 MB 9.7 kB/s " }, { "code": null, "e": 26384, "s": 26358, "text": "Collecting py4j==0.10.9.2" }, { "code": null, "e": 26442, "s": 26384, "text": " Downloading py4j-0.10.9.2-py2.py3-none-any.whl (198 kB)" }, { "code": null, "e": 26500, "s": 26442, "text": " |████████████████████████████████| 198 kB 52.8 MB/s " }, { "code": null, "e": 26547, "s": 26500, "text": "Building wheels for collected packages: pandas" }, { "code": null, "e": 26595, "s": 26547, "text": " Building wheel for pandas (setup.py) ... done" }, { "code": null, "e": 26754, "s": 26595, "text": " Created wheel for pandas: filename=pyspark-3.2.0-py2.py3-none-any.whl size=281805912 sha256=c6c9edb963f9a25f31d11d88374ce3be6b3c73ac73ac467ef40b51b5f4eca737" }, { "code": null, "e": 26861, "s": 26754, "text": " Stored in directory: /root/.cache/pip/wheels/0b/de/d2/9be5d59d7331c6c2a7c1b6d1a4f463ce107332b1ecd4e80718" }, { "code": null, "e": 26887, "s": 26861, "text": "Successfully built pandas" }, { "code": null, "e": 26931, "s": 26887, "text": "Installing collected packages: py4j, pandas" }, { "code": null, "e": 26981, "s": 26931, "text": "Successfully installed py4j-0.10.9.2 pandas-3.2.0" }, { "code": null, "e": 27049, "s": 26981, "text": "We can verify by again typing same command then the output will be:" }, { "code": null, "e": 27057, "s": 27049, "text": "Output:" }, { "code": null, "e": 27145, "s": 27057, "text": "Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.1.5)" }, { "code": null, "e": 27284, "s": 27145, "text": "To get the pandas description in our environment we can use the show command. This can help keep track of the module and its installation." }, { "code": null, "e": 27318, "s": 27284, "text": "Example: Show module description " }, { "code": null, "e": 27326, "s": 27318, "text": "Python3" }, { "code": "# display pandas detailspip show pandas", "e": 27366, "s": 27326, "text": null }, { "code": null, "e": 27374, "s": 27366, "text": "Output:" }, { "code": null, "e": 27387, "s": 27374, "text": "Name: pandas" }, { "code": null, "e": 27402, "s": 27387, "text": "Version: 1.1.5" }, { "code": null, "e": 27483, "s": 27402, "text": "Summary: Powerful data structures for data analysis, time series, and statistics" }, { "code": null, "e": 27520, "s": 27483, "text": "Home-page: https://pandas.pydata.org" }, { "code": null, "e": 27533, "s": 27520, "text": "Author: None" }, { "code": null, "e": 27552, "s": 27533, "text": "Author-email: None" }, { "code": null, "e": 27565, "s": 27552, "text": "License: BSD" }, { "code": null, "e": 27614, "s": 27565, "text": "Location: /usr/local/lib/python3.7/dist-packages" }, { "code": null, "e": 27653, "s": 27614, "text": "Requires: numpy, python-dateutil, pytz" }, { "code": null, "e": 27928, "s": 27653, "text": "Required-by: xarray, vega-datasets, statsmodels, sklearn-pandas, seaborn, pymc3, plotnine, pandas-profiling, pandas-gbq, pandas-datareader, mlxtend, mizani, holoviews, gspread-dataframe, google-colab, fix-yahoo-finance, fbprophet, fastai, cufflinks, cmdstanpy, arviz, altair" }, { "code": null, "e": 28058, "s": 27928, "text": "Upgrading pandas is the best advantage to get error-free in your environment. So, we have to upgrade using the following command." }, { "code": null, "e": 28084, "s": 28058, "text": "Example: Upgrading Pandas" }, { "code": null, "e": 28092, "s": 28084, "text": "Python3" }, { "code": "pip3 install pandas - -upgrade", "e": 28123, "s": 28092, "text": null }, { "code": null, "e": 28131, "s": 28123, "text": "Output:" }, { "code": null, "e": 28222, "s": 28131, "text": "To install a specific version of pandas we have to specify the version in the pip command." }, { "code": null, "e": 28273, "s": 28222, "text": "Example: Installing a specific version of a module" }, { "code": null, "e": 28281, "s": 28273, "text": "Python3" }, { "code": "# install 1.3.4 versionpip3 install pandas == 1.3.4", "e": 28333, "s": 28281, "text": null }, { "code": null, "e": 28341, "s": 28333, "text": "Output:" }, { "code": null, "e": 28404, "s": 28341, "text": "If we want to find the version then we have to use __version__" }, { "code": null, "e": 28412, "s": 28404, "text": "Syntax:" }, { "code": null, "e": 28436, "s": 28412, "text": "module_name.__version__" }, { "code": null, "e": 28464, "s": 28436, "text": "Example: Get pandas version" }, { "code": null, "e": 28472, "s": 28464, "text": "Python3" }, { "code": "#import moduleimport pandas as pd # get the versionpd.__version__", "e": 28539, "s": 28472, "text": null }, { "code": null, "e": 28547, "s": 28539, "text": "Output:" }, { "code": null, "e": 28553, "s": 28547, "text": "1.1.5" }, { "code": null, "e": 28560, "s": 28553, "text": "Picked" }, { "code": null, "e": 28578, "s": 28560, "text": "Python How-to-fix" }, { "code": null, "e": 28592, "s": 28578, "text": "Python-pandas" }, { "code": null, "e": 28599, "s": 28592, "text": "Python" }, { "code": null, "e": 28697, "s": 28599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28729, "s": 28697, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28771, "s": 28729, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28813, "s": 28771, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28869, "s": 28813, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28896, "s": 28869, "text": "Python Classes and Objects" }, { "code": null, "e": 28927, "s": 28896, "text": "Python | os.path.join() method" }, { "code": null, "e": 28956, "s": 28927, "text": "Create a directory in Python" }, { "code": null, "e": 28978, "s": 28956, "text": "Defaultdict in Python" }, { "code": null, "e": 29017, "s": 28978, "text": "Python | Get unique values from a list" } ]
Node.js Redis Module - GeeksforGeeks
08 Oct, 2021 Redis is an Open Source store for storing data structures. It is used in multiple ways. It is used as a database, cache, and message broker. It can store data structures such as strings, hashes, sets, sorted sets, bitmaps, indexes, and streams. Redis is very useful for Node.js developers as it reduces the cache size which makes the application more efficient. However, it is very easy to integrate Redis with Node.js applications. Prerequisites: Before starting with our application, make sure the following installation in your system: An IDE of your choice.Redis installed in your system. Check the version that you are using the following command:redis cli --versionNode.js, NPM installed and configured in your system.Basic knowledge of Node.js and Redis. An IDE of your choice. Redis installed in your system. Check the version that you are using the following command:redis cli --version redis cli --version Node.js, NPM installed and configured in your system. Basic knowledge of Node.js and Redis. Getting Started: First initialize the application with package.json file. Type the following command: npm init Now, install the redis module by the following command: npm install redis --save Now, create a new file and name it as app.js. You can name your file whatever you want. In app.js file, write the following code: Filename: app.js var redis = require("redis");var client = redis.createClient(); client.on("connect", function() { console.log("Connection Successful!!");}); Here, we are importing the redis module and then creating a client for redis. The client is then used to manipulate the module. In the above code, we are creating a server. To run the application just type the following command: node app.js The output for the above code will be logged in the console as: Connection Successful!! Storing of String: To store a string in Redis, write the following code in app.js file: var redis = require("redis");var client = redis.createClient(); client.on("connect", function() { console.log("Connection Successful!!");}); client.set("Intern", "gfg", (err, stu) => { if (err) console.log(err); else console.log(stu);}); The client.set() function takes the key-value format. Here, Intern is the key and gfg is the value. Further, it takes a callback function which will return error (if any) or it will log the value as OK if string is successfully stored. The output for the above code will be: Connection Successful!! OK To get the value of the key stored in the redis database, we will use the get function as shown below: var redis = require("redis");var client = redis.createClient(); client.on("connect", function() { console.log("Connection Successful!!");}); client.set("Intern", "gfg", (err, stu) => { if (err) console.log(err); else console.log(stu);}); client.get('Intern', (err, stu) => { if (err) console.log(err); else console.log(stu); }); Here, client.get() method will get the value of the key Intern and log it in the console. The output for the above code will be: Connection Successful!! OK gfg Storing Objects: To store objects in redis database, write the following code: var redis = require("redis");var client = redis.createClient(); client.on("connect", function() { console.log("Connection Successful!!");}); client.set("Intern", "gfg", (err, stu) => { if (err) console.log(err); else console.log(stu);}); client.get('Intern', (err, reply) => { console.log(reply); }); client.hmset("Interns", { pos: "Tech Writer", Org: "GFG" }); Now, the key will be Interns and its value will be { pos: “Tech Writer”, Org: “GFG” }. To get the value from the redis database, write the following code: var redis = require("redis");var client = redis.createClient(); client.on("connect", function() { console.log("Connection Successful!!");}); client.set("Intern", "gfg", (err, stu) => { if (err) console.log(err); else console.log(stu);}); client.get('Intern', (err, reply) => { console.log(reply); }) client.hmset("Interns", { pos: "Tech Writer", Org: "GFG" }); client.hgetall("Interns", (err, stu) => { if (err) console.log(err); else console.log(stu); }); Here, hgetall method is used to get all values of the key and log it in the console. The output for the above code will be: Connection Successful!! OK gfg { pos: 'Tech Writer', Org: 'GFG' } Conclusion: Redis can make Node.js applications fast, powerful, and efficient. Redis can be called as database storage for various data structures. nidhi_biet Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Mongoose find() Function How to connect Node.js with React.js ? Node.js Export Module Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26377, "s": 26349, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26622, "s": 26377, "text": "Redis is an Open Source store for storing data structures. It is used in multiple ways. It is used as a database, cache, and message broker. It can store data structures such as strings, hashes, sets, sorted sets, bitmaps, indexes, and streams." }, { "code": null, "e": 26811, "s": 26622, "text": "Redis is very useful for Node.js developers as it reduces the cache size which makes the application more efficient. However, it is very easy to integrate Redis with Node.js applications. " }, { "code": null, "e": 26917, "s": 26811, "text": "Prerequisites: Before starting with our application, make sure the following installation in your system:" }, { "code": null, "e": 27140, "s": 26917, "text": "An IDE of your choice.Redis installed in your system. Check the version that you are using the following command:redis cli --versionNode.js, NPM installed and configured in your system.Basic knowledge of Node.js and Redis." }, { "code": null, "e": 27163, "s": 27140, "text": "An IDE of your choice." }, { "code": null, "e": 27274, "s": 27163, "text": "Redis installed in your system. Check the version that you are using the following command:redis cli --version" }, { "code": null, "e": 27294, "s": 27274, "text": "redis cli --version" }, { "code": null, "e": 27348, "s": 27294, "text": "Node.js, NPM installed and configured in your system." }, { "code": null, "e": 27386, "s": 27348, "text": "Basic knowledge of Node.js and Redis." }, { "code": null, "e": 27488, "s": 27386, "text": "Getting Started: First initialize the application with package.json file. Type the following command:" }, { "code": null, "e": 27497, "s": 27488, "text": "npm init" }, { "code": null, "e": 27553, "s": 27497, "text": "Now, install the redis module by the following command:" }, { "code": null, "e": 27578, "s": 27553, "text": "npm install redis --save" }, { "code": null, "e": 27708, "s": 27578, "text": "Now, create a new file and name it as app.js. You can name your file whatever you want. In app.js file, write the following code:" }, { "code": null, "e": 27725, "s": 27708, "text": "Filename: app.js" }, { "code": "var redis = require(\"redis\");var client = redis.createClient(); client.on(\"connect\", function() { console.log(\"Connection Successful!!\");});", "e": 27868, "s": 27725, "text": null }, { "code": null, "e": 28097, "s": 27868, "text": "Here, we are importing the redis module and then creating a client for redis. The client is then used to manipulate the module. In the above code, we are creating a server. To run the application just type the following command:" }, { "code": null, "e": 28109, "s": 28097, "text": "node app.js" }, { "code": null, "e": 28173, "s": 28109, "text": "The output for the above code will be logged in the console as:" }, { "code": null, "e": 28197, "s": 28173, "text": "Connection Successful!!" }, { "code": null, "e": 28285, "s": 28197, "text": "Storing of String: To store a string in Redis, write the following code in app.js file:" }, { "code": "var redis = require(\"redis\");var client = redis.createClient(); client.on(\"connect\", function() { console.log(\"Connection Successful!!\");}); client.set(\"Intern\", \"gfg\", (err, stu) => { if (err) console.log(err); else console.log(stu);});", "e": 28532, "s": 28285, "text": null }, { "code": null, "e": 28807, "s": 28532, "text": "The client.set() function takes the key-value format. Here, Intern is the key and gfg is the value. Further, it takes a callback function which will return error (if any) or it will log the value as OK if string is successfully stored. The output for the above code will be:" }, { "code": null, "e": 28834, "s": 28807, "text": "Connection Successful!!\nOK" }, { "code": null, "e": 28937, "s": 28834, "text": "To get the value of the key stored in the redis database, we will use the get function as shown below:" }, { "code": "var redis = require(\"redis\");var client = redis.createClient(); client.on(\"connect\", function() { console.log(\"Connection Successful!!\");}); client.set(\"Intern\", \"gfg\", (err, stu) => { if (err) console.log(err); else console.log(stu);}); client.get('Intern', (err, stu) => { if (err) console.log(err); else console.log(stu); });", "e": 29282, "s": 28937, "text": null }, { "code": null, "e": 29411, "s": 29282, "text": "Here, client.get() method will get the value of the key Intern and log it in the console. The output for the above code will be:" }, { "code": null, "e": 29443, "s": 29411, "text": "Connection Successful!!\nOK\ngfg\n" }, { "code": null, "e": 29522, "s": 29443, "text": "Storing Objects: To store objects in redis database, write the following code:" }, { "code": "var redis = require(\"redis\");var client = redis.createClient(); client.on(\"connect\", function() { console.log(\"Connection Successful!!\");}); client.set(\"Intern\", \"gfg\", (err, stu) => { if (err) console.log(err); else console.log(stu);}); client.get('Intern', (err, reply) => { console.log(reply); }); client.hmset(\"Interns\", { pos: \"Tech Writer\", Org: \"GFG\" });", "e": 29898, "s": 29522, "text": null }, { "code": null, "e": 29985, "s": 29898, "text": "Now, the key will be Interns and its value will be { pos: “Tech Writer”, Org: “GFG” }." }, { "code": null, "e": 30053, "s": 29985, "text": "To get the value from the redis database, write the following code:" }, { "code": "var redis = require(\"redis\");var client = redis.createClient(); client.on(\"connect\", function() { console.log(\"Connection Successful!!\");}); client.set(\"Intern\", \"gfg\", (err, stu) => { if (err) console.log(err); else console.log(stu);}); client.get('Intern', (err, reply) => { console.log(reply); }) client.hmset(\"Interns\", { pos: \"Tech Writer\", Org: \"GFG\" }); client.hgetall(\"Interns\", (err, stu) => { if (err) console.log(err); else console.log(stu); });", "e": 30532, "s": 30053, "text": null }, { "code": null, "e": 30656, "s": 30532, "text": "Here, hgetall method is used to get all values of the key and log it in the console. The output for the above code will be:" }, { "code": null, "e": 30723, "s": 30656, "text": "Connection Successful!!\nOK\ngfg\n{ pos: 'Tech Writer', Org: 'GFG' }\n" }, { "code": null, "e": 30871, "s": 30723, "text": "Conclusion: Redis can make Node.js applications fast, powerful, and efficient. Redis can be called as database storage for various data structures." }, { "code": null, "e": 30882, "s": 30871, "text": "nidhi_biet" }, { "code": null, "e": 30895, "s": 30882, "text": "Node.js-Misc" }, { "code": null, "e": 30903, "s": 30895, "text": "Node.js" }, { "code": null, "e": 30920, "s": 30903, "text": "Web Technologies" }, { "code": null, "e": 31018, "s": 30920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31088, "s": 31018, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 31113, "s": 31088, "text": "Mongoose find() Function" }, { "code": null, "e": 31152, "s": 31113, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 31174, "s": 31152, "text": "Node.js Export Module" }, { "code": null, "e": 31201, "s": 31174, "text": "Mongoose Populate() Method" }, { "code": null, "e": 31241, "s": 31201, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31286, "s": 31241, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31329, "s": 31286, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31379, "s": 31329, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to get started with the Graph Data Science Library of Neo4j | by CJ Sullivan | Towards Data Science
The field of graph analytics has been around for a long time. The general idea is to create a database of things connecting to other things. Those things might be people connecting to other people on social media or maybe flights between cities or any number of other examples. Graphs are regularly used to enhance search capabilities, recommend products to shoppers on e-commerce sites, detect fraud, or to map the shortest route from point A to point B. Neo4j has long been a key player in the world of graph databases. It historically uses the Cypher query language to interact with the database. There are many primers out there on how to analyze graphs or use Cypher. This post, instead, means to provide an introduction to how to achieve tasks in data science using the new Neo4j Graph Data Science Library (GDS)1, which represents a significant enhancement to the original Neo4j Graph Algorithms library (now deprecated). There are some fundamental shifts from Graph Algorithms to GDS, but for those who have used the former once you get the hang of the new modalities of usage it will become second nature. For the purposes of this writeup, it is not necessary to have used either to get started on solving graph problems with data science approaches. We will be starting with the premise that you have a running Neo4j server. If you don’t already have this, you can download the open source Community Edition here. It is important to note that in order to have access to the GDS library you will want to download a version of v4 of Neo4j. The current version is always the best and offers the latest functionality of GDS (and they are always adding great new features!). Once you have the Neo4j server up and running, you will need to have some graph data with which to populate it. While there are some sample graphs built in to Neo4j, it can be instructive to go through how to import your own data. Graph data usually comes in the form of edge lists and node lists, which are typically separate files. Neo4j makes importing these files easy when they are in .csv format and we will discuss one of the easiest formats to import. Let’s talk about each of these files separately. Node lists: in this .csv file we provide the information about the nodes — their labels. There can be many types of labels, or you can provide just a generic node ID. These labels will be used as the identifiers in node1 and node2 above. There can be any number of labels associated with a node. Good choices are things like a unique identifier, the name of the known (if known), and the generic type of the node (think of things like “this node is a person” or “this node is a place,” which could be used to give a node type like “person” or “place”). The format would look something like node1, label1, label2, ... Edge lists: in this .csv file you have the information about which nodes connect to which other nodes. It also can specify the type of relationship. So the format follows something typical like node1, node2, relationship_type, weight where node1 is the starting node, node2 is the terminating node, relationship_type specifies the edge label (optional) and weight indicates the strength of that relationship (optional). Note that it is generally good practice (although not required) to have a header line for each file so you can keep track of what columns are what. Once you have these files, we can get them loaded into Neo4j. For the sake of this tutorial we will be using a graph of the characters from Game of Thrones (GoT). There are several sources of graph data on GoT out there, but I particularly like the one maintained by Andrew Beveridge in this repo due to its simplicity, organization, and ease of use. The data is conveniently broken into .csv files for both nodes and edges, one file for each season. In this tutorial I have cloned the repo onto my local machine for reading the files, but you can also choose to read them from the web. WARNING!!! Graph analytics is a powerful tool and will reveal some serious spoilers of GoT as we get into it! So if you don’t want the series spoiled, turn back now! Loading data into the database is pretty straight forward using the built in LOAD CSV command. Because we are loading .csv files from our local machine, you will want to be sure to go into the neo4j.conf file and comment out the line dbms.directories.import=import in order to allow us to load files from anywhere on your local machine. There are many ways to load .csv data into the database, and I have picked on that I find the easiest below. We will begin by loading in the node lists using the following command: WITH "file:///Users/cj2001/gameofthrones/data/got-s1-nodes.csv" AS uriLOAD CSV WITH HEADERS FROM uri AS rowMERGE (c:Character {id:row.Id})SET c.name = row.Label (This is the command to load in the season 1 file, and you can just repeat this command to load in whichever seasons you want. I have executed this command for each of the s1 through s8 files. Head’s up: the season 5 filename has a mild typo in it.) Using the above command, I now have a series of nodes of type Character that have properties called id and name . Note that we have loaded this file in line-by-line with Id and Label corresponding to the column names available from the header line. Next, we will load in the edge lists with the following command: WITH "file:///Users/cj2001/gameofthrones/data/got-s1-edges.csv" AS uriLOAD CSV WITH HEADERS FROM uri AS rowMATCH (source:Character {id: row.Source})MATCH (target:Character {id: row.Target})MERGE (source)-[:SEASON1 {weight: toInteger(row.Weight)}]-(target) (Again, we will repeat the above for each of the edge files we would like to incorporate.) The above command creates the relationships between the characters where the edge type is :SEASON1 . I find it convenient to give each season its own edge type to allow for exploration of changes to the graph between seasons. The edge itself is weighted by the number of times the source and target characters interact. Note that on import Neo4j considers all columns to be strings, but for our future calculations we want Neo4j to know that Weight is actually an integer, so we have to recast it as such. Also observe that we have used the format (source)-[edge_type]-(target) . Because we have no arrows in this relationship indicating direction, we have created an undirected graph. If we wanted to do otherwise, this relationship would instead look like (source)-[edge_type]->(target) . The creation of in-memory graphs represents a revolutionary step for Neo4j. Basically, what it allows us to do is to create different graphs or subgraphs for analysis. We can run commands on portions of the database rather than the entire database. For example, in the GoT data, we might care about calculations done on the entire graph, or we might only want to do calculations on a single season. I cannot emphasize enough how this new philosophical approach opens a lot of doors for data science and machine learning on graphs! We will begin by creating an in-memory graph of the entire 8 seasons. There are two main ways this can be done in GDS: using a Cypher projection or a “Native” projection. I will use the former here since this is a pretty straight forward set of commands and it is pretty easy to understand what is going on. Native projections are pretty fast and powerful though, but beyond the scope of this tutorial. To create the in-memory graph with a Cypher projection, we use the command CALL gds.graph.create.cypher( 'full_graph', 'MATCH (n) RETURN id(n) AS id', 'MATCH (n)-[e]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target') The graph creation requires three things: A graph name (full_graph)A node query (MATCH (n) RETURN id(n) AS id)An edge query (MATCH (n)-[e]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target) A graph name (full_graph) A node query (MATCH (n) RETURN id(n) AS id) An edge query (MATCH (n)-[e]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target) The graph name is pretty clear. But the node and edge queries require a little explanation. For speed reasons, Neo4j works on node IDs and not the actual node information. Typically these IDs tend to not map to anything other than a set of integers not related to any node or edge labels we have. But when you see id(n), this is how GDS is actually relating to that data. We obtain these IDs in the node query and then return them back in the edge query. Now we have a graph that we can do some math on. One of the more basic things we could do is to calculate the PageRank of every character in the graph. We can view and use these results in one of two different ways. In order to understand the difference, we consider that the bulk of GDS functions can call either the stream or write methods. The former outputs the results of the calculation to the screen. For example, to calculate PageRank on this graph and output it to the screen, we would do CALL gds.pageRank.stream('full_graph', { maxIterations: 20, dampingFactor: 0.85, relationshipWeightProperty: 'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).id AS id, gds.util.asNode(nodeId).name as name, score as full_pagerankORDER BY full_pagerank DESC (I am just using the default values for maxIterations and dampingFactor .) Note that we are working with the node IDs from before where we convert these from their respective IDs through the gds.util.asNode(nodeId) commands to properties we recognize, like id and name . If we were to do this on the graph of all 8 seasons, we would find some unsurprising results. The five characters with the highest PageRank across all seasons are, in order, Tyrion, Jon, Daenerys, Cersei, and Sansa. (Don’t worry...Arya is #6.) This result is unsurprising and maybe we want to actually use it as a node property for future analyses outside of the in-memory graph. To do this, we want to use the write method, which will take the results of the calculation and write them as properties to the nodes. To do that, we do CALL gds.pageRank.write('full_graph', { maxIterations: 20, dampingFactor: 0.85, relationshipWeightProperty: 'weight', writeProperty: 'full_pagerank'}) We can now do a simple MATCH (c:Character RETURN c.name ORDER BY c.full_pagerank DESC to see the same result as above. However, we can see that in this case the PageRank has been added as a node property called full_pagerank. This is interesting, but if we know anything about GoT we would expect PageRank to change with each season as characters gain and lose prominence or, well, die. To explore this theory, I am going to create two additional in-memory graphs — one for season 1 and one for season 8. For season 1, this would look something like CALL gds.graph.create.cypher( 's1_graph', 'MATCH (n) RETURN id(n) AS id', 'MATCH (n)-[e:SEASON1]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target') and season 8 would be similar. You can check that the graphs made it in with CALL gds.graph.list() . Now, if I run the same PageRank calculation for season 1, I get that Ned, Tyrion, Catelyn, Jon, and Daenerys are the top 5 most influential characters. Repeating this then for season 8, I get that the top 5 are Tyrion, Jon, Daenerys, Jaime, and Sansa. Again, if you know the show, none of this is really surprising. One powerful tool included in the GDS Library is the ability to run Louvain clustering on in-memory graphs. To do this on the full graph of all 8 seasons and write the calculated community as a property to each node, we would run CALL gds.louvain.write('full_graph', {relationshipWeightProperty: 'weight', writeProperty: 'full_community_id'}) (Note that you will not get great modularity in doing this, but tuning the parameters for Louvain is beyond the scope of this tutorial.) If I want to get the detected community for all 8 seasons for Tyrion, we would start by getting that ID value (MATCH (c:Character {name: ‘Tyrion’}) RETURN c.name, c.full_community_id which gave me community 143, but yours will likely be different) and then finding the top PageRank characters within the same community. In my case, I would do MATCH (c:Character {full_community_id: 143}) RETURN c.name, c.full_community_id ORDER BY c.full_pagerank DESC and I would get the 5 most influential characters in Tyrion’s life across all 8 seasons are Cersei, Jaime, Varys, Joffrey, and Tywin. Not surprising. I leave it as an exercise for the reader to explore other characters or look at how the detected communities change by season. I have really been impressed by the Neo4j move from basic querying to a formalized treatments of graphs that enable data science and machine learning. There is a lot of power here, and I have only scratched the surface in this tutorial. I hope to write others in the future discussing things like Native projections and the whole host of possibilities provided by the vector embeddings of node2vec and GraphSAGE that have moved out of alpha release in the more recent versions of the GDS Library. [1] M. Needham and A. Hodler, Graph Algorithms: Practical Examples in Apache Spark and Neo4j (2020), O’Reilly Media.
[ { "code": null, "e": 627, "s": 171, "text": "The field of graph analytics has been around for a long time. The general idea is to create a database of things connecting to other things. Those things might be people connecting to other people on social media or maybe flights between cities or any number of other examples. Graphs are regularly used to enhance search capabilities, recommend products to shoppers on e-commerce sites, detect fraud, or to map the shortest route from point A to point B." }, { "code": null, "e": 1431, "s": 627, "text": "Neo4j has long been a key player in the world of graph databases. It historically uses the Cypher query language to interact with the database. There are many primers out there on how to analyze graphs or use Cypher. This post, instead, means to provide an introduction to how to achieve tasks in data science using the new Neo4j Graph Data Science Library (GDS)1, which represents a significant enhancement to the original Neo4j Graph Algorithms library (now deprecated). There are some fundamental shifts from Graph Algorithms to GDS, but for those who have used the former once you get the hang of the new modalities of usage it will become second nature. For the purposes of this writeup, it is not necessary to have used either to get started on solving graph problems with data science approaches." }, { "code": null, "e": 1851, "s": 1431, "text": "We will be starting with the premise that you have a running Neo4j server. If you don’t already have this, you can download the open source Community Edition here. It is important to note that in order to have access to the GDS library you will want to download a version of v4 of Neo4j. The current version is always the best and offers the latest functionality of GDS (and they are always adding great new features!)." }, { "code": null, "e": 2082, "s": 1851, "text": "Once you have the Neo4j server up and running, you will need to have some graph data with which to populate it. While there are some sample graphs built in to Neo4j, it can be instructive to go through how to import your own data." }, { "code": null, "e": 2360, "s": 2082, "text": "Graph data usually comes in the form of edge lists and node lists, which are typically separate files. Neo4j makes importing these files easy when they are in .csv format and we will discuss one of the easiest formats to import. Let’s talk about each of these files separately." }, { "code": null, "e": 2950, "s": 2360, "text": "Node lists: in this .csv file we provide the information about the nodes — their labels. There can be many types of labels, or you can provide just a generic node ID. These labels will be used as the identifiers in node1 and node2 above. There can be any number of labels associated with a node. Good choices are things like a unique identifier, the name of the known (if known), and the generic type of the node (think of things like “this node is a person” or “this node is a place,” which could be used to give a node type like “person” or “place”). The format would look something like" }, { "code": null, "e": 2977, "s": 2950, "text": "node1, label1, label2, ..." }, { "code": null, "e": 3171, "s": 2977, "text": "Edge lists: in this .csv file you have the information about which nodes connect to which other nodes. It also can specify the type of relationship. So the format follows something typical like" }, { "code": null, "e": 3211, "s": 3171, "text": "node1, node2, relationship_type, weight" }, { "code": null, "e": 3397, "s": 3211, "text": "where node1 is the starting node, node2 is the terminating node, relationship_type specifies the edge label (optional) and weight indicates the strength of that relationship (optional)." }, { "code": null, "e": 3896, "s": 3397, "text": "Note that it is generally good practice (although not required) to have a header line for each file so you can keep track of what columns are what. Once you have these files, we can get them loaded into Neo4j. For the sake of this tutorial we will be using a graph of the characters from Game of Thrones (GoT). There are several sources of graph data on GoT out there, but I particularly like the one maintained by Andrew Beveridge in this repo due to its simplicity, organization, and ease of use." }, { "code": null, "e": 4132, "s": 3896, "text": "The data is conveniently broken into .csv files for both nodes and edges, one file for each season. In this tutorial I have cloned the repo onto my local machine for reading the files, but you can also choose to read them from the web." }, { "code": null, "e": 4298, "s": 4132, "text": "WARNING!!! Graph analytics is a powerful tool and will reveal some serious spoilers of GoT as we get into it! So if you don’t want the series spoiled, turn back now!" }, { "code": null, "e": 4744, "s": 4298, "text": "Loading data into the database is pretty straight forward using the built in LOAD CSV command. Because we are loading .csv files from our local machine, you will want to be sure to go into the neo4j.conf file and comment out the line dbms.directories.import=import in order to allow us to load files from anywhere on your local machine. There are many ways to load .csv data into the database, and I have picked on that I find the easiest below." }, { "code": null, "e": 4816, "s": 4744, "text": "We will begin by loading in the node lists using the following command:" }, { "code": null, "e": 4977, "s": 4816, "text": "WITH \"file:///Users/cj2001/gameofthrones/data/got-s1-nodes.csv\" AS uriLOAD CSV WITH HEADERS FROM uri AS rowMERGE (c:Character {id:row.Id})SET c.name = row.Label" }, { "code": null, "e": 5227, "s": 4977, "text": "(This is the command to load in the season 1 file, and you can just repeat this command to load in whichever seasons you want. I have executed this command for each of the s1 through s8 files. Head’s up: the season 5 filename has a mild typo in it.)" }, { "code": null, "e": 5476, "s": 5227, "text": "Using the above command, I now have a series of nodes of type Character that have properties called id and name . Note that we have loaded this file in line-by-line with Id and Label corresponding to the column names available from the header line." }, { "code": null, "e": 5541, "s": 5476, "text": "Next, we will load in the edge lists with the following command:" }, { "code": null, "e": 5797, "s": 5541, "text": "WITH \"file:///Users/cj2001/gameofthrones/data/got-s1-edges.csv\" AS uriLOAD CSV WITH HEADERS FROM uri AS rowMATCH (source:Character {id: row.Source})MATCH (target:Character {id: row.Target})MERGE (source)-[:SEASON1 {weight: toInteger(row.Weight)}]-(target)" }, { "code": null, "e": 5888, "s": 5797, "text": "(Again, we will repeat the above for each of the edge files we would like to incorporate.)" }, { "code": null, "e": 6679, "s": 5888, "text": "The above command creates the relationships between the characters where the edge type is :SEASON1 . I find it convenient to give each season its own edge type to allow for exploration of changes to the graph between seasons. The edge itself is weighted by the number of times the source and target characters interact. Note that on import Neo4j considers all columns to be strings, but for our future calculations we want Neo4j to know that Weight is actually an integer, so we have to recast it as such. Also observe that we have used the format (source)-[edge_type]-(target) . Because we have no arrows in this relationship indicating direction, we have created an undirected graph. If we wanted to do otherwise, this relationship would instead look like (source)-[edge_type]->(target) ." }, { "code": null, "e": 7210, "s": 6679, "text": "The creation of in-memory graphs represents a revolutionary step for Neo4j. Basically, what it allows us to do is to create different graphs or subgraphs for analysis. We can run commands on portions of the database rather than the entire database. For example, in the GoT data, we might care about calculations done on the entire graph, or we might only want to do calculations on a single season. I cannot emphasize enough how this new philosophical approach opens a lot of doors for data science and machine learning on graphs!" }, { "code": null, "e": 7688, "s": 7210, "text": "We will begin by creating an in-memory graph of the entire 8 seasons. There are two main ways this can be done in GDS: using a Cypher projection or a “Native” projection. I will use the former here since this is a pretty straight forward set of commands and it is pretty easy to understand what is going on. Native projections are pretty fast and powerful though, but beyond the scope of this tutorial. To create the in-memory graph with a Cypher projection, we use the command" }, { "code": null, "e": 7854, "s": 7688, "text": "CALL gds.graph.create.cypher( 'full_graph', 'MATCH (n) RETURN id(n) AS id', 'MATCH (n)-[e]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target')" }, { "code": null, "e": 7896, "s": 7854, "text": "The graph creation requires three things:" }, { "code": null, "e": 8058, "s": 7896, "text": "A graph name (full_graph)A node query (MATCH (n) RETURN id(n) AS id)An edge query (MATCH (n)-[e]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target)" }, { "code": null, "e": 8084, "s": 8058, "text": "A graph name (full_graph)" }, { "code": null, "e": 8128, "s": 8084, "text": "A node query (MATCH (n) RETURN id(n) AS id)" }, { "code": null, "e": 8222, "s": 8128, "text": "An edge query (MATCH (n)-[e]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target)" }, { "code": null, "e": 8677, "s": 8222, "text": "The graph name is pretty clear. But the node and edge queries require a little explanation. For speed reasons, Neo4j works on node IDs and not the actual node information. Typically these IDs tend to not map to anything other than a set of integers not related to any node or edge labels we have. But when you see id(n), this is how GDS is actually relating to that data. We obtain these IDs in the node query and then return them back in the edge query." }, { "code": null, "e": 9175, "s": 8677, "text": "Now we have a graph that we can do some math on. One of the more basic things we could do is to calculate the PageRank of every character in the graph. We can view and use these results in one of two different ways. In order to understand the difference, we consider that the bulk of GDS functions can call either the stream or write methods. The former outputs the results of the calculation to the screen. For example, to calculate PageRank on this graph and output it to the screen, we would do" }, { "code": null, "e": 9450, "s": 9175, "text": "CALL gds.pageRank.stream('full_graph', { maxIterations: 20, dampingFactor: 0.85, relationshipWeightProperty: 'weight'})YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).id AS id, gds.util.asNode(nodeId).name as name, score as full_pagerankORDER BY full_pagerank DESC" }, { "code": null, "e": 9721, "s": 9450, "text": "(I am just using the default values for maxIterations and dampingFactor .) Note that we are working with the node IDs from before where we convert these from their respective IDs through the gds.util.asNode(nodeId) commands to properties we recognize, like id and name ." }, { "code": null, "e": 9965, "s": 9721, "text": "If we were to do this on the graph of all 8 seasons, we would find some unsurprising results. The five characters with the highest PageRank across all seasons are, in order, Tyrion, Jon, Daenerys, Cersei, and Sansa. (Don’t worry...Arya is #6.)" }, { "code": null, "e": 10254, "s": 9965, "text": "This result is unsurprising and maybe we want to actually use it as a node property for future analyses outside of the in-memory graph. To do this, we want to use the write method, which will take the results of the calculation and write them as properties to the nodes. To do that, we do" }, { "code": null, "e": 10417, "s": 10254, "text": "CALL gds.pageRank.write('full_graph', { maxIterations: 20, dampingFactor: 0.85, relationshipWeightProperty: 'weight', writeProperty: 'full_pagerank'})" }, { "code": null, "e": 10643, "s": 10417, "text": "We can now do a simple MATCH (c:Character RETURN c.name ORDER BY c.full_pagerank DESC to see the same result as above. However, we can see that in this case the PageRank has been added as a node property called full_pagerank." }, { "code": null, "e": 10967, "s": 10643, "text": "This is interesting, but if we know anything about GoT we would expect PageRank to change with each season as characters gain and lose prominence or, well, die. To explore this theory, I am going to create two additional in-memory graphs — one for season 1 and one for season 8. For season 1, this would look something like" }, { "code": null, "e": 11139, "s": 10967, "text": "CALL gds.graph.create.cypher( 's1_graph', 'MATCH (n) RETURN id(n) AS id', 'MATCH (n)-[e:SEASON1]-(m) RETURN id(n) AS source, e.weight AS weight, id(m) AS target')" }, { "code": null, "e": 11240, "s": 11139, "text": "and season 8 would be similar. You can check that the graphs made it in with CALL gds.graph.list() ." }, { "code": null, "e": 11556, "s": 11240, "text": "Now, if I run the same PageRank calculation for season 1, I get that Ned, Tyrion, Catelyn, Jon, and Daenerys are the top 5 most influential characters. Repeating this then for season 8, I get that the top 5 are Tyrion, Jon, Daenerys, Jaime, and Sansa. Again, if you know the show, none of this is really surprising." }, { "code": null, "e": 11786, "s": 11556, "text": "One powerful tool included in the GDS Library is the ability to run Louvain clustering on in-memory graphs. To do this on the full graph of all 8 seasons and write the calculated community as a property to each node, we would run" }, { "code": null, "e": 11908, "s": 11786, "text": "CALL gds.louvain.write('full_graph', {relationshipWeightProperty: 'weight', writeProperty: 'full_community_id'})" }, { "code": null, "e": 12775, "s": 11908, "text": "(Note that you will not get great modularity in doing this, but tuning the parameters for Louvain is beyond the scope of this tutorial.) If I want to get the detected community for all 8 seasons for Tyrion, we would start by getting that ID value (MATCH (c:Character {name: ‘Tyrion’}) RETURN c.name, c.full_community_id which gave me community 143, but yours will likely be different) and then finding the top PageRank characters within the same community. In my case, I would do MATCH (c:Character {full_community_id: 143}) RETURN c.name, c.full_community_id ORDER BY c.full_pagerank DESC and I would get the 5 most influential characters in Tyrion’s life across all 8 seasons are Cersei, Jaime, Varys, Joffrey, and Tywin. Not surprising. I leave it as an exercise for the reader to explore other characters or look at how the detected communities change by season." }, { "code": null, "e": 13272, "s": 12775, "text": "I have really been impressed by the Neo4j move from basic querying to a formalized treatments of graphs that enable data science and machine learning. There is a lot of power here, and I have only scratched the surface in this tutorial. I hope to write others in the future discussing things like Native projections and the whole host of possibilities provided by the vector embeddings of node2vec and GraphSAGE that have moved out of alpha release in the more recent versions of the GDS Library." } ]
Laravel - Facades
Facades provide a static interface to classes that are available in the application's service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. The following are the steps to create Facade in Laravel − Step 1 − Create PHP Class File. Step 1 − Create PHP Class File. Step 2 − Bind that class to Service Provider. Step 2 − Bind that class to Service Provider. Step 3 − Register that ServiceProvider to Config\app.php as providers. Step 3 − Register that ServiceProvider to Config\app.php as providers. Step 4 − Create Class which is this class extends to lluminate\Support\Facades\Facade. Step 4 − Create Class which is this class extends to lluminate\Support\Facades\Facade. Step 5 − Register point 4 to Config\app.php as aliases. Step 5 − Register point 4 to Config\app.php as aliases. Laravel ships with many Facades. The following table show the in-built Facade class references − Step 1 − Create a service provider called TestFacadesServiceProvider by executing the following command. php artisan make:provider TestFacadesServiceProvider Step 2 − After successful execution, you will receive the following output − Step 3 − Create a class called TestFacades.php at App/Test. App/Test/TestFacades.php <?php namespace App\Test; class TestFacades{ public function testingFacades() { echo "Testing the Facades in Laravel."; } } ?> Step 4 − Create a Facade class called “TestFacades.php” at “App/Test/Facades”. App/Test/Facades/TestFacades.php <?php namespace app\Test\Facades; use Illuminate\Support\Facades\Facade; class TestFacades extends Facade { protected static function getFacadeAccessor() { return 'test'; } } Step 5 − Create a Facade class called TestFacadesServiceProviders.php at App/Test/Facades. App/Providers/TestFacadesServiceProviders.php <?php namespace App\Providers; use App; use Illuminate\Support\ServiceProvider; class TestFacadesServiceProvider extends ServiceProvider { public function boot() { // } public function register() { App::bind('test',function() { return new \App\Test\TestFacades; }); } } Step 6 − Add a service provider in a file config/app.php as shown in the below figure. config/app.php Step 7 − Add an alias in a file config/app.php as shown in the below figure. config/app.php Step 8 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('/facadeex', function() { return TestFacades::testingFacades(); }); Step 9 − Visit the following URL to test the Facade. http://localhost:8000/facadeex Step 10 − After visiting the URL, you will receive the following output − 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2801, "s": 2472, "text": "Facades provide a static interface to classes that are available in the application's service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods." }, { "code": null, "e": 2859, "s": 2801, "text": "The following are the steps to create Facade in Laravel −" }, { "code": null, "e": 2891, "s": 2859, "text": "Step 1 − Create PHP Class File." }, { "code": null, "e": 2923, "s": 2891, "text": "Step 1 − Create PHP Class File." }, { "code": null, "e": 2969, "s": 2923, "text": "Step 2 − Bind that class to Service Provider." }, { "code": null, "e": 3015, "s": 2969, "text": "Step 2 − Bind that class to Service Provider." }, { "code": null, "e": 3086, "s": 3015, "text": "Step 3 − Register that ServiceProvider to\nConfig\\app.php as providers." }, { "code": null, "e": 3128, "s": 3086, "text": "Step 3 − Register that ServiceProvider to" }, { "code": null, "e": 3157, "s": 3128, "text": "Config\\app.php as providers." }, { "code": null, "e": 3244, "s": 3157, "text": "Step 4 − Create Class which is this class extends to\nlluminate\\Support\\Facades\\Facade." }, { "code": null, "e": 3297, "s": 3244, "text": "Step 4 − Create Class which is this class extends to" }, { "code": null, "e": 3331, "s": 3297, "text": "lluminate\\Support\\Facades\\Facade." }, { "code": null, "e": 3387, "s": 3331, "text": "Step 5 − Register point 4 to Config\\app.php as aliases." }, { "code": null, "e": 3443, "s": 3387, "text": "Step 5 − Register point 4 to Config\\app.php as aliases." }, { "code": null, "e": 3540, "s": 3443, "text": "Laravel ships with many Facades. The following table show the in-built Facade class references −" }, { "code": null, "e": 3645, "s": 3540, "text": "Step 1 − Create a service provider called TestFacadesServiceProvider by executing the following command." }, { "code": null, "e": 3699, "s": 3645, "text": "php artisan make:provider TestFacadesServiceProvider\n" }, { "code": null, "e": 3776, "s": 3699, "text": "Step 2 − After successful execution, you will receive the following output −" }, { "code": null, "e": 3836, "s": 3776, "text": "Step 3 − Create a class called TestFacades.php at App/Test." }, { "code": null, "e": 3861, "s": 3836, "text": "App/Test/TestFacades.php" }, { "code": null, "e": 4018, "s": 3861, "text": "<?php\n namespace App\\Test;\n class TestFacades{\n public function testingFacades() {\n echo \"Testing the Facades in Laravel.\";\n }\n }\n?>" }, { "code": null, "e": 4097, "s": 4018, "text": "Step 4 − Create a Facade class called “TestFacades.php” at “App/Test/Facades”." }, { "code": null, "e": 4130, "s": 4097, "text": "App/Test/Facades/TestFacades.php" }, { "code": null, "e": 4311, "s": 4130, "text": "<?php\n\nnamespace app\\Test\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\nclass TestFacades extends Facade {\n protected static function getFacadeAccessor() { return 'test'; }\n}" }, { "code": null, "e": 4402, "s": 4311, "text": "Step 5 − Create a Facade class called TestFacadesServiceProviders.php at App/Test/Facades." }, { "code": null, "e": 4448, "s": 4402, "text": "App/Providers/TestFacadesServiceProviders.php" }, { "code": null, "e": 4760, "s": 4448, "text": "<?php\n\nnamespace App\\Providers;\n\nuse App;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass TestFacadesServiceProvider extends ServiceProvider {\n public function boot() {\n //\n }\n public function register() {\n App::bind('test',function() {\n return new \\App\\Test\\TestFacades;\n });\n }\n}" }, { "code": null, "e": 4847, "s": 4760, "text": "Step 6 − Add a service provider in a file config/app.php as shown in the below figure." }, { "code": null, "e": 4862, "s": 4847, "text": "config/app.php" }, { "code": null, "e": 4939, "s": 4862, "text": "Step 7 − Add an alias in a file config/app.php as shown in the below figure." }, { "code": null, "e": 4954, "s": 4939, "text": "config/app.php" }, { "code": null, "e": 5011, "s": 4954, "text": "Step 8 − Add the following lines in app/Http/routes.php." }, { "code": null, "e": 5031, "s": 5011, "text": "app/Http/routes.php" }, { "code": null, "e": 5114, "s": 5031, "text": "Route::get('/facadeex', function() {\n return TestFacades::testingFacades();\n});\n" }, { "code": null, "e": 5167, "s": 5114, "text": "Step 9 − Visit the following URL to test the Facade." }, { "code": null, "e": 5199, "s": 5167, "text": "http://localhost:8000/facadeex\n" }, { "code": null, "e": 5273, "s": 5199, "text": "Step 10 − After visiting the URL, you will receive the following output −" }, { "code": null, "e": 5306, "s": 5273, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 5326, "s": 5306, "text": " Sebastian Sulinski" }, { "code": null, "e": 5361, "s": 5326, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5375, "s": 5361, "text": " Antonio Papa" }, { "code": null, "e": 5409, "s": 5375, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5429, "s": 5409, "text": " Sebastian Sulinski" }, { "code": null, "e": 5462, "s": 5429, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 5482, "s": 5462, "text": " Skillbakerystudios" }, { "code": null, "e": 5517, "s": 5482, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5540, "s": 5517, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5575, "s": 5540, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 5595, "s": 5575, "text": " Hafizullah Masoudi" }, { "code": null, "e": 5602, "s": 5595, "text": " Print" }, { "code": null, "e": 5613, "s": 5602, "text": " Add Notes" } ]
BigInteger toByteArray() Method in Java - GeeksforGeeks
12 Apr, 2022 The java.math.BigInteger.toByteArray() method returns a array of byte containing the two’s-complement representation of this BigInteger. The most significant byte of byte array is present in the zeroth element. The returning array from this method contain sing bit and contain the minimum number of bytes required to represent this BigInteger. The sign bit position is (ceil((this.bitLength() + 1)/8)). Syntax: public byte[] toByteArray() Parameters: This method does not accepts any parameters. Return Value: This method returns a byte array containing the two’s-complement representation of this BigInteger. Below programs illustrate toByteArray() method of BigInteger class: Example 1: Java // Java program to demonstrate toByteArray() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger bigInt = BigInteger.valueOf(10); // create a byte array byte b1[]; b1 = bigInt.toByteArray(); // print result System.out.print("ByteArray of BigInteger " + bigInt + " is"); for (int i = 0; i < b1.length; i++) { System.out.format(" " + "0x%02X", b1[i]); } }} ByteArray of BigInteger 10 is 0x0A Example 2: Java // Java program to demonstrate toByteArray() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // create byte array byte b[] = { 0x1, 0x2, 0x1 }; // Creating BigInteger object using byte Array BigInteger bigInt = new BigInteger(b); // apply toByteArray() on BigInteger byte b1[] = bigInt.toByteArray(); // print result System.out.print("ByteArray of BigInteger " + bigInt + " is"); for (int i = 0; i < b1.length; i++) { System.out.format(" " + "0x%02X", b1[i]); } }} ByteArray of BigInteger 66049 is 0x01 0x02 0x01 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toByteArray() sumitgumber28 Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples Strings in Java HashMap get() Method in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23948, "s": 23920, "text": "\n12 Apr, 2022" }, { "code": null, "e": 24359, "s": 23948, "text": "The java.math.BigInteger.toByteArray() method returns a array of byte containing the two’s-complement representation of this BigInteger. The most significant byte of byte array is present in the zeroth element. The returning array from this method contain sing bit and contain the minimum number of bytes required to represent this BigInteger. The sign bit position is (ceil((this.bitLength() + 1)/8)). Syntax:" }, { "code": null, "e": 24387, "s": 24359, "text": "public byte[] toByteArray()" }, { "code": null, "e": 24638, "s": 24387, "text": "Parameters: This method does not accepts any parameters. Return Value: This method returns a byte array containing the two’s-complement representation of this BigInteger. Below programs illustrate toByteArray() method of BigInteger class: Example 1: " }, { "code": null, "e": 24643, "s": 24638, "text": "Java" }, { "code": "// Java program to demonstrate toByteArray() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger bigInt = BigInteger.valueOf(10); // create a byte array byte b1[]; b1 = bigInt.toByteArray(); // print result System.out.print(\"ByteArray of BigInteger \" + bigInt + \" is\"); for (int i = 0; i < b1.length; i++) { System.out.format(\" \" + \"0x%02X\", b1[i]); } }}", "e": 25271, "s": 24643, "text": null }, { "code": null, "e": 25306, "s": 25271, "text": "ByteArray of BigInteger 10 is 0x0A" }, { "code": null, "e": 25318, "s": 25306, "text": "Example 2: " }, { "code": null, "e": 25323, "s": 25318, "text": "Java" }, { "code": "// Java program to demonstrate toByteArray() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // create byte array byte b[] = { 0x1, 0x2, 0x1 }; // Creating BigInteger object using byte Array BigInteger bigInt = new BigInteger(b); // apply toByteArray() on BigInteger byte b1[] = bigInt.toByteArray(); // print result System.out.print(\"ByteArray of BigInteger \" + bigInt + \" is\"); for (int i = 0; i < b1.length; i++) { System.out.format(\" \" + \"0x%02X\", b1[i]); } }}", "e": 26032, "s": 25323, "text": null }, { "code": null, "e": 26080, "s": 26032, "text": "ByteArray of BigInteger 66049 is 0x01 0x02 0x01" }, { "code": null, "e": 26173, "s": 26080, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toByteArray()" }, { "code": null, "e": 26187, "s": 26173, "text": "sumitgumber28" }, { "code": null, "e": 26203, "s": 26187, "text": "Java-BigInteger" }, { "code": null, "e": 26218, "s": 26203, "text": "Java-Functions" }, { "code": null, "e": 26228, "s": 26218, "text": "java-math" }, { "code": null, "e": 26246, "s": 26228, "text": "Java-math-package" }, { "code": null, "e": 26251, "s": 26246, "text": "Java" }, { "code": null, "e": 26267, "s": 26251, "text": "Java-BigInteger" }, { "code": null, "e": 26272, "s": 26267, "text": "Java" }, { "code": null, "e": 26370, "s": 26272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26379, "s": 26370, "text": "Comments" }, { "code": null, "e": 26392, "s": 26379, "text": "Old Comments" }, { "code": null, "e": 26438, "s": 26392, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26459, "s": 26438, "text": "Constructors in Java" }, { "code": null, "e": 26474, "s": 26459, "text": "Stream In Java" }, { "code": null, "e": 26493, "s": 26474, "text": "Exceptions in Java" }, { "code": null, "e": 26510, "s": 26493, "text": "Generics in Java" }, { "code": null, "e": 26540, "s": 26510, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26583, "s": 26540, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26599, "s": 26583, "text": "Strings in Java" }, { "code": null, "e": 26628, "s": 26599, "text": "HashMap get() Method in Java" } ]
Pangram Checking - GeeksforGeeks
08 Apr, 2022 Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet.Examples : The quick brown fox jumps over the lazy dog ” is a Pangram [Contains all the characters from ‘a’ to ‘z’] “The quick brown fox jumps over the dog” is not a Pangram [Doesn’t contain all the characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing] We create a mark[] array of Boolean type. We iterate through all the characters of our string and whenever we see a character we mark it. Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25. After iterating through all the characters we check whether all the characters are marked or not. If not then return false as this is not a pangram else return true. C++ C Java Python3 C# Javascript // A C++ Program to check if the given// string is a pangram or not#include <bits/stdc++.h>using namespace std; // Returns true if the string is pangram else falsebool checkPangram(string& str){ // Create a hash table to mark the characters // present in the string vector<bool> mark(26, false); // For indexing in mark[] int index; // Traverse all characters for (int i = 0; i < str.length(); i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, subtract 'a' // to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true);} // Driver Program to test above functionsint main(){ string str = "The quick brown fox jumps over the" " lazy dog"; if (checkPangram(str) == true) printf(" %s is a pangram", str.c_str()); else printf(" %s is not a pangram", str.c_str()); return (0);} // This code is contributed by Aditya kumar (adityakumar129) // A C Program to check if the given// string is a pangram or not#include <stdbool.h>#include <stdio.h>#include <string.h> // Returns true if the string is pangram else falsebool checkPangram(char str[]){ // Create a hash table to mark the characters // present in the string bool mark[26]; for (int i = 0; i < 26; i++) mark[i] = false; // For indexing in mark[] int index; // Traverse all characters size_t size = strlen(str); for (int i = 0; i < size; i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, subtract 'a' // to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true);} // Driver Program to test above functionsint main(){ char str[] = "The quick brown fox jumps over the lazy dog"; if (checkPangram(str) == true) printf(" %s is a pangram", str); else printf(" %s is not a pangram", str); return (0);} // This code is contributed by Aditya kumar (adityakumar129) // Java Program to illustrate Pangramclass GFG { // Returns true if the string // is pangram else false public static boolean checkPangram(String str) { // Create a hash table to mark the // characters present in the string // By default all the elements of // mark would be false. boolean[] mark = new boolean[26]; // For indexing in mark[] int index = 0; // Traverse all characters for (int i = 0; i < str.length(); i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str.charAt(i) && str.charAt(i) <= 'Z') index = str.charAt(i) - 'A'; // If lowercase character, subtract 'a' // to find index. else if ('a' <= str.charAt(i) && str.charAt(i) <= 'z') index = str.charAt(i) - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true); } // Driver Code public static void main(String[] args) { String str = "The quick brown fox jumps over the lazy dog"; if (checkPangram(str) == true) System.out.print(str + " is a pangram."); else System.out.print(str + " is not a pangram."); }} # A Python Program to check if the given# string is a pangram or not def checkPangram(s): List = [] # create list of 26 characters and set false each entry for i in range(26): List.append(False) # converting the sentence to lowercase and iterating # over the sentence for c in s.lower(): if not c == " ": # make the corresponding entry True List[ord(c) -ord('a')]= True # check if any character is missing then return False for ch in List: if ch == False: return False return True # Driver Program to test above functionssentence = "The quick brown fox jumps over the little lazy dog" if (checkPangram(sentence)): print ('"'+sentence+'"') print ("is a pangram")else: print ('"'+sentence+'"') print ("is not a pangram") # This code is contributed by Danish Mushtaq // C# Program to illustrate Pangramusing System;class GFG { // Returns true if the string // is pangram else false public static bool checkPangram(string str) { // Create a hash table to mark the // characters present in the string // By default all the elements of // mark would be false. bool[] mark = new bool[26]; // For indexing in mark[] int index = 0; // Traverse all characters for (int i = 0; i < str.Length; i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, // subtract 'a' to find // index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any // character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters // were present return (true); } // Driver Code public static void Main() { string str = "The quick brown fox jumps over the lazy dog"; if (checkPangram(str) == true) Console.WriteLine(str + " is a pangram."); else Console.WriteLine(str + " is not a pangram."); }} // This code is contributed by nitin mittal. <script> // A JavaScript Program to check if the given// string is a pangram or not // Returns true if the string is pangram else falsefunction checkPangram(str){ // Create a hash table to mark the characters // present in the string mark = new Array(26).fill(false); // For indexing in mark[] let index; // Traverse all characters for (let i = 0; i < str.length; i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str.charCodeAt(i) - 'A'.charCodeAt(0); // If lowercase character, subtract 'a' // to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str.charCodeAt(i) - 'a'.charCodeAt(0); // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (let i = 0; i <= 25; i++) if (mark[i] == false) return false; // If all characters were present return true;} // Driver Program to test above functions let str = "The quick brown fox jumps over the lazy dog"; document.write(str,"</br>") if (checkPangram(str) == true) document.write("is a pangram");else document.write("is not a pangram"); // This code is contributed by shinjanpatra.</script> Output : Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. "The quick brown fox jumps over the lazy dog" is a pangram Time Complexity: O(n), where n is the length of our string Auxiliary Space – O(1). https://youtu.be/Yv4ARV -Hrow This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to 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 panwarabhishek345 nitin mittal HimanshuUppal anikaseth98 amartyaniel20 shinjanpatra adityakumar129 Snapdeal Zoho Strings Zoho Snapdeal Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters Check whether two strings are anagram of each other
[ { "code": null, "e": 26614, "s": 26586, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26989, "s": 26614, "text": "Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet.Examples : The quick brown fox jumps over the lazy dog ” is a Pangram [Contains all the characters from ‘a’ to ‘z’] “The quick brown fox jumps over the dog” is not a Pangram [Doesn’t contain all the characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing]" }, { "code": null, "e": 27263, "s": 26989, "text": "We create a mark[] array of Boolean type. We iterate through all the characters of our string and whenever we see a character we mark it. Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25." }, { "code": null, "e": 27430, "s": 27263, "text": "After iterating through all the characters we check whether all the characters are marked or not. If not then return false as this is not a pangram else return true. " }, { "code": null, "e": 27434, "s": 27430, "text": "C++" }, { "code": null, "e": 27436, "s": 27434, "text": "C" }, { "code": null, "e": 27441, "s": 27436, "text": "Java" }, { "code": null, "e": 27449, "s": 27441, "text": "Python3" }, { "code": null, "e": 27452, "s": 27449, "text": "C#" }, { "code": null, "e": 27463, "s": 27452, "text": "Javascript" }, { "code": "// A C++ Program to check if the given// string is a pangram or not#include <bits/stdc++.h>using namespace std; // Returns true if the string is pangram else falsebool checkPangram(string& str){ // Create a hash table to mark the characters // present in the string vector<bool> mark(26, false); // For indexing in mark[] int index; // Traverse all characters for (int i = 0; i < str.length(); i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, subtract 'a' // to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true);} // Driver Program to test above functionsint main(){ string str = \"The quick brown fox jumps over the\" \" lazy dog\"; if (checkPangram(str) == true) printf(\" %s is a pangram\", str.c_str()); else printf(\" %s is not a pangram\", str.c_str()); return (0);} // This code is contributed by Aditya kumar (adityakumar129)", "e": 28895, "s": 27463, "text": null }, { "code": "// A C Program to check if the given// string is a pangram or not#include <stdbool.h>#include <stdio.h>#include <string.h> // Returns true if the string is pangram else falsebool checkPangram(char str[]){ // Create a hash table to mark the characters // present in the string bool mark[26]; for (int i = 0; i < 26; i++) mark[i] = false; // For indexing in mark[] int index; // Traverse all characters size_t size = strlen(str); for (int i = 0; i < size; i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, subtract 'a' // to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true);} // Driver Program to test above functionsint main(){ char str[] = \"The quick brown fox jumps over the lazy dog\"; if (checkPangram(str) == true) printf(\" %s is a pangram\", str); else printf(\" %s is not a pangram\", str); return (0);} // This code is contributed by Aditya kumar (adityakumar129)", "e": 30379, "s": 28895, "text": null }, { "code": "// Java Program to illustrate Pangramclass GFG { // Returns true if the string // is pangram else false public static boolean checkPangram(String str) { // Create a hash table to mark the // characters present in the string // By default all the elements of // mark would be false. boolean[] mark = new boolean[26]; // For indexing in mark[] int index = 0; // Traverse all characters for (int i = 0; i < str.length(); i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str.charAt(i) && str.charAt(i) <= 'Z') index = str.charAt(i) - 'A'; // If lowercase character, subtract 'a' // to find index. else if ('a' <= str.charAt(i) && str.charAt(i) <= 'z') index = str.charAt(i) - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true); } // Driver Code public static void main(String[] args) { String str = \"The quick brown fox jumps over the lazy dog\"; if (checkPangram(str) == true) System.out.print(str + \" is a pangram.\"); else System.out.print(str + \" is not a pangram.\"); }}", "e": 31968, "s": 30379, "text": null }, { "code": "# A Python Program to check if the given# string is a pangram or not def checkPangram(s): List = [] # create list of 26 characters and set false each entry for i in range(26): List.append(False) # converting the sentence to lowercase and iterating # over the sentence for c in s.lower(): if not c == \" \": # make the corresponding entry True List[ord(c) -ord('a')]= True # check if any character is missing then return False for ch in List: if ch == False: return False return True # Driver Program to test above functionssentence = \"The quick brown fox jumps over the little lazy dog\" if (checkPangram(sentence)): print ('\"'+sentence+'\"') print (\"is a pangram\")else: print ('\"'+sentence+'\"') print (\"is not a pangram\") # This code is contributed by Danish Mushtaq ", "e": 32849, "s": 31968, "text": null }, { "code": "// C# Program to illustrate Pangramusing System;class GFG { // Returns true if the string // is pangram else false public static bool checkPangram(string str) { // Create a hash table to mark the // characters present in the string // By default all the elements of // mark would be false. bool[] mark = new bool[26]; // For indexing in mark[] int index = 0; // Traverse all characters for (int i = 0; i < str.Length; i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, // subtract 'a' to find // index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any // character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters // were present return (true); } // Driver Code public static void Main() { string str = \"The quick brown fox jumps over the lazy dog\"; if (checkPangram(str) == true) Console.WriteLine(str + \" is a pangram.\"); else Console.WriteLine(str + \" is not a pangram.\"); }} // This code is contributed by nitin mittal.", "e": 34465, "s": 32849, "text": null }, { "code": "<script> // A JavaScript Program to check if the given// string is a pangram or not // Returns true if the string is pangram else falsefunction checkPangram(str){ // Create a hash table to mark the characters // present in the string mark = new Array(26).fill(false); // For indexing in mark[] let index; // Traverse all characters for (let i = 0; i < str.length; i++) { // If uppercase character, subtract 'A' // to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str.charCodeAt(i) - 'A'.charCodeAt(0); // If lowercase character, subtract 'a' // to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str.charCodeAt(i) - 'a'.charCodeAt(0); // If this character is other than english // lowercase and uppercase characters. else continue; mark[index] = true; } // Return false if any character is unmarked for (let i = 0; i <= 25; i++) if (mark[i] == false) return false; // If all characters were present return true;} // Driver Program to test above functions let str = \"The quick brown fox jumps over the lazy dog\"; document.write(str,\"</br>\") if (checkPangram(str) == true) document.write(\"is a pangram\");else document.write(\"is not a pangram\"); // This code is contributed by shinjanpatra.</script>", "e": 35847, "s": 34465, "text": null }, { "code": null, "e": 35857, "s": 35847, "text": "Output : " }, { "code": null, "e": 35866, "s": 35857, "text": "Chapters" }, { "code": null, "e": 35893, "s": 35866, "text": "descriptions off, selected" }, { "code": null, "e": 35943, "s": 35893, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 35966, "s": 35943, "text": "captions off, selected" }, { "code": null, "e": 35974, "s": 35966, "text": "English" }, { "code": null, "e": 35998, "s": 35974, "text": "This is a modal window." }, { "code": null, "e": 36067, "s": 35998, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 36089, "s": 36067, "text": "End of dialog window." }, { "code": null, "e": 36150, "s": 36089, "text": " \"The quick brown fox jumps over the lazy dog\"\n is a pangram" }, { "code": null, "e": 36234, "s": 36150, "text": "Time Complexity: O(n), where n is the length of our string Auxiliary Space – O(1). " }, { "code": null, "e": 36258, "s": 36234, "text": "https://youtu.be/Yv4ARV" }, { "code": null, "e": 36659, "s": 36258, "text": "-Hrow This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to 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": 36677, "s": 36659, "text": "panwarabhishek345" }, { "code": null, "e": 36690, "s": 36677, "text": "nitin mittal" }, { "code": null, "e": 36704, "s": 36690, "text": "HimanshuUppal" }, { "code": null, "e": 36716, "s": 36704, "text": "anikaseth98" }, { "code": null, "e": 36730, "s": 36716, "text": "amartyaniel20" }, { "code": null, "e": 36743, "s": 36730, "text": "shinjanpatra" }, { "code": null, "e": 36758, "s": 36743, "text": "adityakumar129" }, { "code": null, "e": 36767, "s": 36758, "text": "Snapdeal" }, { "code": null, "e": 36772, "s": 36767, "text": "Zoho" }, { "code": null, "e": 36780, "s": 36772, "text": "Strings" }, { "code": null, "e": 36785, "s": 36780, "text": "Zoho" }, { "code": null, "e": 36794, "s": 36785, "text": "Snapdeal" }, { "code": null, "e": 36802, "s": 36794, "text": "Strings" }, { "code": null, "e": 36900, "s": 36802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36975, "s": 36900, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 37032, "s": 36975, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 37068, "s": 37032, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 37115, "s": 37068, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 37151, "s": 37115, "text": "Convert string to char array in C++" }, { "code": null, "e": 37189, "s": 37151, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 37219, "s": 37189, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 37264, "s": 37219, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 37325, "s": 37264, "text": "Length of the longest substring without repeating characters" } ]
Rotating Images using OpenCV in Java - GeeksforGeeks
21 Dec, 2021 Image rotation is a common image processing routine used to rotate images at any desired angle. This helps in image reversal, flipping, and obtaining an intended view of the image. Image rotation has applications in matching, alignment, and other image-based algorithms. OpenCV is a well-known library used for image processing. Approach: Before switching ahead, set up an OpenCV environment for Java in order to deal with images and later to perform the action on them. Now, image rotation is performed in OpenCV with the help of the warpAffine() method. The image can be rotated at any angle using this technique for which it is required to define around which point or axis rotation is to be performed. Following steps are serially followed as mentioned: Identify a point about which rotation is to be done and rotation angle.Get a rotation matrix for the source image.Use Affine transformation on the source image using the rotation matrix obtained. Identify a point about which rotation is to be done and rotation angle. Get a rotation matrix for the source image. Use Affine transformation on the source image using the rotation matrix obtained. Besides this approach, there are two more approaches for rotating an image in angles that are multiples of 90 degrees (i.e., ±90, ±180, ±270). An affine transform is dozens of times more computationally intensive. Affine interpolates and uses a lot of floating-point arithmetic. Following approaches are much more effective than warpAffine() for angles that are multiples of 90 degrees. Use-Cases in image rotation that can occur Rotate methodTranspose and Flip method Rotate method Transpose and Flip method Methods Required: warpAffine()getRotationMatrix2D()rotate()flip()Transpose() warpAffine() getRotationMatrix2D() rotate() flip() Transpose() Methods are described below: 1. warpAffine(): Applies an affine transformation to an image. Syntax: Imgproc.warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags) Parameters: src – input image. dst – output image that has the size dsize and the same type as src. M – 2×3 transformation (rotation) matrix. dsize – size of the output image. flags – Optional field. WARP_INVERSE_MAP flag.When flag is not provided, image mapping is in counterclockwise direction.If the WARP_INVERSE_MAP flag is set, image mapping is in clockwise direction. When flag is not provided, image mapping is in counterclockwise direction. If the WARP_INVERSE_MAP flag is set, image mapping is in clockwise direction. 2. getRotationMatrix2D() : Calculates an affine matrix of 2D rotation. Syntax: Imgproc.getRotationMatrix2D(Point center, double angle, double scale) Parameters: center – Center of the rotation in the source image. angle – Rotation angle in degrees. Positive values mean counter-clockwise rotation scale – Isotropic scale factor. 3. rotate() : Rotates a 2D array in multiples of 90 degrees. Syntax: Core.rotate(Mat src, Mat dst, int rotateCode) Parameters: src – input array. dst – output array of the same type as src. rotateCode – An enum to specify how to rotate the array.ROTATE_90_CLOCKWISE : Rotate image by 90 degrees clockwise or 270 degrees counter clockwiseROTATE_90_COUNTERCLOCKWISE : Rotate image by 90 degrees counterclockwise or 270 degrees clockwiseROTATE_180 : Rotate by 180 degrees. ROTATE_90_CLOCKWISE : Rotate image by 90 degrees clockwise or 270 degrees counter clockwise ROTATE_90_COUNTERCLOCKWISE : Rotate image by 90 degrees counterclockwise or 270 degrees clockwise ROTATE_180 : Rotate by 180 degrees. 4. flip(): Flips a 2D array around vertical, horizontal, or both axes. Syntax: Core.flip(Mat src, Mat dst, int flipCode) Parameters: src – input array. dst – output array of the same size and type as src. flipCode – a flag to specify how to flip the array.flipCode=0 means flipping around the x-axis.flipCode>0 (Positive value such as, 1) means flipping around y-axis.flipcode<0 (Negative value such as, -1) means flipping around both axes. flipCode=0 means flipping around the x-axis. flipCode>0 (Positive value such as, 1) means flipping around y-axis. flipcode<0 (Negative value such as, -1) means flipping around both axes. 5. Transpose() : Transposes a matrix. Syntax: Core.transpose(Mat src, Mat dst) Parameters: src – input array. dst – output array of the same type as src. Illustration: Input: Considering a sample input image: Input Image Pseudo Code: double angle=45 Point rotPoint=new Point(src.cols()/2.0, src.rows()/2.0) Mat rotMat = Imgproc.getRotationMatrix2D( rotPoint, angle, 1); Imgproc.warpAffine(src, dst, rotMat, src.size()); Steps to be followed- midpoint of a source image, rotPoint, is considered for rotation, rotation angle is 45°.Rotation matrix is obtained by getRotationMatrix2D() method.Affine transformation is performed using warpAffine() method. Rotation matrix is obtained by getRotationMatrix2D() method. Affine transformation is performed using warpAffine() method. Input image will be rotated in 45° counterclockwise direction as shown below. Output: Image is as shown: 45° Counter clockwise Rotated Image Sample input image: For implementation purposes Input Image Case 1: Rotate method- considering the same input image for the implementation part. Rotate an image using the rotate method involves the correct use of rotatecode. If the angle is 90° or -270°Use rotatecode → ROTATE_90_CLOCKWISE Use rotatecode → ROTATE_90_CLOCKWISE If the angle is 180° or -180°Use rotatecode → ROTATE_180 Use rotatecode → ROTATE_180 If the angle is 270° or -90°Use rotatecode → ROTATE_90_COUNTERCLOCKWISE Use rotatecode → ROTATE_90_COUNTERCLOCKWISE Example Java // import required packagesimport org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.Point;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc; // Class to rotate imagepublic class GFG { // Main driver method public static void main(String args[]) { // Load library required for OpenCV functions System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Read an image and store in a Matrix object // Local directory from where image is picked String file = "C:/opencv/image.jpg"; Mat src = Imgcodecs.imread(file); // Create empty Mat object to store output image Mat dst = new Mat(); // Define Rotation Angle double angle = 90; // Image rotation according to the angle provided if (angle == 90 || angle == -270) Core.rotate(src, dst, Core.ROTATE_90_CLOCKWISE); else if (angle == 180 || angle == -180) Core.rotate(src, dst, Core.ROTATE_180); else if (angle == 270 || angle == -90) Core.rotate(src, dst, Core.ROTATE_90_COUNTERCLOCKWISE); else { // Center of the rotation is given by // midpoint of source image : // (width/2.0,height/2.0) Point rotPoint = new Point(src.cols() / 2.0, src.rows() / 2.0); // Create Rotation Matrix Mat rotMat = Imgproc.getRotationMatrix2D( rotPoint, angle, 1); // Apply Affine Transformation Imgproc.warpAffine(src, dst, rotMat, src.size(), Imgproc.WARP_INVERSE_MAP); // If counterclockwise rotation is required use // following: Imgproc.warpAffine(src, dst, // rotMat, src.size()); } // Save rotated image // Destination where rotated image is saved // on local directory Imgcodecs.imwrite("C:/opencv/rotated_image.jpg", dst // Print message for successful execution of program System.out.println("Image Rotated Successfully"); }} Output: Case 2: Transpose and Flip method If the angle is 90° or -270°, transpose the source image matrix and thenflip it with positive value as flipcode flip it with positive value as flipcode If the angle is 270° or -90°, transpose the source image matrix and thenflip it with 0 as flipcode flip it with 0 as flipcode If the angle is 180°, flip source image with -1 as flipcode Implementation: Java // Importing openCV librariesimport org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.Point;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc; // Class to rotate imagespublic class GFG { // Main driver method public static void main(String args[]) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); String file = "C:/opencv/image.jpg"; Mat src = Imgcodecs.imread(file); Mat dst = new Mat(); double angle = 180; // Rotate clockwise at 90 degrees if (angle == 90 || angle == -270) { Core.transpose(src, dst); Core.flip(dst, dst, 1); } // Rotate clockwise at 180 degrees else if (angle == 180 || angle == -180) Core.flip(src, dst, -1); // Rotate clockwise at 270 degrees else if (angle == 270 || angle == -90) { Core.transpose(src, dst); Core.flip(dst, dst, 0); } // Rotate Clockwise with any other angles else { Point rotPoint = new Point(src.cols() / 2.0, src.rows() / 2.0) Mat rotMat = Imgproc.getRotationMatrix2D(rotpoint, angle, 1); Imgproc.warpAffine(src, dst, rotMat, src.size(), Imgproc.WARP_INVERSE_MAP); } // Destination where image is written in local // directory Imgcodecs.imwrite("C:/opencv/rotated_image.jpg", dst); // Print command for successful execution of program System.out.println("Image Rotated Successfully"); }} Output: kk773572498 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. Object Oriented Programming (OOPs) Concept in Java Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 26231, "s": 26203, "text": "\n21 Dec, 2021" }, { "code": null, "e": 26560, "s": 26231, "text": "Image rotation is a common image processing routine used to rotate images at any desired angle. This helps in image reversal, flipping, and obtaining an intended view of the image. Image rotation has applications in matching, alignment, and other image-based algorithms. OpenCV is a well-known library used for image processing." }, { "code": null, "e": 26571, "s": 26560, "text": "Approach: " }, { "code": null, "e": 26938, "s": 26571, "text": "Before switching ahead, set up an OpenCV environment for Java in order to deal with images and later to perform the action on them. Now, image rotation is performed in OpenCV with the help of the warpAffine() method. The image can be rotated at any angle using this technique for which it is required to define around which point or axis rotation is to be performed." }, { "code": null, "e": 26990, "s": 26938, "text": "Following steps are serially followed as mentioned:" }, { "code": null, "e": 27186, "s": 26990, "text": "Identify a point about which rotation is to be done and rotation angle.Get a rotation matrix for the source image.Use Affine transformation on the source image using the rotation matrix obtained." }, { "code": null, "e": 27258, "s": 27186, "text": "Identify a point about which rotation is to be done and rotation angle." }, { "code": null, "e": 27302, "s": 27258, "text": "Get a rotation matrix for the source image." }, { "code": null, "e": 27384, "s": 27302, "text": "Use Affine transformation on the source image using the rotation matrix obtained." }, { "code": null, "e": 27771, "s": 27384, "text": "Besides this approach, there are two more approaches for rotating an image in angles that are multiples of 90 degrees (i.e., ±90, ±180, ±270). An affine transform is dozens of times more computationally intensive. Affine interpolates and uses a lot of floating-point arithmetic. Following approaches are much more effective than warpAffine() for angles that are multiples of 90 degrees." }, { "code": null, "e": 27814, "s": 27771, "text": "Use-Cases in image rotation that can occur" }, { "code": null, "e": 27853, "s": 27814, "text": "Rotate methodTranspose and Flip method" }, { "code": null, "e": 27867, "s": 27853, "text": "Rotate method" }, { "code": null, "e": 27893, "s": 27867, "text": "Transpose and Flip method" }, { "code": null, "e": 27911, "s": 27893, "text": "Methods Required:" }, { "code": null, "e": 27970, "s": 27911, "text": "warpAffine()getRotationMatrix2D()rotate()flip()Transpose()" }, { "code": null, "e": 27983, "s": 27970, "text": "warpAffine()" }, { "code": null, "e": 28005, "s": 27983, "text": "getRotationMatrix2D()" }, { "code": null, "e": 28014, "s": 28005, "text": "rotate()" }, { "code": null, "e": 28021, "s": 28014, "text": "flip()" }, { "code": null, "e": 28033, "s": 28021, "text": "Transpose()" }, { "code": null, "e": 28062, "s": 28033, "text": "Methods are described below:" }, { "code": null, "e": 28125, "s": 28062, "text": "1. warpAffine(): Applies an affine transformation to an image." }, { "code": null, "e": 28134, "s": 28125, "text": "Syntax: " }, { "code": null, "e": 28201, "s": 28134, "text": "Imgproc.warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags)" }, { "code": null, "e": 28213, "s": 28201, "text": "Parameters:" }, { "code": null, "e": 28232, "s": 28213, "text": "src – input image." }, { "code": null, "e": 28301, "s": 28232, "text": "dst – output image that has the size dsize and the same type as src." }, { "code": null, "e": 28343, "s": 28301, "text": "M – 2×3 transformation (rotation) matrix." }, { "code": null, "e": 28377, "s": 28343, "text": "dsize – size of the output image." }, { "code": null, "e": 28575, "s": 28377, "text": "flags – Optional field. WARP_INVERSE_MAP flag.When flag is not provided, image mapping is in counterclockwise direction.If the WARP_INVERSE_MAP flag is set, image mapping is in clockwise direction." }, { "code": null, "e": 28650, "s": 28575, "text": "When flag is not provided, image mapping is in counterclockwise direction." }, { "code": null, "e": 28728, "s": 28650, "text": "If the WARP_INVERSE_MAP flag is set, image mapping is in clockwise direction." }, { "code": null, "e": 28799, "s": 28728, "text": "2. getRotationMatrix2D() : Calculates an affine matrix of 2D rotation." }, { "code": null, "e": 28808, "s": 28799, "text": "Syntax: " }, { "code": null, "e": 28878, "s": 28808, "text": "Imgproc.getRotationMatrix2D(Point center, double angle, double scale)" }, { "code": null, "e": 28890, "s": 28878, "text": "Parameters:" }, { "code": null, "e": 28943, "s": 28890, "text": "center – Center of the rotation in the source image." }, { "code": null, "e": 29026, "s": 28943, "text": "angle – Rotation angle in degrees. Positive values mean counter-clockwise rotation" }, { "code": null, "e": 29058, "s": 29026, "text": "scale – Isotropic scale factor." }, { "code": null, "e": 29119, "s": 29058, "text": "3. rotate() : Rotates a 2D array in multiples of 90 degrees." }, { "code": null, "e": 29127, "s": 29119, "text": "Syntax:" }, { "code": null, "e": 29173, "s": 29127, "text": "Core.rotate(Mat src, Mat dst, int rotateCode)" }, { "code": null, "e": 29185, "s": 29173, "text": "Parameters:" }, { "code": null, "e": 29204, "s": 29185, "text": "src – input array." }, { "code": null, "e": 29248, "s": 29204, "text": "dst – output array of the same type as src." }, { "code": null, "e": 29528, "s": 29248, "text": "rotateCode – An enum to specify how to rotate the array.ROTATE_90_CLOCKWISE : Rotate image by 90 degrees clockwise or 270 degrees counter clockwiseROTATE_90_COUNTERCLOCKWISE : Rotate image by 90 degrees counterclockwise or 270 degrees clockwiseROTATE_180 : Rotate by 180 degrees." }, { "code": null, "e": 29620, "s": 29528, "text": "ROTATE_90_CLOCKWISE : Rotate image by 90 degrees clockwise or 270 degrees counter clockwise" }, { "code": null, "e": 29718, "s": 29620, "text": "ROTATE_90_COUNTERCLOCKWISE : Rotate image by 90 degrees counterclockwise or 270 degrees clockwise" }, { "code": null, "e": 29754, "s": 29718, "text": "ROTATE_180 : Rotate by 180 degrees." }, { "code": null, "e": 29825, "s": 29754, "text": "4. flip(): Flips a 2D array around vertical, horizontal, or both axes." }, { "code": null, "e": 29834, "s": 29825, "text": "Syntax: " }, { "code": null, "e": 29876, "s": 29834, "text": "Core.flip(Mat src, Mat dst, int flipCode)" }, { "code": null, "e": 29888, "s": 29876, "text": "Parameters:" }, { "code": null, "e": 29907, "s": 29888, "text": "src – input array." }, { "code": null, "e": 29960, "s": 29907, "text": "dst – output array of the same size and type as src." }, { "code": null, "e": 30196, "s": 29960, "text": "flipCode – a flag to specify how to flip the array.flipCode=0 means flipping around the x-axis.flipCode>0 (Positive value such as, 1) means flipping around y-axis.flipcode<0 (Negative value such as, -1) means flipping around both axes." }, { "code": null, "e": 30241, "s": 30196, "text": "flipCode=0 means flipping around the x-axis." }, { "code": null, "e": 30310, "s": 30241, "text": "flipCode>0 (Positive value such as, 1) means flipping around y-axis." }, { "code": null, "e": 30383, "s": 30310, "text": "flipcode<0 (Negative value such as, -1) means flipping around both axes." }, { "code": null, "e": 30421, "s": 30383, "text": "5. Transpose() : Transposes a matrix." }, { "code": null, "e": 30430, "s": 30421, "text": "Syntax: " }, { "code": null, "e": 30463, "s": 30430, "text": "Core.transpose(Mat src, Mat dst)" }, { "code": null, "e": 30475, "s": 30463, "text": "Parameters:" }, { "code": null, "e": 30494, "s": 30475, "text": "src – input array." }, { "code": null, "e": 30538, "s": 30494, "text": "dst – output array of the same type as src." }, { "code": null, "e": 30553, "s": 30538, "text": "Illustration: " }, { "code": null, "e": 30594, "s": 30553, "text": "Input: Considering a sample input image:" }, { "code": null, "e": 30607, "s": 30594, "text": "Input Image " }, { "code": null, "e": 30806, "s": 30607, "text": "Pseudo Code:\ndouble angle=45\nPoint rotPoint=new Point(src.cols()/2.0, src.rows()/2.0)\nMat rotMat = Imgproc.getRotationMatrix2D( rotPoint, angle, 1);\nImgproc.warpAffine(src, dst, rotMat, src.size());" }, { "code": null, "e": 30828, "s": 30806, "text": "Steps to be followed-" }, { "code": null, "e": 30856, "s": 30828, "text": "midpoint of a source image," }, { "code": null, "e": 30894, "s": 30856, "text": "rotPoint, is considered for rotation," }, { "code": null, "e": 31038, "s": 30894, "text": "rotation angle is 45°.Rotation matrix is obtained by getRotationMatrix2D() method.Affine transformation is performed using warpAffine() method." }, { "code": null, "e": 31099, "s": 31038, "text": "Rotation matrix is obtained by getRotationMatrix2D() method." }, { "code": null, "e": 31161, "s": 31099, "text": "Affine transformation is performed using warpAffine() method." }, { "code": null, "e": 31239, "s": 31161, "text": "Input image will be rotated in 45° counterclockwise direction as shown below." }, { "code": null, "e": 31266, "s": 31239, "text": "Output: Image is as shown:" }, { "code": null, "e": 31302, "s": 31266, "text": "45° Counter clockwise Rotated Image" }, { "code": null, "e": 31350, "s": 31302, "text": "Sample input image: For implementation purposes" }, { "code": null, "e": 31363, "s": 31350, "text": "Input Image " }, { "code": null, "e": 31448, "s": 31363, "text": "Case 1: Rotate method- considering the same input image for the implementation part." }, { "code": null, "e": 31528, "s": 31448, "text": "Rotate an image using the rotate method involves the correct use of rotatecode." }, { "code": null, "e": 31593, "s": 31528, "text": "If the angle is 90° or -270°Use rotatecode → ROTATE_90_CLOCKWISE" }, { "code": null, "e": 31630, "s": 31593, "text": "Use rotatecode → ROTATE_90_CLOCKWISE" }, { "code": null, "e": 31687, "s": 31630, "text": "If the angle is 180° or -180°Use rotatecode → ROTATE_180" }, { "code": null, "e": 31715, "s": 31687, "text": "Use rotatecode → ROTATE_180" }, { "code": null, "e": 31787, "s": 31715, "text": "If the angle is 270° or -90°Use rotatecode → ROTATE_90_COUNTERCLOCKWISE" }, { "code": null, "e": 31831, "s": 31787, "text": "Use rotatecode → ROTATE_90_COUNTERCLOCKWISE" }, { "code": null, "e": 31839, "s": 31831, "text": "Example" }, { "code": null, "e": 31844, "s": 31839, "text": "Java" }, { "code": "// import required packagesimport org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.Point;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc; // Class to rotate imagepublic class GFG { // Main driver method public static void main(String args[]) { // Load library required for OpenCV functions System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Read an image and store in a Matrix object // Local directory from where image is picked String file = \"C:/opencv/image.jpg\"; Mat src = Imgcodecs.imread(file); // Create empty Mat object to store output image Mat dst = new Mat(); // Define Rotation Angle double angle = 90; // Image rotation according to the angle provided if (angle == 90 || angle == -270) Core.rotate(src, dst, Core.ROTATE_90_CLOCKWISE); else if (angle == 180 || angle == -180) Core.rotate(src, dst, Core.ROTATE_180); else if (angle == 270 || angle == -90) Core.rotate(src, dst, Core.ROTATE_90_COUNTERCLOCKWISE); else { // Center of the rotation is given by // midpoint of source image : // (width/2.0,height/2.0) Point rotPoint = new Point(src.cols() / 2.0, src.rows() / 2.0); // Create Rotation Matrix Mat rotMat = Imgproc.getRotationMatrix2D( rotPoint, angle, 1); // Apply Affine Transformation Imgproc.warpAffine(src, dst, rotMat, src.size(), Imgproc.WARP_INVERSE_MAP); // If counterclockwise rotation is required use // following: Imgproc.warpAffine(src, dst, // rotMat, src.size()); } // Save rotated image // Destination where rotated image is saved // on local directory Imgcodecs.imwrite(\"C:/opencv/rotated_image.jpg\", dst // Print message for successful execution of program System.out.println(\"Image Rotated Successfully\"); }}", "e": 33988, "s": 31844, "text": null }, { "code": null, "e": 33996, "s": 33988, "text": "Output:" }, { "code": null, "e": 34030, "s": 33996, "text": "Case 2: Transpose and Flip method" }, { "code": null, "e": 34142, "s": 34030, "text": "If the angle is 90° or -270°, transpose the source image matrix and thenflip it with positive value as flipcode" }, { "code": null, "e": 34182, "s": 34142, "text": "flip it with positive value as flipcode" }, { "code": null, "e": 34281, "s": 34182, "text": "If the angle is 270° or -90°, transpose the source image matrix and thenflip it with 0 as flipcode" }, { "code": null, "e": 34308, "s": 34281, "text": "flip it with 0 as flipcode" }, { "code": null, "e": 34368, "s": 34308, "text": "If the angle is 180°, flip source image with -1 as flipcode" }, { "code": null, "e": 34384, "s": 34368, "text": "Implementation:" }, { "code": null, "e": 34389, "s": 34384, "text": "Java" }, { "code": "// Importing openCV librariesimport org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.Point;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc; // Class to rotate imagespublic class GFG { // Main driver method public static void main(String args[]) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); String file = \"C:/opencv/image.jpg\"; Mat src = Imgcodecs.imread(file); Mat dst = new Mat(); double angle = 180; // Rotate clockwise at 90 degrees if (angle == 90 || angle == -270) { Core.transpose(src, dst); Core.flip(dst, dst, 1); } // Rotate clockwise at 180 degrees else if (angle == 180 || angle == -180) Core.flip(src, dst, -1); // Rotate clockwise at 270 degrees else if (angle == 270 || angle == -90) { Core.transpose(src, dst); Core.flip(dst, dst, 0); } // Rotate Clockwise with any other angles else { Point rotPoint = new Point(src.cols() / 2.0, src.rows() / 2.0) Mat rotMat = Imgproc.getRotationMatrix2D(rotpoint, angle, 1); Imgproc.warpAffine(src, dst, rotMat, src.size(), Imgproc.WARP_INVERSE_MAP); } // Destination where image is written in local // directory Imgcodecs.imwrite(\"C:/opencv/rotated_image.jpg\", dst); // Print command for successful execution of program System.out.println(\"Image Rotated Successfully\"); }}", "e": 36063, "s": 34389, "text": null }, { "code": null, "e": 36071, "s": 36063, "text": "Output:" }, { "code": null, "e": 36083, "s": 36071, "text": "kk773572498" }, { "code": null, "e": 36090, "s": 36083, "text": "Picked" }, { "code": null, "e": 36114, "s": 36090, "text": "Technical Scripter 2020" }, { "code": null, "e": 36119, "s": 36114, "text": "Java" }, { "code": null, "e": 36133, "s": 36119, "text": "Java Programs" }, { "code": null, "e": 36152, "s": 36133, "text": "Technical Scripter" }, { "code": null, "e": 36157, "s": 36152, "text": "Java" }, { "code": null, "e": 36255, "s": 36157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36306, "s": 36255, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 36321, "s": 36306, "text": "Stream In Java" }, { "code": null, "e": 36351, "s": 36321, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36370, "s": 36351, "text": "Interfaces in Java" }, { "code": null, "e": 36401, "s": 36370, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36429, "s": 36401, "text": "Initializing a List in Java" }, { "code": null, "e": 36473, "s": 36429, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 36499, "s": 36473, "text": "Java Programming Examples" }, { "code": null, "e": 36533, "s": 36499, "text": "Convert Double to Integer in Java" } ]
How to Capture Weather Data with your own IoT Home Station | by Marcelo Rovai | Towards Data Science
When we are talking about physical variables, as temperature, pressure, etc., as a Data Scientist, usually you start working from a dataset that was created somewhere else. But have you thought about how to capture those data yourself? On this tutorial we will learn how to get data from several different sensors, sending them to an IoT service, ThingSpeak.com and to a mobile App (Thingsview), where we can log and play with data. We will also explore several different communication ways of connecting sensors to a Raspberry Pi, as: DHT22 — Temperature & Humidity Sensor — Digital Comm DS18B20 — Temperature Sensor — 1-Wire BMP180 — Temperature & Pressure Sensor — I2C UV — Ultra Violet Sensor — Analog Sensor via A/D and SPI bus In short, all data will be captured, saved locally on a CSV file and send to an IoT service (ThingSpeak.com), via MQTT protocol, as you can see on below block diagram: To complete a real Weather Station, on the final step you will also learn how to measure wind speed and direction, following Mauricio Pinto’s tutorial. Raspberry Pi V3 DHT22 Temperature and Relative Humidity Sensor Resistor 4K7 ohm DS18B20 Waterproof Temperature Sensor Resistor 4K7 ohm BMP180 Barometric Pressure, Temperature and Altitude Sensor UV Sensor Adafruit MCP3008 8-Channel 10-Bit ADC With SPI Interface Jupyter Notebook is a fantastic tool, or better, an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Jupyter notebook is largely used in Data Science, for cleaning and transforming data, doing numerical simulation, statistical modeling, data visualization, machine learning, and much more! On this tutorial, we will use Jupyter Notebook to interact with Raspberry Pi GPIOs, directly reading sensors and sending data to the internet. Installation You may skip this step if already have Jupyter Notebook installed on your RPi To install Jupyter on your Raspberry (that will run with Python 3), open Terminal and enter with following commands: sudo pip3 install jupytersudo ipython3 kernelspec install-self Now on your terminal, run the command: jupyter notebook And that’s it!!!! Amazing! very simple and easy. The Jupyter Notebook will be running as a server on: http:localhost:8888 Note that your default browser will be automatically opened on the above address, running as a “Home Page”, as shown at above pictures. To stop the server and close the “kernels” (the Jupyter notebooks), you must use [Ctrl] + [C] from your keyboard. From now one, any time that you start your Pi and want to use Jupyter Notebook, just type the command: “Jupyter notebook” on your terminal and keep it running all the time. This is very important! If you need to use the terminal for another task as run a program, for example, open a new Terminal window. You can follow this tutorial step by step, creating your own Notebook, or download the final one from my GitHub: Rpi_Weather_Station.ipynb. The first sensor to be installed will be the DHT22 for capturing air temperature and relative humidity data. The ADAFRUIT siteprovides great information about those sensors. Bellow, some information retrieved from there: Overview The low-cost DHT temperature & humidity sensors are very basic and slow but are great for hobbyists who want to do some basic data logging. The DHT sensors are made of two parts, a capacitive humidity sensor, and a thermistor. There is also a very basic chip inside that does some analog to digital conversion and spits out a digital signal with the temperature and humidity. The digital signal is fairly easy to be read using any microcontroller. DHT22 Main characteristics: Good for 0–100% humidity readings with 2–5% accuracy Good for -40 to 125°C temperature readings ±0.5°C accuracy No more than 0.5 Hz sampling rate (once every 2 seconds) Low cost 3 to 5V power and I/O 2.5mA max current use during conversion (while requesting data) Body size 15.1mm x 25mm x 7.7mm 4 pins with 0.1" spacing Once usually you will use the sensor on distances less than 20m, a 4K7 ohm resistor should be connected between Data and VCC pins. The DHT22 output data pin will be connected to Raspberry GPIO 16. Check the above electrical diagram, connecting the sensor to RPi pins as below: Pin 1 — Vcc ==> 3.3V Pin 2 — Data ==> GPIO 16 Pin 3 — Not Connect Pin 4 — Gnd ==> Gnd Do not forget to Install the 4K7 ohm resistor between Vcc and Data pins Once the sensor is connected, we must also install its library on our RPi. Installing DHT Library: On your Raspberry, starting on /home, go to /Documents cd Documents Create a directory to install the library and move to there: mkdir DHT22_Sensorcd DHT22_Sensor On your browser, go to Adafruit GitHub: github.com Download the library by clicking the download zip link to the right and unzip the archive on your Raspberry Pi recently created folder. Then go to the directory of the library (subfolder that is automatically created when you unzipped the file), and execute the command: sudo python3 setup.py install On The Jupyter Notebook, Import Adafrut DHT Library, define the digital pin to connect the DHT with RPi and run the code to capture temperature and humidity: import Adafruit_DHTDHT22Sensor = Adafruit_DHT.DHT22DHTpin = 16humDHT, tempDHT = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin)if (humDHT is not None) and (tempDHT is not None): hum = round (humDHT,1) temp = round (tempDHT, 1) Run the Cell and print the results: print(‘Temperature = {}*C Humidity = {}%’.format(temp, hum)) Below, the portion of Jupyter Notebook showing the result: Sensor Overview: We will use in this tutorial a waterproofed version of the DS18B20 sensor. It is very useful for for capturing temperature in wet conditions, for example on humid soil. The sensor is isolated and can take measurements until 125oC (Adafrut does not recommend to use it over 100oC due to its cable PVC jacket). The DS18B20 is a digital sensor what makes it good to use even over long distances! These 1-wire digital temperature sensors are fairly precise (±0.5°C over much of the range) and can give up to 12 bits of precision from the onboard digital-to-analog converter. They work great with the RPi using a single digital pin, and you can even connect multiple ones to the same pin, each one has a unique 64-bit ID burned in at the factory to differentiate them. The sensor works from 3.0 to 5.0V, which means that it can be powered directly from the 3.3V provided by one of the Raspberry pins (1 or 17). The sensor has 3 wires: Black: GND Red: VCC Yellow: 1-Wire Data Here, you can find the full data: DS18B20 Datasheet Sensor Installation: Follow the above diagram and make the connections: Vcc ==> 3.3V Gnd ==> Gnd Data ==> GPIO 4 (default for library) Installing the Python Library: Next, let’s install the Python library that will handle the sensor: sudo pip3 install w1thermsensor Before running the script to test the sensor, check if the “1-Wire” interface is enabled in your RPi (see below print screen) Enable Interfaces Do not forget to restart your RPi, after changeing its configuration Testing the sensor: For testing the sensor a simple python code can be used: from w1thermsensor import W1ThermSensords18b20Sensor = W1ThermSensor()tempExt = round(ds18b20Sensor.get_temperature(), 1)print('External Temperature = {}*C'.format(tempExt)) Below, the portion of Jupyter Notebook showing the result: Sensor Overview: The BMP180 is the successor of the BMP085, a new generation of high precision digital pressure sensors for consumer applications. The ultra-low power, low voltage electronics of the BMP180 is optimized for use in mobile phones, PDAs, GPS navigation devices and outdoor equipment. With a low altitude noise of merely 0.25m at fast conversion time, the BMP180 offers superior performance. The I2C interface allows for easy system integration with a microcontroller. The BMP180 is based on piezo-resistive technology for EMC robustness, high accuracy, and linearity as well as long-term stability. The complete BMP datasheet can be found here: BMP180 — Digital Pressure Sensor Sensor Installation: Follow the above diagram and make the connections: Vin ==> 3.3V GND ==> GND SCL ==> GPIO 3 SDA ==> GPIO 2 Enabling I2C Interface Go to RPi Configuration and confirm that I2C interface is enabled. If not, enable it and restart the RPi. Using the BMP180 If everything has been installed and connected okay, you are now ready to turn on your Pi and start seeing what the BMP180 is telling you about the world around you. The first thing to do is to check if the Pi sees your BMP180. Try the following in a terminal window: sudo i2cdetect -y 1 If the command worked, you should see something similar to the below Terminal Printscreen, showing that the BMP180 is on channel ‘77’. Installing the BMP180 Library: Create a directory to install the library and go there: mkdir BMP180_Sensorcd BMP180_Sensor On your browser, go to Adafruit GITHub: github.com Download the library by clicking the download zip link to the right and unzip the archive on your Raspberry Pi created folder. Then go to the created subfolder and execute the following command in the directory of the library: sudo python3 setup.py install On Jupyter, write the following code: import Adafruit_BMP.BMP085 as BMP085bmp180Sensor = BMP085.BMP085()tempBMP = round(bmp180Sensor.read_temperature(), 1)presBMP = round(bmp180Sensor.read_pressure()/100, 1)altBMP = round(bmp180Sensor.read_altitude(),1) Check the variables read by the sensor with bellow code: print ('Temperature = {} C '.format(tempBMP))print ('Pressure = {} hPa [or mbar]'.format(presBMP))print ('Altitud = {} m '.format(altBMP)) Below, the portion of Jupyter Notebook showing the result Note that the sensor pressure is presented in Pa (Pascals). See next step to better understand about this unit. Sea Level Pressure Let’s take a time to understand a little bit more about what we will get, with the BMP readings. You can skip this part of the tutorial, or return later, and if you want to know more about Sensor readings, please go to this great tutorial:https://learn.sparkfun.com/tutorials/bmp180-barome... The BMP180 was designed to accurately measure atmospheric pressure. Atmospheric pressure varies with both weather and altitude. What is Atmospheric Pressure? The definition of atmospheric pressure is a force that the air around you is exerting on everything. The weight of the gasses in the atmosphere creates atmospheric pressure. A common unit of pressure is “pounds per square inch” or psi. We will use here the international notation, that is newtons per square meter, which are called pascals (Pa). If you took 1 cm wide column of air would weigh about 1 kg This weight, pressing down on the footprint of that column, creates the atmospheric pressure that we can measure with sensors like the BMP180. Because that cm-wide column of air weighs about 1Kg, it follows that the average sea level pressure is about 101325 pascals, or better, 1013.25 hPa (1 hPa is also known as milibar — mbar). This will drop by about 4% for every 300 meters you ascend. The higher you get, the less pressure you’ll see, because the column to the top of the atmosphere is that much shorter and therefore weighs less. This is useful to know because by measuring the pressure and doing some math, you can determine your altitude. The air pressure at 3, 810 meters is only half of that at sea level. The BMP180 outputs absolute pressure in pascals (Pa). One pascal is a very small amount of pressure, approximately the amount that a sheet of paper will exert resting on a table. You will more often see measurements in hectopascals (1 hPa = 100 Pa). The library used here provides outputs floating-point values in hPa, which also happens to equal one millibar (mbar). Here are some conversions to other pressure units: 1 hPa = 100 Pa = 1 mbar = 0.001 bar 1 hPa = 0.75006168 Torr 1 hPa = 0.01450377 psi (pounds per square inch) 1 hPa = 0.02953337 inHg (inches of mercury) 1 hpa = 0.00098692 atm (standard atmospheres) Temperature Effects Because temperature affects the density of a gas, and density affects the mass of a gas, and mass affects the pressure (whew), atmospheric pressure will change dramatically with temperature. Pilots know this as “density altitude”, which makes it easier to take off on a cold day than a hot one because the air is denser and has a greater aerodynamic effect. To compensate for temperature, the BMP180 includes a rather good temperature sensor as well as a pressure sensor. To perform a pressure reading, you first take a temperature reading, then combine that with a raw pressure reading to come up with a final temperature-compensated pressure measurement. (The library makes all of this very easy.) Measuring Absolute Pressure If your application requires measuring absolute pressure, all you have to do is get a temperature reading, then perform a pressure reading (see the example sketch for details). The final pressure reading will be in hPa = mbar. If you wish, you can convert this to a different unit using the above conversion factors. Note that the absolute pressure of the atmosphere will vary with both your altitude and the current weather patterns, both of which are useful things to measure. Weather Observations The atmospheric pressure at any given location on earth (or anywhere with an atmosphere) isn’t constant. The complex interaction between the earth’s spin, axis tilt, and many other factors result in moving areas of higher and lower pressure, which in turn cause the variations in weather we see every day. By watching for changes in pressure, you can predict short-term changes in the weather. For example, dropping pressure usually means wet weather or a storm is approaching (a low-pressure system is moving in). Rising pressure usually means that clear weather is approaching (a high-pressure system is moving through). But remember that atmospheric pressure also varies with altitude. The absolute pressure in my house, Lo Barnechea in Chile (altitude 950m) will always be lower than the absolute pressure in San Francisco for example (less than 2 meters, almost sea level). If weather stations just reported their absolute pressure, it would be difficult to directly compare pressure measurements from one location to another (and large-scale weather predictions depend on measurements from as many stations as possible). To solve this problem, weather stations always remove the effects of altitude from their reported pressure readings by mathematically adding the equivalent fixed pressure to make it appear as if the reading was taken at sea level. When you do this, a higher reading in San Francisco than Lo Barnechea will always be because of weather patterns, and not because of altitude. To do this, there is a function in the library called sea level(P, A). This takes the absolute pressure (P) in hPa, and the station’s current altitude (A) in meters, and removes the effects of the altitude from the pressure. You can use the output of this function to directly compare your weather readings to other stations around the world. Determining Altitude Since pressure varies with altitude, you can use a pressure sensor to measure altitude (with a few caveats). The average pressure of the atmosphere at sea level is 1013.25 hPa (or mbar). This drops off to zero as you climb towards the vacuum of space. Because the curve of this drop-off is well understood, you can compute the altitude difference between two pressure measurements (p and p0) by using a specific equation. If you use sea level pressure (1013.25 hPa) as the baseline pressure (p0), the output of the equation will be your current altitude above sea level. There’s a function in the library called altitude(P, P0) that lets you get the “calculated altitude”. The above explanation was extracted from BMP 180 Sparkfun tutorial. As we could learn on the previous step, it is important to have on hand the Sea Level pressure, that is calculated once we have the real altitude where we are measuring the absolute pressure. The below function will help us with that: def bmp180GetData(altitude): temp = bmp180Sensor.read_temperature() pres = bmp180Sensor.read_pressure() alt = bmp180Sensor.read_altitude() presSeaLevel = pres / pow(1.0 - altitude/44330.0, 5.255) temp = round (temp, 1) pres = round (pres/100, 2) alt = round (alt) presSeaLevel = round (presSeaLevel/100, 2) return temp, pres, alt, presSeaLevel On my case, I have the BMP180 installed on a real measured altitude of 957 meters, so we can have the following updated data from sensors: On the next step, we will discuss how to get UV data from a very simple, but good analog sensor. The problem here is that the Raspberry Pi does not have analog input pins as an Arduino or NodeMCU, but we can overcome this problem by using an analog to digital (A/D) converter which will help in interfacing the analog sensors with the Raspberry Pi. The A/D converter that we will use on this project is the popular MCP3008. MCP3008 is a 10bit 8-channel ADC (Analog to Digital Converter) which use the SPI bus protocol for interfacing with Raspberry Pi. It is cheap and doesn’t require any additional components with it. It gives you 8 analog inputs and it uses just four GPIOs of Raspberry Pi, plus power and ground pins. MCP3008 output will be a range from 0–1,023 where 0 means 0V and 1,023 means 3.3V. MCP3008 Pinout The pin’s numbering of the MCP3008 starts from the top/left (Pin 1: CH0), having the half circle on top as you can see in the above pinout diagram. MCP3008 ADC has a total of 16 pins out of which 8 pins are for taking the analog input. The analog input pins are from CH0-CH7 (Pins 1–8). On the other side (pins 9–16), we have different functions as follows: 09 — DGND is a digital ground pin for the chip. 10 — CS is the chip select pin. Connected to RPi pin 24 (SPI0 — CE) 11 — DIN is the data input pin from the Raspberry Pi pin 19 (SPI0 — MOSI) 12 — DOUT is the data output pin. Connected to RPi pin 21 (SPI0 — MISO) 13 — CLK is the clock pin. Connected to RPi pin 23 (SPI0 — SCLK) 14 — AGND is the analog ground pin. 15 — VREF is the analog reference voltage. Connect to 3.3V. You can change it if you want to change the scale. 16 — VDD is the power pin for the chip. On this project, we will use Channel 0 (Pin 1) as the analog input. SPI The Raspberry Pi is equipped with one SPI bus that has 2 chip selects. The SPI master driver is disabled by default on Raspbian. To enable it, use raspi-config to confirm that SPI bus is enabled (the same procedure that was done before with 1-Wire). As a start, import spidev, a Linux driver to access the SPI bus: import spidev And open and configure the bus: spi = spidev.SpiDev()spi.open(0,0)spi.max_speed_hz=1000000 From there, you can access any of the analog channels of our ADC. For testing write the below function: def ReadChannel(channel): adc = spi.xfer2([1,(8+channel)<<4,0]) data = ((adc[1]&3) << 8) + adc[2] return data and, connect Channel 0 (MCP3008 pin 1) to 3.3V and run the function: ReadChannel(0) As a result, you should see: 1023 This UV sensor generates an analog output proportional to Ultra-Violet radiation found on the light-sensing spectrum. It uses a UV photodiode (based on Gallium Nitride), which can detect the 240–370nm range of light (which covers UVB and most of UVA spectrum). The signal level from the photodiode is very small, in the nano-ampere level, so the module has embedded an operational amplifier to amplify the signal to a more readable volt-level (0 to 1V). The sensor and op-amp can be powered, by connecting VCC to 3.3VDC and GND to power ground. The analog signal can be gotten from the OUT pin. Its output will be in millivolts and will be read by Analog Input (CH0) of ADC connected to our RPi. Using the same code shown in the last step, we can see the “raw data” generated by our UV sensor (in this case “43”): Having the raw sensor data, we should “convert” (or “ map”) it for values to be better handled by the code. We can do it with the function readSensorUV(). This function reads the UV sensor 3 times, taking the average and converting the measured value to mV: def readSensorUV(): numOfReadings = 3 dataSensorUV = 0 for i in range(numOfReadings): dataSensorUV += ReadChannel(0) time.sleep(0.2) dataSensorUV /= numOfReadings dataSensorUV = (dataSensorUV * (3.3 / 1023.0))*1000; return round(dataSensorUV) For example, a raw measurement of “43” is, in fact, equivalent to 128mV: If we look at the table and curve below: we will see that 128mV should be related to radiation between index 0 and 1. Let’s create a function to calculate this index that is the most common measurement of UV radiation. What we will do is consider a range, having the Vout shown at the above table as the start point, with a range of 110mV. For example, UV measurements between 227mV and 337mv will be considered Index 1. def indexCalculate(dataSensorUV): if dataSensorUV < 227: indexUV = 0 elif (227 <= dataSensorUV) & (dataSensorUV < 318): indexUV = 1 elif (318 <= dataSensorUV) & (dataSensorUV < 408): indexUV = 2 elif (408 <= dataSensorUV) & (dataSensorUV < 503): indexUV = 3 elif (503 <= dataSensorUV) & (dataSensorUV < 606): indexUV = 4 elif (606 <= dataSensorUV) & (dataSensorUV < 696): indexUV = 5 elif (696 <= dataSensorUV) & (dataSensorUV < 795): indexUV = 6 elif (795 <= dataSensorUV) & (dataSensorUV < 881): indexUV = 7 elif (881 <= dataSensorUV) & (dataSensorUV < 976): indexUV = 8 elif (976 <= dataSensorUV) & (dataSensorUV < 1079): indexUV = 9 elif (1079 <= dataSensorUV) & (dataSensorUV < 1170): indexUV =10 else: indexUV = 11 return indexUV So, for the previous measurement (128mV), the index should be 0. At this point, we have all the sensors installed and tested. Let’s now develop a function to capture all data at once: import datetimedef getSensorData(): global timeString global humLab global tempExt global tempLab global presSL global altLab global presAbs global UV_mV global UV_index now = datetime.datetime.now() timeString = now.strftime("%Y-%m-%d %H:%M") tempExt = round(ds18b20Sensor.get_temperature(), 1) tempLab, presAbs, altLab, presSL = bmp180GetData(altReal) humDHT, tempDHT = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin) if humDHT is not None and tempDHT is not None: humLab = round (humDHT) UV_mV = readSensorUV() UV_index = indexCalculate(UV_mV) Note that I have defined all sensors variables as global. You can keep them local, returning the values from the function (This is a better practice). At this point, you have all the tools to capture a lot of data from sensors. But what to do with them? The most simple answer is to create a single loop function to capture the data at regular bases, saving them on a local file. with open("/home/pi/rpi_weather_station.csv", "a") as log: while True: getSensorData() log.write("{},{},{},{},{},{},{},{},{}\n".format(timeString, humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)) time.sleep(30) The above code opens a file named “rpi_weather_station.csv” on your root directory. Every 30 seconds, the timestamp plus the data from all sensors will be “append” to this file, as you can see above. At this point, we have learned how to capture data from sensors, saving them on a local CSV file. Now, it is time to see how to send those data to an IoT platform. On this tutorial, we will use ThingSpeak.com. “ThingSpeak is an open source Internet of Things (IoT) application to store and retrieve data from things, using REST and MQTT APIs. ThingSpeak enables the creation of sensor logging applications, location tracking applications, and a social network of things with status updates.” First, you must have an account at ThinkSpeak.com. Next, follow the instructions to create a Channel, taking note of its Channel ID and Write API Key. When creating the channel, you must also define what info will be uploaded to each one of the 8 fields, as shown above. MQTT is a publish/subscribe architecture that was developed primarily to connect bandwidth and power-constrained devices over wireless networks. It is a simple and lightweight protocol that runs over TCP/IP sockets or WebSockets. MQTT over WebSockets can be secured with SSL. The publish/subscribe architecture enables messages to be pushed to the client devices without the device needing to continuously poll the server. The MQTT broker is the central point of communication, and it is in charge of dispatching all messages between the senders and the rightful receivers. A client is any device that connects to the broker and can publish or subscribe to topics to access the information. A topic contains routing information for the broker. Each client that wants to send messages publishes them to a certain topic, and each client that wants to receive messages subscribes to a certain topic. The broker delivers all messages with the matching topic to the appropriate clients. ThingSpeakTM has an MQTT broker at the URL mqtt.thingspeak.com and port 1883. The ThingSpeak broker supports both MQTT publish and MQTT subscribe. In our case, we will use the MQTT Publish. MQTT Publish For starting, let’s install the Eclipse Paho MQTT Python client library, that implements versions 3.1 and 3.1.1 of the MQTT protocol. sudo pip install paho-mqtt Next, let’s import the paho library: import paho.mqtt.publish as publish and initiate the Thingspeak channel and MQTT protocol. This connection method is the simplest and requires the least system resources: channelID = "YOUR CHANNEL ID"apiKey = "YOUR WRITE KEY"topic = "channels/" + channelID + "/publish/" + apiKeymqttHost = "mqtt.thingspeak.com"tTransport = "tcp"tPort = 1883tTLS = None Now, you must define the topic payload (”tPayload") to be upload to your IoT service: tPayload = “field1=” + str(humLab)+ “&field2=” + str(tempExt)+ “&field3=” + str(tempLab)+ “&field4=” + str(presSL)+ “&field5=” + str(altLab) + “&field6=” + str(presAbs)+ “&field7=” + str(UV_mV) + “&field8=” + str(UV_index) And send it: print ("[INFO] Data prepared to be uploaded")try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport) print ("[INFO] Data sent for 8 fields: ", humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)except: print ("[INFO] Failure in sending data") If everything is OK you will get an “Echo” of the data sent and on ThingSpeak channel page, you can see the data. ThingSpeak Channel uploaded data Now, that we know that with only a few lines of code it is possible to upload data to an IoT service, let’s create a loop function to do it automatically at a regular interval of time (similar to what we have done with “Logging Data Locally”). A simple code to continuously capture data, logging them on our channel would be: import timewhile(True): getSensorData() tPayload = "field1=" + str(humLab)+ "&field2=" + str(tempExt)+ "&field3=" + str(tempLab)+ "&field4=" + str(presSL)+ "&field5=" + str(altLab) + "&field6=" + str(presAbs)+ "&field7=" + str(UV_mV) + "&field8=" + str(UV_index) try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport) save_log() except (KeyboardInterrupt): break except: print ("[INFO] Failure in sending data") time.sleep(60) Looking for your ThingSpeak channel page, you will observe that the data will be loaded continuously to each field. The channel will automatically “log” those data for future analysis. A complete CSV file of the data could be also be downloaded from the site. We have included a function (save_Log()) to also log data locally on a CSV file: def save_log(): with open("/home/pi/rpi_weather_station.csv", "a") as log: log.write("{},{},{},{},{},{},{},{},{}\n".format(timeString, humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)) log.close() The complete Jupyter notebook that was used for development can be found here: Rpi_Weather_Station.ipynb. The logged data can be viewed directly on local saved CSV file, on ThingSpeak.com site or via an APP, for example, ThingsView! ThingView is an APP developed by CINETICA, that enables you to visualize your ThingSpeak channels in an easy way. Just enter the channel ID and you are ready to go. For public channels, the application will respect your windows settings: color, timescale, chart type and the number of results. The current version supports line and column charts, the spline charts are displayed as line charts. For private channels, the data will be displayed using the default settings, as there is no way to read the private windows settings with the API key only. The ThingView APP can be download for ANDROID and IPHONE. This Weather Station tutorial is part of a joint project developed with my friend Mauricio Pinto. Here, we learned how to capture several important data, related to weather, as Air Temperature and Humidity, Pressure and UV. Another very important data to be added to a Weather Station are Wind Speed and Direction. Mauricio did a great job, writing a very detailed tutorial, explained how to construct an Anemometer, mostly with recycled material. You can find his project on this 2 part tutorial: Part 1 — Construction of the devices Anemometer and Wind Vane Direction. Part 2 — The sketch using Arduino IDE for Esp8266 Nodemcu and transmission to ThingSpeak As Mauricio explained in his tutorial, the anemometer is a device capable of measuring the wind speed and its direction. Using a Hall Effect sensor he was able to count how many rotations the cups give on a period of time, being the intensity of the wind, proportional to the speed of rotation of the axis. With some simple physics equations, he could determine the linear velocity of the wind, at that moment. The wind direction was measured through a windshield with a neodymium magnet and reed switches. Here, you can see the anemometer installed in his house (that is located around 400 meters far from my Weather Station): The wind speed and direction are also sent to Thingspeak.com. As always, I hope this project can help others find their way into the exciting world of Electronics and Data Science! For details and final code, please visit my GitHub depository: RPi-Weather-Station For more projects, please visit my blog: MJRoBot.org Saludos from the south of the world! See you in my next article!
[ { "code": null, "e": 407, "s": 171, "text": "When we are talking about physical variables, as temperature, pressure, etc., as a Data Scientist, usually you start working from a dataset that was created somewhere else. But have you thought about how to capture those data yourself?" }, { "code": null, "e": 707, "s": 407, "text": "On this tutorial we will learn how to get data from several different sensors, sending them to an IoT service, ThingSpeak.com and to a mobile App (Thingsview), where we can log and play with data. We will also explore several different communication ways of connecting sensors to a Raspberry Pi, as:" }, { "code": null, "e": 760, "s": 707, "text": "DHT22 — Temperature & Humidity Sensor — Digital Comm" }, { "code": null, "e": 798, "s": 760, "text": "DS18B20 — Temperature Sensor — 1-Wire" }, { "code": null, "e": 843, "s": 798, "text": "BMP180 — Temperature & Pressure Sensor — I2C" }, { "code": null, "e": 904, "s": 843, "text": "UV — Ultra Violet Sensor — Analog Sensor via A/D and SPI bus" }, { "code": null, "e": 1072, "s": 904, "text": "In short, all data will be captured, saved locally on a CSV file and send to an IoT service (ThingSpeak.com), via MQTT protocol, as you can see on below block diagram:" }, { "code": null, "e": 1224, "s": 1072, "text": "To complete a real Weather Station, on the final step you will also learn how to measure wind speed and direction, following Mauricio Pinto’s tutorial." }, { "code": null, "e": 1240, "s": 1224, "text": "Raspberry Pi V3" }, { "code": null, "e": 1287, "s": 1240, "text": "DHT22 Temperature and Relative Humidity Sensor" }, { "code": null, "e": 1304, "s": 1287, "text": "Resistor 4K7 ohm" }, { "code": null, "e": 1342, "s": 1304, "text": "DS18B20 Waterproof Temperature Sensor" }, { "code": null, "e": 1359, "s": 1342, "text": "Resistor 4K7 ohm" }, { "code": null, "e": 1419, "s": 1359, "text": "BMP180 Barometric Pressure, Temperature and Altitude Sensor" }, { "code": null, "e": 1429, "s": 1419, "text": "UV Sensor" }, { "code": null, "e": 1486, "s": 1429, "text": "Adafruit MCP3008 8-Channel 10-Bit ADC With SPI Interface" }, { "code": null, "e": 1872, "s": 1486, "text": "Jupyter Notebook is a fantastic tool, or better, an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Jupyter notebook is largely used in Data Science, for cleaning and transforming data, doing numerical simulation, statistical modeling, data visualization, machine learning, and much more!" }, { "code": null, "e": 2015, "s": 1872, "text": "On this tutorial, we will use Jupyter Notebook to interact with Raspberry Pi GPIOs, directly reading sensors and sending data to the internet." }, { "code": null, "e": 2028, "s": 2015, "text": "Installation" }, { "code": null, "e": 2106, "s": 2028, "text": "You may skip this step if already have Jupyter Notebook installed on your RPi" }, { "code": null, "e": 2223, "s": 2106, "text": "To install Jupyter on your Raspberry (that will run with Python 3), open Terminal and enter with following commands:" }, { "code": null, "e": 2286, "s": 2223, "text": "sudo pip3 install jupytersudo ipython3 kernelspec install-self" }, { "code": null, "e": 2325, "s": 2286, "text": "Now on your terminal, run the command:" }, { "code": null, "e": 2342, "s": 2325, "text": "jupyter notebook" }, { "code": null, "e": 2444, "s": 2342, "text": "And that’s it!!!! Amazing! very simple and easy. The Jupyter Notebook will be running as a server on:" }, { "code": null, "e": 2464, "s": 2444, "text": "http:localhost:8888" }, { "code": null, "e": 2600, "s": 2464, "text": "Note that your default browser will be automatically opened on the above address, running as a “Home Page”, as shown at above pictures." }, { "code": null, "e": 2714, "s": 2600, "text": "To stop the server and close the “kernels” (the Jupyter notebooks), you must use [Ctrl] + [C] from your keyboard." }, { "code": null, "e": 2911, "s": 2714, "text": "From now one, any time that you start your Pi and want to use Jupyter Notebook, just type the command: “Jupyter notebook” on your terminal and keep it running all the time. This is very important!" }, { "code": null, "e": 3019, "s": 2911, "text": "If you need to use the terminal for another task as run a program, for example, open a new Terminal window." }, { "code": null, "e": 3159, "s": 3019, "text": "You can follow this tutorial step by step, creating your own Notebook, or download the final one from my GitHub: Rpi_Weather_Station.ipynb." }, { "code": null, "e": 3380, "s": 3159, "text": "The first sensor to be installed will be the DHT22 for capturing air temperature and relative humidity data. The ADAFRUIT siteprovides great information about those sensors. Bellow, some information retrieved from there:" }, { "code": null, "e": 3389, "s": 3380, "text": "Overview" }, { "code": null, "e": 3837, "s": 3389, "text": "The low-cost DHT temperature & humidity sensors are very basic and slow but are great for hobbyists who want to do some basic data logging. The DHT sensors are made of two parts, a capacitive humidity sensor, and a thermistor. There is also a very basic chip inside that does some analog to digital conversion and spits out a digital signal with the temperature and humidity. The digital signal is fairly easy to be read using any microcontroller." }, { "code": null, "e": 3865, "s": 3837, "text": "DHT22 Main characteristics:" }, { "code": null, "e": 4034, "s": 3865, "text": "Good for 0–100% humidity readings with 2–5% accuracy Good for -40 to 125°C temperature readings ±0.5°C accuracy No more than 0.5 Hz sampling rate (once every 2 seconds)" }, { "code": null, "e": 4043, "s": 4034, "text": "Low cost" }, { "code": null, "e": 4065, "s": 4043, "text": "3 to 5V power and I/O" }, { "code": null, "e": 4129, "s": 4065, "text": "2.5mA max current use during conversion (while requesting data)" }, { "code": null, "e": 4161, "s": 4129, "text": "Body size 15.1mm x 25mm x 7.7mm" }, { "code": null, "e": 4186, "s": 4161, "text": "4 pins with 0.1\" spacing" }, { "code": null, "e": 4463, "s": 4186, "text": "Once usually you will use the sensor on distances less than 20m, a 4K7 ohm resistor should be connected between Data and VCC pins. The DHT22 output data pin will be connected to Raspberry GPIO 16. Check the above electrical diagram, connecting the sensor to RPi pins as below:" }, { "code": null, "e": 4484, "s": 4463, "text": "Pin 1 — Vcc ==> 3.3V" }, { "code": null, "e": 4509, "s": 4484, "text": "Pin 2 — Data ==> GPIO 16" }, { "code": null, "e": 4529, "s": 4509, "text": "Pin 3 — Not Connect" }, { "code": null, "e": 4549, "s": 4529, "text": "Pin 4 — Gnd ==> Gnd" }, { "code": null, "e": 4621, "s": 4549, "text": "Do not forget to Install the 4K7 ohm resistor between Vcc and Data pins" }, { "code": null, "e": 4696, "s": 4621, "text": "Once the sensor is connected, we must also install its library on our RPi." }, { "code": null, "e": 4720, "s": 4696, "text": "Installing DHT Library:" }, { "code": null, "e": 4775, "s": 4720, "text": "On your Raspberry, starting on /home, go to /Documents" }, { "code": null, "e": 4788, "s": 4775, "text": "cd Documents" }, { "code": null, "e": 4849, "s": 4788, "text": "Create a directory to install the library and move to there:" }, { "code": null, "e": 4883, "s": 4849, "text": "mkdir DHT22_Sensorcd DHT22_Sensor" }, { "code": null, "e": 4923, "s": 4883, "text": "On your browser, go to Adafruit GitHub:" }, { "code": null, "e": 4934, "s": 4923, "text": "github.com" }, { "code": null, "e": 5205, "s": 4934, "text": "Download the library by clicking the download zip link to the right and unzip the archive on your Raspberry Pi recently created folder. Then go to the directory of the library (subfolder that is automatically created when you unzipped the file), and execute the command:" }, { "code": null, "e": 5235, "s": 5205, "text": "sudo python3 setup.py install" }, { "code": null, "e": 5393, "s": 5235, "text": "On The Jupyter Notebook, Import Adafrut DHT Library, define the digital pin to connect the DHT with RPi and run the code to capture temperature and humidity:" }, { "code": null, "e": 5623, "s": 5393, "text": "import Adafruit_DHTDHT22Sensor = Adafruit_DHT.DHT22DHTpin = 16humDHT, tempDHT = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin)if (humDHT is not None) and (tempDHT is not None): hum = round (humDHT,1) temp = round (tempDHT, 1)" }, { "code": null, "e": 5659, "s": 5623, "text": "Run the Cell and print the results:" }, { "code": null, "e": 5720, "s": 5659, "text": "print(‘Temperature = {}*C Humidity = {}%’.format(temp, hum))" }, { "code": null, "e": 5779, "s": 5720, "text": "Below, the portion of Jupyter Notebook showing the result:" }, { "code": null, "e": 5796, "s": 5779, "text": "Sensor Overview:" }, { "code": null, "e": 6105, "s": 5796, "text": "We will use in this tutorial a waterproofed version of the DS18B20 sensor. It is very useful for for capturing temperature in wet conditions, for example on humid soil. The sensor is isolated and can take measurements until 125oC (Adafrut does not recommend to use it over 100oC due to its cable PVC jacket)." }, { "code": null, "e": 6560, "s": 6105, "text": "The DS18B20 is a digital sensor what makes it good to use even over long distances! These 1-wire digital temperature sensors are fairly precise (±0.5°C over much of the range) and can give up to 12 bits of precision from the onboard digital-to-analog converter. They work great with the RPi using a single digital pin, and you can even connect multiple ones to the same pin, each one has a unique 64-bit ID burned in at the factory to differentiate them." }, { "code": null, "e": 6702, "s": 6560, "text": "The sensor works from 3.0 to 5.0V, which means that it can be powered directly from the 3.3V provided by one of the Raspberry pins (1 or 17)." }, { "code": null, "e": 6726, "s": 6702, "text": "The sensor has 3 wires:" }, { "code": null, "e": 6737, "s": 6726, "text": "Black: GND" }, { "code": null, "e": 6746, "s": 6737, "text": "Red: VCC" }, { "code": null, "e": 6766, "s": 6746, "text": "Yellow: 1-Wire Data" }, { "code": null, "e": 6818, "s": 6766, "text": "Here, you can find the full data: DS18B20 Datasheet" }, { "code": null, "e": 6839, "s": 6818, "text": "Sensor Installation:" }, { "code": null, "e": 6890, "s": 6839, "text": "Follow the above diagram and make the connections:" }, { "code": null, "e": 6903, "s": 6890, "text": "Vcc ==> 3.3V" }, { "code": null, "e": 6915, "s": 6903, "text": "Gnd ==> Gnd" }, { "code": null, "e": 6953, "s": 6915, "text": "Data ==> GPIO 4 (default for library)" }, { "code": null, "e": 6984, "s": 6953, "text": "Installing the Python Library:" }, { "code": null, "e": 7052, "s": 6984, "text": "Next, let’s install the Python library that will handle the sensor:" }, { "code": null, "e": 7084, "s": 7052, "text": "sudo pip3 install w1thermsensor" }, { "code": null, "e": 7210, "s": 7084, "text": "Before running the script to test the sensor, check if the “1-Wire” interface is enabled in your RPi (see below print screen)" }, { "code": null, "e": 7228, "s": 7210, "text": "Enable Interfaces" }, { "code": null, "e": 7297, "s": 7228, "text": "Do not forget to restart your RPi, after changeing its configuration" }, { "code": null, "e": 7317, "s": 7297, "text": "Testing the sensor:" }, { "code": null, "e": 7374, "s": 7317, "text": "For testing the sensor a simple python code can be used:" }, { "code": null, "e": 7548, "s": 7374, "text": "from w1thermsensor import W1ThermSensords18b20Sensor = W1ThermSensor()tempExt = round(ds18b20Sensor.get_temperature(), 1)print('External Temperature = {}*C'.format(tempExt))" }, { "code": null, "e": 7607, "s": 7548, "text": "Below, the portion of Jupyter Notebook showing the result:" }, { "code": null, "e": 7624, "s": 7607, "text": "Sensor Overview:" }, { "code": null, "e": 8219, "s": 7624, "text": "The BMP180 is the successor of the BMP085, a new generation of high precision digital pressure sensors for consumer applications. The ultra-low power, low voltage electronics of the BMP180 is optimized for use in mobile phones, PDAs, GPS navigation devices and outdoor equipment. With a low altitude noise of merely 0.25m at fast conversion time, the BMP180 offers superior performance. The I2C interface allows for easy system integration with a microcontroller. The BMP180 is based on piezo-resistive technology for EMC robustness, high accuracy, and linearity as well as long-term stability." }, { "code": null, "e": 8298, "s": 8219, "text": "The complete BMP datasheet can be found here: BMP180 — Digital Pressure Sensor" }, { "code": null, "e": 8319, "s": 8298, "text": "Sensor Installation:" }, { "code": null, "e": 8370, "s": 8319, "text": "Follow the above diagram and make the connections:" }, { "code": null, "e": 8383, "s": 8370, "text": "Vin ==> 3.3V" }, { "code": null, "e": 8395, "s": 8383, "text": "GND ==> GND" }, { "code": null, "e": 8410, "s": 8395, "text": "SCL ==> GPIO 3" }, { "code": null, "e": 8425, "s": 8410, "text": "SDA ==> GPIO 2" }, { "code": null, "e": 8448, "s": 8425, "text": "Enabling I2C Interface" }, { "code": null, "e": 8554, "s": 8448, "text": "Go to RPi Configuration and confirm that I2C interface is enabled. If not, enable it and restart the RPi." }, { "code": null, "e": 8571, "s": 8554, "text": "Using the BMP180" }, { "code": null, "e": 8737, "s": 8571, "text": "If everything has been installed and connected okay, you are now ready to turn on your Pi and start seeing what the BMP180 is telling you about the world around you." }, { "code": null, "e": 8839, "s": 8737, "text": "The first thing to do is to check if the Pi sees your BMP180. Try the following in a terminal window:" }, { "code": null, "e": 8859, "s": 8839, "text": "sudo i2cdetect -y 1" }, { "code": null, "e": 8994, "s": 8859, "text": "If the command worked, you should see something similar to the below Terminal Printscreen, showing that the BMP180 is on channel ‘77’." }, { "code": null, "e": 9025, "s": 8994, "text": "Installing the BMP180 Library:" }, { "code": null, "e": 9081, "s": 9025, "text": "Create a directory to install the library and go there:" }, { "code": null, "e": 9117, "s": 9081, "text": "mkdir BMP180_Sensorcd BMP180_Sensor" }, { "code": null, "e": 9157, "s": 9117, "text": "On your browser, go to Adafruit GITHub:" }, { "code": null, "e": 9168, "s": 9157, "text": "github.com" }, { "code": null, "e": 9395, "s": 9168, "text": "Download the library by clicking the download zip link to the right and unzip the archive on your Raspberry Pi created folder. Then go to the created subfolder and execute the following command in the directory of the library:" }, { "code": null, "e": 9425, "s": 9395, "text": "sudo python3 setup.py install" }, { "code": null, "e": 9463, "s": 9425, "text": "On Jupyter, write the following code:" }, { "code": null, "e": 9680, "s": 9463, "text": "import Adafruit_BMP.BMP085 as BMP085bmp180Sensor = BMP085.BMP085()tempBMP = round(bmp180Sensor.read_temperature(), 1)presBMP = round(bmp180Sensor.read_pressure()/100, 1)altBMP = round(bmp180Sensor.read_altitude(),1)" }, { "code": null, "e": 9737, "s": 9680, "text": "Check the variables read by the sensor with bellow code:" }, { "code": null, "e": 9876, "s": 9737, "text": "print ('Temperature = {} C '.format(tempBMP))print ('Pressure = {} hPa [or mbar]'.format(presBMP))print ('Altitud = {} m '.format(altBMP))" }, { "code": null, "e": 9934, "s": 9876, "text": "Below, the portion of Jupyter Notebook showing the result" }, { "code": null, "e": 10046, "s": 9934, "text": "Note that the sensor pressure is presented in Pa (Pascals). See next step to better understand about this unit." }, { "code": null, "e": 10065, "s": 10046, "text": "Sea Level Pressure" }, { "code": null, "e": 10162, "s": 10065, "text": "Let’s take a time to understand a little bit more about what we will get, with the BMP readings." }, { "code": null, "e": 10358, "s": 10162, "text": "You can skip this part of the tutorial, or return later, and if you want to know more about Sensor readings, please go to this great tutorial:https://learn.sparkfun.com/tutorials/bmp180-barome..." }, { "code": null, "e": 10486, "s": 10358, "text": "The BMP180 was designed to accurately measure atmospheric pressure. Atmospheric pressure varies with both weather and altitude." }, { "code": null, "e": 10516, "s": 10486, "text": "What is Atmospheric Pressure?" }, { "code": null, "e": 10862, "s": 10516, "text": "The definition of atmospheric pressure is a force that the air around you is exerting on everything. The weight of the gasses in the atmosphere creates atmospheric pressure. A common unit of pressure is “pounds per square inch” or psi. We will use here the international notation, that is newtons per square meter, which are called pascals (Pa)." }, { "code": null, "e": 10921, "s": 10862, "text": "If you took 1 cm wide column of air would weigh about 1 kg" }, { "code": null, "e": 11570, "s": 10921, "text": "This weight, pressing down on the footprint of that column, creates the atmospheric pressure that we can measure with sensors like the BMP180. Because that cm-wide column of air weighs about 1Kg, it follows that the average sea level pressure is about 101325 pascals, or better, 1013.25 hPa (1 hPa is also known as milibar — mbar). This will drop by about 4% for every 300 meters you ascend. The higher you get, the less pressure you’ll see, because the column to the top of the atmosphere is that much shorter and therefore weighs less. This is useful to know because by measuring the pressure and doing some math, you can determine your altitude." }, { "code": null, "e": 11639, "s": 11570, "text": "The air pressure at 3, 810 meters is only half of that at sea level." }, { "code": null, "e": 12007, "s": 11639, "text": "The BMP180 outputs absolute pressure in pascals (Pa). One pascal is a very small amount of pressure, approximately the amount that a sheet of paper will exert resting on a table. You will more often see measurements in hectopascals (1 hPa = 100 Pa). The library used here provides outputs floating-point values in hPa, which also happens to equal one millibar (mbar)." }, { "code": null, "e": 12058, "s": 12007, "text": "Here are some conversions to other pressure units:" }, { "code": null, "e": 12094, "s": 12058, "text": "1 hPa = 100 Pa = 1 mbar = 0.001 bar" }, { "code": null, "e": 12118, "s": 12094, "text": "1 hPa = 0.75006168 Torr" }, { "code": null, "e": 12166, "s": 12118, "text": "1 hPa = 0.01450377 psi (pounds per square inch)" }, { "code": null, "e": 12210, "s": 12166, "text": "1 hPa = 0.02953337 inHg (inches of mercury)" }, { "code": null, "e": 12256, "s": 12210, "text": "1 hpa = 0.00098692 atm (standard atmospheres)" }, { "code": null, "e": 12276, "s": 12256, "text": "Temperature Effects" }, { "code": null, "e": 12748, "s": 12276, "text": "Because temperature affects the density of a gas, and density affects the mass of a gas, and mass affects the pressure (whew), atmospheric pressure will change dramatically with temperature. Pilots know this as “density altitude”, which makes it easier to take off on a cold day than a hot one because the air is denser and has a greater aerodynamic effect. To compensate for temperature, the BMP180 includes a rather good temperature sensor as well as a pressure sensor." }, { "code": null, "e": 12976, "s": 12748, "text": "To perform a pressure reading, you first take a temperature reading, then combine that with a raw pressure reading to come up with a final temperature-compensated pressure measurement. (The library makes all of this very easy.)" }, { "code": null, "e": 13004, "s": 12976, "text": "Measuring Absolute Pressure" }, { "code": null, "e": 13321, "s": 13004, "text": "If your application requires measuring absolute pressure, all you have to do is get a temperature reading, then perform a pressure reading (see the example sketch for details). The final pressure reading will be in hPa = mbar. If you wish, you can convert this to a different unit using the above conversion factors." }, { "code": null, "e": 13483, "s": 13321, "text": "Note that the absolute pressure of the atmosphere will vary with both your altitude and the current weather patterns, both of which are useful things to measure." }, { "code": null, "e": 13504, "s": 13483, "text": "Weather Observations" }, { "code": null, "e": 14631, "s": 13504, "text": "The atmospheric pressure at any given location on earth (or anywhere with an atmosphere) isn’t constant. The complex interaction between the earth’s spin, axis tilt, and many other factors result in moving areas of higher and lower pressure, which in turn cause the variations in weather we see every day. By watching for changes in pressure, you can predict short-term changes in the weather. For example, dropping pressure usually means wet weather or a storm is approaching (a low-pressure system is moving in). Rising pressure usually means that clear weather is approaching (a high-pressure system is moving through). But remember that atmospheric pressure also varies with altitude. The absolute pressure in my house, Lo Barnechea in Chile (altitude 950m) will always be lower than the absolute pressure in San Francisco for example (less than 2 meters, almost sea level). If weather stations just reported their absolute pressure, it would be difficult to directly compare pressure measurements from one location to another (and large-scale weather predictions depend on measurements from as many stations as possible)." }, { "code": null, "e": 15005, "s": 14631, "text": "To solve this problem, weather stations always remove the effects of altitude from their reported pressure readings by mathematically adding the equivalent fixed pressure to make it appear as if the reading was taken at sea level. When you do this, a higher reading in San Francisco than Lo Barnechea will always be because of weather patterns, and not because of altitude." }, { "code": null, "e": 15348, "s": 15005, "text": "To do this, there is a function in the library called sea level(P, A). This takes the absolute pressure (P) in hPa, and the station’s current altitude (A) in meters, and removes the effects of the altitude from the pressure. You can use the output of this function to directly compare your weather readings to other stations around the world." }, { "code": null, "e": 15369, "s": 15348, "text": "Determining Altitude" }, { "code": null, "e": 15791, "s": 15369, "text": "Since pressure varies with altitude, you can use a pressure sensor to measure altitude (with a few caveats). The average pressure of the atmosphere at sea level is 1013.25 hPa (or mbar). This drops off to zero as you climb towards the vacuum of space. Because the curve of this drop-off is well understood, you can compute the altitude difference between two pressure measurements (p and p0) by using a specific equation." }, { "code": null, "e": 16042, "s": 15791, "text": "If you use sea level pressure (1013.25 hPa) as the baseline pressure (p0), the output of the equation will be your current altitude above sea level. There’s a function in the library called altitude(P, P0) that lets you get the “calculated altitude”." }, { "code": null, "e": 16110, "s": 16042, "text": "The above explanation was extracted from BMP 180 Sparkfun tutorial." }, { "code": null, "e": 16345, "s": 16110, "text": "As we could learn on the previous step, it is important to have on hand the Sea Level pressure, that is calculated once we have the real altitude where we are measuring the absolute pressure. The below function will help us with that:" }, { "code": null, "e": 16722, "s": 16345, "text": "def bmp180GetData(altitude): temp = bmp180Sensor.read_temperature() pres = bmp180Sensor.read_pressure() alt = bmp180Sensor.read_altitude() presSeaLevel = pres / pow(1.0 - altitude/44330.0, 5.255) temp = round (temp, 1) pres = round (pres/100, 2) alt = round (alt) presSeaLevel = round (presSeaLevel/100, 2) return temp, pres, alt, presSeaLevel" }, { "code": null, "e": 16861, "s": 16722, "text": "On my case, I have the BMP180 installed on a real measured altitude of 957 meters, so we can have the following updated data from sensors:" }, { "code": null, "e": 17285, "s": 16861, "text": "On the next step, we will discuss how to get UV data from a very simple, but good analog sensor. The problem here is that the Raspberry Pi does not have analog input pins as an Arduino or NodeMCU, but we can overcome this problem by using an analog to digital (A/D) converter which will help in interfacing the analog sensors with the Raspberry Pi. The A/D converter that we will use on this project is the popular MCP3008." }, { "code": null, "e": 17666, "s": 17285, "text": "MCP3008 is a 10bit 8-channel ADC (Analog to Digital Converter) which use the SPI bus protocol for interfacing with Raspberry Pi. It is cheap and doesn’t require any additional components with it. It gives you 8 analog inputs and it uses just four GPIOs of Raspberry Pi, plus power and ground pins. MCP3008 output will be a range from 0–1,023 where 0 means 0V and 1,023 means 3.3V." }, { "code": null, "e": 17681, "s": 17666, "text": "MCP3008 Pinout" }, { "code": null, "e": 18039, "s": 17681, "text": "The pin’s numbering of the MCP3008 starts from the top/left (Pin 1: CH0), having the half circle on top as you can see in the above pinout diagram. MCP3008 ADC has a total of 16 pins out of which 8 pins are for taking the analog input. The analog input pins are from CH0-CH7 (Pins 1–8). On the other side (pins 9–16), we have different functions as follows:" }, { "code": null, "e": 18087, "s": 18039, "text": "09 — DGND is a digital ground pin for the chip." }, { "code": null, "e": 18155, "s": 18087, "text": "10 — CS is the chip select pin. Connected to RPi pin 24 (SPI0 — CE)" }, { "code": null, "e": 18229, "s": 18155, "text": "11 — DIN is the data input pin from the Raspberry Pi pin 19 (SPI0 — MOSI)" }, { "code": null, "e": 18301, "s": 18229, "text": "12 — DOUT is the data output pin. Connected to RPi pin 21 (SPI0 — MISO)" }, { "code": null, "e": 18366, "s": 18301, "text": "13 — CLK is the clock pin. Connected to RPi pin 23 (SPI0 — SCLK)" }, { "code": null, "e": 18402, "s": 18366, "text": "14 — AGND is the analog ground pin." }, { "code": null, "e": 18553, "s": 18402, "text": "15 — VREF is the analog reference voltage. Connect to 3.3V. You can change it if you want to change the scale. 16 — VDD is the power pin for the chip." }, { "code": null, "e": 18621, "s": 18553, "text": "On this project, we will use Channel 0 (Pin 1) as the analog input." }, { "code": null, "e": 18625, "s": 18621, "text": "SPI" }, { "code": null, "e": 18875, "s": 18625, "text": "The Raspberry Pi is equipped with one SPI bus that has 2 chip selects. The SPI master driver is disabled by default on Raspbian. To enable it, use raspi-config to confirm that SPI bus is enabled (the same procedure that was done before with 1-Wire)." }, { "code": null, "e": 18940, "s": 18875, "text": "As a start, import spidev, a Linux driver to access the SPI bus:" }, { "code": null, "e": 18954, "s": 18940, "text": "import spidev" }, { "code": null, "e": 18986, "s": 18954, "text": "And open and configure the bus:" }, { "code": null, "e": 19045, "s": 18986, "text": "spi = spidev.SpiDev()spi.open(0,0)spi.max_speed_hz=1000000" }, { "code": null, "e": 19149, "s": 19045, "text": "From there, you can access any of the analog channels of our ADC. For testing write the below function:" }, { "code": null, "e": 19268, "s": 19149, "text": "def ReadChannel(channel): adc = spi.xfer2([1,(8+channel)<<4,0]) data = ((adc[1]&3) << 8) + adc[2] return data" }, { "code": null, "e": 19337, "s": 19268, "text": "and, connect Channel 0 (MCP3008 pin 1) to 3.3V and run the function:" }, { "code": null, "e": 19352, "s": 19337, "text": "ReadChannel(0)" }, { "code": null, "e": 19386, "s": 19352, "text": "As a result, you should see: 1023" }, { "code": null, "e": 19840, "s": 19386, "text": "This UV sensor generates an analog output proportional to Ultra-Violet radiation found on the light-sensing spectrum. It uses a UV photodiode (based on Gallium Nitride), which can detect the 240–370nm range of light (which covers UVB and most of UVA spectrum). The signal level from the photodiode is very small, in the nano-ampere level, so the module has embedded an operational amplifier to amplify the signal to a more readable volt-level (0 to 1V)." }, { "code": null, "e": 20082, "s": 19840, "text": "The sensor and op-amp can be powered, by connecting VCC to 3.3VDC and GND to power ground. The analog signal can be gotten from the OUT pin. Its output will be in millivolts and will be read by Analog Input (CH0) of ADC connected to our RPi." }, { "code": null, "e": 20200, "s": 20082, "text": "Using the same code shown in the last step, we can see the “raw data” generated by our UV sensor (in this case “43”):" }, { "code": null, "e": 20458, "s": 20200, "text": "Having the raw sensor data, we should “convert” (or “ map”) it for values to be better handled by the code. We can do it with the function readSensorUV(). This function reads the UV sensor 3 times, taking the average and converting the measured value to mV:" }, { "code": null, "e": 20733, "s": 20458, "text": "def readSensorUV(): numOfReadings = 3 dataSensorUV = 0 for i in range(numOfReadings): dataSensorUV += ReadChannel(0) time.sleep(0.2) dataSensorUV /= numOfReadings dataSensorUV = (dataSensorUV * (3.3 / 1023.0))*1000; return round(dataSensorUV)" }, { "code": null, "e": 20806, "s": 20733, "text": "For example, a raw measurement of “43” is, in fact, equivalent to 128mV:" }, { "code": null, "e": 20847, "s": 20806, "text": "If we look at the table and curve below:" }, { "code": null, "e": 21227, "s": 20847, "text": "we will see that 128mV should be related to radiation between index 0 and 1. Let’s create a function to calculate this index that is the most common measurement of UV radiation. What we will do is consider a range, having the Vout shown at the above table as the start point, with a range of 110mV. For example, UV measurements between 227mV and 337mv will be considered Index 1." }, { "code": null, "e": 22002, "s": 21227, "text": "def indexCalculate(dataSensorUV): if dataSensorUV < 227: indexUV = 0 elif (227 <= dataSensorUV) & (dataSensorUV < 318): indexUV = 1 elif (318 <= dataSensorUV) & (dataSensorUV < 408): indexUV = 2 elif (408 <= dataSensorUV) & (dataSensorUV < 503): indexUV = 3 elif (503 <= dataSensorUV) & (dataSensorUV < 606): indexUV = 4 elif (606 <= dataSensorUV) & (dataSensorUV < 696): indexUV = 5 elif (696 <= dataSensorUV) & (dataSensorUV < 795): indexUV = 6 elif (795 <= dataSensorUV) & (dataSensorUV < 881): indexUV = 7 elif (881 <= dataSensorUV) & (dataSensorUV < 976): indexUV = 8 elif (976 <= dataSensorUV) & (dataSensorUV < 1079): indexUV = 9 elif (1079 <= dataSensorUV) & (dataSensorUV < 1170): indexUV =10 else: indexUV = 11 return indexUV" }, { "code": null, "e": 22067, "s": 22002, "text": "So, for the previous measurement (128mV), the index should be 0." }, { "code": null, "e": 22186, "s": 22067, "text": "At this point, we have all the sensors installed and tested. Let’s now develop a function to capture all data at once:" }, { "code": null, "e": 22788, "s": 22186, "text": "import datetimedef getSensorData(): global timeString global humLab global tempExt global tempLab global presSL global altLab global presAbs global UV_mV global UV_index now = datetime.datetime.now() timeString = now.strftime(\"%Y-%m-%d %H:%M\") tempExt = round(ds18b20Sensor.get_temperature(), 1) tempLab, presAbs, altLab, presSL = bmp180GetData(altReal) humDHT, tempDHT = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin) if humDHT is not None and tempDHT is not None: humLab = round (humDHT) UV_mV = readSensorUV() UV_index = indexCalculate(UV_mV)" }, { "code": null, "e": 22939, "s": 22788, "text": "Note that I have defined all sensors variables as global. You can keep them local, returning the values from the function (This is a better practice)." }, { "code": null, "e": 23042, "s": 22939, "text": "At this point, you have all the tools to capture a lot of data from sensors. But what to do with them?" }, { "code": null, "e": 23168, "s": 23042, "text": "The most simple answer is to create a single loop function to capture the data at regular bases, saving them on a local file." }, { "code": null, "e": 23423, "s": 23168, "text": "with open(\"/home/pi/rpi_weather_station.csv\", \"a\") as log: while True: getSensorData() log.write(\"{},{},{},{},{},{},{},{},{}\\n\".format(timeString, humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)) time.sleep(30)" }, { "code": null, "e": 23507, "s": 23423, "text": "The above code opens a file named “rpi_weather_station.csv” on your root directory." }, { "code": null, "e": 23623, "s": 23507, "text": "Every 30 seconds, the timestamp plus the data from all sensors will be “append” to this file, as you can see above." }, { "code": null, "e": 23833, "s": 23623, "text": "At this point, we have learned how to capture data from sensors, saving them on a local CSV file. Now, it is time to see how to send those data to an IoT platform. On this tutorial, we will use ThingSpeak.com." }, { "code": null, "e": 24115, "s": 23833, "text": "“ThingSpeak is an open source Internet of Things (IoT) application to store and retrieve data from things, using REST and MQTT APIs. ThingSpeak enables the creation of sensor logging applications, location tracking applications, and a social network of things with status updates.”" }, { "code": null, "e": 24266, "s": 24115, "text": "First, you must have an account at ThinkSpeak.com. Next, follow the instructions to create a Channel, taking note of its Channel ID and Write API Key." }, { "code": null, "e": 24386, "s": 24266, "text": "When creating the channel, you must also define what info will be uploaded to each one of the 8 fields, as shown above." }, { "code": null, "e": 24809, "s": 24386, "text": "MQTT is a publish/subscribe architecture that was developed primarily to connect bandwidth and power-constrained devices over wireless networks. It is a simple and lightweight protocol that runs over TCP/IP sockets or WebSockets. MQTT over WebSockets can be secured with SSL. The publish/subscribe architecture enables messages to be pushed to the client devices without the device needing to continuously poll the server." }, { "code": null, "e": 25368, "s": 24809, "text": "The MQTT broker is the central point of communication, and it is in charge of dispatching all messages between the senders and the rightful receivers. A client is any device that connects to the broker and can publish or subscribe to topics to access the information. A topic contains routing information for the broker. Each client that wants to send messages publishes them to a certain topic, and each client that wants to receive messages subscribes to a certain topic. The broker delivers all messages with the matching topic to the appropriate clients." }, { "code": null, "e": 25515, "s": 25368, "text": "ThingSpeakTM has an MQTT broker at the URL mqtt.thingspeak.com and port 1883. The ThingSpeak broker supports both MQTT publish and MQTT subscribe." }, { "code": null, "e": 25558, "s": 25515, "text": "In our case, we will use the MQTT Publish." }, { "code": null, "e": 25571, "s": 25558, "text": "MQTT Publish" }, { "code": null, "e": 25705, "s": 25571, "text": "For starting, let’s install the Eclipse Paho MQTT Python client library, that implements versions 3.1 and 3.1.1 of the MQTT protocol." }, { "code": null, "e": 25732, "s": 25705, "text": "sudo pip install paho-mqtt" }, { "code": null, "e": 25769, "s": 25732, "text": "Next, let’s import the paho library:" }, { "code": null, "e": 25805, "s": 25769, "text": "import paho.mqtt.publish as publish" }, { "code": null, "e": 25940, "s": 25805, "text": "and initiate the Thingspeak channel and MQTT protocol. This connection method is the simplest and requires the least system resources:" }, { "code": null, "e": 26122, "s": 25940, "text": "channelID = \"YOUR CHANNEL ID\"apiKey = \"YOUR WRITE KEY\"topic = \"channels/\" + channelID + \"/publish/\" + apiKeymqttHost = \"mqtt.thingspeak.com\"tTransport = \"tcp\"tPort = 1883tTLS = None" }, { "code": null, "e": 26208, "s": 26122, "text": "Now, you must define the topic payload (”tPayload\") to be upload to your IoT service:" }, { "code": null, "e": 26431, "s": 26208, "text": "tPayload = “field1=” + str(humLab)+ “&field2=” + str(tempExt)+ “&field3=” + str(tempLab)+ “&field4=” + str(presSL)+ “&field5=” + str(altLab) + “&field6=” + str(presAbs)+ “&field7=” + str(UV_mV) + “&field8=” + str(UV_index)" }, { "code": null, "e": 26444, "s": 26431, "text": "And send it:" }, { "code": null, "e": 26764, "s": 26444, "text": "print (\"[INFO] Data prepared to be uploaded\")try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport) print (\"[INFO] Data sent for 8 fields: \", humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)except: print (\"[INFO] Failure in sending data\")" }, { "code": null, "e": 26878, "s": 26764, "text": "If everything is OK you will get an “Echo” of the data sent and on ThingSpeak channel page, you can see the data." }, { "code": null, "e": 26911, "s": 26878, "text": "ThingSpeak Channel uploaded data" }, { "code": null, "e": 27155, "s": 26911, "text": "Now, that we know that with only a few lines of code it is possible to upload data to an IoT service, let’s create a loop function to do it automatically at a regular interval of time (similar to what we have done with “Logging Data Locally”)." }, { "code": null, "e": 27237, "s": 27155, "text": "A simple code to continuously capture data, logging them on our channel would be:" }, { "code": null, "e": 27771, "s": 27237, "text": "import timewhile(True): getSensorData() tPayload = \"field1=\" + str(humLab)+ \"&field2=\" + str(tempExt)+ \"&field3=\" + str(tempLab)+ \"&field4=\" + str(presSL)+ \"&field5=\" + str(altLab) + \"&field6=\" + str(presAbs)+ \"&field7=\" + str(UV_mV) + \"&field8=\" + str(UV_index) try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport) save_log() except (KeyboardInterrupt): break except: print (\"[INFO] Failure in sending data\") time.sleep(60)" }, { "code": null, "e": 28031, "s": 27771, "text": "Looking for your ThingSpeak channel page, you will observe that the data will be loaded continuously to each field. The channel will automatically “log” those data for future analysis. A complete CSV file of the data could be also be downloaded from the site." }, { "code": null, "e": 28112, "s": 28031, "text": "We have included a function (save_Log()) to also log data locally on a CSV file:" }, { "code": null, "e": 28341, "s": 28112, "text": "def save_log(): with open(\"/home/pi/rpi_weather_station.csv\", \"a\") as log: log.write(\"{},{},{},{},{},{},{},{},{}\\n\".format(timeString, humLab, tempExt, tempLab, presSL, altLab, presAbs, UV_mV, UV_index)) log.close()" }, { "code": null, "e": 28447, "s": 28341, "text": "The complete Jupyter notebook that was used for development can be found here: Rpi_Weather_Station.ipynb." }, { "code": null, "e": 28574, "s": 28447, "text": "The logged data can be viewed directly on local saved CSV file, on ThingSpeak.com site or via an APP, for example, ThingsView!" }, { "code": null, "e": 28739, "s": 28574, "text": "ThingView is an APP developed by CINETICA, that enables you to visualize your ThingSpeak channels in an easy way. Just enter the channel ID and you are ready to go." }, { "code": null, "e": 28969, "s": 28739, "text": "For public channels, the application will respect your windows settings: color, timescale, chart type and the number of results. The current version supports line and column charts, the spline charts are displayed as line charts." }, { "code": null, "e": 29125, "s": 28969, "text": "For private channels, the data will be displayed using the default settings, as there is no way to read the private windows settings with the API key only." }, { "code": null, "e": 29183, "s": 29125, "text": "The ThingView APP can be download for ANDROID and IPHONE." }, { "code": null, "e": 29498, "s": 29183, "text": "This Weather Station tutorial is part of a joint project developed with my friend Mauricio Pinto. Here, we learned how to capture several important data, related to weather, as Air Temperature and Humidity, Pressure and UV. Another very important data to be added to a Weather Station are Wind Speed and Direction." }, { "code": null, "e": 29681, "s": 29498, "text": "Mauricio did a great job, writing a very detailed tutorial, explained how to construct an Anemometer, mostly with recycled material. You can find his project on this 2 part tutorial:" }, { "code": null, "e": 29754, "s": 29681, "text": "Part 1 — Construction of the devices Anemometer and Wind Vane Direction." }, { "code": null, "e": 29843, "s": 29754, "text": "Part 2 — The sketch using Arduino IDE for Esp8266 Nodemcu and transmission to ThingSpeak" }, { "code": null, "e": 30350, "s": 29843, "text": "As Mauricio explained in his tutorial, the anemometer is a device capable of measuring the wind speed and its direction. Using a Hall Effect sensor he was able to count how many rotations the cups give on a period of time, being the intensity of the wind, proportional to the speed of rotation of the axis. With some simple physics equations, he could determine the linear velocity of the wind, at that moment. The wind direction was measured through a windshield with a neodymium magnet and reed switches." }, { "code": null, "e": 30471, "s": 30350, "text": "Here, you can see the anemometer installed in his house (that is located around 400 meters far from my Weather Station):" }, { "code": null, "e": 30533, "s": 30471, "text": "The wind speed and direction are also sent to Thingspeak.com." }, { "code": null, "e": 30652, "s": 30533, "text": "As always, I hope this project can help others find their way into the exciting world of Electronics and Data Science!" }, { "code": null, "e": 30735, "s": 30652, "text": "For details and final code, please visit my GitHub depository: RPi-Weather-Station" }, { "code": null, "e": 30788, "s": 30735, "text": "For more projects, please visit my blog: MJRoBot.org" }, { "code": null, "e": 30825, "s": 30788, "text": "Saludos from the south of the world!" } ]
Java Program to Compare Strings
You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true. Live Demo public class StringCompareEmp{ public static void main(String args[]){ String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; System.out.println( str.compareTo(anotherString) ); System.out.println( str.compareToIgnoreCase(anotherString) ); System.out.println( str.compareTo(objStr.toString())); } } -32 0 0 The equals() method of the String class compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. Live Demo public class StringCompareEqual{ public static void main(String []args){ String s1 = "tutorialspoint"; String s2 = "tutorialspoint"; String s3 = new String ("Tutorials Point"); System.out.println(s1.equals(s2)); System.out.println(s2.equals(s3)); } } true false You can also compare two strings using == operator. But, it compares references to the given variables, not values. public class StringCompareequl{ public static void main(String []args){ String s1 = "tutorialspoint"; String s2 = "tutorialspoint"; String s3 = new String ("Tutorials Point"); System.out.println(s1 == s2); System.out.println(s2 == s3); } } true false
[ { "code": null, "e": 1160, "s": 1062, "text": "You can compare two Strings in Java using the compareTo() method, equals() method or == operator." }, { "code": null, "e": 1433, "s": 1160, "text": "The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string." }, { "code": null, "e": 1536, "s": 1433, "text": "The result is a negative integer if this String object lexicographically precedes the argument string." }, { "code": null, "e": 1638, "s": 1536, "text": "The result is a positive integer if this String object lexicographically follows the argument string." }, { "code": null, "e": 1761, "s": 1638, "text": "The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true." }, { "code": null, "e": 1771, "s": 1761, "text": "Live Demo" }, { "code": null, "e": 2144, "s": 1771, "text": "public class StringCompareEmp{\n public static void main(String args[]){\n String str = \"Hello World\";\n String anotherString = \"hello world\";\n Object objStr = str;\n System.out.println( str.compareTo(anotherString) );\n System.out.println( str.compareToIgnoreCase(anotherString) );\n System.out.println( str.compareTo(objStr.toString()));\n }\n}" }, { "code": null, "e": 2152, "s": 2144, "text": "-32\n0\n0" }, { "code": null, "e": 2384, "s": 2152, "text": "The equals() method of the String class compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object." }, { "code": null, "e": 2394, "s": 2384, "text": "Live Demo" }, { "code": null, "e": 2681, "s": 2394, "text": "public class StringCompareEqual{\n public static void main(String []args){\n String s1 = \"tutorialspoint\";\n String s2 = \"tutorialspoint\";\n String s3 = new String (\"Tutorials Point\");\n System.out.println(s1.equals(s2));\n System.out.println(s2.equals(s3));\n }\n}" }, { "code": null, "e": 2692, "s": 2681, "text": "true\nfalse" }, { "code": null, "e": 2808, "s": 2692, "text": "You can also compare two strings using == operator. But, it compares references to the given variables, not values." }, { "code": null, "e": 3084, "s": 2808, "text": "public class StringCompareequl{\n public static void main(String []args){\n String s1 = \"tutorialspoint\";\n String s2 = \"tutorialspoint\";\n String s3 = new String (\"Tutorials Point\");\n System.out.println(s1 == s2);\n System.out.println(s2 == s3);\n }\n}" }, { "code": null, "e": 3095, "s": 3084, "text": "true\nfalse" } ]
Add a column with the literal value in PySpark DataFrame - GeeksforGeeks
24 Sep, 2021 In this article, we are going to see how to add a column with the literal value in PySpark Dataframe. Creating dataframe for demonstration: Python3 # import SparkSession from the pysparkfrom pyspark.sql import SparkSession # build and create the# SparkSession with name "lit_value"spark = SparkSession.builder.appName("lit_value").getOrCreate() # create the spark dataframe with columns A,Bdata = spark.createDataFrame([('x',5),('Y',3), ('Z',5) ],['A','B']) # showing the schema and tabledata.printSchema()data.show() Output: Here we can add the constant column ‘literal_values_1’ with value 1 by Using the select method. The lit() function will insert constant values to all the rows. Select table by using select() method and pass the arguments first one is the column name, or “*” for selecting the whole table and second argument pass the lit() function with constant values. Python3 # Import the lit() function# from the pyspark.sql.functionsfrom pyspark.sql.functions import lit # select all the columns from data# table and insert new columns# 'literal_values_1' with values 1df2 = data.select('*' ,lit("1").alias("literal_values_1")) # showing the schema and updated tabledf2.printSchema()df2.show() Output: In this method first, we have to create the temp view of the table with the help of createTempView we can create the temporary view. The life of this temp is up to the life of the sparkSession. CreateOrReplace will create the temp table if it is not available or if it is available then replace it. Then after creating the table select the table by SQL clause which will take all the values as a string Python3 # this will create a temp view of the table as lit_valdf2.createOrReplaceTempView("temp") # select all the columns and rows# from data table and insert new# columns 'literal_values_2' with values 2df2 = spark.sql("select *, 2 as literal_values_2 from temp") # showing the schema and updated tabledf2.printSchema()df2.show() Output: This function allows us to create the new function as per our requirements that’s why this is also called a user-defined function. Now we define the datatype of the UDF function and create the functions which will return the values in the form of a new column Python3 # import the udf from pysparkfrom pyspark.sql.functions import udf # defining the data types of udf which is# integer type@udf("int") # defining the lit_col() function which# will return literal values to data framedef lit_col(): return 3 # create new column as# 'literal_values_3' with values 3df2 = df2.withColumn('literal_values_3', lit_col()) # showing the schema and updated tabledf2.printSchema()df2.show() Output: arorakashish0911 Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23939, "s": 23911, "text": "\n24 Sep, 2021" }, { "code": null, "e": 24041, "s": 23939, "text": "In this article, we are going to see how to add a column with the literal value in PySpark Dataframe." }, { "code": null, "e": 24079, "s": 24041, "text": "Creating dataframe for demonstration:" }, { "code": null, "e": 24087, "s": 24079, "text": "Python3" }, { "code": "# import SparkSession from the pysparkfrom pyspark.sql import SparkSession # build and create the# SparkSession with name \"lit_value\"spark = SparkSession.builder.appName(\"lit_value\").getOrCreate() # create the spark dataframe with columns A,Bdata = spark.createDataFrame([('x',5),('Y',3), ('Z',5) ],['A','B']) # showing the schema and tabledata.printSchema()data.show()", "e": 24485, "s": 24087, "text": null }, { "code": null, "e": 24495, "s": 24485, "text": " Output: " }, { "code": null, "e": 24655, "s": 24495, "text": "Here we can add the constant column ‘literal_values_1’ with value 1 by Using the select method. The lit() function will insert constant values to all the rows." }, { "code": null, "e": 24852, "s": 24655, "text": "Select table by using select() method and pass the arguments first one is the column name, or “*” for selecting the whole table and second argument pass the lit() function with constant values. " }, { "code": null, "e": 24860, "s": 24852, "text": "Python3" }, { "code": "# Import the lit() function# from the pyspark.sql.functionsfrom pyspark.sql.functions import lit # select all the columns from data# table and insert new columns# 'literal_values_1' with values 1df2 = data.select('*' ,lit(\"1\").alias(\"literal_values_1\")) # showing the schema and updated tabledf2.printSchema()df2.show()", "e": 25181, "s": 24860, "text": null }, { "code": null, "e": 25189, "s": 25181, "text": "Output:" }, { "code": null, "e": 25488, "s": 25189, "text": "In this method first, we have to create the temp view of the table with the help of createTempView we can create the temporary view. The life of this temp is up to the life of the sparkSession. CreateOrReplace will create the temp table if it is not available or if it is available then replace it." }, { "code": null, "e": 25593, "s": 25488, "text": "Then after creating the table select the table by SQL clause which will take all the values as a string " }, { "code": null, "e": 25601, "s": 25593, "text": "Python3" }, { "code": "# this will create a temp view of the table as lit_valdf2.createOrReplaceTempView(\"temp\") # select all the columns and rows# from data table and insert new# columns 'literal_values_2' with values 2df2 = spark.sql(\"select *, 2 as literal_values_2 from temp\") # showing the schema and updated tabledf2.printSchema()df2.show()", "e": 25925, "s": 25601, "text": null }, { "code": null, "e": 25933, "s": 25925, "text": "Output:" }, { "code": null, "e": 26193, "s": 25933, "text": "This function allows us to create the new function as per our requirements that’s why this is also called a user-defined function. Now we define the datatype of the UDF function and create the functions which will return the values in the form of a new column" }, { "code": null, "e": 26201, "s": 26193, "text": "Python3" }, { "code": "# import the udf from pysparkfrom pyspark.sql.functions import udf # defining the data types of udf which is# integer type@udf(\"int\") # defining the lit_col() function which# will return literal values to data framedef lit_col(): return 3 # create new column as# 'literal_values_3' with values 3df2 = df2.withColumn('literal_values_3', lit_col()) # showing the schema and updated tabledf2.printSchema()df2.show()", "e": 26618, "s": 26201, "text": null }, { "code": null, "e": 26626, "s": 26618, "text": "Output:" }, { "code": null, "e": 26643, "s": 26626, "text": "arorakashish0911" }, { "code": null, "e": 26650, "s": 26643, "text": "Picked" }, { "code": null, "e": 26665, "s": 26650, "text": "Python-Pyspark" }, { "code": null, "e": 26672, "s": 26665, "text": "Python" }, { "code": null, "e": 26770, "s": 26672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26779, "s": 26770, "text": "Comments" }, { "code": null, "e": 26792, "s": 26779, "text": "Old Comments" }, { "code": null, "e": 26810, "s": 26792, "text": "Python Dictionary" }, { "code": null, "e": 26845, "s": 26810, "text": "Read a file line by line in Python" }, { "code": null, "e": 26867, "s": 26845, "text": "Enumerate() in Python" }, { "code": null, "e": 26899, "s": 26867, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26929, "s": 26899, "text": "Iterate over a list in Python" }, { "code": null, "e": 26971, "s": 26929, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27014, "s": 26971, "text": "Python program to convert a list to string" }, { "code": null, "e": 27040, "s": 27014, "text": "Python String | replace()" }, { "code": null, "e": 27084, "s": 27040, "text": "Reading and Writing to text files in Python" } ]
How do I plot two countplot graphs side by side in Seaborn using Matplotlib?
To plot two countplot graphs side by side in Seaborn, we can take the following steps − To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7). To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7). Create a dataframe with keys, col1 and col2, using Pandas. Create a dataframe with keys, col1 and col2, using Pandas. Use countplot() to show the counts of observations in each categorical bin using bars. Use countplot() to show the counts of observations in each categorical bin using bars. Adjust the padding between and around the subplots. Adjust the padding between and around the subplots. To display the figure, use show() method. To display the figure, use show() method. import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True f, axes = plt.subplots(1, 2) df = pd.DataFrame(dict(col1=np.linspace(1, 10, 5), col2=np.linspace(1, 10, 5))) sns.countplot(df.col1, x='col1', color="red", ax=axes[0]) sns.countplot(df.col2, x="col2", color="green", ax=axes[1]) plt.show()
[ { "code": null, "e": 1150, "s": 1062, "text": "To plot two countplot graphs side by side in Seaborn, we can take the following steps −" }, { "code": null, "e": 1225, "s": 1150, "text": "To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7)." }, { "code": null, "e": 1300, "s": 1225, "text": "To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7)." }, { "code": null, "e": 1359, "s": 1300, "text": "Create a dataframe with keys, col1 and col2, using Pandas." }, { "code": null, "e": 1418, "s": 1359, "text": "Create a dataframe with keys, col1 and col2, using Pandas." }, { "code": null, "e": 1505, "s": 1418, "text": "Use countplot() to show the counts of observations in each categorical bin using bars." }, { "code": null, "e": 1592, "s": 1505, "text": "Use countplot() to show the counts of observations in each categorical bin using bars." }, { "code": null, "e": 1644, "s": 1592, "text": "Adjust the padding between and around the subplots." }, { "code": null, "e": 1696, "s": 1644, "text": "Adjust the padding between and around the subplots." }, { "code": null, "e": 1738, "s": 1696, "text": "To display the figure, use show() method." }, { "code": null, "e": 1780, "s": 1738, "text": "To display the figure, use show() method." }, { "code": null, "e": 2204, "s": 1780, "text": "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nf, axes = plt.subplots(1, 2)\ndf = pd.DataFrame(dict(col1=np.linspace(1, 10, 5), col2=np.linspace(1, 10, 5)))\nsns.countplot(df.col1, x='col1', color=\"red\", ax=axes[0])\nsns.countplot(df.col2, x=\"col2\", color=\"green\", ax=axes[1])\nplt.show()" } ]
Explain Squeeze Function C language
Squeeze(s1,s2) or squeeze(char[],char[]) is a user defined function which is used to delete the common characters or equal characters in two strings. How to delete the common characters in two strings using squeeze function in C programming language? In this program, the user enters two strings in the console and write a code to display first string excluding the common characters present in second string. The C program which demonstrates the functioning of squeeze function is as follows − Live Demo #include<stdio.h> void squeeze(char string1[],char string2[]);//prototype declaration int main(){ char string1[50]; char string2[30]; printf("enter the string1:"); scanf("%s",string1);// read string1 from keyboard printf("enter the string2:"); scanf("%s",string2);// read string2 from keyboard squeeze(string1,string2);//call squeeze function printf("Final string is:%s\n",string1); return 0; } void squeeze(char string1[],char string2[]){ int i,j,k; for(i=k=0;string1[i]!='\0';i++){ for(j=0;string2[j]!='\0' && string2[j]!=string1[i];j++) if(string2[j]=='\0') string1[k++]=string1[i]; } string1[k]='\0'; } The output is stated below − Enter the string1 : Tutorial Enter the string2 : ut Final string : Torial
[ { "code": null, "e": 1212, "s": 1062, "text": "Squeeze(s1,s2) or squeeze(char[],char[]) is a user defined function which is used to delete the common characters or equal characters in two strings." }, { "code": null, "e": 1313, "s": 1212, "text": "How to delete the common characters in two strings using squeeze function in C programming language?" }, { "code": null, "e": 1472, "s": 1313, "text": "In this program, the user enters two strings in the console and write a code to display first string excluding the common characters present in second string." }, { "code": null, "e": 1557, "s": 1472, "text": "The C program which demonstrates the functioning of squeeze function is as follows −" }, { "code": null, "e": 1568, "s": 1557, "text": " Live Demo" }, { "code": null, "e": 2238, "s": 1568, "text": "#include<stdio.h>\nvoid squeeze(char string1[],char string2[]);//prototype declaration\nint main(){\n char string1[50];\n char string2[30];\n printf(\"enter the string1:\");\n scanf(\"%s\",string1);// read string1 from keyboard\n printf(\"enter the string2:\");\n scanf(\"%s\",string2);// read string2 from keyboard\n squeeze(string1,string2);//call squeeze function\n printf(\"Final string is:%s\\n\",string1);\n return 0;\n}\nvoid squeeze(char string1[],char string2[]){\n int i,j,k;\n for(i=k=0;string1[i]!='\\0';i++){\n for(j=0;string2[j]!='\\0' && string2[j]!=string1[i];j++)\n if(string2[j]=='\\0')\n string1[k++]=string1[i];\n }\n string1[k]='\\0';\n}" }, { "code": null, "e": 2267, "s": 2238, "text": "The output is stated below −" }, { "code": null, "e": 2341, "s": 2267, "text": "Enter the string1 : Tutorial\nEnter the string2 : ut\nFinal string : Torial" } ]
How to Remove % Sign From Data Table | by Benjamin Obi Tayo Ph.D. | Towards Data Science
Data wrangling is the process of transforming raw unstructured to a form that is ready for further analysis such as data visualization or for model building. Sometimes after wrangling your data, you may notice that some columns may contain symbols such as the dollar sign ($), plus sign (+), minus sign (-) or the percentage sign (%). Any data column containing one of these signs is treated as string type and hence cannot be used for numerical calculations. In this article, I will show how the percentage sign (%) can be removed from a data column. Then once the % sign is removed, we shall convert the column from string to numeric type, to render it suitable for numerical manipulations and calculations. A similar approach could be used for removing unwanted signs such as plus sign (+), minus sign (-), and so on. I will illustrate this example with a dataset extracted from a pdf file as shown below: a) Copy and past table to Excel and save the file as table_1_raw.csv Data is stored in one-dimensional format and has to be reshaped, cleaned, and transformed. b) Import necessary libraries import pandas as pdimport numpy as np c) Import raw data and reshape the data df = pd.read_csv("table_1_raw.csv", header=None)df2 = pd.DataFrame(df.values.reshape(25,10))column_names = df2[0:1].values[0]df3 = df2[1:]df3.columns = df2[0:1].values[0]df3.head() d) Perform data wrangling using string processing tools We notice from the table above that columns x5, x6, and x7 are expressed in percentages, so we need to get rid of the percent (%) symbol: df4['x5'] = list(map(lambda x: x[:-1], df4['x5'].values))df4['x6'] = list(map(lambda x: x[:-1], df4['x6'].values))df4['x7'] = list(map(lambda x: x[:-1], df4['x7'].values)) e) Convert data to numeric form We note that column values for columns x5, x6, and x7 have data types of string (even after the % symbol has been removed), so we need to convert these to numeric data as follows: df4['x5'] = [float(x) for x in df4['x5'].values]df4['x6'] = [float(x) for x in df4['x6'].values]df4['x7'] = [float(x) for x in df4['x7'].values] f) View final form of the transformed data df4.head(n = 5) g) Export final data to a csv file df4.to_csv('table_1_final.csv',index = False) In summary, we’ve shown how the percent sign (%) can be removed from a data column, and how the column can be converted into numerical type to render it suitable for numerical calculations. A similar approach could be used for removing unwanted signs such as plus sign (+), minus sign (-), and so on.
[ { "code": null, "e": 632, "s": 172, "text": "Data wrangling is the process of transforming raw unstructured to a form that is ready for further analysis such as data visualization or for model building. Sometimes after wrangling your data, you may notice that some columns may contain symbols such as the dollar sign ($), plus sign (+), minus sign (-) or the percentage sign (%). Any data column containing one of these signs is treated as string type and hence cannot be used for numerical calculations." }, { "code": null, "e": 993, "s": 632, "text": "In this article, I will show how the percentage sign (%) can be removed from a data column. Then once the % sign is removed, we shall convert the column from string to numeric type, to render it suitable for numerical manipulations and calculations. A similar approach could be used for removing unwanted signs such as plus sign (+), minus sign (-), and so on." }, { "code": null, "e": 1081, "s": 993, "text": "I will illustrate this example with a dataset extracted from a pdf file as shown below:" }, { "code": null, "e": 1150, "s": 1081, "text": "a) Copy and past table to Excel and save the file as table_1_raw.csv" }, { "code": null, "e": 1241, "s": 1150, "text": "Data is stored in one-dimensional format and has to be reshaped, cleaned, and transformed." }, { "code": null, "e": 1271, "s": 1241, "text": "b) Import necessary libraries" }, { "code": null, "e": 1309, "s": 1271, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 1349, "s": 1309, "text": "c) Import raw data and reshape the data" }, { "code": null, "e": 1530, "s": 1349, "text": "df = pd.read_csv(\"table_1_raw.csv\", header=None)df2 = pd.DataFrame(df.values.reshape(25,10))column_names = df2[0:1].values[0]df3 = df2[1:]df3.columns = df2[0:1].values[0]df3.head()" }, { "code": null, "e": 1586, "s": 1530, "text": "d) Perform data wrangling using string processing tools" }, { "code": null, "e": 1724, "s": 1586, "text": "We notice from the table above that columns x5, x6, and x7 are expressed in percentages, so we need to get rid of the percent (%) symbol:" }, { "code": null, "e": 1896, "s": 1724, "text": "df4['x5'] = list(map(lambda x: x[:-1], df4['x5'].values))df4['x6'] = list(map(lambda x: x[:-1], df4['x6'].values))df4['x7'] = list(map(lambda x: x[:-1], df4['x7'].values))" }, { "code": null, "e": 1928, "s": 1896, "text": "e) Convert data to numeric form" }, { "code": null, "e": 2108, "s": 1928, "text": "We note that column values for columns x5, x6, and x7 have data types of string (even after the % symbol has been removed), so we need to convert these to numeric data as follows:" }, { "code": null, "e": 2253, "s": 2108, "text": "df4['x5'] = [float(x) for x in df4['x5'].values]df4['x6'] = [float(x) for x in df4['x6'].values]df4['x7'] = [float(x) for x in df4['x7'].values]" }, { "code": null, "e": 2296, "s": 2253, "text": "f) View final form of the transformed data" }, { "code": null, "e": 2312, "s": 2296, "text": "df4.head(n = 5)" }, { "code": null, "e": 2347, "s": 2312, "text": "g) Export final data to a csv file" }, { "code": null, "e": 2393, "s": 2347, "text": "df4.to_csv('table_1_final.csv',index = False)" } ]
Building a cryptocurrency dashboard using Plotly and Binance API | by Mayank Vadsola | Towards Data Science
As of now, according to CoinMarketCap, the global cryptocurrency market is worth more than $1.5T. Recent approval from a couple of banks and credit card companies to include cryptocurrencies as one of their financial products indicates a bright future for the crypto market. In the last few years, more people started trading cryptocurrencies, and there are many exchanges worldwide that support different cryptocurrencies. In this article, we will focus on the Binance exchange, which is the world’s number one exchange today. It supports almost all cryptocurrencies and available in many countries. In this article, we will discuss how to access data from Binance API and create a dashboard with Plotly. Here’s what we’ll cover: How to set up Binance API How to get data using Binance API Building a dashboard with Plotly Binance provides two kinds of API access: 1) Actual Binance API and 2) Test Binance API. Actual API provides direct access to your actual account, and any trades made with this API will be reflected into your actual account. That means we need to be careful while using this API. First, you need to sign up with Binance (if you don’t have an account) at https://www.binance.com/en/register?ref=AG3W30LV (This link includes my referral code and will give you a 10% discount on trading fees. More details can be found at https://www.binance.com/en/activity/referral) After registering, you will be asked (or you can do that from security settings) to set up two-factor authentication for additional security. I will recommend choosing Google Authenticator. Once 2FA is set up, you can go to the API management tab under settings. You will be asked to provide a label for your API keys (this will be useful when you have multiple keys associated with a single account). Click on create API after providing a label for your API keys. You will be asked to authenticate one more time, and then you will be able to see your “API Key” and “Secret Key.” This is the only time you will see it, so copy your keys to some safe place. By default, the keys will be given the following access, which can be changed. We will be using both actual API and test API keys to understand how to work with them. For this, we don’t want to mess up our actual account, so we will change the actual API keys permission to read-only. We will be saving our actual API keys into secret.cfg file as mentioned below (Remember, never share or publish your secret.cfg file) Test Binance API provides you with the same feel as you interact with the actual API. I would recommend starting with this (for trading) until you are assured that your application works fine. First, you need to log in at https://testnet.binance.vision/ (For now, login is only supported with GitHub) After logging in, click on “Generate HMAC_SHA256 Key” and you will be again asked to provide a label for keys. After providing the label, click on generate, and you should be able to see your API keys. Copy them to some safe place. Also, read all details on the main page about test API. Now, we will modify secret.cfg file to include test API keys as mentioned below We have successfully set up both actual and test API keys and saved them to secret.cfg file. In the next section, we will focus on getting data using these API keys. Binance doesn’t provide a python library for interacting with the API, but there is one very famous third-party library called python-binance , which we will be using to interact with the API. To install python-binance library $ pip install python-binance By default, you will get some balance in your test account in the form of different cryptocurrencies, and we will use test API for this section (as I don’t want to share my account info). Also, python-binance doesn’t have access to test API, so we need to change the endpoint URL. Here is the code to get the test account info As you can see from the above output, it displays important things such as accountType, balances, permissions, etc. Now, let’s get the ETH balance. You can do many things with the python-binance library and detailed documentation can be found here. As per my observation, test API doesn’t provide real historical data; instead, it provides dummy data. So to access real data, we will be using actual API and actual API keys. Getting ETH price from the earliest date available (on Binance) to the present day The above output represents the following parameters as mentioned on Binance API doc Converting the output to a data frame and saving it as a CSV file We can use the Binance WebSocket to stream real-time data. Here’s how you do it Now, to stop streaming data and to close WebSocket It looks like we have figured out different ways of getting data and information. There are plenty of other things you can do with python-binance library and Binance API. I would encourage you to take a look at this and this. We can now move to build a Plotly dashboard in the next section. In this section, we will build a dashboard with Plotly that will track our portfolio of the test account in real-time and change total account value based on live streaming data. Here is how our final dashboard will look like (don’t mind the aesthetics, as you can change it later) As you can see, we have included the following features in the dashboard. Indicator - Total portfolio value in USDT Indicator - Total portfolio value in BTC Indicator - BNB/USDT conversion Pie chart - Portfolio distribution (in USDT) Bar graph - Tokens distribution Let’s look at the code. First, we will import all required libraries. Second, we will read our keys, establish the connection, and get account info. Third, we will define some functions for taking care of streaming data and calculating metrics based on live data. Forth, we will start streaming data. Fifth, we will define our dashboard layout, graphs and host it That’s it, and you should be able to track your test account portfolio. You can easily set it up for an actual account using actual keys without changing the endpoint URL. This brings us to the end of this article. You can access all code in this GitHub repo. Feel free to star or bookmark for your future reference. Recently, I started writing a series on Algorithmic Trading with Python and Machine Learning. You can find the first article below. pub.towardsai.net Follow me for more articles. Feel free to connect and contact me on LinkedIn. Thank you! Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 773, "s": 172, "text": "As of now, according to CoinMarketCap, the global cryptocurrency market is worth more than $1.5T. Recent approval from a couple of banks and credit card companies to include cryptocurrencies as one of their financial products indicates a bright future for the crypto market. In the last few years, more people started trading cryptocurrencies, and there are many exchanges worldwide that support different cryptocurrencies. In this article, we will focus on the Binance exchange, which is the world’s number one exchange today. It supports almost all cryptocurrencies and available in many countries." }, { "code": null, "e": 878, "s": 773, "text": "In this article, we will discuss how to access data from Binance API and create a dashboard with Plotly." }, { "code": null, "e": 903, "s": 878, "text": "Here’s what we’ll cover:" }, { "code": null, "e": 929, "s": 903, "text": "How to set up Binance API" }, { "code": null, "e": 963, "s": 929, "text": "How to get data using Binance API" }, { "code": null, "e": 996, "s": 963, "text": "Building a dashboard with Plotly" }, { "code": null, "e": 1085, "s": 996, "text": "Binance provides two kinds of API access: 1) Actual Binance API and 2) Test Binance API." }, { "code": null, "e": 1276, "s": 1085, "text": "Actual API provides direct access to your actual account, and any trades made with this API will be reflected into your actual account. That means we need to be careful while using this API." }, { "code": null, "e": 1561, "s": 1276, "text": "First, you need to sign up with Binance (if you don’t have an account) at https://www.binance.com/en/register?ref=AG3W30LV (This link includes my referral code and will give you a 10% discount on trading fees. More details can be found at https://www.binance.com/en/activity/referral)" }, { "code": null, "e": 1751, "s": 1561, "text": "After registering, you will be asked (or you can do that from security settings) to set up two-factor authentication for additional security. I will recommend choosing Google Authenticator." }, { "code": null, "e": 1963, "s": 1751, "text": "Once 2FA is set up, you can go to the API management tab under settings. You will be asked to provide a label for your API keys (this will be useful when you have multiple keys associated with a single account)." }, { "code": null, "e": 2297, "s": 1963, "text": "Click on create API after providing a label for your API keys. You will be asked to authenticate one more time, and then you will be able to see your “API Key” and “Secret Key.” This is the only time you will see it, so copy your keys to some safe place. By default, the keys will be given the following access, which can be changed." }, { "code": null, "e": 2503, "s": 2297, "text": "We will be using both actual API and test API keys to understand how to work with them. For this, we don’t want to mess up our actual account, so we will change the actual API keys permission to read-only." }, { "code": null, "e": 2637, "s": 2503, "text": "We will be saving our actual API keys into secret.cfg file as mentioned below (Remember, never share or publish your secret.cfg file)" }, { "code": null, "e": 2830, "s": 2637, "text": "Test Binance API provides you with the same feel as you interact with the actual API. I would recommend starting with this (for trading) until you are assured that your application works fine." }, { "code": null, "e": 2938, "s": 2830, "text": "First, you need to log in at https://testnet.binance.vision/ (For now, login is only supported with GitHub)" }, { "code": null, "e": 3226, "s": 2938, "text": "After logging in, click on “Generate HMAC_SHA256 Key” and you will be again asked to provide a label for keys. After providing the label, click on generate, and you should be able to see your API keys. Copy them to some safe place. Also, read all details on the main page about test API." }, { "code": null, "e": 3306, "s": 3226, "text": "Now, we will modify secret.cfg file to include test API keys as mentioned below" }, { "code": null, "e": 3472, "s": 3306, "text": "We have successfully set up both actual and test API keys and saved them to secret.cfg file. In the next section, we will focus on getting data using these API keys." }, { "code": null, "e": 3665, "s": 3472, "text": "Binance doesn’t provide a python library for interacting with the API, but there is one very famous third-party library called python-binance , which we will be using to interact with the API." }, { "code": null, "e": 3699, "s": 3665, "text": "To install python-binance library" }, { "code": null, "e": 3728, "s": 3699, "text": "$ pip install python-binance" }, { "code": null, "e": 4009, "s": 3728, "text": "By default, you will get some balance in your test account in the form of different cryptocurrencies, and we will use test API for this section (as I don’t want to share my account info). Also, python-binance doesn’t have access to test API, so we need to change the endpoint URL." }, { "code": null, "e": 4055, "s": 4009, "text": "Here is the code to get the test account info" }, { "code": null, "e": 4171, "s": 4055, "text": "As you can see from the above output, it displays important things such as accountType, balances, permissions, etc." }, { "code": null, "e": 4203, "s": 4171, "text": "Now, let’s get the ETH balance." }, { "code": null, "e": 4304, "s": 4203, "text": "You can do many things with the python-binance library and detailed documentation can be found here." }, { "code": null, "e": 4480, "s": 4304, "text": "As per my observation, test API doesn’t provide real historical data; instead, it provides dummy data. So to access real data, we will be using actual API and actual API keys." }, { "code": null, "e": 4563, "s": 4480, "text": "Getting ETH price from the earliest date available (on Binance) to the present day" }, { "code": null, "e": 4648, "s": 4563, "text": "The above output represents the following parameters as mentioned on Binance API doc" }, { "code": null, "e": 4714, "s": 4648, "text": "Converting the output to a data frame and saving it as a CSV file" }, { "code": null, "e": 4794, "s": 4714, "text": "We can use the Binance WebSocket to stream real-time data. Here’s how you do it" }, { "code": null, "e": 4845, "s": 4794, "text": "Now, to stop streaming data and to close WebSocket" }, { "code": null, "e": 5136, "s": 4845, "text": "It looks like we have figured out different ways of getting data and information. There are plenty of other things you can do with python-binance library and Binance API. I would encourage you to take a look at this and this. We can now move to build a Plotly dashboard in the next section." }, { "code": null, "e": 5315, "s": 5136, "text": "In this section, we will build a dashboard with Plotly that will track our portfolio of the test account in real-time and change total account value based on live streaming data." }, { "code": null, "e": 5418, "s": 5315, "text": "Here is how our final dashboard will look like (don’t mind the aesthetics, as you can change it later)" }, { "code": null, "e": 5492, "s": 5418, "text": "As you can see, we have included the following features in the dashboard." }, { "code": null, "e": 5534, "s": 5492, "text": "Indicator - Total portfolio value in USDT" }, { "code": null, "e": 5575, "s": 5534, "text": "Indicator - Total portfolio value in BTC" }, { "code": null, "e": 5607, "s": 5575, "text": "Indicator - BNB/USDT conversion" }, { "code": null, "e": 5652, "s": 5607, "text": "Pie chart - Portfolio distribution (in USDT)" }, { "code": null, "e": 5684, "s": 5652, "text": "Bar graph - Tokens distribution" }, { "code": null, "e": 5708, "s": 5684, "text": "Let’s look at the code." }, { "code": null, "e": 5754, "s": 5708, "text": "First, we will import all required libraries." }, { "code": null, "e": 5833, "s": 5754, "text": "Second, we will read our keys, establish the connection, and get account info." }, { "code": null, "e": 5948, "s": 5833, "text": "Third, we will define some functions for taking care of streaming data and calculating metrics based on live data." }, { "code": null, "e": 5985, "s": 5948, "text": "Forth, we will start streaming data." }, { "code": null, "e": 6048, "s": 5985, "text": "Fifth, we will define our dashboard layout, graphs and host it" }, { "code": null, "e": 6220, "s": 6048, "text": "That’s it, and you should be able to track your test account portfolio. You can easily set it up for an actual account using actual keys without changing the endpoint URL." }, { "code": null, "e": 6365, "s": 6220, "text": "This brings us to the end of this article. You can access all code in this GitHub repo. Feel free to star or bookmark for your future reference." }, { "code": null, "e": 6497, "s": 6365, "text": "Recently, I started writing a series on Algorithmic Trading with Python and Machine Learning. You can find the first article below." }, { "code": null, "e": 6515, "s": 6497, "text": "pub.towardsai.net" }, { "code": null, "e": 6604, "s": 6515, "text": "Follow me for more articles. Feel free to connect and contact me on LinkedIn. Thank you!" } ]
Character.charValue() in Java with examples - GeeksforGeeks
06 Dec, 2018 Java.lang.Character.charValue() is a built-in method in Java that returns the value of this character object. This method converts the Character object into its primitive data type char. Syntax: public char charValue() The function does not accepts any parameter. Return Type: This method returns the primitive char value represented by this object. Below programs illustrate the Java.lang.Character.charValue() method: Program 1: // Java program to demonstrate the// Java.lang.Character.charValue() method// when the assigned char is a character import java.lang.*; public class Gfg1 { public static void main(String[] args) { // Create a character object Character x = new Character('z'); // assign the primitive value to a character char ch = x.charValue(); System.out.println("Primitive char value is " + ch); }} Primitive char value is z Program 2: When we assign the value of x by any digit: // Java program to demonstrate the// function when the assigned value is// a numberimport java.lang.*; public class Gfg { public static void main(String[] args) { // create a Character object x Character x = new Character('9'); // assign value is a number // assign the primitive value to a character char ch = x.charValue(); // print the primitive char value System.out.println("Primitive char value is " + ch); }} Primitive char value is 9 Java-Character Java-Functions Java-lang package Java 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 ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 23917, "s": 23889, "text": "\n06 Dec, 2018" }, { "code": null, "e": 24104, "s": 23917, "text": "Java.lang.Character.charValue() is a built-in method in Java that returns the value of this character object. This method converts the Character object into its primitive data type char." }, { "code": null, "e": 24112, "s": 24104, "text": "Syntax:" }, { "code": null, "e": 24185, "s": 24112, "text": "public char charValue() \n\nThe function does not accepts any parameter. \n" }, { "code": null, "e": 24271, "s": 24185, "text": "Return Type: This method returns the primitive char value represented by this object." }, { "code": null, "e": 24341, "s": 24271, "text": "Below programs illustrate the Java.lang.Character.charValue() method:" }, { "code": null, "e": 24352, "s": 24341, "text": "Program 1:" }, { "code": "// Java program to demonstrate the// Java.lang.Character.charValue() method// when the assigned char is a character import java.lang.*; public class Gfg1 { public static void main(String[] args) { // Create a character object Character x = new Character('z'); // assign the primitive value to a character char ch = x.charValue(); System.out.println(\"Primitive char value is \" + ch); }}", "e": 24790, "s": 24352, "text": null }, { "code": null, "e": 24817, "s": 24790, "text": "Primitive char value is z\n" }, { "code": null, "e": 24872, "s": 24817, "text": "Program 2: When we assign the value of x by any digit:" }, { "code": "// Java program to demonstrate the// function when the assigned value is// a numberimport java.lang.*; public class Gfg { public static void main(String[] args) { // create a Character object x Character x = new Character('9'); // assign value is a number // assign the primitive value to a character char ch = x.charValue(); // print the primitive char value System.out.println(\"Primitive char value is \" + ch); }}", "e": 25355, "s": 24872, "text": null }, { "code": null, "e": 25382, "s": 25355, "text": "Primitive char value is 9\n" }, { "code": null, "e": 25397, "s": 25382, "text": "Java-Character" }, { "code": null, "e": 25412, "s": 25397, "text": "Java-Functions" }, { "code": null, "e": 25430, "s": 25412, "text": "Java-lang package" }, { "code": null, "e": 25435, "s": 25430, "text": "Java" }, { "code": null, "e": 25440, "s": 25435, "text": "Java" }, { "code": null, "e": 25538, "s": 25440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25547, "s": 25538, "text": "Comments" }, { "code": null, "e": 25560, "s": 25547, "text": "Old Comments" }, { "code": null, "e": 25611, "s": 25560, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 25641, "s": 25611, "text": "HashMap in Java with Examples" }, { "code": null, "e": 25672, "s": 25641, "text": "How to iterate any Map in Java" }, { "code": null, "e": 25691, "s": 25672, "text": "Interfaces in Java" }, { "code": null, "e": 25723, "s": 25691, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 25741, "s": 25723, "text": "ArrayList in Java" }, { "code": null, "e": 25761, "s": 25741, "text": "Stack Class in Java" }, { "code": null, "e": 25793, "s": 25761, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 25817, "s": 25793, "text": "Singleton Class in Java" } ]
Count pairs with sum as a prime number and less than n - GeeksforGeeks
10 Mar, 2022 Given a positive integer n, count distinct number of pairs (x, y) that satisfy following conditions : (x + y) is a prime number. (x + y) < n x != y 1 <= x, y Examples: Input : n = 6 Output : 3 prime pairs whose sum is less than 6 are: (1,2), (1,4), (2,3) Input : 12 Output : 11 prime pairs whose sum is less than 12 are: (1,2), (1,4), (2,3), (1,6), (2,5), (3,4), (1,10), (2,9), (3,8), (4,7), (5,6) Approach: 1) Find all prime numbers less than n using Sieve of Sundaram 2) For each prime number p, count distinct pairs that sum up to p. For any odd number n, number of distinct pairs that add upto n are n/2 Since, a prime number is a odd number, the same applies for it too. Example, For prime number p = 7 distinct pairs that add upto p: p/2 = 7/2 = 3 The three pairs are (1,6), (2,5), (3,4)For prime number p = 23 distinct pairs that add upto p: p/2 = 23/2 = 11 C++ Java Python3 C# PHP Javascript // C++ implementation of prime pairs// whose sum is less than n#include <bits/stdc++.h>using namespace std; // Sieve of Sundaram for generating// prime numbers less than nvoid SieveOfSundaram(bool marked[], int nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for (int i=1; i<=nNew; i++) for (int j=i; (i + j + 2*i*j) <= nNew; j++) marked[i + j + 2*i*j] = true;} // Returns number of pairs with given conditions.int countPrimePairs(int n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half int nNew = (n-2)/2; // This array is used to separate numbers of // the form i+j+2ij from others where // 1 <= i <= j bool marked[nNew + 1]; // Initialize all elements as not marked memset(marked, false, sizeof(marked)); SieveOfSundaram(marked, nNew); int count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for (int i=1; i<=nNew; i++) { if (marked[i] == false) { prime_num = 2*i + 1; // For a given prime number p // number of distinct pairs(i,j) // where (i+j) = p are p/2 count = count + (prime_num / 2); } } return count;} // Driver program to test aboveint main(void){ int n = 12; cout << "Number of prime pairs: " << countPrimePairs(n); return 0;} // Java implementation of prime pairs// whose sum is less than n class GFG{ // Sieve of Sundaram for generating// prime numbers less than nstatic void SieveOfSundaram(boolean marked[], int nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Returns number of pairs with given conditions.static int countPrimePairs(int n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of // the form i+j+2ij from others where // 1 <= i <= j // Initialize all elements as not marked boolean marked[]=new boolean[nNew + 1]; SieveOfSundaram(marked, nNew); int count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for (int i = 1; i <= nNew; i++) { if (marked[i] == false) { prime_num = 2 * i + 1; // For a given prime number p // number of distinct pairs(i, j) // where (i + j) = p are p/2 count = count + (prime_num / 2); } } return count;} // Driver codepublic static void main (String[] args){ int n = 12; System.out.println("Number of prime pairs: " + countPrimePairs(n));}} // This code is contributed by mits # Python3 implementation of prime pairs# whose sum is less than n # Sieve of Sundaram for generating# prime numbers less than ndef SieveOfSundaram(marked, nNew): # Main logic of Sundaram. Mark all numbers # of the form i + j + 2ij as true where # 1 <= i <= j for i in range(1, nNew + 1): for j in range(i, nNew): if i + j + 2 * i * j > nNew: break marked[i + j + 2 * i * j] = True # Returns number of pairs with given conditions.def countPrimePairs(n): # In general Sieve of Sundaram, produces # primes smaller than (2*x + 2) for a number # given number x. Since we want primes smaller # than n, we reduce n to half nNew = (n - 2) // 2 # This array is used to separate numbers # of the form i+j+2ij from others where # 1 <= i <= j marked = [ False for i in range(nNew + 1)] SieveOfSundaram(marked, nNew) count, prime_num = 0, 0 # Find primes. Primes are of the form # 2*i + 1 such that marked[i] is false. for i in range(1, nNew + 1): if (marked[i] == False): prime_num = 2 * i + 1 # For a given prime number p # number of distinct pairs(i,j) # where (i+j) = p are p/2 count = count + (prime_num // 2) return count # Driver Coden = 12print("Number of prime pairs: ", countPrimePairs(n)) # This code is contributed by Mohit kumar 29 // C# implementation of prime pairs// whose sum is less than nusing System; class GFG{ // Sieve of Sundaram for generating// prime numbers less than nstatic void SieveOfSundaram(bool[] marked, int nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Returns number of pairs with given conditions.static int countPrimePairs(int n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers // of the form i+j+2ij from others where // 1 <= i <= j // Initialize all elements as not marked bool[] marked = new bool[nNew + 1]; SieveOfSundaram(marked, nNew); int count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for (int i = 1; i <= nNew; i++) { if (marked[i] == false) { prime_num = 2 * i + 1; // For a given prime number p // number of distinct pairs(i, j) // where (i + j) = p are p/2 count = count + (prime_num / 2); } } return count;} // Driver codepublic static void Main (){ int n = 12; Console.WriteLine("Number of prime pairs: " + countPrimePairs(n));}} // This Code is Contribute by Mukul Singh. <?php// PHP implementation of prime pairs// whose sum is less than n // Sieve of Sundaram for generating// prime numbers less than nfunction SieveOfSundaram(&$marked, $nNew){ // Main logic of Sundaram. Mark all // numbers of the form i + j + 2ij // as true where 1 <= i <= j for ($i = 1; $i <= $nNew; $i++) for ($j = $i; ($i + $j + 2 * $i * $j) <= $nNew; $j++) $marked[$i + $j + 2 * $i * $j] = true;} // Returns number of pairs with// given conditions.function countPrimePairs($n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than n, we reduce n to half $nNew = ($n - 2) / 2; // This array is used to separate numbers // of the form i+j+2ij from others where // 1 <= i <= j $marked = array_fill(0, $nNew + 1, false); SieveOfSundaram($marked, $nNew); $count = 0; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for ($i = 1; $i <= $nNew; $i++) { if ($marked[$i] == false) { $prime_num = 2 * $i + 1; // For a given prime number p // number of distinct pairs(i,j) // where (i+j) = p are p/2 $count = $count + (int)($prime_num / 2); } } return $count;} // Driver Code$n = 12;echo "Number of prime pairs: " . countPrimePairs($n); // This code is contributed by// chandan_jnu?> <script> // Javascript implementation of prime pairs// whose sum is less than n // Sieve of Sundaram for generating// prime numbers less than nfunction SieveOfSundaram(marked, nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for(i = 1; i <= nNew; i++) for(j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Returns number of pairs with given conditions.function countPrimePairs(n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half var nNew = parseInt((n - 2) / 2); // This array is used to separate numbers of // the form i+j+2ij from others where // 1 <= i <= j // Initialize all elements as not marked marked = Array.from({length: nNew + 1}, (_, i) => false); SieveOfSundaram(marked, nNew); var count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for(i = 1; i <= nNew; i++) { if (marked[i] == false) { prime_num = 2 * i + 1; // For a given prime number p // number of distinct pairs(i, j) // where (i + j) = p are p/2 count = count + parseInt(prime_num / 2); } } return count;} // Driver codevar n = 12;document.write("Number of prime pairs: " + countPrimePairs(n)); // This code is contributed by Princi Singh </script> Output: Number of prime pairs: 11 This article is contributed by Ayush Jauhari. 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. mohit kumar 29 Mithun Kumar Code_Mech Chandan_Kumar princi singh surinderdawra388 Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Minimum number of jumps to reach end
[ { "code": null, "e": 24586, "s": 24558, "text": "\n10 Mar, 2022" }, { "code": null, "e": 24689, "s": 24586, "text": "Given a positive integer n, count distinct number of pairs (x, y) that satisfy following conditions : " }, { "code": null, "e": 24716, "s": 24689, "text": "(x + y) is a prime number." }, { "code": null, "e": 24728, "s": 24716, "text": "(x + y) < n" }, { "code": null, "e": 24735, "s": 24728, "text": "x != y" }, { "code": null, "e": 24745, "s": 24735, "text": "1 <= x, y" }, { "code": null, "e": 24756, "s": 24745, "text": "Examples: " }, { "code": null, "e": 24990, "s": 24756, "text": "Input : n = 6\nOutput : 3\nprime pairs whose sum is less than 6 are:\n(1,2), (1,4), (2,3) \n\nInput : 12\nOutput : 11\nprime pairs whose sum is less than 12 are:\n(1,2), (1,4), (2,3), (1,6), (2,5), (3,4), \n(1,10), (2,9), (3,8), (4,7), (5,6)" }, { "code": null, "e": 25001, "s": 24990, "text": "Approach: " }, { "code": null, "e": 25282, "s": 25001, "text": "1) Find all prime numbers less than n using\n Sieve of Sundaram\n\n2) For each prime number p, count distinct\n pairs that sum up to p.\n \nFor any odd number n, number of distinct pairs\nthat add upto n are n/2\nSince, a prime number is a odd number, the \nsame applies for it too. " }, { "code": null, "e": 25473, "s": 25282, "text": "Example, For prime number p = 7 distinct pairs that add upto p: p/2 = 7/2 = 3 The three pairs are (1,6), (2,5), (3,4)For prime number p = 23 distinct pairs that add upto p: p/2 = 23/2 = 11 " }, { "code": null, "e": 25477, "s": 25473, "text": "C++" }, { "code": null, "e": 25482, "s": 25477, "text": "Java" }, { "code": null, "e": 25490, "s": 25482, "text": "Python3" }, { "code": null, "e": 25493, "s": 25490, "text": "C#" }, { "code": null, "e": 25497, "s": 25493, "text": "PHP" }, { "code": null, "e": 25508, "s": 25497, "text": "Javascript" }, { "code": "// C++ implementation of prime pairs// whose sum is less than n#include <bits/stdc++.h>using namespace std; // Sieve of Sundaram for generating// prime numbers less than nvoid SieveOfSundaram(bool marked[], int nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for (int i=1; i<=nNew; i++) for (int j=i; (i + j + 2*i*j) <= nNew; j++) marked[i + j + 2*i*j] = true;} // Returns number of pairs with given conditions.int countPrimePairs(int n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half int nNew = (n-2)/2; // This array is used to separate numbers of // the form i+j+2ij from others where // 1 <= i <= j bool marked[nNew + 1]; // Initialize all elements as not marked memset(marked, false, sizeof(marked)); SieveOfSundaram(marked, nNew); int count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for (int i=1; i<=nNew; i++) { if (marked[i] == false) { prime_num = 2*i + 1; // For a given prime number p // number of distinct pairs(i,j) // where (i+j) = p are p/2 count = count + (prime_num / 2); } } return count;} // Driver program to test aboveint main(void){ int n = 12; cout << \"Number of prime pairs: \" << countPrimePairs(n); return 0;}", "e": 27065, "s": 25508, "text": null }, { "code": "// Java implementation of prime pairs// whose sum is less than n class GFG{ // Sieve of Sundaram for generating// prime numbers less than nstatic void SieveOfSundaram(boolean marked[], int nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Returns number of pairs with given conditions.static int countPrimePairs(int n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of // the form i+j+2ij from others where // 1 <= i <= j // Initialize all elements as not marked boolean marked[]=new boolean[nNew + 1]; SieveOfSundaram(marked, nNew); int count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for (int i = 1; i <= nNew; i++) { if (marked[i] == false) { prime_num = 2 * i + 1; // For a given prime number p // number of distinct pairs(i, j) // where (i + j) = p are p/2 count = count + (prime_num / 2); } } return count;} // Driver codepublic static void main (String[] args){ int n = 12; System.out.println(\"Number of prime pairs: \" + countPrimePairs(n));}} // This code is contributed by mits", "e": 28652, "s": 27065, "text": null }, { "code": "# Python3 implementation of prime pairs# whose sum is less than n # Sieve of Sundaram for generating# prime numbers less than ndef SieveOfSundaram(marked, nNew): # Main logic of Sundaram. Mark all numbers # of the form i + j + 2ij as true where # 1 <= i <= j for i in range(1, nNew + 1): for j in range(i, nNew): if i + j + 2 * i * j > nNew: break marked[i + j + 2 * i * j] = True # Returns number of pairs with given conditions.def countPrimePairs(n): # In general Sieve of Sundaram, produces # primes smaller than (2*x + 2) for a number # given number x. Since we want primes smaller # than n, we reduce n to half nNew = (n - 2) // 2 # This array is used to separate numbers # of the form i+j+2ij from others where # 1 <= i <= j marked = [ False for i in range(nNew + 1)] SieveOfSundaram(marked, nNew) count, prime_num = 0, 0 # Find primes. Primes are of the form # 2*i + 1 such that marked[i] is false. for i in range(1, nNew + 1): if (marked[i] == False): prime_num = 2 * i + 1 # For a given prime number p # number of distinct pairs(i,j) # where (i+j) = p are p/2 count = count + (prime_num // 2) return count # Driver Coden = 12print(\"Number of prime pairs: \", countPrimePairs(n)) # This code is contributed by Mohit kumar 29", "e": 30076, "s": 28652, "text": null }, { "code": "// C# implementation of prime pairs// whose sum is less than nusing System; class GFG{ // Sieve of Sundaram for generating// prime numbers less than nstatic void SieveOfSundaram(bool[] marked, int nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Returns number of pairs with given conditions.static int countPrimePairs(int n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers // of the form i+j+2ij from others where // 1 <= i <= j // Initialize all elements as not marked bool[] marked = new bool[nNew + 1]; SieveOfSundaram(marked, nNew); int count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for (int i = 1; i <= nNew; i++) { if (marked[i] == false) { prime_num = 2 * i + 1; // For a given prime number p // number of distinct pairs(i, j) // where (i + j) = p are p/2 count = count + (prime_num / 2); } } return count;} // Driver codepublic static void Main (){ int n = 12; Console.WriteLine(\"Number of prime pairs: \" + countPrimePairs(n));}} // This Code is Contribute by Mukul Singh.", "e": 31724, "s": 30076, "text": null }, { "code": "<?php// PHP implementation of prime pairs// whose sum is less than n // Sieve of Sundaram for generating// prime numbers less than nfunction SieveOfSundaram(&$marked, $nNew){ // Main logic of Sundaram. Mark all // numbers of the form i + j + 2ij // as true where 1 <= i <= j for ($i = 1; $i <= $nNew; $i++) for ($j = $i; ($i + $j + 2 * $i * $j) <= $nNew; $j++) $marked[$i + $j + 2 * $i * $j] = true;} // Returns number of pairs with// given conditions.function countPrimePairs($n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than n, we reduce n to half $nNew = ($n - 2) / 2; // This array is used to separate numbers // of the form i+j+2ij from others where // 1 <= i <= j $marked = array_fill(0, $nNew + 1, false); SieveOfSundaram($marked, $nNew); $count = 0; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for ($i = 1; $i <= $nNew; $i++) { if ($marked[$i] == false) { $prime_num = 2 * $i + 1; // For a given prime number p // number of distinct pairs(i,j) // where (i+j) = p are p/2 $count = $count + (int)($prime_num / 2); } } return $count;} // Driver Code$n = 12;echo \"Number of prime pairs: \" . countPrimePairs($n); // This code is contributed by// chandan_jnu?>", "e": 33207, "s": 31724, "text": null }, { "code": "<script> // Javascript implementation of prime pairs// whose sum is less than n // Sieve of Sundaram for generating// prime numbers less than nfunction SieveOfSundaram(marked, nNew){ // Main logic of Sundaram. Mark all numbers // of the form i + j + 2ij as true where // 1 <= i <= j for(i = 1; i <= nNew; i++) for(j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Returns number of pairs with given conditions.function countPrimePairs(n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half var nNew = parseInt((n - 2) / 2); // This array is used to separate numbers of // the form i+j+2ij from others where // 1 <= i <= j // Initialize all elements as not marked marked = Array.from({length: nNew + 1}, (_, i) => false); SieveOfSundaram(marked, nNew); var count = 0, prime_num; // Find primes. Primes are of the form // 2*i + 1 such that marked[i] is false. for(i = 1; i <= nNew; i++) { if (marked[i] == false) { prime_num = 2 * i + 1; // For a given prime number p // number of distinct pairs(i, j) // where (i + j) = p are p/2 count = count + parseInt(prime_num / 2); } } return count;} // Driver codevar n = 12;document.write(\"Number of prime pairs: \" + countPrimePairs(n)); // This code is contributed by Princi Singh </script>", "e": 34775, "s": 33207, "text": null }, { "code": null, "e": 34784, "s": 34775, "text": "Output: " }, { "code": null, "e": 34810, "s": 34784, "text": "Number of prime pairs: 11" }, { "code": null, "e": 35232, "s": 34810, "text": "This article is contributed by Ayush Jauhari. 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": 35247, "s": 35232, "text": "mohit kumar 29" }, { "code": null, "e": 35260, "s": 35247, "text": "Mithun Kumar" }, { "code": null, "e": 35270, "s": 35260, "text": "Code_Mech" }, { "code": null, "e": 35284, "s": 35270, "text": "Chandan_Kumar" }, { "code": null, "e": 35297, "s": 35284, "text": "princi singh" }, { "code": null, "e": 35314, "s": 35297, "text": "surinderdawra388" }, { "code": null, "e": 35327, "s": 35314, "text": "Prime Number" }, { "code": null, "e": 35333, "s": 35327, "text": "sieve" }, { "code": null, "e": 35346, "s": 35333, "text": "Mathematical" }, { "code": null, "e": 35359, "s": 35346, "text": "Mathematical" }, { "code": null, "e": 35372, "s": 35359, "text": "Prime Number" }, { "code": null, "e": 35378, "s": 35372, "text": "sieve" }, { "code": null, "e": 35476, "s": 35378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35485, "s": 35476, "text": "Comments" }, { "code": null, "e": 35498, "s": 35485, "text": "Old Comments" }, { "code": null, "e": 35522, "s": 35498, "text": "Merge two sorted arrays" }, { "code": null, "e": 35565, "s": 35522, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35579, "s": 35565, "text": "Prime Numbers" }, { "code": null, "e": 35628, "s": 35579, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35649, "s": 35628, "text": "Operators in C / C++" }, { "code": null, "e": 35683, "s": 35649, "text": "Program for factorial of a number" }, { "code": null, "e": 35715, "s": 35683, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 35788, "s": 35715, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35831, "s": 35788, "text": "The Knight's tour problem | Backtracking-1" } ]
Calculating Wind Chill Factor(WCF) or Wind Chill Index(WCI) in Python
Wind Chill Factor is an indication of how cold we feel not just because of the atmospheric temperature but also taking into account the speed of the wind. It combines both these factors in form of an equation and gives us a measurement of how cold it actually feels when the wind blows at a higher speed even without any change in temperature. Below is the equation for calculating the Wind Chill Factor. Twc=13.12 + 0.6215Ta-11.37v+0.16 + 0.3965Tav+0.16 where Twc is the wind chill index, based on the Celsius temperature scale; Ta is the air temperature in degrees Celsius; and v is the wind speed at 10 m (33 ft) standard anemometer height, in kilometres per hour.[9] To apply this formula for calculating the value of the wind chill factor we will use the python math library as the power function in available in it. The below program achieves this. import math wind = float(input("Enter wind speed in kilometers/hour: ")) temperature = float(input("Enter air temperature in degrees Celsius: ")) wind_chill_factor_index = 13.12 + 0.6215*temperature \ - 11.37*math.pow(wind , 0.16) \ + 0.3965*temperature*math.pow(wind , 0.16) print("The wind chill index is", int(round( wind_chill_factor_index, 0))) Running the above code gives us the following result − Enter wind speed in kilometers/hour: 16 Enter air temperature in degrees Celsius: 27 The wind chill index is 29
[ { "code": null, "e": 1406, "s": 1062, "text": "Wind Chill Factor is an indication of how cold we feel not just because of the atmospheric temperature but also taking into account the speed of the wind. It combines both these factors in form of an equation and gives us a measurement of how cold it actually feels when the wind blows at a higher speed even without any change in temperature." }, { "code": null, "e": 1467, "s": 1406, "text": "Below is the equation for calculating the Wind Chill Factor." }, { "code": null, "e": 1517, "s": 1467, "text": "Twc=13.12 + 0.6215Ta-11.37v+0.16 + 0.3965Tav+0.16" }, { "code": null, "e": 1733, "s": 1517, "text": "where Twc is the wind chill index, based on the Celsius temperature scale;\nTa is the air temperature in degrees Celsius; and v is the wind speed at 10 m\n(33 ft) standard anemometer height, in kilometres per hour.[9]" }, { "code": null, "e": 1919, "s": 1733, "text": " To apply this formula for calculating the value of the wind chill factor we will use the python math library as the power function in available in it. The below program achieves this. " }, { "code": null, "e": 2275, "s": 1919, "text": "import math\nwind = float(input(\"Enter wind speed in kilometers/hour: \"))\ntemperature = float(input(\"Enter air temperature in degrees Celsius: \"))\nwind_chill_factor_index = 13.12 + 0.6215*temperature \\\n - 11.37*math.pow(wind , 0.16) \\\n + 0.3965*temperature*math.pow(wind , 0.16)\nprint(\"The wind chill index is\", int(round( wind_chill_factor_index, 0)))" }, { "code": null, "e": 2330, "s": 2275, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2442, "s": 2330, "text": "Enter wind speed in kilometers/hour: 16\nEnter air temperature in degrees Celsius: 27\nThe wind chill index is 29" } ]
In Android how to register a custom Intent filter to a broadcast receiver?
Before getting into the example, we should know what is intent filter in android. An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml. Android must know what kind of intent it is launching so intent filters give the information to android about intent and actions. Before launching intent, android going to test action test, category test and data test. This example demonstrate about how to use custom intent filters to a broadcast receiver 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:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/buton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="intent filter Register button" /> <Button android:id="@+id/buton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="send Data" /> </LinearLayout> In the above code we have two buttons, one is to register intent and another one is for send data to broadcast. package com.example.andy.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.Toast; public class MainActivity extends AppCompatActivity { RadioButton radioButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button button = findViewById(R.id.buton); final Button send = findViewById(R.id.buton1); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent("com.example.andy.CUSTOM_INTENT"); sendBroadcast(intent); } }); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registerReceiver(mMessageReceiver,new IntentFilter("com.example.andy.CUSTOM_INTENT")); } }); } private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getAction(); Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show(); } }; @Override protected void onPause() { super.onPause(); unregisterReceiver(mMessageReceiver); } } When you click on button it going to register receiver using custom broadcast action as shown below - registerReceiver(mMessageReceiver,new IntentFilter("com.example.andy.CUSTOM_INTENT")); It is a dynamic broadcast receiver so we should unregister onPause() as shown below- unregisterReceiver(mMessageReceiver); There is one more button to send brodcast. it going to send action and data to register receiver as shown below - Intent intent=new Intent("com.example.andy.CUSTOM_INTENT"); sendBroadcast(intent); It is dynamic broadcast register so we dont need to create a new receiver file for broadcast receiver so we have declare broadcast receiver in same activity as shown below - private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getAction(); Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show(); } }; In the above code it going to take data from intent as action and print on Toast. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − First we have register a receiver by clicking "intent filter register button" and click on send data to show toast as shown below - Click here to download the project code
[ { "code": null, "e": 1475, "s": 1062, "text": "Before getting into the example, we should know what is intent filter in android. An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml. Android must know what kind of intent it is launching so intent filters give the information to android about intent and actions." }, { "code": null, "e": 1664, "s": 1475, "text": "Before launching intent, android going to test action test, category test and data test. This example demonstrate about how to use custom intent filters to a broadcast receiver in android." }, { "code": null, "e": 1793, "s": 1664, "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": 1858, "s": 1793, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2607, "s": 1858, "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:gravity=\"center\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/buton\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"intent filter Register button\" />\n <Button\n android:id=\"@+id/buton1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"send Data\" />\n</LinearLayout>" }, { "code": null, "e": 2719, "s": 2607, "text": "In the above code we have two buttons, one is to register intent and another one is for send data to broadcast." }, { "code": null, "e": 4411, "s": 2719, "text": "package com.example.andy.myapplication;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RadioButton;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n RadioButton radioButton;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final Button button = findViewById(R.id.buton);\n final Button send = findViewById(R.id.buton1);\n send.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent=new Intent(\"com.example.andy.CUSTOM_INTENT\");\n sendBroadcast(intent);\n }\n });\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n registerReceiver(mMessageReceiver,new IntentFilter(\"com.example.andy.CUSTOM_INTENT\"));\n }\n });\n }\n private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n // Extract data included in the Intent\n String message = intent.getAction();\n Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();\n }\n };\n @Override\n protected void onPause() {\n super.onPause();\n unregisterReceiver(mMessageReceiver);\n }\n}" }, { "code": null, "e": 4513, "s": 4411, "text": "When you click on button it going to register receiver using custom broadcast action as shown below -" }, { "code": null, "e": 4600, "s": 4513, "text": "registerReceiver(mMessageReceiver,new IntentFilter(\"com.example.andy.CUSTOM_INTENT\"));" }, { "code": null, "e": 4685, "s": 4600, "text": "It is a dynamic broadcast receiver so we should unregister onPause() as shown below-" }, { "code": null, "e": 4723, "s": 4685, "text": "unregisterReceiver(mMessageReceiver);" }, { "code": null, "e": 4837, "s": 4723, "text": "There is one more button to send brodcast. it going to send action and data to register receiver as shown below -" }, { "code": null, "e": 4920, "s": 4837, "text": "Intent intent=new Intent(\"com.example.andy.CUSTOM_INTENT\");\nsendBroadcast(intent);" }, { "code": null, "e": 5094, "s": 4920, "text": "It is dynamic broadcast register so we dont need to create a new receiver file for broadcast receiver so we have declare broadcast receiver in same activity as shown below -" }, { "code": null, "e": 5407, "s": 5094, "text": "private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n // Extract data included in the Intent\n String message = intent.getAction();\n Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();\n }\n};" }, { "code": null, "e": 5836, "s": 5407, "text": "In the above code it going to take data from intent as action and print on Toast. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click 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": 5968, "s": 5836, "text": "First we have register a receiver by clicking \"intent filter register button\" and click on send data to show toast as shown below -" }, { "code": null, "e": 6008, "s": 5968, "text": "Click here to download the project code" } ]
How to create an ordered list using HTML5 ? - GeeksforGeeks
03 Jun, 2020 In this article, we define an ordered list by using the <ol> tag in the document, This tag is used for ordered list, an ordered list can be numerical or alphabetical. Inside the <ol> tag you have to make a list li of items that will follow the order. Syntax: <ol> <li>Item1</li> <li>Item2</li> <li>Item3</li> </ol> Example: <!DOCTYPE html><html> <head> <title> Define an ordered list? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> HTML5: How to define an ordered list? </h3> <p>reversed attribute</p> <ol reversed> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol> <p>start attribute</p> <ol start=5> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol> <p>type attribute</p> <ol type="i"> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol></body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Basics HTML-Misc HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n03 Jun, 2020" }, { "code": null, "e": 24754, "s": 24503, "text": "In this article, we define an ordered list by using the <ol> tag in the document, This tag is used for ordered list, an ordered list can be numerical or alphabetical. Inside the <ol> tag you have to make a list li of items that will follow the order." }, { "code": null, "e": 24762, "s": 24754, "text": "Syntax:" }, { "code": null, "e": 24828, "s": 24762, "text": "<ol>\n <li>Item1</li>\n <li>Item2</li>\n <li>Item3</li>\n</ol>\n" }, { "code": null, "e": 24837, "s": 24828, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Define an ordered list? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> HTML5: How to define an ordered list? </h3> <p>reversed attribute</p> <ol reversed> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol> <p>start attribute</p> <ol start=5> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol> <p>type attribute</p> <ol type=\"i\"> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol></body> </html> ", "e": 25427, "s": 24837, "text": null }, { "code": null, "e": 25435, "s": 25427, "text": "Output:" }, { "code": null, "e": 25455, "s": 25435, "text": "Supported Browsers:" }, { "code": null, "e": 25469, "s": 25455, "text": "Google Chrome" }, { "code": null, "e": 25487, "s": 25469, "text": "Internet Explorer" }, { "code": null, "e": 25495, "s": 25487, "text": "Firefox" }, { "code": null, "e": 25501, "s": 25495, "text": "Opera" }, { "code": null, "e": 25508, "s": 25501, "text": "Safari" }, { "code": null, "e": 25647, "s": 25510, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 25659, "s": 25647, "text": "HTML-Basics" }, { "code": null, "e": 25669, "s": 25659, "text": "HTML-Misc" }, { "code": null, "e": 25674, "s": 25669, "text": "HTML" }, { "code": null, "e": 25691, "s": 25674, "text": "Web Technologies" }, { "code": null, "e": 25718, "s": 25691, "text": "Web technologies Questions" }, { "code": null, "e": 25723, "s": 25718, "text": "HTML" }, { "code": null, "e": 25821, "s": 25723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25830, "s": 25821, "text": "Comments" }, { "code": null, "e": 25843, "s": 25830, "text": "Old Comments" }, { "code": null, "e": 25867, "s": 25843, "text": "REST API (Introduction)" }, { "code": null, "e": 25904, "s": 25867, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 25933, "s": 25904, "text": "Form validation using jQuery" }, { "code": null, "e": 25980, "s": 25933, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 26042, "s": 25980, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26098, "s": 26042, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26131, "s": 26098, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26174, "s": 26131, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26235, "s": 26174, "text": "Difference between var, let and const keywords in JavaScript" } ]
C Hello World Program - GeeksforGeeks
17 Jul, 2020 To begin with, the “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. All one needs to do is display the message “Hello World” on the screen. Let’s look at the program and try to understand the terminologies involved in it. C program to print Hello World // Simple C program to display "Hello World" // Header file for input output functions#include <stdio.h> // main function -// where the execution of program beginsint main(){ // prints hello world printf("Hello World"); return 0;} Hello World Compiling the First C Program:Before proceeding to write the first program, the user needs to set up a C program compiler, which would compile and execute the “Hello World” program. Here we have used Windows-based GCC compiler to compile and run the program. To know more on how to set up the local GCC compiler or running using online ide refer to Setting C Development Environment. Step 1: This requires writing the “Hello World” program, in a text editor and save the file with the extension .c, for example, we have stored the program in a C-type file HelloWorld.c. Step 2: This includes opening CMD or command prompt line navigating to the directory where the file HelloWorld.c is present. Here it is present in C:\Users\Chin\Sample. Step 3: To compile the code execute the following command:gcc HelloWorld.cThis would create a C-executable file with a random name given by the compiler itself. We got the executable filename as a.To give a user-oriented name, run the following command.gcc -o helloworld HelloWorld.c/pre> This would create a C-executable file by the name helloworld. Step 4: To run the executable file to get the result, just run the file. helloworld gcc HelloWorld.c This would create a C-executable file with a random name given by the compiler itself. We got the executable filename as a.To give a user-oriented name, run the following command. gcc -o helloworld HelloWorld.c/pre> This would create a C-executable file by the name helloworld. Step 4: To run the executable file to get the result, just run the file. helloworld Step 4: To run the executable file to get the result, just run the file. helloworld helloworld Explanation of the code: Let us now understand the terminologies of the above program: // Simple C program to display “Hello World”This is a single comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C+ is a comment.More on Comments in C#include In C, all lines that start with pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for Standard Input Output file which contains declarations of all the standard input/output library functions.More on Preprocessors in C.int main()This line is used to declare a function named "main" which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of program begins.More on main() function in C.{ and }: The opening braces '{' indicates the beginning of the main function and the closing braces '}' indicates the ending of the main function. Everything between these two comprises the body of the main function and are called the blocks.printf("Hello World");This line tells the compiler to display the message "Hello World" on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ';' is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The printf() function is used to print character stream of data on stdout console. Everything within " " is displayed to the output device.More on Input/Output in C.return 0;This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.More on return in C.Indentation: As you can see the printf and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not seem to hold much relevance but as the program becomes more complex, it makes the code more readable and less error-prone. Therefore, one must always use indentations and comments to make the code more readable.FAQ on the style of writing programs. // Simple C program to display “Hello World”This is a single comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C+ is a comment.More on Comments in C // Simple C program to display “Hello World” This is a single comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C+ is a comment.More on Comments in C #include In C, all lines that start with pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for Standard Input Output file which contains declarations of all the standard input/output library functions.More on Preprocessors in C. #include In C, all lines that start with pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for Standard Input Output file which contains declarations of all the standard input/output library functions.More on Preprocessors in C. int main()This line is used to declare a function named "main" which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of program begins.More on main() function in C. int main() This line is used to declare a function named "main" which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of program begins.More on main() function in C. { and }: The opening braces '{' indicates the beginning of the main function and the closing braces '}' indicates the ending of the main function. Everything between these two comprises the body of the main function and are called the blocks. printf("Hello World");This line tells the compiler to display the message "Hello World" on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ';' is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The printf() function is used to print character stream of data on stdout console. Everything within " " is displayed to the output device.More on Input/Output in C. printf("Hello World"); This line tells the compiler to display the message "Hello World" on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ';' is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The printf() function is used to print character stream of data on stdout console. Everything within " " is displayed to the output device.More on Input/Output in C. return 0;This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.More on return in C. return 0; This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.More on return in C. Indentation: As you can see the printf and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not seem to hold much relevance but as the program becomes more complex, it makes the code more readable and less error-prone. Therefore, one must always use indentations and comments to make the code more readable.FAQ on the style of writing programs. Akanksha_Rai C Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24563, "s": 24535, "text": "\n17 Jul, 2020" }, { "code": null, "e": 24872, "s": 24563, "text": "To begin with, the “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. All one needs to do is display the message “Hello World” on the screen. Let’s look at the program and try to understand the terminologies involved in it." }, { "code": null, "e": 24903, "s": 24872, "text": "C program to print Hello World" }, { "code": "// Simple C program to display \"Hello World\" // Header file for input output functions#include <stdio.h> // main function -// where the execution of program beginsint main(){ // prints hello world printf(\"Hello World\"); return 0;}", "e": 25149, "s": 24903, "text": null }, { "code": null, "e": 25162, "s": 25149, "text": "Hello World\n" }, { "code": null, "e": 25546, "s": 25162, "text": "Compiling the First C Program:Before proceeding to write the first program, the user needs to set up a C program compiler, which would compile and execute the “Hello World” program. Here we have used Windows-based GCC compiler to compile and run the program. To know more on how to set up the local GCC compiler or running using online ide refer to Setting C Development Environment." }, { "code": null, "e": 25732, "s": 25546, "text": "Step 1: This requires writing the “Hello World” program, in a text editor and save the file with the extension .c, for example, we have stored the program in a C-type file HelloWorld.c." }, { "code": null, "e": 25901, "s": 25732, "text": "Step 2: This includes opening CMD or command prompt line navigating to the directory where the file HelloWorld.c is present. Here it is present in C:\\Users\\Chin\\Sample." }, { "code": null, "e": 26343, "s": 25901, "text": "Step 3: To compile the code execute the following command:gcc HelloWorld.cThis would create a C-executable file with a random name given by the compiler itself. We got the executable filename as a.To give a user-oriented name, run the following command.gcc -o helloworld HelloWorld.c/pre>\nThis would create a C-executable file by the name helloworld.\n\n\n\n Step 4: To run the executable file to get the result, just run the file.\nhelloworld" }, { "code": null, "e": 26360, "s": 26343, "text": "gcc HelloWorld.c" }, { "code": null, "e": 26540, "s": 26360, "text": "This would create a C-executable file with a random name given by the compiler itself. We got the executable filename as a.To give a user-oriented name, run the following command." }, { "code": null, "e": 26729, "s": 26540, "text": "gcc -o helloworld HelloWorld.c/pre>\nThis would create a C-executable file by the name helloworld.\n\n\n\n Step 4: To run the executable file to get the result, just run the file.\nhelloworld" }, { "code": null, "e": 26813, "s": 26729, "text": "Step 4: To run the executable file to get the result, just run the file.\nhelloworld" }, { "code": null, "e": 26824, "s": 26813, "text": "helloworld" }, { "code": null, "e": 26849, "s": 26824, "text": "Explanation of the code:" }, { "code": null, "e": 26911, "s": 26849, "text": "Let us now understand the terminologies of the above program:" }, { "code": null, "e": 29657, "s": 26911, "text": "// Simple C program to display “Hello World”This is a single comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C+ is a comment.More on Comments in C#include In C, all lines that start with pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for Standard Input Output file which contains declarations of all the standard input/output library functions.More on Preprocessors in C.int main()This line is used to declare a function named \"main\" which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of program begins.More on main() function in C.{ and }: The opening braces '{' indicates the beginning of the main function and the closing braces '}' indicates the ending of the main function. Everything between these two comprises the body of the main function and are called the blocks.printf(\"Hello World\");This line tells the compiler to display the message \"Hello World\" on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ';' is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The printf() function is used to print character stream of data on stdout console. Everything within \" \" is displayed to the output device.More on Input/Output in C.return 0;This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.More on return in C.Indentation: As you can see the printf and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not seem to hold much relevance but as the program becomes more complex, it makes the code more readable and less error-prone. Therefore, one must always use indentations and comments to make the code more readable.FAQ on the style of writing programs." }, { "code": null, "e": 30084, "s": 29657, "text": "// Simple C program to display “Hello World”This is a single comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C+ is a comment.More on Comments in C" }, { "code": null, "e": 30129, "s": 30084, "text": "// Simple C program to display “Hello World”" }, { "code": null, "e": 30512, "s": 30129, "text": "This is a single comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic as it is not read by the compiler. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C+ is a comment.More on Comments in C" }, { "code": null, "e": 30938, "s": 30512, "text": "#include In C, all lines that start with pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for Standard Input Output file which contains declarations of all the standard input/output library functions.More on Preprocessors in C." }, { "code": null, "e": 30948, "s": 30938, "text": "#include " }, { "code": null, "e": 31365, "s": 30948, "text": "In C, all lines that start with pound (#) sign are called directives. These statements are processed by preprocessor program invoked by the compiler. The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to include the header file for Standard Input Output file which contains declarations of all the standard input/output library functions.More on Preprocessors in C." }, { "code": null, "e": 31805, "s": 31365, "text": "int main()This line is used to declare a function named \"main\" which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of program begins.More on main() function in C." }, { "code": null, "e": 31816, "s": 31805, "text": "int main()" }, { "code": null, "e": 32246, "s": 31816, "text": "This line is used to declare a function named \"main\" which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C program begins with the main() function, no matter where the function is located in the program. So, every C program must have a main() function and this is the function where the execution of program begins.More on main() function in C." }, { "code": null, "e": 32489, "s": 32246, "text": "{ and }: The opening braces '{' indicates the beginning of the main function and the closing braces '}' indicates the ending of the main function. Everything between these two comprises the body of the main function and are called the blocks." }, { "code": null, "e": 32993, "s": 32489, "text": "printf(\"Hello World\");This line tells the compiler to display the message \"Hello World\" on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ';' is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The printf() function is used to print character stream of data on stdout console. Everything within \" \" is displayed to the output device.More on Input/Output in C." }, { "code": null, "e": 33016, "s": 32993, "text": "printf(\"Hello World\");" }, { "code": null, "e": 33498, "s": 33016, "text": "This line tells the compiler to display the message \"Hello World\" on the screen. This line is called a statement in C. Every statement is meant to perform some task. A semi-colon ';' is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The printf() function is used to print character stream of data on stdout console. Everything within \" \" is displayed to the output device.More on Input/Output in C." }, { "code": null, "e": 33764, "s": 33498, "text": "return 0;This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.More on return in C." }, { "code": null, "e": 33774, "s": 33764, "text": "return 0;" }, { "code": null, "e": 34031, "s": 33774, "text": "This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.More on return in C." }, { "code": null, "e": 34477, "s": 34031, "text": "Indentation: As you can see the printf and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not seem to hold much relevance but as the program becomes more complex, it makes the code more readable and less error-prone. Therefore, one must always use indentations and comments to make the code more readable.FAQ on the style of writing programs." }, { "code": null, "e": 34490, "s": 34477, "text": "Akanksha_Rai" }, { "code": null, "e": 34501, "s": 34490, "text": "C Programs" }, { "code": null, "e": 34520, "s": 34501, "text": "School Programming" }, { "code": null, "e": 34618, "s": 34520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34627, "s": 34618, "text": "Comments" }, { "code": null, "e": 34640, "s": 34627, "text": "Old Comments" }, { "code": null, "e": 34681, "s": 34640, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 34712, "s": 34681, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 34753, "s": 34712, "text": "C program to find the length of a string" }, { "code": null, "e": 34787, "s": 34753, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 34840, "s": 34787, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 34858, "s": 34840, "text": "Python Dictionary" }, { "code": null, "e": 34874, "s": 34858, "text": "Arrays in C/C++" }, { "code": null, "e": 34899, "s": 34874, "text": "Reverse a string in Java" }, { "code": null, "e": 34918, "s": 34899, "text": "Inheritance in C++" } ]
Central Limit Theorem — Explained with Examples | by Soner Yıldırım | Towards Data Science
The central limit theorem (CLT) is a fundamental and widely used theorem in the field of statistics. Before we go in detail on CLT, let’s define some terms that will make it easier to comprehend the idea behind CLT. Population is all elements in a group. For example, college students in US is a population that includes all of the college students in US. 25-year-old people in Europe is a population that includes all of the people that fits the description. It is not always feasible or possible to do analysis on population because we cannot collect all the data of a population. Therefore, we use samples. Sample is a subset of a population. For example, 1000 college students in US is a subset of “college students in US” population. Probability distribution: A function that shows the probabilities of the outcomes of an event or experiment. Consider rolling a dice example. There are 6 possible outcomes (1,2,3,4,5,6). If the dice in unbiased, the probability of observing each number on top side is equal so the probability distibution is a discrete uniform distribution. Normal (Gaussian) distribution: A probability distribution that looks like a bell: Two terms that describe a normal distribution are mean and standard deviation. Mean is the average value that has the highest probability to be observed. Standard deviation is a measure of how spread out the values are. As standard deviation increases, the normal distribution curve gets wider. Normal distribution is used to represent random variables with unknown distributions. Thus, it is widely used in many fields including natural and social sciences. The reason to justify why it can used to represent random variables with unknown distributions is the central limit theorem (CLT). According to the CLT, as we take more samples from a distribution, the sample averages will tend towards a normal distribution regardless of the population distribution. Consider a case that we need to learn the distribution of the heights of all 20-year-old people in a country. It is almost impossible and, of course not practical, to collect this data. So, we take samples of 20-year-old people across the country and calculate the average height of the people in samples. According to the CLT, as we take more samples from the population, sampling distribution will get close to a normal distribution. Why is it so important to have a normal distribution? Normal distribution is described in terms of mean and standard deviation which can easily be calculated. And, if we know the mean and standard deviation of a normal distribution, we can compute pretty much everything about it. Let’s go over a few examples and prove that CLT is true. We will use python libraries to create populations, samples, and plots. As always, we start with importing related libraries: import numpy as npimport pandas as pd #Data visualizationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='darkgrid')%matplotlib inline We first define a function that will create random samples from a distribution. We can use sample function of pandas that will select random elements without replacement. def random_samples(population, sample_qty, sample_size): sample_means = [] for i in range(sample_qty): sample = population.sample(n=sample_size) sample_mean = np.array(sample).mean() sample_means.append(sample_mean) return sample_means We just need to input a population, how many samples we need (sample_qty), and the how many observations each sample includes (sample_size). Then the function will pick samples and calculate their means. The returned list will include the sample means. Let’s first define a population that actually has a normal distribution. We use np.random.randn function to create an array with a size of 10000 and a normal distribution. norm = list(np.random.randn(10000))plt.figure(figsize=(8,5))plt.title("Normal Distribution", fontsize=18)sns.distplot(norm, hist=False) Now we take 30 samples from this population and each sample includes 30 values. Please note that we need to convert the population to pandas series because sample function will not accept numpy arrays. population = pd.Series(norm)samples_from_normal = random_samples(population, 30, 30)plt.figure(figsize=(7,4))plt.title("Distribution of Sample Means - Normal Distribution", fontsize=15)sns.distplot(samples_from_normal, hist=False) The sampling distribution (distribution of sample means) looks pretty close to a normal distribution. As we take more samples with larges size, sampling distribution will look more “normal”. Let’s apply the same procedure to a population with random distribution. We first create an array with 1000 random numbers: random = np.random.random(1000)plt.figure(figsize=(7,4))plt.title("A Random Distribution", fontsize=15)sns.distplot(random, hist=False) Let’s see how sampling distribution will look like with 30 samples with 30 values each: population = pd.Series(random)samples_from_normal = random_samples(population, 30, 30)plt.figure(figsize=(7,4))plt.title("Distribution of Sample Means (30 samples)", fontsize=15)sns.distplot(samples_from_normal, hist=False) It is getting close to a normal distribution. We now try with 50 samples and also increase the sample size to 50: It definitely looks more “normal”. I added the code as texts so you can just copy-paste and try out with different sample quantity and sizes. We can also try the exponential distribution and see CLT applies: exp = np.random.exponential(0.01, 5000)plt.figure(figsize=(7,4))plt.title("Exponential Distribution", fontsize=15)sns.distplot(exp, hist=False) If we randomly take 50 samples with a size of 50, the distribution of the sample means look like: population = pd.Series(exp)samples_from_normal = random_samples(population, 50, 50)plt.figure(figsize=(7,4))plt.title("Distribution of Sample Means (50 samples)", fontsize=15)sns.distplot(samples_from_normal, hist=False) It looks more like a normal distribution than an exponential distribution. With 100 samples, normality is more prominent: As we have seen in the examples, regardless of the population distribution, the distribution of sample means get closer to a normal distribution as we take more samples. This is exactly what central limit theorem states. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 388, "s": 172, "text": "The central limit theorem (CLT) is a fundamental and widely used theorem in the field of statistics. Before we go in detail on CLT, let’s define some terms that will make it easier to comprehend the idea behind CLT." }, { "code": null, "e": 632, "s": 388, "text": "Population is all elements in a group. For example, college students in US is a population that includes all of the college students in US. 25-year-old people in Europe is a population that includes all of the people that fits the description." }, { "code": null, "e": 782, "s": 632, "text": "It is not always feasible or possible to do analysis on population because we cannot collect all the data of a population. Therefore, we use samples." }, { "code": null, "e": 911, "s": 782, "text": "Sample is a subset of a population. For example, 1000 college students in US is a subset of “college students in US” population." }, { "code": null, "e": 1252, "s": 911, "text": "Probability distribution: A function that shows the probabilities of the outcomes of an event or experiment. Consider rolling a dice example. There are 6 possible outcomes (1,2,3,4,5,6). If the dice in unbiased, the probability of observing each number on top side is equal so the probability distibution is a discrete uniform distribution." }, { "code": null, "e": 1335, "s": 1252, "text": "Normal (Gaussian) distribution: A probability distribution that looks like a bell:" }, { "code": null, "e": 1630, "s": 1335, "text": "Two terms that describe a normal distribution are mean and standard deviation. Mean is the average value that has the highest probability to be observed. Standard deviation is a measure of how spread out the values are. As standard deviation increases, the normal distribution curve gets wider." }, { "code": null, "e": 1925, "s": 1630, "text": "Normal distribution is used to represent random variables with unknown distributions. Thus, it is widely used in many fields including natural and social sciences. The reason to justify why it can used to represent random variables with unknown distributions is the central limit theorem (CLT)." }, { "code": null, "e": 2095, "s": 1925, "text": "According to the CLT, as we take more samples from a distribution, the sample averages will tend towards a normal distribution regardless of the population distribution." }, { "code": null, "e": 2531, "s": 2095, "text": "Consider a case that we need to learn the distribution of the heights of all 20-year-old people in a country. It is almost impossible and, of course not practical, to collect this data. So, we take samples of 20-year-old people across the country and calculate the average height of the people in samples. According to the CLT, as we take more samples from the population, sampling distribution will get close to a normal distribution." }, { "code": null, "e": 2812, "s": 2531, "text": "Why is it so important to have a normal distribution? Normal distribution is described in terms of mean and standard deviation which can easily be calculated. And, if we know the mean and standard deviation of a normal distribution, we can compute pretty much everything about it." }, { "code": null, "e": 2995, "s": 2812, "text": "Let’s go over a few examples and prove that CLT is true. We will use python libraries to create populations, samples, and plots. As always, we start with importing related libraries:" }, { "code": null, "e": 3148, "s": 2995, "text": "import numpy as npimport pandas as pd #Data visualizationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='darkgrid')%matplotlib inline" }, { "code": null, "e": 3319, "s": 3148, "text": "We first define a function that will create random samples from a distribution. We can use sample function of pandas that will select random elements without replacement." }, { "code": null, "e": 3585, "s": 3319, "text": "def random_samples(population, sample_qty, sample_size): sample_means = [] for i in range(sample_qty): sample = population.sample(n=sample_size) sample_mean = np.array(sample).mean() sample_means.append(sample_mean) return sample_means" }, { "code": null, "e": 3838, "s": 3585, "text": "We just need to input a population, how many samples we need (sample_qty), and the how many observations each sample includes (sample_size). Then the function will pick samples and calculate their means. The returned list will include the sample means." }, { "code": null, "e": 4010, "s": 3838, "text": "Let’s first define a population that actually has a normal distribution. We use np.random.randn function to create an array with a size of 10000 and a normal distribution." }, { "code": null, "e": 4146, "s": 4010, "text": "norm = list(np.random.randn(10000))plt.figure(figsize=(8,5))plt.title(\"Normal Distribution\", fontsize=18)sns.distplot(norm, hist=False)" }, { "code": null, "e": 4348, "s": 4146, "text": "Now we take 30 samples from this population and each sample includes 30 values. Please note that we need to convert the population to pandas series because sample function will not accept numpy arrays." }, { "code": null, "e": 4579, "s": 4348, "text": "population = pd.Series(norm)samples_from_normal = random_samples(population, 30, 30)plt.figure(figsize=(7,4))plt.title(\"Distribution of Sample Means - Normal Distribution\", fontsize=15)sns.distplot(samples_from_normal, hist=False)" }, { "code": null, "e": 4770, "s": 4579, "text": "The sampling distribution (distribution of sample means) looks pretty close to a normal distribution. As we take more samples with larges size, sampling distribution will look more “normal”." }, { "code": null, "e": 4894, "s": 4770, "text": "Let’s apply the same procedure to a population with random distribution. We first create an array with 1000 random numbers:" }, { "code": null, "e": 5030, "s": 4894, "text": "random = np.random.random(1000)plt.figure(figsize=(7,4))plt.title(\"A Random Distribution\", fontsize=15)sns.distplot(random, hist=False)" }, { "code": null, "e": 5118, "s": 5030, "text": "Let’s see how sampling distribution will look like with 30 samples with 30 values each:" }, { "code": null, "e": 5342, "s": 5118, "text": "population = pd.Series(random)samples_from_normal = random_samples(population, 30, 30)plt.figure(figsize=(7,4))plt.title(\"Distribution of Sample Means (30 samples)\", fontsize=15)sns.distplot(samples_from_normal, hist=False)" }, { "code": null, "e": 5456, "s": 5342, "text": "It is getting close to a normal distribution. We now try with 50 samples and also increase the sample size to 50:" }, { "code": null, "e": 5598, "s": 5456, "text": "It definitely looks more “normal”. I added the code as texts so you can just copy-paste and try out with different sample quantity and sizes." }, { "code": null, "e": 5664, "s": 5598, "text": "We can also try the exponential distribution and see CLT applies:" }, { "code": null, "e": 5808, "s": 5664, "text": "exp = np.random.exponential(0.01, 5000)plt.figure(figsize=(7,4))plt.title(\"Exponential Distribution\", fontsize=15)sns.distplot(exp, hist=False)" }, { "code": null, "e": 5906, "s": 5808, "text": "If we randomly take 50 samples with a size of 50, the distribution of the sample means look like:" }, { "code": null, "e": 6127, "s": 5906, "text": "population = pd.Series(exp)samples_from_normal = random_samples(population, 50, 50)plt.figure(figsize=(7,4))plt.title(\"Distribution of Sample Means (50 samples)\", fontsize=15)sns.distplot(samples_from_normal, hist=False)" }, { "code": null, "e": 6249, "s": 6127, "text": "It looks more like a normal distribution than an exponential distribution. With 100 samples, normality is more prominent:" }, { "code": null, "e": 6470, "s": 6249, "text": "As we have seen in the examples, regardless of the population distribution, the distribution of sample means get closer to a normal distribution as we take more samples. This is exactly what central limit theorem states." } ]
How do we upload external file on a website using HTML forms?
If you want to allow a user to upload an external file to your website, you need to use a file upload box, also known as a file select box. This is also created using the <input> element but type attribute is set to file. Live Demo You can try to run the following code to upload an external file to your website − <!DOCTYPE html> <html> <head> <title>File Upload</title> </head> <body> <form> <input type = "file" name = "upload" accept = "image/*" /> </form> </body> </html> Here are the attributes of the file upload box −
[ { "code": null, "e": 1284, "s": 1062, "text": "If you want to allow a user to upload an external file to your website, you need to use a file upload box, also known as a file select box. This is also created using the <input> element but type attribute is set to file." }, { "code": null, "e": 1294, "s": 1284, "text": "Live Demo" }, { "code": null, "e": 1377, "s": 1294, "text": "You can try to run the following code to upload an external file to your website −" }, { "code": null, "e": 1578, "s": 1377, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>File Upload</title>\n </head>\n <body>\n <form>\n <input type = \"file\" name = \"upload\" accept = \"image/*\" />\n </form>\n </body>\n</html>" }, { "code": null, "e": 1627, "s": 1578, "text": "Here are the attributes of the file upload box −" } ]
TensorFlow - Single Layer Perceptron
For understanding single layer perceptron, it is important to understand Artificial Neural Networks (ANN). Artificial neural networks is the information processing system the mechanism of which is inspired with the functionality of biological neural circuits. An artificial neural network possesses many processing units connected to each other. Following is the schematic representation of artificial neural network − The diagram shows that the hidden units communicate with the external layer. While the input and output units communicate only through the hidden layer of the network. The pattern of connection with nodes, the total number of layers and level of nodes between inputs and outputs with the number of neurons per layer define the architecture of a neural network. There are two types of architecture. These types focus on the functionality artificial neural networks as follows − Single Layer Perceptron Multi-Layer Perceptron Single layer perceptron is the first proposed neural model created. The content of the local memory of the neuron consists of a vector of weights. The computation of a single layer perceptron is performed over the calculation of sum of the input vector each with the value multiplied by corresponding element of vector of the weights. The value which is displayed in the output will be the input of an activation function. Let us focus on the implementation of single layer perceptron for an image classification problem using TensorFlow. The best example to illustrate the single layer perceptron is through representation of “Logistic Regression”. Now, let us consider the following basic steps of training logistic regression − The weights are initialized with random values at the beginning of the training. The weights are initialized with random values at the beginning of the training. For each element of the training set, the error is calculated with the difference between desired output and the actual output. The error calculated is used to adjust the weights. For each element of the training set, the error is calculated with the difference between desired output and the actual output. The error calculated is used to adjust the weights. The process is repeated until the error made on the entire training set is not less than the specified threshold, until the maximum number of iterations is reached. The process is repeated until the error made on the entire training set is not less than the specified threshold, until the maximum number of iterations is reached. The complete code for evaluation of logistic regression is mentioned below − # Import MINST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) import tensorflow as tf import matplotlib.pyplot as plt # Parameters learning_rate = 0.01 training_epochs = 25 batch_size = 100 display_step = 1 # tf Graph Input x = tf.placeholder("float", [None, 784]) # mnist data image of shape 28*28 = 784 y = tf.placeholder("float", [None, 10]) # 0-9 digits recognition => 10 classes # Create model # Set model weights W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # Construct model activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax # Minimize error using cross entropy cross_entropy = y*tf.log(activation) cost = tf.reduce_mean\ (-tf.reduce_sum\ (cross_entropy,reduction_indices = 1)) optimizer = tf.train.\ GradientDescentOptimizer(learning_rate).minimize(cost) #Plot settings avg_set = [] epoch_set = [] # Initializing the variables init = tf.initialize_all_variables() # Launch the graph with tf.Session() as sess: sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = \ mnist.train.next_batch(batch_size) # Fit training using batch data sess.run(optimizer, \ feed_dict = { x: batch_xs, y: batch_ys}) # Compute average loss avg_cost += sess.run(cost, \ feed_dict = { x: batch_xs, \ y: batch_ys})/total_batch # Display logs per epoch step if epoch % display_step == 0: print ("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) avg_set.append(avg_cost) epoch_set.append(epoch+1) print ("Training phase finished") plt.plot(epoch_set,avg_set, 'o', label = 'Logistic Regression Training phase') plt.ylabel('cost') plt.xlabel('epoch') plt.legend() plt.show() # Test model correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print ("Model accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) The above code generates the following output − The logistic regression is considered as a predictive analysis. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal or independent variables. 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 29 Lectures 3.5 hours Mohammad Nauman 82 Lectures 4 hours Anis Koubaa Print Add Notes Bookmark this page
[ { "code": null, "e": 2734, "s": 2315, "text": "For understanding single layer perceptron, it is important to understand Artificial Neural Networks (ANN). Artificial neural networks is the information processing system the mechanism of which is inspired with the functionality of biological neural circuits. An artificial neural network possesses many processing units connected to each other. Following is the schematic representation of artificial neural network −" }, { "code": null, "e": 2902, "s": 2734, "text": "The diagram shows that the hidden units communicate with the external layer. While the input and output units communicate only through the hidden layer of the network." }, { "code": null, "e": 3095, "s": 2902, "text": "The pattern of connection with nodes, the total number of layers and level of nodes between inputs and outputs with the number of neurons per layer define the architecture of a neural network." }, { "code": null, "e": 3211, "s": 3095, "text": "There are two types of architecture. These types focus on the functionality artificial neural networks as follows −" }, { "code": null, "e": 3235, "s": 3211, "text": "Single Layer Perceptron" }, { "code": null, "e": 3258, "s": 3235, "text": "Multi-Layer Perceptron" }, { "code": null, "e": 3681, "s": 3258, "text": "Single layer perceptron is the first proposed neural model created. The content of the local memory of the neuron consists of a vector of weights. The computation of a single layer perceptron is performed over the calculation of sum of the input vector each with the value multiplied by corresponding element of vector of the weights. The value which is displayed in the output will be the input of an activation function." }, { "code": null, "e": 3908, "s": 3681, "text": "Let us focus on the implementation of single layer perceptron for an image classification problem using TensorFlow. The best example to illustrate the single layer perceptron is through representation of “Logistic Regression”." }, { "code": null, "e": 3989, "s": 3908, "text": "Now, let us consider the following basic steps of training logistic regression −" }, { "code": null, "e": 4070, "s": 3989, "text": "The weights are initialized with random values at the beginning of the training." }, { "code": null, "e": 4151, "s": 4070, "text": "The weights are initialized with random values at the beginning of the training." }, { "code": null, "e": 4331, "s": 4151, "text": "For each element of the training set, the error is calculated with the difference between desired output and the actual output. The error calculated is used to adjust the weights." }, { "code": null, "e": 4511, "s": 4331, "text": "For each element of the training set, the error is calculated with the difference between desired output and the actual output. The error calculated is used to adjust the weights." }, { "code": null, "e": 4676, "s": 4511, "text": "The process is repeated until the error made on the entire training set is not less than the specified threshold, until the maximum number of iterations is reached." }, { "code": null, "e": 4841, "s": 4676, "text": "The process is repeated until the error made on the entire training set is not less than the specified threshold, until the maximum number of iterations is reached." }, { "code": null, "e": 4918, "s": 4841, "text": "The complete code for evaluation of logistic regression is mentioned below −" }, { "code": null, "e": 7242, "s": 4918, "text": "# Import MINST data \nfrom tensorflow.examples.tutorials.mnist import input_data \nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot = True) \n\nimport tensorflow as tf \nimport matplotlib.pyplot as plt \n\n# Parameters \nlearning_rate = 0.01 \ntraining_epochs = 25 \nbatch_size = 100 \ndisplay_step = 1 \n\n# tf Graph Input \nx = tf.placeholder(\"float\", [None, 784]) # mnist data image of shape 28*28 = 784 \ny = tf.placeholder(\"float\", [None, 10]) # 0-9 digits recognition => 10 classes \n\n# Create model \n# Set model weights \nW = tf.Variable(tf.zeros([784, 10])) \nb = tf.Variable(tf.zeros([10])) \n\n# Construct model \nactivation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax \n\n# Minimize error using cross entropy \ncross_entropy = y*tf.log(activation) \ncost = tf.reduce_mean\\ (-tf.reduce_sum\\ (cross_entropy,reduction_indices = 1)) \n\noptimizer = tf.train.\\ GradientDescentOptimizer(learning_rate).minimize(cost) \n\n#Plot settings \navg_set = [] \nepoch_set = [] \n\n# Initializing the variables init = tf.initialize_all_variables()\n# Launch the graph \nwith tf.Session() as sess:\n sess.run(init)\n \n # Training cycle\n for epoch in range(training_epochs):\n avg_cost = 0.\n total_batch = int(mnist.train.num_examples/batch_size)\n \n # Loop over all batches\n for i in range(total_batch):\n batch_xs, batch_ys = \\ mnist.train.next_batch(batch_size)\n # Fit training using batch data sess.run(optimizer, \\ feed_dict = {\n x: batch_xs, y: batch_ys}) \n # Compute average loss avg_cost += sess.run(cost, \\ feed_dict = {\n x: batch_xs, \\ y: batch_ys})/total_batch\n # Display logs per epoch step\n if epoch % display_step == 0:\n print (\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost))\n avg_set.append(avg_cost) epoch_set.append(epoch+1)\n print (\"Training phase finished\")\n \n plt.plot(epoch_set,avg_set, 'o', label = 'Logistic Regression Training phase') \n plt.ylabel('cost') \n plt.xlabel('epoch') \n plt.legend() \n plt.show() \n \n # Test model \n correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1)) \n \n # Calculate accuracy \n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\")) print \n (\"Model accuracy:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))" }, { "code": null, "e": 7290, "s": 7242, "text": "The above code generates the following output −" }, { "code": null, "e": 7519, "s": 7290, "text": "The logistic regression is considered as a predictive analysis. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal or independent variables." }, { "code": null, "e": 7552, "s": 7519, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 7574, "s": 7552, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7607, "s": 7574, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 7629, "s": 7607, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7662, "s": 7629, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 7684, "s": 7662, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7717, "s": 7684, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 7739, "s": 7717, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7774, "s": 7739, "text": "\n 29 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7791, "s": 7774, "text": " Mohammad Nauman" }, { "code": null, "e": 7824, "s": 7791, "text": "\n 82 Lectures \n 4 hours \n" }, { "code": null, "e": 7837, "s": 7824, "text": " Anis Koubaa" }, { "code": null, "e": 7844, "s": 7837, "text": " Print" }, { "code": null, "e": 7855, "s": 7844, "text": " Add Notes" } ]
How can I restore multiple databases or all databases dumped by mysqldump?
Suppose if we have dumped multiple databases or all the databases and now want to restore it then we can do it with the following example − C:\mysql\bin>mysql -u root < tutorials_query1.sql With the help of above query, we are restoring the dumped multiple databases named ‘tutorials’ and ‘query1’, which are dumped in the file named ‘tutorials_query1.sql’. In this case, we do not need to write the name of the database. Similarly, with the help of the following query, we can restore all the databases dumped by mysqldump − C:\mysql\bin>mysql -u root < alldatabases.sql With the help of above query, we are restoring all the dumped databases, which are dumped in the file named ‘alldatabases.sql’. In this case, we do not need to write the name of the database.
[ { "code": null, "e": 1327, "s": 1187, "text": "Suppose if we have dumped multiple databases or all the databases and now want to restore it then we can do it with the following example −" }, { "code": null, "e": 1377, "s": 1327, "text": "C:\\mysql\\bin>mysql -u root < tutorials_query1.sql" }, { "code": null, "e": 1609, "s": 1377, "text": "With the help of above query, we are restoring the dumped multiple databases named ‘tutorials’ and ‘query1’, which are dumped in the file named ‘tutorials_query1.sql’. In this case, we do not need to write the name of the database." }, { "code": null, "e": 1713, "s": 1609, "text": "Similarly, with the help of the following query, we can restore all the databases dumped by mysqldump −" }, { "code": null, "e": 1759, "s": 1713, "text": "C:\\mysql\\bin>mysql -u root < alldatabases.sql" }, { "code": null, "e": 1951, "s": 1759, "text": "With the help of above query, we are restoring all the dumped databases, which are dumped in the file named ‘alldatabases.sql’. In this case, we do not need to write the name of the database." } ]
Python program to print the hexadecimal value of the numbers from 1 to N
03 Jan, 2021 Given a number N, the task is to write a Python program to print the hexadecimal value of the numbers from 1 to N. Examples: Input: 3 Output: 1 2 3 Input: 11 Output: 1 2 3 4 5 6 7 8 9 a b Approach: We will take the value of N as input. Then, we will run the for loop from 1 to N+1 and traverse each “i” through hex() function. Print each hexadecimal value. Note: The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Below are the implementations based on the above approach: Python3 # Python program to print the hexadecimal value of the # numbers from 1 to N # Function to find the hexadecimal value of the numbers# in the range 1 to Ndef hex_in_range(n): # For loop traversing from 1 to N (Both Inclusive) for i in range(1, n+1): # Printing hexadecimal value of i print(hex(i)[2:]) # Calling the function with input 3print("Input: 3")hex_in_range(3) # Calling the function with input 11print("Input: 11")hex_in_range(11) Output: Input: 3 1 2 3 Input: 11 1 2 3 4 5 6 7 8 9 a b Python-Built-in-functions Technical Scripter 2020 Python Python Programs Technical Scripter 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 | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2021" }, { "code": null, "e": 143, "s": 28, "text": "Given a number N, the task is to write a Python program to print the hexadecimal value of the numbers from 1 to N." }, { "code": null, "e": 153, "s": 143, "text": "Examples:" }, { "code": null, "e": 313, "s": 153, "text": "Input: 3\nOutput: 1\n 2\n 3\n\nInput: 11\nOutput: 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n a\n b" }, { "code": null, "e": 323, "s": 313, "text": "Approach:" }, { "code": null, "e": 361, "s": 323, "text": "We will take the value of N as input." }, { "code": null, "e": 452, "s": 361, "text": "Then, we will run the for loop from 1 to N+1 and traverse each “i” through hex() function." }, { "code": null, "e": 482, "s": 452, "text": "Print each hexadecimal value." }, { "code": null, "e": 636, "s": 482, "text": "Note: The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form." }, { "code": null, "e": 695, "s": 636, "text": "Below are the implementations based on the above approach:" }, { "code": null, "e": 703, "s": 695, "text": "Python3" }, { "code": "# Python program to print the hexadecimal value of the # numbers from 1 to N # Function to find the hexadecimal value of the numbers# in the range 1 to Ndef hex_in_range(n): # For loop traversing from 1 to N (Both Inclusive) for i in range(1, n+1): # Printing hexadecimal value of i print(hex(i)[2:]) # Calling the function with input 3print(\"Input: 3\")hex_in_range(3) # Calling the function with input 11print(\"Input: 11\")hex_in_range(11)", "e": 1182, "s": 703, "text": null }, { "code": null, "e": 1190, "s": 1182, "text": "Output:" }, { "code": null, "e": 1237, "s": 1190, "text": "Input: 3\n1\n2\n3\nInput: 11\n1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb" }, { "code": null, "e": 1263, "s": 1237, "text": "Python-Built-in-functions" }, { "code": null, "e": 1287, "s": 1263, "text": "Technical Scripter 2020" }, { "code": null, "e": 1294, "s": 1287, "text": "Python" }, { "code": null, "e": 1310, "s": 1294, "text": "Python Programs" }, { "code": null, "e": 1329, "s": 1310, "text": "Technical Scripter" }, { "code": null, "e": 1427, "s": 1329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1459, "s": 1427, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1486, "s": 1459, "text": "Python Classes and Objects" }, { "code": null, "e": 1507, "s": 1486, "text": "Python OOPs Concepts" }, { "code": null, "e": 1530, "s": 1507, "text": "Introduction To PYTHON" }, { "code": null, "e": 1586, "s": 1530, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1608, "s": 1586, "text": "Defaultdict in Python" }, { "code": null, "e": 1647, "s": 1608, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1685, "s": 1647, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1734, "s": 1685, "text": "Python | Convert string dictionary to dictionary" } ]
Containers in Bootstrap with examples
27 Apr, 2022 In bootstrap, the container is used to set the content’s margin. It contains row elements and the row elements are containers of columns. This is known as the grid system. There are two container classes in bootstrap: .container.container-fluid .container .container-fluid Let’s look at each of the above two classes in detail with examples: .container: The .container class provides a responsive fixed width container.In the below example, the div with class “container” will have a fixed left and right margin and will not take the complete width of its parent or the viewport. HTML <!-- Bootstrap container class --><!DOCTYPE html><html><head> <title>Bootstrap Container Example</title> <!-- Add Bootstrap Links --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script></head><body> <!-- Since we are using the class container, the below div will not take complete width of its parent. --> <div class="container" style="background: green;"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks.</p> </div></body></html> Output: .container-fluid: The .container-fluid class provides a full-width container which spans the entire width of the viewport.In the below example, the div with class “container-fluid” will take up the complete width of the viewport and will expand or shrink whenever the viewport is resized. HTML <!-- Bootstrap container-fluid class --><!DOCTYPE html><html><head> <title>Bootstrap Container Example</title> <!-- Add Bootstrap Links --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script></head><body> <!-- Since we are using the class container-fluid, the below div will expand whenever the viewport is resized. --> <div class="container-fluid" style="background: green;"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks.</p> </div></body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 sahilintern Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to set Bootstrap Timepicker using datetimepicker library ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n27 Apr, 2022" }, { "code": null, "e": 273, "s": 53, "text": "In bootstrap, the container is used to set the content’s margin. It contains row elements and the row elements are containers of columns. This is known as the grid system. There are two container classes in bootstrap: " }, { "code": null, "e": 300, "s": 273, "text": ".container.container-fluid" }, { "code": null, "e": 311, "s": 300, "text": ".container" }, { "code": null, "e": 328, "s": 311, "text": ".container-fluid" }, { "code": null, "e": 397, "s": 328, "text": "Let’s look at each of the above two classes in detail with examples:" }, { "code": null, "e": 635, "s": 397, "text": ".container: The .container class provides a responsive fixed width container.In the below example, the div with class “container” will have a fixed left and right margin and will not take the complete width of its parent or the viewport." }, { "code": null, "e": 640, "s": 635, "text": "HTML" }, { "code": "<!-- Bootstrap container class --><!DOCTYPE html><html><head> <title>Bootstrap Container Example</title> <!-- Add Bootstrap Links --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script></head><body> <!-- Since we are using the class container, the below div will not take complete width of its parent. --> <div class=\"container\" style=\"background: green;\"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks.</p> </div></body></html>", "e": 1370, "s": 640, "text": null }, { "code": null, "e": 1378, "s": 1370, "text": "Output:" }, { "code": null, "e": 1668, "s": 1378, "text": ".container-fluid: The .container-fluid class provides a full-width container which spans the entire width of the viewport.In the below example, the div with class “container-fluid” will take up the complete width of the viewport and will expand or shrink whenever the viewport is resized. " }, { "code": null, "e": 1673, "s": 1668, "text": "HTML" }, { "code": "<!-- Bootstrap container-fluid class --><!DOCTYPE html><html><head> <title>Bootstrap Container Example</title> <!-- Add Bootstrap Links --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script></head><body> <!-- Since we are using the class container-fluid, the below div will expand whenever the viewport is resized. --> <div class=\"container-fluid\" style=\"background: green;\"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks.</p> </div></body></html>", "e": 2423, "s": 1673, "text": null }, { "code": null, "e": 2431, "s": 2423, "text": "Output:" }, { "code": null, "e": 2450, "s": 2431, "text": "Supported Browser:" }, { "code": null, "e": 2464, "s": 2450, "text": "Google Chrome" }, { "code": null, "e": 2482, "s": 2464, "text": "Internet Explorer" }, { "code": null, "e": 2490, "s": 2482, "text": "Firefox" }, { "code": null, "e": 2496, "s": 2490, "text": "Opera" }, { "code": null, "e": 2503, "s": 2496, "text": "Safari" }, { "code": null, "e": 2515, "s": 2503, "text": "ysachin2314" }, { "code": null, "e": 2527, "s": 2515, "text": "sahilintern" }, { "code": null, "e": 2534, "s": 2527, "text": "Picked" }, { "code": null, "e": 2544, "s": 2534, "text": "Bootstrap" }, { "code": null, "e": 2561, "s": 2544, "text": "Web Technologies" }, { "code": null, "e": 2659, "s": 2561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2709, "s": 2659, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 2738, "s": 2709, "text": "Form validation using jQuery" }, { "code": null, "e": 2779, "s": 2738, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 2835, "s": 2779, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 2898, "s": 2835, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 2931, "s": 2898, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2993, "s": 2931, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3054, "s": 2993, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3104, "s": 3054, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to specify no border in CSS ?
26 Mar, 2021 We can specify the no border property using CSS border: none, border-width : 0, border : 0 properties. Approach 1: We will give border-color, border-style properties to both headings, for showing text with border and no-border. For no border heading, we will use the border-width : 0 which will result in no border. Example: HTML <!DOCTYPE html><html><head> <title>No Border CSS</title></head><body> <h1 style="border-color : red ; border-style : solid ; border-width : 0">GFG Best For Interview Preparation And Much more</h1> <h1 style="border-color : red ; border-style : solid ;">GFG Best For Interview Preparation And Much more</h1></body></html> Output : no border Approach 2 : We will give border-color, border-style properties to both headings, for showing text with border and no-border. For no border heading, we will use the border : 0 which will result in no border. Example: HTML <!DOCTYPE html><html><head> <title>No Border CSS</title></head><body> <h1 style="border-color : green ; border-style : solid ; border : 0">GFG Best For Interview Preparation And Much more</h1> <h1 style="border-color : green ; border-style : solid ;">GFG Best For Interview Preparation And Much more</h1></body></html> Output : no border Approach 3: We will give border-color, border-style properties to both headings, for showing text with border and no-border. For no border heading, we will use the border: none which will result in no border. Example: HTML <!DOCTYPE html><html><head> <title>No Border CSS</title></head><body> <h1 style="border-color : green ; border-style : solid ; border : none">GFG Best For Interview Preparation And Much more</h1> <h1 style="border-color : green ; border-style : solid ;">GFG Best For Interview Preparation And Much more</h1></body></html> Output : no border CSS-Properties CSS-Questions Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2021" }, { "code": null, "e": 131, "s": 28, "text": "We can specify the no border property using CSS border: none, border-width : 0, border : 0 properties." }, { "code": null, "e": 143, "s": 131, "text": "Approach 1:" }, { "code": null, "e": 256, "s": 143, "text": "We will give border-color, border-style properties to both headings, for showing text with border and no-border." }, { "code": null, "e": 344, "s": 256, "text": "For no border heading, we will use the border-width : 0 which will result in no border." }, { "code": null, "e": 353, "s": 344, "text": "Example:" }, { "code": null, "e": 358, "s": 353, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>No Border CSS</title></head><body> <h1 style=\"border-color : red ; border-style : solid ; border-width : 0\">GFG Best For Interview Preparation And Much more</h1> <h1 style=\"border-color : red ; border-style : solid ;\">GFG Best For Interview Preparation And Much more</h1></body></html>", "e": 714, "s": 358, "text": null }, { "code": null, "e": 723, "s": 714, "text": "Output :" }, { "code": null, "e": 734, "s": 723, "text": "no border " }, { "code": null, "e": 747, "s": 734, "text": "Approach 2 :" }, { "code": null, "e": 861, "s": 747, "text": " We will give border-color, border-style properties to both headings, for showing text with border and no-border." }, { "code": null, "e": 943, "s": 861, "text": "For no border heading, we will use the border : 0 which will result in no border." }, { "code": null, "e": 952, "s": 943, "text": "Example:" }, { "code": null, "e": 957, "s": 952, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>No Border CSS</title></head><body> <h1 style=\"border-color : green ; border-style : solid ; border : 0\">GFG Best For Interview Preparation And Much more</h1> <h1 style=\"border-color : green ; border-style : solid ;\">GFG Best For Interview Preparation And Much more</h1></body></html>", "e": 1310, "s": 957, "text": null }, { "code": null, "e": 1319, "s": 1310, "text": "Output :" }, { "code": null, "e": 1330, "s": 1319, "text": "no border " }, { "code": null, "e": 1342, "s": 1330, "text": "Approach 3:" }, { "code": null, "e": 1456, "s": 1342, "text": " We will give border-color, border-style properties to both headings, for showing text with border and no-border." }, { "code": null, "e": 1540, "s": 1456, "text": "For no border heading, we will use the border: none which will result in no border." }, { "code": null, "e": 1549, "s": 1540, "text": "Example:" }, { "code": null, "e": 1554, "s": 1549, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>No Border CSS</title></head><body> <h1 style=\"border-color : green ; border-style : solid ; border : none\">GFG Best For Interview Preparation And Much more</h1> <h1 style=\"border-color : green ; border-style : solid ;\">GFG Best For Interview Preparation And Much more</h1></body></html>", "e": 1909, "s": 1554, "text": null }, { "code": null, "e": 1918, "s": 1909, "text": "Output :" }, { "code": null, "e": 1928, "s": 1918, "text": "no border" }, { "code": null, "e": 1943, "s": 1928, "text": "CSS-Properties" }, { "code": null, "e": 1957, "s": 1943, "text": "CSS-Questions" }, { "code": null, "e": 1964, "s": 1957, "text": "Picked" }, { "code": null, "e": 1968, "s": 1964, "text": "CSS" }, { "code": null, "e": 1985, "s": 1968, "text": "Web Technologies" }, { "code": null, "e": 2083, "s": 1985, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2122, "s": 2083, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2161, "s": 2122, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2200, "s": 2161, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2229, "s": 2200, "text": "Form validation using jQuery" }, { "code": null, "e": 2266, "s": 2229, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2299, "s": 2266, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2360, "s": 2299, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2403, "s": 2360, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2475, "s": 2403, "text": "Differences between Functional Components and Class Components in React" } ]
MongoDB – countDocuments() Method
05 Feb, 2021 In MongoDB, the countDocuments() method counts the number of documents that matches to the selection criteria. It returns a numeric value that represents the total number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and other is optional. This method does not use metadata to return the count. It performs aggregation of the documents and returns a precise count. You are allowed to use this method in multi-document transactions. This method returns 0 for empty collection or if the given collection is not present in the database. In this method, you are not allowed to use $where, $near, and $nearSphere operators as a part of the query expressions. Syntax: db.Collection_name.countDocuments( <Selection_criteria>, { limit: <integer>, skip: <integer>, hint: <string or document>, maxTimeMS: <integer>, }) Parameters: The first parameter is a selection criteria. The type of this parameter is a document. If you want to count the total number of documents present in the collection pass an empty document({}). The second parameter is optional. Optional Parameters: limit: It is the maximum number of documents to count. skip: It is the number of documents to skip before counting. hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error. maxTimeMs: It is the maximum amount of time to allow the query to run. Return: This method returns the number of documents that match to selection criteria. Examples: In the following examples, we are working with: Database: gfg Collections: student Document: Four documents contains name and age of the students Count the number of documents in the given collection: db.student.countDocuments({}) Here, we are counting the total number of documents present in the student collection. Count the number of documents that match the given selection criteria: db.student.countDocuments({age:{$gt:18}}) Here, we are counting the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18. Note: Here, $gt mean greater than MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. MongoDB Cursor MongoDB - Index Types Capped Collections in MongoDB MongoDB - Map Reduce How to connect MongoDB with ReactJS ? MongoDB - Replication and Sharding MongoDB Tutorial MongoDB - sort() Method Spring Boot - CRUD Operations using MongoDB MongoDB updateOne() Method - db.Collection.updateOne()
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2021" }, { "code": null, "e": 330, "s": 28, "text": "In MongoDB, the countDocuments() method counts the number of documents that matches to the selection criteria. It returns a numeric value that represents the total number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and other is optional. " }, { "code": null, "e": 455, "s": 330, "text": "This method does not use metadata to return the count. It performs aggregation of the documents and returns a precise count." }, { "code": null, "e": 522, "s": 455, "text": "You are allowed to use this method in multi-document transactions." }, { "code": null, "e": 624, "s": 522, "text": "This method returns 0 for empty collection or if the given collection is not present in the database." }, { "code": null, "e": 745, "s": 624, "text": "In this method, you are not allowed to use $where, $near, and $nearSphere operators as a part of the query expressions. " }, { "code": null, "e": 753, "s": 745, "text": "Syntax:" }, { "code": null, "e": 788, "s": 753, "text": "db.Collection_name.countDocuments(" }, { "code": null, "e": 810, "s": 788, "text": "<Selection_criteria>," }, { "code": null, "e": 812, "s": 810, "text": "{" }, { "code": null, "e": 834, "s": 812, "text": " limit: <integer>," }, { "code": null, "e": 855, "s": 834, "text": " skip: <integer>," }, { "code": null, "e": 887, "s": 855, "text": " hint: <string or document>," }, { "code": null, "e": 915, "s": 887, "text": " maxTimeMS: <integer>, " }, { "code": null, "e": 918, "s": 915, "text": "})" }, { "code": null, "e": 930, "s": 918, "text": "Parameters:" }, { "code": null, "e": 1122, "s": 930, "text": "The first parameter is a selection criteria. The type of this parameter is a document. If you want to count the total number of documents present in the collection pass an empty document({})." }, { "code": null, "e": 1156, "s": 1122, "text": "The second parameter is optional." }, { "code": null, "e": 1177, "s": 1156, "text": "Optional Parameters:" }, { "code": null, "e": 1232, "s": 1177, "text": "limit: It is the maximum number of documents to count." }, { "code": null, "e": 1293, "s": 1232, "text": "skip: It is the number of documents to skip before counting." }, { "code": null, "e": 1526, "s": 1293, "text": "hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error." }, { "code": null, "e": 1597, "s": 1526, "text": "maxTimeMs: It is the maximum amount of time to allow the query to run." }, { "code": null, "e": 1607, "s": 1597, "text": "Return: " }, { "code": null, "e": 1685, "s": 1607, "text": "This method returns the number of documents that match to selection criteria." }, { "code": null, "e": 1695, "s": 1685, "text": "Examples:" }, { "code": null, "e": 1743, "s": 1695, "text": "In the following examples, we are working with:" }, { "code": null, "e": 1757, "s": 1743, "text": "Database: gfg" }, { "code": null, "e": 1778, "s": 1757, "text": "Collections: student" }, { "code": null, "e": 1841, "s": 1778, "text": "Document: Four documents contains name and age of the students" }, { "code": null, "e": 1896, "s": 1841, "text": "Count the number of documents in the given collection:" }, { "code": null, "e": 1926, "s": 1896, "text": "db.student.countDocuments({})" }, { "code": null, "e": 2013, "s": 1926, "text": "Here, we are counting the total number of documents present in the student collection." }, { "code": null, "e": 2084, "s": 2013, "text": "Count the number of documents that match the given selection criteria:" }, { "code": null, "e": 2126, "s": 2084, "text": "db.student.countDocuments({age:{$gt:18}})" }, { "code": null, "e": 2268, "s": 2126, "text": "Here, we are counting the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18." }, { "code": null, "e": 2302, "s": 2268, "text": "Note: Here, $gt mean greater than" }, { "code": null, "e": 2317, "s": 2302, "text": "MongoDB-method" }, { "code": null, "e": 2324, "s": 2317, "text": "Picked" }, { "code": null, "e": 2332, "s": 2324, "text": "MongoDB" }, { "code": null, "e": 2430, "s": 2332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2445, "s": 2430, "text": "MongoDB Cursor" }, { "code": null, "e": 2467, "s": 2445, "text": "MongoDB - Index Types" }, { "code": null, "e": 2497, "s": 2467, "text": "Capped Collections in MongoDB" }, { "code": null, "e": 2518, "s": 2497, "text": "MongoDB - Map Reduce" }, { "code": null, "e": 2556, "s": 2518, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 2591, "s": 2556, "text": "MongoDB - Replication and Sharding" }, { "code": null, "e": 2608, "s": 2591, "text": "MongoDB Tutorial" }, { "code": null, "e": 2632, "s": 2608, "text": "MongoDB - sort() Method" }, { "code": null, "e": 2676, "s": 2632, "text": "Spring Boot - CRUD Operations using MongoDB" } ]
SUBSTRING_INDEX() function in MySQL
23 Sep, 2020 SUBSTRING_INDEX() function in MySQL is used to return a substring from a string before a specified number of occurrences of the delimiter. Syntax : SUBSTRING_INDEX( str, delim, count ) Parameter : This method accepts three-parameter as mentioned above and described below : str : The original string from which we want to create a substring. delim : Is a string that acts as a delimiter. The function performs a case-sensitive match when searching for the delimiter. count : It identifies the number of times to search for the delimiter. It can be both a positive or negative number. If it is a positive number, this function returns all to the left of the delimiter. If it is a negative number, this function returns all to the right of the delimiter. Returns : It returns substring from a given string. Example-1 : SUBSTRING_INDEX() function with a positive number of occurrences of a delimiter SELECT SUBSTRING_INDEX("www.geeksforgeeks.org", ".", 2) as Sub_Str; Output : Example-2 : SUBSTRING_INDEX() function with a negative number of occurrences of a delimiter. SELECT SUBSTRING_INDEX("www.geeksforgeeks.org", ".", -2) as Sub_Str; Output : Example-3 : SUBSTRING_INDEX() function with the table data. Table : Employee : Now, we will find the pin number address of every employee by using SUBSTRING_INDEX function. SELECT SUBSTRING_INDEX(Address, ' ', 1 ) AS Pin_Num FROM Employee Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Sep, 2020" }, { "code": null, "e": 193, "s": 54, "text": "SUBSTRING_INDEX() function in MySQL is used to return a substring from a string before a specified number of occurrences of the delimiter." }, { "code": null, "e": 202, "s": 193, "text": "Syntax :" }, { "code": null, "e": 240, "s": 202, "text": "SUBSTRING_INDEX( str, delim, count )\n" }, { "code": null, "e": 329, "s": 240, "text": "Parameter : This method accepts three-parameter as mentioned above and described below :" }, { "code": null, "e": 397, "s": 329, "text": "str : The original string from which we want to create a substring." }, { "code": null, "e": 522, "s": 397, "text": "delim : Is a string that acts as a delimiter. The function performs a case-sensitive match when searching for the delimiter." }, { "code": null, "e": 808, "s": 522, "text": "count : It identifies the number of times to search for the delimiter. It can be both a positive or negative number. If it is a positive number, this function returns all to the left of the delimiter. If it is a negative number, this function returns all to the right of the delimiter." }, { "code": null, "e": 860, "s": 808, "text": "Returns : It returns substring from a given string." }, { "code": null, "e": 952, "s": 860, "text": "Example-1 : SUBSTRING_INDEX() function with a positive number of occurrences of a delimiter" }, { "code": null, "e": 1021, "s": 952, "text": "SELECT SUBSTRING_INDEX(\"www.geeksforgeeks.org\", \".\", 2) as Sub_Str;\n" }, { "code": null, "e": 1030, "s": 1021, "text": "Output :" }, { "code": null, "e": 1123, "s": 1030, "text": "Example-2 : SUBSTRING_INDEX() function with a negative number of occurrences of a delimiter." }, { "code": null, "e": 1193, "s": 1123, "text": "SELECT SUBSTRING_INDEX(\"www.geeksforgeeks.org\", \".\", -2) as Sub_Str;\n" }, { "code": null, "e": 1202, "s": 1193, "text": "Output :" }, { "code": null, "e": 1262, "s": 1202, "text": "Example-3 : SUBSTRING_INDEX() function with the table data." }, { "code": null, "e": 1281, "s": 1262, "text": "Table : Employee :" }, { "code": null, "e": 1375, "s": 1281, "text": "Now, we will find the pin number address of every employee by using SUBSTRING_INDEX function." }, { "code": null, "e": 1446, "s": 1375, "text": "SELECT SUBSTRING_INDEX(Address, ' ', 1 ) AS Pin_Num FROM Employee \n" }, { "code": null, "e": 1455, "s": 1446, "text": "Output :" }, { "code": null, "e": 1464, "s": 1455, "text": "DBMS-SQL" }, { "code": null, "e": 1470, "s": 1464, "text": "mysql" }, { "code": null, "e": 1474, "s": 1470, "text": "SQL" }, { "code": null, "e": 1478, "s": 1474, "text": "SQL" }, { "code": null, "e": 1576, "s": 1478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1642, "s": 1576, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1666, "s": 1642, "text": "Window functions in SQL" }, { "code": null, "e": 1698, "s": 1666, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1715, "s": 1698, "text": "SQL using Python" }, { "code": null, "e": 1748, "s": 1715, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1826, "s": 1748, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1856, "s": 1826, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1892, "s": 1856, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1923, "s": 1892, "text": "SQL Query to Compare Two Dates" } ]
Streams on Arrays in Java 8
21 Aug, 2021 In this article, we would be going through stream method of Arrays class which is added in Java 8, it simplifies many operations on arrays as well have improved the efficiency. Addition of different features like lambdas and streams in java 8 have made java efficient to write elegant code which have improve the readability providing increase in efficiency of performance in most case. Syntax : public static IntStream stream(int[] arr) Parameter : arr - An array which is to be converted to the stream Returns : An IntStream of an array Variations : public static IntStream stream(int[] array) public static IntStream stream(int[] array, int startInclusive, int endExclusive) public static DoubleStream stream(double[] array) public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) public static LongStream stream(long[] array) public static LongStream stream(long[] array, int startInclusive, int endExclusive) public static Stream stream(T[] array) public static Stream stream(T[] array, int startInclusive, int endExclusive) Prerequisite:- Lambda Expressions in Java 8 Stream In Java Note: – Even if you are not familiar with these topics, you can go through the article as it uses very basic lambda expression and explains how to use method of stream class. Let’s see an example of streams on Arrays. In this example, we will be finding average over the array elements and will see the difference in way of writing code in imperative and declarative styles Example 1: Java import java.util.Arrays;class GFG_Demo_1 { public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // Let's try the imperative style first(which we // are familiar with) int sum = 0; for (int i = 0; i < arr.length; i++) sum += arr[i]; System.out.println("Average using iteration :" + (sum / arr.length)); // Let's try the declarative style now sum = Arrays.stream(arr) // Step 1 .sum(); // Step 2 System.out.println("Average using streams : " + (sum / arr.length)); // forEach() // It iterates through the entire streams System.out.println("Printing array elements : "); Arrays.stream(arr) .forEach(e->System.out.print(e + " ")); }} Output: Average using iteration :10 Average using streams : 10 Printing array elements : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 In the above example you have seen stream working let’s see what these step does. Step 1: Arrays.stream(arr) – In this step we call the stream method on the Arrays class passing arr as the parameter to the function this statement returns IntStream. Step 2: Arrays.stream(arr).sum() – Once we get the IntStream we can use different methods of the IntStream interface. While you go through IntStream. interface documentation you can open each method to see whether it’s perform a terminal operation or intermediate operation. And we should use this method accordingly either at the terminal or in between. Now let’s go through different methods of IntStream and see what operations this methods perform.We will see example of all this methods in contrast of an array.. We will going through the following methods in the example below. asDoubleStream()asLongStream()anyMatch()allMatch()noneMatch() asDoubleStream() asLongStream() anyMatch() allMatch() noneMatch() Java import java.util.Arrays;import java.util.function.IntPredicate;class GFG_Demo_2 { public static void main(String[] args) { int arr_sample1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // asDoubleStream() // It converts the original array to double System.out.println("Example of asDoubleStream(): "); Arrays.stream(arr_sample1) .asDoubleStream() .forEach(e->System.out.print(e + " ")); // asLongStream() // It converts the original array to Long System.out.println("\nExample of asLongStream"); Arrays.stream(arr_sample1) .asLongStream() .forEach(e->System.out.print(e + " ")); int arr_sample2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // anyMatch() // This method find whether the given predicate // is in the array or not System.out.println("\nExample of anyMatch"); // Test whether any of the element in array is // divisible by 11 or not IntPredicate predicate = e->e % 11 == 0; System.out.println(Arrays.stream(arr_sample2) .anyMatch(predicate)); // You can directly write the lambda expression // which computes to IntPredicate // Uncomment to test // System.out.println(Arrays.stream(arr) // .anyMatch(e -> e % 11 == 0)); int arr_sample3[] = { 2, 4, 6, 8, 10 }; int arr_sample4[] = { 1, 3, 5, 7, 11 }; // allMatch() // This method finds whether the given predicate // matches the entire array or not System.out.println("Example of allMatch :"); // Returns true as all the elements of arr_sample3 // is even System.out.println(Arrays.stream(arr_sample3) .allMatch(e->e % 2 == 0)); // Returns false as all the elements of arr_sammple4 // is odd System.out.println(Arrays.stream(arr_sample4) .allMatch(e->e % 2 == 0)); // noneMatch() System.out.println("Example of noneMatch"); System.out.println(Arrays.stream(arr_sample4) .noneMatch(e->e % 2 == 0)); }} Output: Example of asDoubleStream(): 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 20.0 Example of asLongStream 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Example of anyMatch false Example of allMatch : true false Example of noneMatch true We have seen very few methods though IntStream provides many more, lets try some more. We will going through the following methods in the example below. average()findAny()findFirst()max()min()reduce() average() findAny() findFirst() max() min() reduce() Remember all this method returns OptionalInt or OptionalDouble instead of int or double. Java import java.util.Arrays;class GFG_Demo_3 { public static void main(String[] args) { int arr_sample1[] = { 11, 2, 3, 42, 5, 6, 17, 8, 9, 10, 11, 12, 13, 24, 55, 16, 47, 18, 19, 20 }; System.out.println("These method returns Optional"); // average() // This method returns a average of an array System.out.println("Example of average() : "); System.out.println((Arrays.stream(arr_sample1) .average())); // findAny() // It can return any value from the stream // Most of the time it returns the first value // but it is not assured it can return any value System.out.println("Example of findAny() : "); System.out.println(Arrays.stream(arr_sample1) .findAny()); // findFirst() // It returns the first element of the stream System.out.println("Example of findFirst() :"); System.out.println(Arrays.stream(arr_sample1) .findFirst()); // max() // It returns the max element in an array System.out.println("Example of max() :"); System.out.println(Arrays.stream(arr_sample1) .max()); // min() // It returns the max element in an array System.out.println("Example of max() :"); System.out.println(Arrays.stream(arr_sample1) .min()); // reduce() // It reduces the array by certain operation // Here it performs addition of array elements System.out.println("Example of reduce() :"); System.out.println(Arrays.stream(arr_sample1) .reduce((x, y)->x + y)); // reduce() have another variation which we will // see in different example }} These method returns Optional Example of average() : OptionalDouble[17.4] Example of findAny() : OptionalInt[11] Example of findFirst() : OptionalInt[11] Example of max() : OptionalInt[55] Example of max() : OptionalInt[2] Example of reduce() : OptionalInt[348] But it becomes really difficult to work with this OptionalInt and OptionalDouble, hence Java provides method to convert them into double and int values such that it can be easily reused Java import java.util.Arrays;class GFG_Demo_4 {public static void main(String[] args) { int arr_sample1[] = { 11, 2, 3, 42, 5, 6, 17, 8, 9, 10, 11, 12, 13, 24, 55, 16, 47, 18, 19, 20 }; System.out.println("These method convert Optional to primitive"); // OptionalDouble can be converted to double by using getAsDouble() // if average doesn't contains any value it throws NoSuchElementException System.out.println("Example of average() : "); System.out.println((Arrays.stream(arr_sample1) .average() .getAsDouble())); // OptionalInt can be converted to int by using getAsInt() System.out.println("Example of findAny() : "); System.out.println(Arrays.stream(arr_sample1) .findAny() .getAsInt()); }} Output: These method convert Optional to primitive Example of average() : 17.4 Example of findAny() : 11 There are some more methods provided by IntStream which we will be going through in different article and would be working with different variations of stream method. Reference : https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html This article is contributed by Sumit Ghosh. 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. sahibbajaj sumitgumber28 array-stream Java-Array-Programs java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Aug, 2021" }, { "code": null, "e": 415, "s": 28, "text": "In this article, we would be going through stream method of Arrays class which is added in Java 8, it simplifies many operations on arrays as well have improved the efficiency. Addition of different features like lambdas and streams in java 8 have made java efficient to write elegant code which have improve the readability providing increase in efficiency of performance in most case." }, { "code": null, "e": 425, "s": 415, "text": "Syntax : " }, { "code": null, "e": 568, "s": 425, "text": "public static IntStream stream(int[] arr)\nParameter :\narr - An array which is to be converted to the stream\nReturns :\nAn IntStream of an array" }, { "code": null, "e": 582, "s": 568, "text": "Variations : " }, { "code": null, "e": 1094, "s": 582, "text": "public static IntStream stream(int[] array)\npublic static IntStream stream(int[] array, int startInclusive, int endExclusive)\npublic static DoubleStream stream(double[] array)\npublic static DoubleStream stream(double[] array, int startInclusive, int endExclusive)\npublic static LongStream stream(long[] array)\npublic static LongStream stream(long[] array, int startInclusive, int endExclusive)\npublic static Stream stream(T[] array)\npublic static Stream stream(T[] array, int startInclusive, int endExclusive)" }, { "code": null, "e": 1110, "s": 1094, "text": "Prerequisite:- " }, { "code": null, "e": 1139, "s": 1110, "text": "Lambda Expressions in Java 8" }, { "code": null, "e": 1154, "s": 1139, "text": "Stream In Java" }, { "code": null, "e": 1330, "s": 1154, "text": "Note: – Even if you are not familiar with these topics, you can go through the article as it uses very basic lambda expression and explains how to use method of stream class. " }, { "code": null, "e": 1530, "s": 1330, "text": "Let’s see an example of streams on Arrays. In this example, we will be finding average over the array elements and will see the difference in way of writing code in imperative and declarative styles " }, { "code": null, "e": 1542, "s": 1530, "text": "Example 1: " }, { "code": null, "e": 1547, "s": 1542, "text": "Java" }, { "code": "import java.util.Arrays;class GFG_Demo_1 { public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // Let's try the imperative style first(which we // are familiar with) int sum = 0; for (int i = 0; i < arr.length; i++) sum += arr[i]; System.out.println(\"Average using iteration :\" + (sum / arr.length)); // Let's try the declarative style now sum = Arrays.stream(arr) // Step 1 .sum(); // Step 2 System.out.println(\"Average using streams : \" + (sum / arr.length)); // forEach() // It iterates through the entire streams System.out.println(\"Printing array elements : \"); Arrays.stream(arr) .forEach(e->System.out.print(e + \" \")); }}", "e": 2474, "s": 1547, "text": null }, { "code": null, "e": 2483, "s": 2474, "text": "Output: " }, { "code": null, "e": 2615, "s": 2483, "text": "Average using iteration :10\nAverage using streams : 10\nPrinting array elements :\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20" }, { "code": null, "e": 2698, "s": 2615, "text": "In the above example you have seen stream working let’s see what these step does. " }, { "code": null, "e": 2866, "s": 2698, "text": "Step 1: Arrays.stream(arr) – In this step we call the stream method on the Arrays class passing arr as the parameter to the function this statement returns IntStream. " }, { "code": null, "e": 3385, "s": 2866, "text": "Step 2: Arrays.stream(arr).sum() – Once we get the IntStream we can use different methods of the IntStream interface. While you go through IntStream. interface documentation you can open each method to see whether it’s perform a terminal operation or intermediate operation. And we should use this method accordingly either at the terminal or in between. Now let’s go through different methods of IntStream and see what operations this methods perform.We will see example of all this methods in contrast of an array.. " }, { "code": null, "e": 3453, "s": 3385, "text": "We will going through the following methods in the example below. " }, { "code": null, "e": 3515, "s": 3453, "text": "asDoubleStream()asLongStream()anyMatch()allMatch()noneMatch()" }, { "code": null, "e": 3532, "s": 3515, "text": "asDoubleStream()" }, { "code": null, "e": 3547, "s": 3532, "text": "asLongStream()" }, { "code": null, "e": 3558, "s": 3547, "text": "anyMatch()" }, { "code": null, "e": 3569, "s": 3558, "text": "allMatch()" }, { "code": null, "e": 3581, "s": 3569, "text": "noneMatch()" }, { "code": null, "e": 3586, "s": 3581, "text": "Java" }, { "code": "import java.util.Arrays;import java.util.function.IntPredicate;class GFG_Demo_2 { public static void main(String[] args) { int arr_sample1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // asDoubleStream() // It converts the original array to double System.out.println(\"Example of asDoubleStream(): \"); Arrays.stream(arr_sample1) .asDoubleStream() .forEach(e->System.out.print(e + \" \")); // asLongStream() // It converts the original array to Long System.out.println(\"\\nExample of asLongStream\"); Arrays.stream(arr_sample1) .asLongStream() .forEach(e->System.out.print(e + \" \")); int arr_sample2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // anyMatch() // This method find whether the given predicate // is in the array or not System.out.println(\"\\nExample of anyMatch\"); // Test whether any of the element in array is // divisible by 11 or not IntPredicate predicate = e->e % 11 == 0; System.out.println(Arrays.stream(arr_sample2) .anyMatch(predicate)); // You can directly write the lambda expression // which computes to IntPredicate // Uncomment to test // System.out.println(Arrays.stream(arr) // .anyMatch(e -> e % 11 == 0)); int arr_sample3[] = { 2, 4, 6, 8, 10 }; int arr_sample4[] = { 1, 3, 5, 7, 11 }; // allMatch() // This method finds whether the given predicate // matches the entire array or not System.out.println(\"Example of allMatch :\"); // Returns true as all the elements of arr_sample3 // is even System.out.println(Arrays.stream(arr_sample3) .allMatch(e->e % 2 == 0)); // Returns false as all the elements of arr_sammple4 // is odd System.out.println(Arrays.stream(arr_sample4) .allMatch(e->e % 2 == 0)); // noneMatch() System.out.println(\"Example of noneMatch\"); System.out.println(Arrays.stream(arr_sample4) .noneMatch(e->e % 2 == 0)); }}", "e": 5889, "s": 3586, "text": null }, { "code": null, "e": 5898, "s": 5889, "text": "Output: " }, { "code": null, "e": 6178, "s": 5898, "text": "Example of asDoubleStream():\n1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0\n14.0 15.0 16.0 17.0 18.0 19.0 20.0\nExample of asLongStream\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\nExample of anyMatch\nfalse\nExample of allMatch :\ntrue\nfalse\nExample of noneMatch\ntrue" }, { "code": null, "e": 6333, "s": 6178, "text": "We have seen very few methods though IntStream provides many more, lets try some more. We will going through the following methods in the example below. " }, { "code": null, "e": 6381, "s": 6333, "text": "average()findAny()findFirst()max()min()reduce()" }, { "code": null, "e": 6391, "s": 6381, "text": "average()" }, { "code": null, "e": 6401, "s": 6391, "text": "findAny()" }, { "code": null, "e": 6413, "s": 6401, "text": "findFirst()" }, { "code": null, "e": 6419, "s": 6413, "text": "max()" }, { "code": null, "e": 6425, "s": 6419, "text": "min()" }, { "code": null, "e": 6434, "s": 6425, "text": "reduce()" }, { "code": null, "e": 6524, "s": 6434, "text": "Remember all this method returns OptionalInt or OptionalDouble instead of int or double. " }, { "code": null, "e": 6529, "s": 6524, "text": "Java" }, { "code": "import java.util.Arrays;class GFG_Demo_3 { public static void main(String[] args) { int arr_sample1[] = { 11, 2, 3, 42, 5, 6, 17, 8, 9, 10, 11, 12, 13, 24, 55, 16, 47, 18, 19, 20 }; System.out.println(\"These method returns Optional\"); // average() // This method returns a average of an array System.out.println(\"Example of average() : \"); System.out.println((Arrays.stream(arr_sample1) .average())); // findAny() // It can return any value from the stream // Most of the time it returns the first value // but it is not assured it can return any value System.out.println(\"Example of findAny() : \"); System.out.println(Arrays.stream(arr_sample1) .findAny()); // findFirst() // It returns the first element of the stream System.out.println(\"Example of findFirst() :\"); System.out.println(Arrays.stream(arr_sample1) .findFirst()); // max() // It returns the max element in an array System.out.println(\"Example of max() :\"); System.out.println(Arrays.stream(arr_sample1) .max()); // min() // It returns the max element in an array System.out.println(\"Example of max() :\"); System.out.println(Arrays.stream(arr_sample1) .min()); // reduce() // It reduces the array by certain operation // Here it performs addition of array elements System.out.println(\"Example of reduce() :\"); System.out.println(Arrays.stream(arr_sample1) .reduce((x, y)->x + y)); // reduce() have another variation which we will // see in different example }}", "e": 8382, "s": 6529, "text": null }, { "code": null, "e": 8646, "s": 8382, "text": "These method returns Optional\nExample of average() : \nOptionalDouble[17.4]\nExample of findAny() : \nOptionalInt[11]\nExample of findFirst() :\nOptionalInt[11]\nExample of max() :\nOptionalInt[55]\nExample of max() :\nOptionalInt[2]\nExample of reduce() :\nOptionalInt[348]" }, { "code": null, "e": 8833, "s": 8646, "text": "But it becomes really difficult to work with this OptionalInt and OptionalDouble, hence Java provides method to convert them into double and int values such that it can be easily reused " }, { "code": null, "e": 8838, "s": 8833, "text": "Java" }, { "code": "import java.util.Arrays;class GFG_Demo_4 {public static void main(String[] args) { int arr_sample1[] = { 11, 2, 3, 42, 5, 6, 17, 8, 9, 10, 11, 12, 13, 24, 55, 16, 47, 18, 19, 20 }; System.out.println(\"These method convert Optional to primitive\"); // OptionalDouble can be converted to double by using getAsDouble() // if average doesn't contains any value it throws NoSuchElementException System.out.println(\"Example of average() : \"); System.out.println((Arrays.stream(arr_sample1) .average() .getAsDouble())); // OptionalInt can be converted to int by using getAsInt() System.out.println(\"Example of findAny() : \"); System.out.println(Arrays.stream(arr_sample1) .findAny() .getAsInt()); }}", "e": 9738, "s": 8838, "text": null }, { "code": null, "e": 9747, "s": 9738, "text": "Output: " }, { "code": null, "e": 9844, "s": 9747, "text": "These method convert Optional to primitive\nExample of average() :\n17.4\nExample of findAny() :\n11" }, { "code": null, "e": 10011, "s": 9844, "text": "There are some more methods provided by IntStream which we will be going through in different article and would be working with different variations of stream method." }, { "code": null, "e": 10161, "s": 10011, "text": "Reference : https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html" }, { "code": null, "e": 10581, "s": 10161, "text": "This article is contributed by Sumit Ghosh. 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": 10592, "s": 10581, "text": "sahibbajaj" }, { "code": null, "e": 10606, "s": 10592, "text": "sumitgumber28" }, { "code": null, "e": 10619, "s": 10606, "text": "array-stream" }, { "code": null, "e": 10639, "s": 10619, "text": "Java-Array-Programs" }, { "code": null, "e": 10651, "s": 10639, "text": "java-stream" }, { "code": null, "e": 10656, "s": 10651, "text": "Java" }, { "code": null, "e": 10661, "s": 10656, "text": "Java" }, { "code": null, "e": 10759, "s": 10661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10810, "s": 10759, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 10841, "s": 10810, "text": "How to iterate any Map in Java" }, { "code": null, "e": 10860, "s": 10841, "text": "Interfaces in Java" }, { "code": null, "e": 10890, "s": 10860, "text": "HashMap in Java with Examples" }, { "code": null, "e": 10908, "s": 10890, "text": "ArrayList in Java" }, { "code": null, "e": 10928, "s": 10908, "text": "Collections in Java" }, { "code": null, "e": 10952, "s": 10928, "text": "Singleton Class in Java" }, { "code": null, "e": 10984, "s": 10952, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 10996, "s": 10984, "text": "Set in Java" } ]
numpy.degrees() and rad2deg() in Python
04 Dec, 2020 The numpy.degrees() is a mathematical function that helps user to convert angles from radians to degrees. Syntax : numpy.degrees(x[, out]) = ufunc ‘degrees’)Parameters : array : [array_like] elements are in radians.out : [ndaaray, optional] Output array of same shape as x. 2pi Radians = 360 degrees Return : An array with degree values in place of radian values. Code #1 : Working # Python3 program explaining# degrees() functionimport numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Radian values : \n", in_array) degree_Values = np.degrees(in_array)print ("\nDegree values : \n", degree_Values) Output : Radian values : [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793] Degree values : [ 0. 90. 60. 180.] numpy.rad2deg(x[, out]) = ufunc ‘rad2deg’) : This mathematical function helps user to convert angles from radians to degrees. Parameters : array : [array_like] elements are in radians.out : [ndaaray, optional]Output array of same shape as x. 2pi Radians = 36o degrees Return : Corresponding angles in degree. Code #2 : rad2deg() Equivalent to degree() # Python3 program explaining# rad2deg() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Radian values : \n", in_array) out_Values = np.rad2deg(in_array)print ("\nDegree values : \n", out_Values) Output : Radian values : [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793] Degree values : [ 0. 90. 60. 180.] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.degrees.html#numpy.degrees. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe 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 Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 134, "s": 28, "text": "The numpy.degrees() is a mathematical function that helps user to convert angles from radians to degrees." }, { "code": null, "e": 198, "s": 134, "text": "Syntax : numpy.degrees(x[, out]) = ufunc ‘degrees’)Parameters :" }, { "code": null, "e": 335, "s": 198, "text": "array : [array_like] elements are in radians.out : [ndaaray, optional] Output array of same shape as x. 2pi Radians = 360 degrees" }, { "code": null, "e": 399, "s": 335, "text": "Return : An array with degree values in place of radian values." }, { "code": null, "e": 418, "s": 399, "text": " Code #1 : Working" }, { "code": "# Python3 program explaining# degrees() functionimport numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print (\"Radian values : \\n\", in_array) degree_Values = np.degrees(in_array)print (\"\\nDegree values : \\n\", degree_Values)", "e": 664, "s": 418, "text": null }, { "code": null, "e": 673, "s": 664, "text": "Output :" }, { "code": null, "e": 800, "s": 673, "text": "Radian values : \n [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]\n\nDegree values : \n [ 0. 90. 60. 180.]\n" }, { "code": null, "e": 928, "s": 802, "text": "numpy.rad2deg(x[, out]) = ufunc ‘rad2deg’) : This mathematical function helps user to convert angles from radians to degrees." }, { "code": null, "e": 941, "s": 928, "text": "Parameters :" }, { "code": null, "e": 1077, "s": 941, "text": "array : [array_like] elements are in radians.out : [ndaaray, optional]Output array of same shape as x. 2pi Radians = 36o degrees" }, { "code": null, "e": 1118, "s": 1077, "text": "Return : Corresponding angles in degree." }, { "code": null, "e": 1162, "s": 1118, "text": " Code #2 : rad2deg() Equivalent to degree()" }, { "code": "# Python3 program explaining# rad2deg() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print (\"Radian values : \\n\", in_array) out_Values = np.rad2deg(in_array)print (\"\\nDegree values : \\n\", out_Values)", "e": 1404, "s": 1162, "text": null }, { "code": null, "e": 1413, "s": 1404, "text": "Output :" }, { "code": null, "e": 1540, "s": 1413, "text": "Radian values : \n [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]\n\nDegree values : \n [ 0. 90. 60. 180.]\n" }, { "code": null, "e": 1645, "s": 1540, "text": " References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.degrees.html#numpy.degrees." }, { "code": null, "e": 1680, "s": 1645, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1693, "s": 1680, "text": "Python-numpy" }, { "code": null, "e": 1700, "s": 1693, "text": "Python" }, { "code": null, "e": 1798, "s": 1700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1816, "s": 1798, "text": "Python Dictionary" }, { "code": null, "e": 1858, "s": 1816, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1880, "s": 1858, "text": "Enumerate() in Python" }, { "code": null, "e": 1915, "s": 1880, "text": "Read a file line by line in Python" }, { "code": null, "e": 1941, "s": 1915, "text": "Python String | replace()" }, { "code": null, "e": 1973, "s": 1941, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2002, "s": 1973, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2029, "s": 2002, "text": "Python Classes and Objects" }, { "code": null, "e": 2059, "s": 2029, "text": "Iterate over a list in Python" } ]
Python – Edge Detection using Pillow
16 Dec, 2021 Edge Detection, is an Image Processing discipline that incorporates mathematics methods to find edges in a Digital Image. Edge Detection internally works by running a filter/Kernel over a Digital Image, which detects discontinuities in Image regions like stark changes in brightness/Intensity value of pixels. There are two forms of edge detection: Search Based Edge detection (First order derivative) Zero Crossing Based Edge detection (Second order derivative) Some of the commonly known edge detection methods are: Laplacian Operator or Laplacian Based Edge detection (Second order derivative) Canny edge detector (First order derivative) Prewitt operator (First order derivative) Sobel Operator (First order derivative) We would be implementing a Laplacian Operator in order to incorporate Edge detection in one of our later examples. For this purpose, we will be using pillow library. To install the library, execute the following command in the command-line : pip install pillow NOTE:- Several Linux distributions tend to have Python and Pillow preinstalled onto them. There are two ways in which we would be implementing Edge detection on our images. In the first method we would be using an inbuilt method provided in the pillow library (ImageFilter.FIND_EDGES) for edge detection. In the second one we would be creating a Laplacian Filter using PIL.ImageFilter.Kernel(), and then would use that filter for edge detection. LAPLACIAN KERNEL:- SAMPLE IMAGE:- Method 1: Python3 from PIL import Image, ImageFilter # Opening the image (R prefixed to string# in order to deal with '\' in paths)image = Image.open(r"Sample.png") # Converting the image to grayscale, as edge detection # requires input image to be of mode = Grayscale (L)image = image.convert("L") # Detecting Edges on the Image using the argument ImageFilter.FIND_EDGESimage = image.filter(ImageFilter.FIND_EDGES) # Saving the Image Under the name Edge_Sample.pngimage.save(r"Edge_Sample.png") Output (Edge_Sample.png): Explanation:- Firstly we create an image object of our image using Image.open(). Then we convert the Image color mode to grayscale, as the input to the Laplacian operator is in grayscale mode (in general). Then we pass the image onto Image.filter() function by specifying ImageFilter.FIND_EDGES argument, which in turns runs a edge detection kernel on top of the image. The output of the above function results in an image with high intensity changes (edges) in shades of white, and rest of the image in black color. Method 2: Python3 from PIL import Image, ImageFilter img = Image.open(r"sample.png") # Converting the image to grayscale, as Sobel Operator requires# input image to be of mode Grayscale (L)img = img.convert("L") # Calculating Edges using the passed laplican Kernelfinal = img.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8, -1, -1, -1, -1), 1, 0)) final.save("EDGE_sample.png") Output (EDGE_sample.png): Explanation:- Firstly we create an image object of our image using Image.open(). Then we convert the Image color mode to grayscale, as the input to the Laplacian operator is in grayscale mode (in general). Then we pass the image onto Image.filter() function by specifying our operator/Kernel inside the function as an argument. The Kernel is specified by using ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8, -1, -1, -1, -1), 1, 0)) which create a 3 X 3 Kernel (3 pixel Wide and 3 pixel long) with the values (-1, -1, -1, -1, 8, -1, -1, -1, -1) (as stated in the Laplacian Kernel image). The 1 argument (after the kernel) stands for the Scale value, which divides the final value after each kernel operation, therefore we set that value to 1 as we don’t want any division to our final value. The 0 argument (after the Scale value) is the offset which is added after the division by Scale value. We have set that value to 0 as we don’t want any increment to the final intensity value after the Kernel Convolution. The output of the above function results in an image with high intensity changes (edges) in shades of white, and rest of the image in black color. Addendum – Both the programs yielded the same result. The reason for which being the fact that the inbuilt function ImageFilter.FIND_EDGE uses a 3 X 3 sized Laplacian Kernel/Operator internally. Due to which we ended up with identical results. The benefit of using a Kernel instead of relying on inbuilt functions is that we can define kernels according to our needs, which may/may not be in the library. Such as we can create a Kernel for Blurring, Sharpening, Edge detection (using other Kernels) etc. Also, I intentionally chose the Laplacian so that we can maintain consistency in results. Benefits of using Laplacian:-Fast and decent results. Other common edge detectors like Sobel (first order derivative) are more expensive on computation, as they require finding Gradients in two directions and then Normalizing the results. Drawbacks of using laplacian:-Convolving with Laplacian Kernel leads to a lot of noise in the output. This issue is resolved by other Edge Detection methods such as Sobel, Perwitt Operator etc. As they have a built-in Gaussian Blur Kernel in them. Which reduces the noise obtained from the input image. They also lead to more accurate edge detection, due to the higher computation involved into finding them. sooda367 Image-Processing OpenCV Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Dec, 2021" }, { "code": null, "e": 364, "s": 54, "text": "Edge Detection, is an Image Processing discipline that incorporates mathematics methods to find edges in a Digital Image. Edge Detection internally works by running a filter/Kernel over a Digital Image, which detects discontinuities in Image regions like stark changes in brightness/Intensity value of pixels." }, { "code": null, "e": 403, "s": 364, "text": "There are two forms of edge detection:" }, { "code": null, "e": 456, "s": 403, "text": "Search Based Edge detection (First order derivative)" }, { "code": null, "e": 517, "s": 456, "text": "Zero Crossing Based Edge detection (Second order derivative)" }, { "code": null, "e": 572, "s": 517, "text": "Some of the commonly known edge detection methods are:" }, { "code": null, "e": 651, "s": 572, "text": "Laplacian Operator or Laplacian Based Edge detection (Second order derivative)" }, { "code": null, "e": 696, "s": 651, "text": "Canny edge detector (First order derivative)" }, { "code": null, "e": 738, "s": 696, "text": "Prewitt operator (First order derivative)" }, { "code": null, "e": 778, "s": 738, "text": "Sobel Operator (First order derivative)" }, { "code": null, "e": 1020, "s": 778, "text": "We would be implementing a Laplacian Operator in order to incorporate Edge detection in one of our later examples. For this purpose, we will be using pillow library. To install the library, execute the following command in the command-line :" }, { "code": null, "e": 1040, "s": 1020, "text": "pip install pillow\n" }, { "code": null, "e": 1130, "s": 1040, "text": "NOTE:- Several Linux distributions tend to have Python and Pillow preinstalled onto them." }, { "code": null, "e": 1486, "s": 1130, "text": "There are two ways in which we would be implementing Edge detection on our images. In the first method we would be using an inbuilt method provided in the pillow library (ImageFilter.FIND_EDGES) for edge detection. In the second one we would be creating a Laplacian Filter using PIL.ImageFilter.Kernel(), and then would use that filter for edge detection." }, { "code": null, "e": 1505, "s": 1486, "text": "LAPLACIAN KERNEL:-" }, { "code": null, "e": 1520, "s": 1505, "text": "SAMPLE IMAGE:-" }, { "code": null, "e": 1530, "s": 1520, "text": "Method 1:" }, { "code": null, "e": 1538, "s": 1530, "text": "Python3" }, { "code": "from PIL import Image, ImageFilter # Opening the image (R prefixed to string# in order to deal with '\\' in paths)image = Image.open(r\"Sample.png\") # Converting the image to grayscale, as edge detection # requires input image to be of mode = Grayscale (L)image = image.convert(\"L\") # Detecting Edges on the Image using the argument ImageFilter.FIND_EDGESimage = image.filter(ImageFilter.FIND_EDGES) # Saving the Image Under the name Edge_Sample.pngimage.save(r\"Edge_Sample.png\")", "e": 2022, "s": 1538, "text": null }, { "code": null, "e": 2048, "s": 2022, "text": "Output (Edge_Sample.png):" }, { "code": null, "e": 2062, "s": 2048, "text": "Explanation:-" }, { "code": null, "e": 2565, "s": 2062, "text": "Firstly we create an image object of our image using Image.open(). Then we convert the Image color mode to grayscale, as the input to the Laplacian operator is in grayscale mode (in general). Then we pass the image onto Image.filter() function by specifying ImageFilter.FIND_EDGES argument, which in turns runs a edge detection kernel on top of the image. The output of the above function results in an image with high intensity changes (edges) in shades of white, and rest of the image in black color." }, { "code": null, "e": 2577, "s": 2567, "text": "Method 2:" }, { "code": null, "e": 2585, "s": 2577, "text": "Python3" }, { "code": "from PIL import Image, ImageFilter img = Image.open(r\"sample.png\") # Converting the image to grayscale, as Sobel Operator requires# input image to be of mode Grayscale (L)img = img.convert(\"L\") # Calculating Edges using the passed laplican Kernelfinal = img.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8, -1, -1, -1, -1), 1, 0)) final.save(\"EDGE_sample.png\")", "e": 2996, "s": 2585, "text": null }, { "code": null, "e": 3022, "s": 2996, "text": "Output (EDGE_sample.png):" }, { "code": null, "e": 3036, "s": 3022, "text": "Explanation:-" }, { "code": null, "e": 4181, "s": 3036, "text": "Firstly we create an image object of our image using Image.open(). Then we convert the Image color mode to grayscale, as the input to the Laplacian operator is in grayscale mode (in general). Then we pass the image onto Image.filter() function by specifying our operator/Kernel inside the function as an argument. The Kernel is specified by using ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8, -1, -1, -1, -1), 1, 0)) which create a 3 X 3 Kernel (3 pixel Wide and 3 pixel long) with the values (-1, -1, -1, -1, 8, -1, -1, -1, -1) (as stated in the Laplacian Kernel image). The 1 argument (after the kernel) stands for the Scale value, which divides the final value after each kernel operation, therefore we set that value to 1 as we don’t want any division to our final value. The 0 argument (after the Scale value) is the offset which is added after the division by Scale value. We have set that value to 0 as we don’t want any increment to the final intensity value after the Kernel Convolution. The output of the above function results in an image with high intensity changes (edges) in shades of white, and rest of the image in black color." }, { "code": null, "e": 4194, "s": 4183, "text": "Addendum –" }, { "code": null, "e": 4777, "s": 4194, "text": "Both the programs yielded the same result. The reason for which being the fact that the inbuilt function ImageFilter.FIND_EDGE uses a 3 X 3 sized Laplacian Kernel/Operator internally. Due to which we ended up with identical results. The benefit of using a Kernel instead of relying on inbuilt functions is that we can define kernels according to our needs, which may/may not be in the library. Such as we can create a Kernel for Blurring, Sharpening, Edge detection (using other Kernels) etc. Also, I intentionally chose the Laplacian so that we can maintain consistency in results." }, { "code": null, "e": 5019, "s": 4779, "text": "Benefits of using Laplacian:-Fast and decent results. Other common edge detectors like Sobel (first order derivative) are more expensive on computation, as they require finding Gradients in two directions and then Normalizing the results. " }, { "code": null, "e": 5428, "s": 5019, "text": "Drawbacks of using laplacian:-Convolving with Laplacian Kernel leads to a lot of noise in the output. This issue is resolved by other Edge Detection methods such as Sobel, Perwitt Operator etc. As they have a built-in Gaussian Blur Kernel in them. Which reduces the noise obtained from the input image. They also lead to more accurate edge detection, due to the higher computation involved into finding them." }, { "code": null, "e": 5437, "s": 5428, "text": "sooda367" }, { "code": null, "e": 5454, "s": 5437, "text": "Image-Processing" }, { "code": null, "e": 5461, "s": 5454, "text": "OpenCV" }, { "code": null, "e": 5475, "s": 5461, "text": "Python-OpenCV" }, { "code": null, "e": 5482, "s": 5475, "text": "Python" }, { "code": null, "e": 5580, "s": 5482, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5598, "s": 5580, "text": "Python Dictionary" }, { "code": null, "e": 5640, "s": 5598, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5662, "s": 5640, "text": "Enumerate() in Python" }, { "code": null, "e": 5688, "s": 5662, "text": "Python String | replace()" }, { "code": null, "e": 5720, "s": 5688, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5749, "s": 5720, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5776, "s": 5749, "text": "Python Classes and Objects" }, { "code": null, "e": 5806, "s": 5776, "text": "Iterate over a list in Python" }, { "code": null, "e": 5827, "s": 5806, "text": "Python OOPs Concepts" } ]
Leap Year | Practice | GeeksforGeeks
For an input year N, find whether the year is a leap or not. Example 1: Input: N = 4 Output: 1 Explanation: 4 is not divisible by 100 and is divisible by 4 so its a leap year Example 2: Input: N = 2021 Output: 0 Explanation: 2021 is not divisible by 100 and is also not divisible by 4 so its not a leap year Your Task: You don't need to read input or print anything. Your task is to complete the function isLeap() which takes an integer N as input parameter and returns 1 is N is a leap year and 0 otherwise. Expected Time Complexity: O(1) Expected Space Complexity: O(1) Constraints: 1<=N<=9999 +1 dasilashubham396 days ago //code here if(N%4!=0){ return 0; } else{ if(N%100!=0){ return 1; } else{ if(N%400==0){ return 1; } else{ return 0; } } } 0 dasilashubham39 This comment was deleted. +1 kumarr32033 weeks ago //c++ solution int isLeap(int n){ //code here if(n%4==0) { if(n%100==0) { if(n%400==0) { return 1; } else { return 0; } } else { return 1; } } else { return 0; } }}; 0 singhanurudh061 month ago int isLeap(int N){if ((N%4==0 && N%100!=0) || N%400==0) return 1;else return 0;} 0 haroonhnpwd11 month ago { // If a year is multiple of 400, // then it is a leap year if (year % 400 == 0) return true; // Else If a year is multiple of 100, // then it is not a leap year if (year % 100 == 0) return false; // Else If a year is multiple of 4, // then it is a leap year if (year % 4 == 0) return true; return false; } // Driver code int main() { int year = 2000; checkYear(year) ? cout << "Leap Year": cout << "Not a Leap Year"; return 0; } // This is code is contributed // by rathbhupendra 0 mco0lPremium1 month ago return (N%4 == 0) && (N%100 != 0) || (N%400 == 0); 0 itmithu1432 months ago if((N%4==0 && N%100!=0)|| N%400==0) return true; else return false; +1 upadhyayshikhar065 months ago int isLeap(int N) { return(((N % 4 == 0) &&(N % 100!= 0))||(N % 400 == 0)); } 0 badgujarsachin837 months ago int isLeap(int N){ //code here if(N>=400 && N%400==0){ return 1; } if(N%4==0 && N%100!=0){ return 1; } return 0; } -1 xasha1227999 months ago /* 1. Leap Year: A year is a leap year if the following conditions are satisfied: The year is multiple of 400. The year is multiple of 4 and not multiple of 100. */ #include <bits/stdc++.h> using namespace std; // Function Declarations // Driver Code int main() { int N; cin >> N; isLeap(N); return 0; } // Main Ends Function Definition int isLeap(int N) { // Basically we, need to check for 3 conditions: Nested Loops is what is required to evaluate either a year is leap or not if (N % 4 == 0) { // come here if year passed is divisible by 4 if (N % 100 == 0) { // come here if year passed is divisible by 100 if (N % 400 == 0) { // come here if year passed is divisible by 400 cout << "leap year"; } else { // come here if year passed is divisible by 100 but not by 400 cout << "not leap year"; } } else { // come here if year passed is divisible by 4 and not divisible by 100 cout << "leap year"; } } else { // come here if year passed is not divisible by 4 cout << "not leap year"; } } OR int isLeap(int N) { // 4 and 100 walli condition for normal years and 400 waali condition is for century year's if ((N % 4 == 0 and N % 100 != 0) or (N % 400 == 0)) { return 1; } else { return 0; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 302, "s": 238, "text": "For an input year N, find whether the year is a leap or not. \n " }, { "code": null, "e": 313, "s": 302, "text": "Example 1:" }, { "code": null, "e": 416, "s": 313, "text": "Input:\nN = 4\nOutput:\n1\nExplanation:\n4 is not divisible by 100\nand is divisible by 4 so its\na leap year" }, { "code": null, "e": 427, "s": 416, "text": "Example 2:" }, { "code": null, "e": 549, "s": 427, "text": "Input:\nN = 2021\nOutput:\n0\nExplanation:\n2021 is not divisible by 100\nand is also not divisible by 4\nso its not a leap year" }, { "code": null, "e": 753, "s": 549, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isLeap() which takes an integer N as input parameter and returns 1 is N is a leap year and 0 otherwise.\n " }, { "code": null, "e": 816, "s": 753, "text": "Expected Time Complexity: O(1)\nExpected Space Complexity: O(1)" }, { "code": null, "e": 841, "s": 816, "text": "\nConstraints:\n1<=N<=9999" }, { "code": null, "e": 844, "s": 841, "text": "+1" }, { "code": null, "e": 870, "s": 844, "text": "dasilashubham396 days ago" }, { "code": null, "e": 882, "s": 870, "text": "//code here" }, { "code": null, "e": 1181, "s": 882, "text": "if(N%4!=0){\n return 0;\n }\n else{\n if(N%100!=0){\n return 1;\n }\n else{\n if(N%400==0){\n return 1;\n }\n else{\n return 0;\n }\n }\n }" }, { "code": null, "e": 1183, "s": 1181, "text": "0" }, { "code": null, "e": 1199, "s": 1183, "text": "dasilashubham39" }, { "code": null, "e": 1225, "s": 1199, "text": "This comment was deleted." }, { "code": null, "e": 1228, "s": 1225, "text": "+1" }, { "code": null, "e": 1250, "s": 1228, "text": "kumarr32033 weeks ago" }, { "code": null, "e": 1265, "s": 1250, "text": "//c++ solution" }, { "code": null, "e": 1677, "s": 1267, "text": " int isLeap(int n){ //code here if(n%4==0) { if(n%100==0) { if(n%400==0) { return 1; } else { return 0; } } else { return 1; } } else { return 0; } }}; " }, { "code": null, "e": 1679, "s": 1677, "text": "0" }, { "code": null, "e": 1705, "s": 1679, "text": "singhanurudh061 month ago" }, { "code": null, "e": 1790, "s": 1705, "text": "int isLeap(int N){if ((N%4==0 && N%100!=0) || N%400==0) return 1;else return 0;}" }, { "code": null, "e": 1792, "s": 1790, "text": "0" }, { "code": null, "e": 1816, "s": 1792, "text": "haroonhnpwd11 month ago" }, { "code": null, "e": 1818, "s": 1816, "text": "{" }, { "code": null, "e": 1855, "s": 1818, "text": " // If a year is multiple of 400," }, { "code": null, "e": 1885, "s": 1855, "text": " // then it is a leap year" }, { "code": null, "e": 1910, "s": 1885, "text": " if (year % 400 == 0)" }, { "code": null, "e": 1931, "s": 1910, "text": " return true;" }, { "code": null, "e": 1973, "s": 1931, "text": " // Else If a year is multiple of 100," }, { "code": null, "e": 2007, "s": 1973, "text": " // then it is not a leap year" }, { "code": null, "e": 2032, "s": 2007, "text": " if (year % 100 == 0)" }, { "code": null, "e": 2054, "s": 2032, "text": " return false;" }, { "code": null, "e": 2094, "s": 2054, "text": " // Else If a year is multiple of 4," }, { "code": null, "e": 2124, "s": 2094, "text": " // then it is a leap year" }, { "code": null, "e": 2147, "s": 2124, "text": " if (year % 4 == 0)" }, { "code": null, "e": 2168, "s": 2147, "text": " return true;" }, { "code": null, "e": 2186, "s": 2168, "text": " return false;" }, { "code": null, "e": 2188, "s": 2186, "text": "}" }, { "code": null, "e": 2203, "s": 2188, "text": "// Driver code" }, { "code": null, "e": 2214, "s": 2203, "text": "int main()" }, { "code": null, "e": 2216, "s": 2214, "text": "{" }, { "code": null, "e": 2237, "s": 2216, "text": " int year = 2000;" }, { "code": null, "e": 2280, "s": 2237, "text": " checkYear(year) ? cout << \"Leap Year\":" }, { "code": null, "e": 2329, "s": 2280, "text": " cout << \"Not a Leap Year\";" }, { "code": null, "e": 2343, "s": 2329, "text": " return 0;" }, { "code": null, "e": 2345, "s": 2343, "text": "}" }, { "code": null, "e": 2376, "s": 2345, "text": "// This is code is contributed" }, { "code": null, "e": 2396, "s": 2376, "text": "// by rathbhupendra" }, { "code": null, "e": 2400, "s": 2398, "text": "0" }, { "code": null, "e": 2424, "s": 2400, "text": "mco0lPremium1 month ago" }, { "code": null, "e": 2475, "s": 2424, "text": "return (N%4 == 0) && (N%100 != 0) || (N%400 == 0);" }, { "code": null, "e": 2477, "s": 2475, "text": "0" }, { "code": null, "e": 2500, "s": 2477, "text": "itmithu1432 months ago" }, { "code": null, "e": 2586, "s": 2500, "text": "if((N%4==0 && N%100!=0)|| N%400==0) return true; else return false;" }, { "code": null, "e": 2591, "s": 2588, "text": "+1" }, { "code": null, "e": 2621, "s": 2591, "text": "upadhyayshikhar065 months ago" }, { "code": null, "e": 2639, "s": 2621, "text": "int isLeap(int N)" }, { "code": null, "e": 2713, "s": 2639, "text": "{ return(((N % 4 == 0) &&(N % 100!= 0))||(N % 400 == 0)); }" }, { "code": null, "e": 2715, "s": 2713, "text": "0" }, { "code": null, "e": 2744, "s": 2715, "text": "badgujarsachin837 months ago" }, { "code": null, "e": 2948, "s": 2744, "text": "int isLeap(int N){\n //code here\n if(N>=400 && N%400==0){\n return 1;\n }\n if(N%4==0 && N%100!=0){\n return 1;\n \n }\n return 0;\n }" }, { "code": null, "e": 2951, "s": 2948, "text": "-1" }, { "code": null, "e": 2975, "s": 2951, "text": "xasha1227999 months ago" }, { "code": null, "e": 2978, "s": 2975, "text": "/*" }, { "code": null, "e": 2992, "s": 2978, "text": "1. Leap Year:" }, { "code": null, "e": 3057, "s": 2992, "text": "A year is a leap year if the following conditions are satisfied:" }, { "code": null, "e": 3086, "s": 3057, "text": "The year is multiple of 400." }, { "code": null, "e": 3137, "s": 3086, "text": "The year is multiple of 4 and not multiple of 100." }, { "code": null, "e": 3140, "s": 3137, "text": "*/" }, { "code": null, "e": 3167, "s": 3142, "text": "#include <bits/stdc++.h>" }, { "code": null, "e": 3188, "s": 3167, "text": "using namespace std;" }, { "code": null, "e": 3215, "s": 3190, "text": "// Function Declarations" }, { "code": null, "e": 3232, "s": 3217, "text": "// Driver Code" }, { "code": null, "e": 3243, "s": 3232, "text": "int main()" }, { "code": null, "e": 3245, "s": 3243, "text": "{" }, { "code": null, "e": 3252, "s": 3245, "text": "int N;" }, { "code": null, "e": 3262, "s": 3252, "text": "cin >> N;" }, { "code": null, "e": 3273, "s": 3262, "text": "isLeap(N);" }, { "code": null, "e": 3285, "s": 3275, "text": "return 0;" }, { "code": null, "e": 3300, "s": 3285, "text": "} // Main Ends" }, { "code": null, "e": 3322, "s": 3302, "text": "Function Definition" }, { "code": null, "e": 3342, "s": 3324, "text": "int isLeap(int N)" }, { "code": null, "e": 3344, "s": 3342, "text": "{" }, { "code": null, "e": 3467, "s": 3344, "text": "// Basically we, need to check for 3 conditions: Nested Loops is what is required to evaluate either a year is leap or not" }, { "code": null, "e": 3485, "s": 3469, "text": "if (N % 4 == 0)" }, { "code": null, "e": 3533, "s": 3485, "text": "{ // come here if year passed is divisible by 4" }, { "code": null, "e": 3551, "s": 3533, "text": "if (N % 100 == 0)" }, { "code": null, "e": 3601, "s": 3551, "text": "{ // come here if year passed is divisible by 100" }, { "code": null, "e": 3619, "s": 3601, "text": "if (N % 400 == 0)" }, { "code": null, "e": 3669, "s": 3619, "text": "{ // come here if year passed is divisible by 400" }, { "code": null, "e": 3690, "s": 3669, "text": "cout << \"leap year\";" }, { "code": null, "e": 3692, "s": 3690, "text": "}" }, { "code": null, "e": 3697, "s": 3692, "text": "else" }, { "code": null, "e": 3762, "s": 3697, "text": "{ // come here if year passed is divisible by 100 but not by 400" }, { "code": null, "e": 3787, "s": 3762, "text": "cout << \"not leap year\";" }, { "code": null, "e": 3789, "s": 3787, "text": "}" }, { "code": null, "e": 3791, "s": 3789, "text": "}" }, { "code": null, "e": 3796, "s": 3791, "text": "else" }, { "code": null, "e": 3869, "s": 3796, "text": "{ // come here if year passed is divisible by 4 and not divisible by 100" }, { "code": null, "e": 3890, "s": 3869, "text": "cout << \"leap year\";" }, { "code": null, "e": 3892, "s": 3890, "text": "}" }, { "code": null, "e": 3894, "s": 3892, "text": "}" }, { "code": null, "e": 3899, "s": 3894, "text": "else" }, { "code": null, "e": 3951, "s": 3899, "text": "{ // come here if year passed is not divisible by 4" }, { "code": null, "e": 3976, "s": 3951, "text": "cout << \"not leap year\";" }, { "code": null, "e": 3978, "s": 3976, "text": "}" }, { "code": null, "e": 3980, "s": 3978, "text": "}" }, { "code": null, "e": 3985, "s": 3982, "text": "OR" }, { "code": null, "e": 4005, "s": 3987, "text": "int isLeap(int N)" }, { "code": null, "e": 4007, "s": 4005, "text": "{" }, { "code": null, "e": 4099, "s": 4007, "text": "// 4 and 100 walli condition for normal years and 400 waali condition is for century year's" }, { "code": null, "e": 4152, "s": 4099, "text": "if ((N % 4 == 0 and N % 100 != 0) or (N % 400 == 0))" }, { "code": null, "e": 4154, "s": 4152, "text": "{" }, { "code": null, "e": 4164, "s": 4154, "text": "return 1;" }, { "code": null, "e": 4166, "s": 4164, "text": "}" }, { "code": null, "e": 4171, "s": 4166, "text": "else" }, { "code": null, "e": 4173, "s": 4171, "text": "{" }, { "code": null, "e": 4183, "s": 4173, "text": "return 0;" }, { "code": null, "e": 4185, "s": 4183, "text": "}" }, { "code": null, "e": 4187, "s": 4185, "text": "}" }, { "code": null, "e": 4333, "s": 4187, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4369, "s": 4333, "text": " Login to access your submissions. " }, { "code": null, "e": 4379, "s": 4369, "text": "\nProblem\n" }, { "code": null, "e": 4389, "s": 4379, "text": "\nContest\n" }, { "code": null, "e": 4452, "s": 4389, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4637, "s": 4452, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4921, "s": 4637, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 5067, "s": 4921, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 5144, "s": 5067, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5185, "s": 5144, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5213, "s": 5185, "text": "Disable browser extensions." }, { "code": null, "e": 5284, "s": 5213, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 5471, "s": 5284, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Chronometer in Kotlin
28 Mar, 2022 Android ChronoMeter is user interface control which shows timer in the view. We can easily start up or down counter with base time using the chronometer widget. By default, start() method can assume base time and starts the counter.Generally, we can create use ChronoMeter widget in XML layout but we can do it programmatically also. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we use the ChronoMeter widget along with a button to start or stop the meter and also set attributes for both of them. 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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/constraint_layout"> <Chronometer android:id="@+id/c_meter" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:layout_marginStart="68dp" android:layout_marginTop="256dp" android:layout_marginEnd="68dp" android:layout_marginBottom="28dp" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textColor="#092FEC" android:textSize="36sp" app:layout_constraintBottom_toTopOf="@+id/btn" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="163dp" android:layout_marginTop="20dp" android:layout_marginEnd="163dp" android:text="@string/start" app:layout_constraintEnd_toEndOf="@id/c_meter" app:layout_constraintHorizontal_bias="0.485" app:layout_constraintStart_toEndOf="@+id/c_meter" app:layout_constraintStart_toStartOf="@id/c_meter" app:layout_constraintTop_toBottomOf="@+id/c_meter" /> </androidx.constraintlayout.widget.ConstraintLayout> Here, we update the name of the application using the string tag. We also other strings which can be used in MainActivity.kt file. XML <resources> <string name="app_name">ChronometerInKotlin</string> <string name="stop">Stop Timer</string> <string name="start">Start Timer</string> <string name="working">Started</string> <string name="stopped">Stopped</string></resources> First, we declare a variable meter to access the Chronometer from the XML layout file. val meter = findViewById<Chronometer>(R.id.c_meter) then, we access the button from the xml file and set setOnClickListener to start and stop the timer. val btn = findViewById<Button>(R.id.btn) btn?.setOnClickListener(object : View.OnClickListener {...} Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundleimport android.widget.Buttonimport android.view.Viewimport android.widget.Chronometerimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the chronometer from XML file val meter = findViewById<Chronometer>(R.id.c_meter) //access the button using id val btn = findViewById<Button>(R.id.btn) btn?.setOnClickListener(object : View.OnClickListener { var isWorking = false override fun onClick(v: View) { if (!isWorking) { meter.start() isWorking = true } else { meter.stop() isWorking = false } btn.setText(if (isWorking) R.string.start else R.string.stop) Toast.makeText(this@MainActivity, getString( if (isWorking) R.string.working else R.string.stopped), Toast.LENGTH_SHORT).show() } }) }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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> anikaseth98 ayushpandey3july Android-Date-time Kotlin Android Android Kotlin 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 RecyclerView in Kotlin Android SDK and it's Components How to Communicate Between Fragments in Android? Broadcast Receiver in Android With Example How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin How to Communicate Between Fragments in Android? Android UI Layouts Broadcast Receiver in Android With Example
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Mar, 2022" }, { "code": null, "e": 388, "s": 54, "text": "Android ChronoMeter is user interface control which shows timer in the view. We can easily start up or down counter with base time using the chronometer widget. By default, start() method can assume base time and starts the counter.Generally, we can create use ChronoMeter widget in XML layout but we can do it programmatically also." }, { "code": null, "e": 449, "s": 388, "text": "First we create a new project by following the below steps: " }, { "code": null, "e": 658, "s": 449, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 698, "s": 658, "text": "Click on File, then New => New Project." }, { "code": null, "e": 755, "s": 698, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 820, "s": 755, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 870, "s": 820, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 1003, "s": 870, "text": "In this file, we use the ChronoMeter widget along with a button to start or stop the meter and also set attributes for both of them." }, { "code": null, "e": 1007, "s": 1003, "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\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:id=\"@+id/constraint_layout\"> <Chronometer android:id=\"@+id/c_meter\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:layout_marginStart=\"68dp\" android:layout_marginTop=\"256dp\" android:layout_marginEnd=\"68dp\" android:layout_marginBottom=\"28dp\" android:textAppearance=\"@style/TextAppearance.AppCompat.Large\" android:textColor=\"#092FEC\" android:textSize=\"36sp\" app:layout_constraintBottom_toTopOf=\"@+id/btn\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"163dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"163dp\" android:text=\"@string/start\" app:layout_constraintEnd_toEndOf=\"@id/c_meter\" app:layout_constraintHorizontal_bias=\"0.485\" app:layout_constraintStart_toEndOf=\"@+id/c_meter\" app:layout_constraintStart_toStartOf=\"@id/c_meter\" app:layout_constraintTop_toBottomOf=\"@+id/c_meter\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2670, "s": 1007, "text": null }, { "code": null, "e": 2802, "s": 2670, "text": "Here, we update the name of the application using the string tag. We also other strings which can be used in MainActivity.kt file. " }, { "code": null, "e": 2806, "s": 2802, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">ChronometerInKotlin</string> <string name=\"stop\">Stop Timer</string> <string name=\"start\">Start Timer</string> <string name=\"working\">Started</string> <string name=\"stopped\">Stopped</string></resources>", "e": 3060, "s": 2806, "text": null }, { "code": null, "e": 3148, "s": 3060, "text": "First, we declare a variable meter to access the Chronometer from the XML layout file. " }, { "code": null, "e": 3200, "s": 3148, "text": "val meter = findViewById<Chronometer>(R.id.c_meter)" }, { "code": null, "e": 3302, "s": 3200, "text": "then, we access the button from the xml file and set setOnClickListener to start and stop the timer. " }, { "code": null, "e": 3411, "s": 3302, "text": "val btn = findViewById<Button>(R.id.btn)\n btn?.setOnClickListener(object : View.OnClickListener {...}" }, { "code": null, "e": 3418, "s": 3411, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundleimport android.widget.Buttonimport android.view.Viewimport android.widget.Chronometerimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the chronometer from XML file val meter = findViewById<Chronometer>(R.id.c_meter) //access the button using id val btn = findViewById<Button>(R.id.btn) btn?.setOnClickListener(object : View.OnClickListener { var isWorking = false override fun onClick(v: View) { if (!isWorking) { meter.start() isWorking = true } else { meter.stop() isWorking = false } btn.setText(if (isWorking) R.string.start else R.string.stop) Toast.makeText(this@MainActivity, getString( if (isWorking) R.string.working else R.string.stopped), Toast.LENGTH_SHORT).show() } }) }}", "e": 4743, "s": 3418, "text": null }, { "code": null, "e": 4747, "s": 4743, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>", "e": 5402, "s": 4747, "text": null }, { "code": null, "e": 5414, "s": 5402, "text": "anikaseth98" }, { "code": null, "e": 5431, "s": 5414, "text": "ayushpandey3july" }, { "code": null, "e": 5449, "s": 5431, "text": "Android-Date-time" }, { "code": null, "e": 5464, "s": 5449, "text": "Kotlin Android" }, { "code": null, "e": 5472, "s": 5464, "text": "Android" }, { "code": null, "e": 5479, "s": 5472, "text": "Kotlin" }, { "code": null, "e": 5487, "s": 5479, "text": "Android" }, { "code": null, "e": 5585, "s": 5487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5654, "s": 5585, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5685, "s": 5654, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 5717, "s": 5685, "text": "Android SDK and it's Components" }, { "code": null, "e": 5766, "s": 5717, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5809, "s": 5766, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 5878, "s": 5809, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5909, "s": 5878, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 5958, "s": 5909, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5977, "s": 5958, "text": "Android UI Layouts" } ]
ML | K-Medoids clustering with solved example
07 Aug, 2020 K-Medoids (also called as Partitioning Around Medoid) algorithm was proposed in 1987 by Kaufman and Rousseeuw. A medoid can be defined as the point in the cluster, whose dissimilarities with all the other points in the cluster is minimum. The dissimilarity of the medoid(Ci) and object(Pi) is calculated by using E = |Pi - Ci| The cost in K-Medoids algorithm is given as Algorithm: 1. Initialize: select k random points out of the n data points as the medoids.2. Associate each data point to the closest medoid by using any common distance metric methods.3. While the cost decreases: For each medoid m, for each data o point which is not a medoid: 1. Swap m and o, associate each data point to the closest medoid, recompute the cost. 2. If the total cost is more than that in the previous step, undo the swap. Let’s consider the following example: If a graph is drawn using the above data points, we obtain the following: Step 1:Let the randomly selected 2 medoids, so select k = 2 and let C1 -(4, 5) and C2 -(8, 5) are the two medoids. Step 2: Calculating cost.The dissimilarity of each non-medoid point with the medoids is calculated and tabulated: Each point is assigned to the cluster of that medoid whose dissimilarity is less.The points 1, 2, 5 go to cluster C1 and 0, 3, 6, 7, 8 go to cluster C2.The Cost = (3 + 4 + 4) + (3 + 1 + 1 + 2 + 2) = 20 Step 3: randomly select one non-medoid point and recalculate the cost.Let the randomly selected point be (8, 4). The dissimilarity of each non-medoid point with the medoids – C1 (4, 5) and C2 (8, 4) is calculated and tabulated.Each point is assigned to that cluster whose dissimilarity is less. So, the points 1, 2, 5 go to cluster C1 and 0, 3, 6, 7, 8 go to cluster C2.The New cost = (3 + 4 + 4) + (2 + 2 + 1 + 3 + 3) = 22Swap Cost = New Cost – Previous Cost = 22 – 20 and 2 >0 As the swap cost is not less than zero, we undo the swap. Hence (3, 4) and (7, 4) are the final medoids. The clustering would be in the following way The time complexity is . Advantages: It is simple to understand and easy to implement.K-Medoid Algorithm is fast and converges in a fixed number of steps.PAM is less sensitive to outliers than other partitioning algorithms. It is simple to understand and easy to implement. K-Medoid Algorithm is fast and converges in a fixed number of steps. PAM is less sensitive to outliers than other partitioning algorithms. Disadvantages: The main disadvantage of K-Medoid algorithms is that it is not suitable for clustering non-spherical (arbitrary shaped) groups of objects. This is because it relies on minimizing the distances between the non-medoid objects and the medoid (the cluster centre) – briefly, it uses compactness as clustering criteria instead of connectivity.It may obtain different results for different runs on the same dataset because the first k medoids are chosen randomly. The main disadvantage of K-Medoid algorithms is that it is not suitable for clustering non-spherical (arbitrary shaped) groups of objects. This is because it relies on minimizing the distances between the non-medoid objects and the medoid (the cluster centre) – briefly, it uses compactness as clustering criteria instead of connectivity. It may obtain different results for different runs on the same dataset because the first k medoids are chosen randomly. ML-Clustering 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) Support Vector Machine Algorithm 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": 52, "s": 24, "text": "\n07 Aug, 2020" }, { "code": null, "e": 291, "s": 52, "text": "K-Medoids (also called as Partitioning Around Medoid) algorithm was proposed in 1987 by Kaufman and Rousseeuw. A medoid can be defined as the point in the cluster, whose dissimilarities with all the other points in the cluster is minimum." }, { "code": null, "e": 379, "s": 291, "text": "The dissimilarity of the medoid(Ci) and object(Pi) is calculated by using E = |Pi - Ci|" }, { "code": null, "e": 423, "s": 379, "text": "The cost in K-Medoids algorithm is given as" }, { "code": null, "e": 439, "s": 428, "text": "Algorithm:" }, { "code": null, "e": 904, "s": 439, "text": "1. Initialize: select k random points out of the n data points as the medoids.2. Associate each data point to the closest medoid by using any common distance metric methods.3. While the cost decreases: For each medoid m, for each data o point which is not a medoid: 1. Swap m and o, associate each data point to the closest medoid, recompute the cost. 2. If the total cost is more than that in the previous step, undo the swap." }, { "code": null, "e": 942, "s": 904, "text": "Let’s consider the following example:" }, { "code": null, "e": 1016, "s": 942, "text": "If a graph is drawn using the above data points, we obtain the following:" }, { "code": null, "e": 1131, "s": 1016, "text": "Step 1:Let the randomly selected 2 medoids, so select k = 2 and let C1 -(4, 5) and C2 -(8, 5) are the two medoids." }, { "code": null, "e": 1245, "s": 1131, "text": "Step 2: Calculating cost.The dissimilarity of each non-medoid point with the medoids is calculated and tabulated:" }, { "code": null, "e": 1447, "s": 1245, "text": "Each point is assigned to the cluster of that medoid whose dissimilarity is less.The points 1, 2, 5 go to cluster C1 and 0, 3, 6, 7, 8 go to cluster C2.The Cost = (3 + 4 + 4) + (3 + 1 + 1 + 2 + 2) = 20" }, { "code": null, "e": 1926, "s": 1447, "text": "Step 3: randomly select one non-medoid point and recalculate the cost.Let the randomly selected point be (8, 4). The dissimilarity of each non-medoid point with the medoids – C1 (4, 5) and C2 (8, 4) is calculated and tabulated.Each point is assigned to that cluster whose dissimilarity is less. So, the points 1, 2, 5 go to cluster C1 and 0, 3, 6, 7, 8 go to cluster C2.The New cost = (3 + 4 + 4) + (2 + 2 + 1 + 3 + 3) = 22Swap Cost = New Cost – Previous Cost = 22 – 20 and 2 >0" }, { "code": null, "e": 2076, "s": 1926, "text": "As the swap cost is not less than zero, we undo the swap. Hence (3, 4) and (7, 4) are the final medoids. The clustering would be in the following way" }, { "code": null, "e": 2101, "s": 2076, "text": "The time complexity is ." }, { "code": null, "e": 2113, "s": 2101, "text": "Advantages:" }, { "code": null, "e": 2300, "s": 2113, "text": "It is simple to understand and easy to implement.K-Medoid Algorithm is fast and converges in a fixed number of steps.PAM is less sensitive to outliers than other partitioning algorithms." }, { "code": null, "e": 2350, "s": 2300, "text": "It is simple to understand and easy to implement." }, { "code": null, "e": 2419, "s": 2350, "text": "K-Medoid Algorithm is fast and converges in a fixed number of steps." }, { "code": null, "e": 2489, "s": 2419, "text": "PAM is less sensitive to outliers than other partitioning algorithms." }, { "code": null, "e": 2504, "s": 2489, "text": "Disadvantages:" }, { "code": null, "e": 2962, "s": 2504, "text": "The main disadvantage of K-Medoid algorithms is that it is not suitable for clustering non-spherical (arbitrary shaped) groups of objects. This is because it relies on minimizing the distances between the non-medoid objects and the medoid (the cluster centre) – briefly, it uses compactness as clustering criteria instead of connectivity.It may obtain different results for different runs on the same dataset because the first k medoids are chosen randomly." }, { "code": null, "e": 3301, "s": 2962, "text": "The main disadvantage of K-Medoid algorithms is that it is not suitable for clustering non-spherical (arbitrary shaped) groups of objects. This is because it relies on minimizing the distances between the non-medoid objects and the medoid (the cluster centre) – briefly, it uses compactness as clustering criteria instead of connectivity." }, { "code": null, "e": 3421, "s": 3301, "text": "It may obtain different results for different runs on the same dataset because the first k medoids are chosen randomly." }, { "code": null, "e": 3435, "s": 3421, "text": "ML-Clustering" }, { "code": null, "e": 3452, "s": 3435, "text": "Machine Learning" }, { "code": null, "e": 3469, "s": 3452, "text": "Machine Learning" }, { "code": null, "e": 3567, "s": 3469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3608, "s": 3567, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3644, "s": 3608, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3677, "s": 3644, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3701, "s": 3677, "text": "Markov Decision Process" }, { "code": null, "e": 3752, "s": 3701, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 3785, "s": 3752, "text": "Normalization vs Standardization" }, { "code": null, "e": 3825, "s": 3785, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 3866, "s": 3825, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 3894, "s": 3866, "text": "Types of Environments in AI" } ]
HashMap and TreeMap in Java
11 Dec, 2018 HashMap and TreeMap are part of collection framework. HashMap<K, V> hmap = new HashMap<K, V>(); Let us consider below example where we have to count occurrences of each integer in given array of integers. Input: arr[] = {10, 3, 5, 10, 3, 5, 10}; Output: Frequency of 10 is 3 Frequency of 3 is 2 Frequency of 5 is 2 /* Java program to print frequencies of all elements using HashMap */import java.util.*; class Main{ // This function prints frequencies of all elements static void printFreq(int arr[]) { // Creates an empty HashMap HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { Integer c = hmap.get(arr[i]); // If this is first occurrence of element if (hmap.get(arr[i]) == null) hmap.put(arr[i], 1); // If elements already exists in hash map else hmap.put(arr[i], ++c); } // Print result for (Map.Entry m:hmap.entrySet()) System.out.println("Frequency of " + m.getKey() + " is " + m.getValue()); } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 34, 5, 10, 3, 5, 10}; printFreq(arr); }} Output: Frequency of 34 is 1 Frequency of 3 is 1 Frequency of 5 is 2 Frequency of 10 is 3 Key Points HashMap does not maintain any order neither based on key nor on basis of value, If we want the keys to be maintained in a sorted order, we need to use TreeMap. Complexity: get/put/containsKey() operations are O(1) in average case but we can’t guarantee that since it all depends on how much time does it take to compute the hash. Application:HashMap is basically an implementation of hashing. So wherever we need hashing with key value pairs, we can use HashMap. For example, in Web Applications username is stored as a key and user data is stored as a value in the HashMap, for faster retrieval of user data corresponding to a username. TreeMap<K, V> hmap = new TreeMap<K, V>(); Below is TreeMap based implementation of same problem. This solution has more time complexity O(nLogn) compared to previous one which has O(n). The advantage of this method is, we get elements in sorted order. /* Java program to print frequencies of all elements using TreeMap */import java.util.*; class Main{ // This function prints frequencies of all elements static void printFreq(int arr[]) { // Creates an empty TreeMap TreeMap<Integer, Integer> tmap = new TreeMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { Integer c = tmap.get(arr[i]); // If this is first occurrence of element if (tmap.get(arr[i]) == null) tmap.put(arr[i], 1); // If elements already exists in hash map else tmap.put(arr[i], ++c); } // Print result for (Map.Entry m:tmap.entrySet()) System.out.println("Frequency of " + m.getKey() + " is " + m.getValue()); } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 34, 5, 10, 3, 5, 10}; printFreq(arr); }} Output: Frequency of 3 is 1 Frequency of 5 is 2 Frequency of 10 is 3 Frequency of 34 is 1 Key Points For operations like add, remove, containsKey, time complexity is O(log n where n is number of elements present in TreeMap. TreeMap always keeps the elements in a sorted(increasing) order, while the elements in a HashMap have no order. TreeMap also provides some cool methods for first, last, floor and ceiling of keys. HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map.HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing Binary Search Tree). Therefore all differences between Hashing and Balanced Binary Search Tree apply here.Both HashMap and TreeMap have their counterparts HashSet and TreeSet. HashSet and TreeSet implement Set interface. In HashSet and TreeSet, we have only key, no value, these are mainly used to see presence/absence in a set. For above problem, we can’t use HashSet (or TreeSet) as we can’t store counts. An example problem where we would prefer HashSet (or TreeSet) over HashMap (or TreeMap) is to print all distinct elements in an array. HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map. HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing Binary Search Tree). Therefore all differences between Hashing and Balanced Binary Search Tree apply here. Both HashMap and TreeMap have their counterparts HashSet and TreeSet. HashSet and TreeSet implement Set interface. In HashSet and TreeSet, we have only key, no value, these are mainly used to see presence/absence in a set. For above problem, we can’t use HashSet (or TreeSet) as we can’t store counts. An example problem where we would prefer HashSet (or TreeSet) over HashMap (or TreeMap) is to print all distinct elements in an array. Related Articles LinkedHashmap in Java Differences between TreeMap, HashMap and LinkedHashMap in Java Differences between HashMap and HashTable in Java References :https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html This article is contributed by Chirag Agrawal. 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 Java-Collections Java-HashMap Java-Map-Programs java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Collections in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stack Class in Java Stream In Java Queue Interface In Java Constructors in Java Introduction to Java
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Dec, 2018" }, { "code": null, "e": 106, "s": 52, "text": "HashMap and TreeMap are part of collection framework." }, { "code": null, "e": 149, "s": 106, "text": " HashMap<K, V> hmap = new HashMap<K, V>();" }, { "code": null, "e": 258, "s": 149, "text": "Let us consider below example where we have to count occurrences of each integer in given array of integers." }, { "code": null, "e": 385, "s": 258, "text": "Input: arr[] = {10, 3, 5, 10, 3, 5, 10};\nOutput: Frequency of 10 is 3\n Frequency of 3 is 2\n Frequency of 5 is 2\n" }, { "code": "/* Java program to print frequencies of all elements using HashMap */import java.util.*; class Main{ // This function prints frequencies of all elements static void printFreq(int arr[]) { // Creates an empty HashMap HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { Integer c = hmap.get(arr[i]); // If this is first occurrence of element if (hmap.get(arr[i]) == null) hmap.put(arr[i], 1); // If elements already exists in hash map else hmap.put(arr[i], ++c); } // Print result for (Map.Entry m:hmap.entrySet()) System.out.println(\"Frequency of \" + m.getKey() + \" is \" + m.getValue()); } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 34, 5, 10, 3, 5, 10}; printFreq(arr); }}", "e": 1452, "s": 385, "text": null }, { "code": null, "e": 1460, "s": 1452, "text": "Output:" }, { "code": null, "e": 1542, "s": 1460, "text": "Frequency of 34 is 1\nFrequency of 3 is 1\nFrequency of 5 is 2\nFrequency of 10 is 3" }, { "code": null, "e": 1553, "s": 1542, "text": "Key Points" }, { "code": null, "e": 1713, "s": 1553, "text": "HashMap does not maintain any order neither based on key nor on basis of value, If we want the keys to be maintained in a sorted order, we need to use TreeMap." }, { "code": null, "e": 1883, "s": 1713, "text": "Complexity: get/put/containsKey() operations are O(1) in average case but we can’t guarantee that since it all depends on how much time does it take to compute the hash." }, { "code": null, "e": 2191, "s": 1883, "text": "Application:HashMap is basically an implementation of hashing. So wherever we need hashing with key value pairs, we can use HashMap. For example, in Web Applications username is stored as a key and user data is stored as a value in the HashMap, for faster retrieval of user data corresponding to a username." }, { "code": null, "e": 2236, "s": 2193, "text": " TreeMap<K, V> hmap = new TreeMap<K, V>();" }, { "code": null, "e": 2446, "s": 2236, "text": "Below is TreeMap based implementation of same problem. This solution has more time complexity O(nLogn) compared to previous one which has O(n). The advantage of this method is, we get elements in sorted order." }, { "code": "/* Java program to print frequencies of all elements using TreeMap */import java.util.*; class Main{ // This function prints frequencies of all elements static void printFreq(int arr[]) { // Creates an empty TreeMap TreeMap<Integer, Integer> tmap = new TreeMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { Integer c = tmap.get(arr[i]); // If this is first occurrence of element if (tmap.get(arr[i]) == null) tmap.put(arr[i], 1); // If elements already exists in hash map else tmap.put(arr[i], ++c); } // Print result for (Map.Entry m:tmap.entrySet()) System.out.println(\"Frequency of \" + m.getKey() + \" is \" + m.getValue()); } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 34, 5, 10, 3, 5, 10}; printFreq(arr); }}", "e": 3513, "s": 2446, "text": null }, { "code": null, "e": 3521, "s": 3513, "text": "Output:" }, { "code": null, "e": 3603, "s": 3521, "text": "Frequency of 3 is 1\nFrequency of 5 is 2\nFrequency of 10 is 3\nFrequency of 34 is 1" }, { "code": null, "e": 3614, "s": 3603, "text": "Key Points" }, { "code": null, "e": 3737, "s": 3614, "text": "For operations like add, remove, containsKey, time complexity is O(log n where n is number of elements present in TreeMap." }, { "code": null, "e": 3933, "s": 3737, "text": "TreeMap always keeps the elements in a sorted(increasing) order, while the elements in a HashMap have no order. TreeMap also provides some cool methods for first, last, floor and ceiling of keys." }, { "code": null, "e": 4681, "s": 3933, "text": "HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map.HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing Binary Search Tree). Therefore all differences between Hashing and Balanced Binary Search Tree apply here.Both HashMap and TreeMap have their counterparts HashSet and TreeSet. HashSet and TreeSet implement Set interface. In HashSet and TreeSet, we have only key, no value, these are mainly used to see presence/absence in a set. For above problem, we can’t use HashSet (or TreeSet) as we can’t store counts. An example problem where we would prefer HashSet (or TreeSet) over HashMap (or TreeMap) is to print all distinct elements in an array." }, { "code": null, "e": 4802, "s": 4681, "text": "HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map." }, { "code": null, "e": 4994, "s": 4802, "text": "HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing Binary Search Tree). Therefore all differences between Hashing and Balanced Binary Search Tree apply here." }, { "code": null, "e": 5431, "s": 4994, "text": "Both HashMap and TreeMap have their counterparts HashSet and TreeSet. HashSet and TreeSet implement Set interface. In HashSet and TreeSet, we have only key, no value, these are mainly used to see presence/absence in a set. For above problem, we can’t use HashSet (or TreeSet) as we can’t store counts. An example problem where we would prefer HashSet (or TreeSet) over HashMap (or TreeMap) is to print all distinct elements in an array." }, { "code": null, "e": 5448, "s": 5431, "text": "Related Articles" }, { "code": null, "e": 5470, "s": 5448, "text": "LinkedHashmap in Java" }, { "code": null, "e": 5533, "s": 5470, "text": "Differences between TreeMap, HashMap and LinkedHashMap in Java" }, { "code": null, "e": 5583, "s": 5533, "text": "Differences between HashMap and HashTable in Java" }, { "code": null, "e": 5663, "s": 5583, "text": "References :https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html" }, { "code": null, "e": 5932, "s": 5663, "text": "This article is contributed by Chirag Agrawal. 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." }, { "code": null, "e": 6056, "s": 5932, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 6073, "s": 6056, "text": "Java-Collections" }, { "code": null, "e": 6086, "s": 6073, "text": "Java-HashMap" }, { "code": null, "e": 6104, "s": 6086, "text": "Java-Map-Programs" }, { "code": null, "e": 6117, "s": 6104, "text": "java-TreeMap" }, { "code": null, "e": 6122, "s": 6117, "text": "Java" }, { "code": null, "e": 6127, "s": 6122, "text": "Java" }, { "code": null, "e": 6144, "s": 6127, "text": "Java-Collections" }, { "code": null, "e": 6242, "s": 6144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6293, "s": 6242, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6313, "s": 6293, "text": "Collections in Java" }, { "code": null, "e": 6332, "s": 6313, "text": "Interfaces in Java" }, { "code": null, "e": 6362, "s": 6332, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6380, "s": 6362, "text": "ArrayList in Java" }, { "code": null, "e": 6400, "s": 6380, "text": "Stack Class in Java" }, { "code": null, "e": 6415, "s": 6400, "text": "Stream In Java" }, { "code": null, "e": 6439, "s": 6415, "text": "Queue Interface In Java" }, { "code": null, "e": 6460, "s": 6439, "text": "Constructors in Java" } ]
Python | Intensity Transformation Operations on Images
02 Aug, 2019 Intensity transformations are applied on images for contrast manipulation or image thresholding. These are in the spatial domain, i.e. they are performed directly on the pixels of the image at hand, as opposed to being performed on the Fourier transform of the image. The following are commonly used intensity transformations: Image Negatives (Linear)Log TransformationsPower-Law (Gamma) TransformationsPiecewise-Linear Transformation Functions Image Negatives (Linear) Log Transformations Power-Law (Gamma) Transformations Piecewise-Linear Transformation Functions Spatial Domain Processes –Spatial domain processes can be described using the equation: where is the input image, T is an operator on f defined over a neighbourhood of the point (x, y), and is the output. Image Negatives – Image negatives are discussed in this article. Mathematically, assume that an image goes from intensity levels 0 to (L-1). Generally, L = 256. Then, the negative transformation can be described by the expression s = L-1-r where r is the initial intensity level and s is the final intensity level of a pixel. This produces a photographic negative. Mathematically, log transformations can be expressed as s = clog(1+r). Here, s is the output intensity, r>=0 is the input intensity of the pixel, and c is a scaling constant. c is given by 255/(log (1 + m)), where m is the maximum pixel value in the image. It is done to ensure that the final pixel value does not exceed (L-1), or 255. Practically, log transformation maps a narrow range of low-intensity input values to a wide range of output values. Consider the following input image. Below is the code to apply log transformation to the image. import cv2import numpy as np # Open the image.img = cv2.imread('sample.jpg') # Apply log transform.c = 255/(np.log(1 + np.max(img)))log_transformed = c * np.log(1 + img) # Specify the data type.log_transformed = np.array(log_transformed, dtype = np.uint8) # Save the output.cv2.imwrite('log_transformed.jpg', log_transformed) Below is the log-transformed output. Power-law (gamma) transformations can be mathematically expressed as . Gamma correction is important for displaying images on a screen correctly, to prevent bleaching or darkening of images when viewed from different types of monitors with different display settings. This is done because our eyes perceive images in a gamma-shaped curve, whereas cameras capture images in a linear fashion. Below is the Python code to apply gamma correction. import cv2import numpy as np # Open the image.img = cv2.imread('sample.jpg') # Trying 4 gamma values.for gamma in [0.1, 0.5, 1.2, 2.2]: # Apply gamma correction. gamma_corrected = np.array(255*(img / 255) ** gamma, dtype = 'uint8') # Save edited images. cv2.imwrite('gamma_transformed'+str(gamma)+'.jpg', gamma_corrected) Below are the gamma-corrected outputs for different values of gamma. Gamma = 0.1: Gamma = 0.5: Gamma = 1.2: Gamma = 2.2: As can be observed from the outputs as well as the graph, gamma>1 (indicated by the curve corresponding to ‘nth power’ label on the graph), the intensity of pixels decreases i.e. the image becomes darker. On the other hand, gamma<1 (indicated by the curve corresponding to 'nth root' label on the graph), the intensity increases i.e. the image becomes lighter. These functions, as the name suggests, are not entirely linear in nature. However, they are linear between certain x-intervals. One of the most commonly used piecewise-linear transformation functions is contrast stretching. Contrast can be defined as: Contrast = (I_max - I_min)/(I_max + I_min) This process expands the range of intensity levels in an image so that it spans the full intensity of the camera/display. The figure below shows the graph corresponding to the contrast stretching. With (r1, s1), (r2, s2) as parameters, the function stretches the intensity levels by essentially decreasing the intensity of the dark pixels and increasing the intensity of the light pixels. If r1 = s1 = 0 and r2 = s2 = L-1, the function becomes a straight dotted line in the graph (which gives no effect). The function is monotonically increasing so that the order of intensity levels between pixels is preserved. Below is the Python code to perform contrast stretching. import cv2import numpy as np # Function to map each intensity level to output intensity level.def pixelVal(pix, r1, s1, r2, s2): if (0 <= pix and pix <= r1): return (s1 / r1)*pix elif (r1 < pix and pix <= r2): return ((s2 - s1)/(r2 - r1)) * (pix - r1) + s1 else: return ((255 - s2)/(255 - r2)) * (pix - r2) + s2 # Open the image.img = cv2.imread('sample.jpg') # Define parameters.r1 = 70s1 = 0r2 = 140s2 = 255 # Vectorize the function to apply it to each value in the Numpy array.pixelVal_vec = np.vectorize(pixelVal) # Apply contrast stretching.contrast_stretched = pixelVal_vec(img, r1, s1, r2, s2) # Save edited image.cv2.imwrite('contrast_stretch.jpg', contrast_stretched) Output: Image-Processing OpenCV 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": 53, "s": 25, "text": "\n02 Aug, 2019" }, { "code": null, "e": 321, "s": 53, "text": "Intensity transformations are applied on images for contrast manipulation or image thresholding. These are in the spatial domain, i.e. they are performed directly on the pixels of the image at hand, as opposed to being performed on the Fourier transform of the image." }, { "code": null, "e": 380, "s": 321, "text": "The following are commonly used intensity transformations:" }, { "code": null, "e": 498, "s": 380, "text": "Image Negatives (Linear)Log TransformationsPower-Law (Gamma) TransformationsPiecewise-Linear Transformation Functions" }, { "code": null, "e": 523, "s": 498, "text": "Image Negatives (Linear)" }, { "code": null, "e": 543, "s": 523, "text": "Log Transformations" }, { "code": null, "e": 577, "s": 543, "text": "Power-Law (Gamma) Transformations" }, { "code": null, "e": 619, "s": 577, "text": "Piecewise-Linear Transformation Functions" }, { "code": null, "e": 827, "s": 619, "text": "Spatial Domain Processes –Spatial domain processes can be described using the equation: where is the input image, T is an operator on f defined over a neighbourhood of the point (x, y), and is the output." }, { "code": null, "e": 845, "s": 827, "text": "Image Negatives –" }, { "code": null, "e": 1192, "s": 845, "text": "Image negatives are discussed in this article. Mathematically, assume that an image goes from intensity levels 0 to (L-1). Generally, L = 256. Then, the negative transformation can be described by the expression s = L-1-r where r is the initial intensity level and s is the final intensity level of a pixel. This produces a photographic negative." }, { "code": null, "e": 1644, "s": 1192, "text": "Mathematically, log transformations can be expressed as s = clog(1+r). Here, s is the output intensity, r>=0 is the input intensity of the pixel, and c is a scaling constant. c is given by 255/(log (1 + m)), where m is the maximum pixel value in the image. It is done to ensure that the final pixel value does not exceed (L-1), or 255. Practically, log transformation maps a narrow range of low-intensity input values to a wide range of output values." }, { "code": null, "e": 1680, "s": 1644, "text": "Consider the following input image." }, { "code": null, "e": 1740, "s": 1680, "text": "Below is the code to apply log transformation to the image." }, { "code": "import cv2import numpy as np # Open the image.img = cv2.imread('sample.jpg') # Apply log transform.c = 255/(np.log(1 + np.max(img)))log_transformed = c * np.log(1 + img) # Specify the data type.log_transformed = np.array(log_transformed, dtype = np.uint8) # Save the output.cv2.imwrite('log_transformed.jpg', log_transformed)", "e": 2070, "s": 1740, "text": null }, { "code": null, "e": 2107, "s": 2070, "text": "Below is the log-transformed output." }, { "code": null, "e": 2550, "s": 2107, "text": "Power-law (gamma) transformations can be mathematically expressed as . Gamma correction is important for displaying images on a screen correctly, to prevent bleaching or darkening of images when viewed from different types of monitors with different display settings. This is done because our eyes perceive images in a gamma-shaped curve, whereas cameras capture images in a linear fashion. Below is the Python code to apply gamma correction." }, { "code": "import cv2import numpy as np # Open the image.img = cv2.imread('sample.jpg') # Trying 4 gamma values.for gamma in [0.1, 0.5, 1.2, 2.2]: # Apply gamma correction. gamma_corrected = np.array(255*(img / 255) ** gamma, dtype = 'uint8') # Save edited images. cv2.imwrite('gamma_transformed'+str(gamma)+'.jpg', gamma_corrected)", "e": 2894, "s": 2550, "text": null }, { "code": null, "e": 2963, "s": 2894, "text": "Below are the gamma-corrected outputs for different values of gamma." }, { "code": null, "e": 2976, "s": 2963, "text": "Gamma = 0.1:" }, { "code": null, "e": 2989, "s": 2976, "text": "Gamma = 0.5:" }, { "code": null, "e": 3002, "s": 2989, "text": "Gamma = 1.2:" }, { "code": null, "e": 3015, "s": 3002, "text": "Gamma = 2.2:" }, { "code": null, "e": 3376, "s": 3015, "text": "As can be observed from the outputs as well as the graph, gamma>1 (indicated by the curve corresponding to ‘nth power’ label on the graph), the intensity of pixels decreases i.e. the image becomes darker. On the other hand, gamma<1 (indicated by the curve corresponding to 'nth root' label on the graph), the intensity increases i.e. the image becomes lighter." }, { "code": null, "e": 3600, "s": 3376, "text": "These functions, as the name suggests, are not entirely linear in nature. However, they are linear between certain x-intervals. One of the most commonly used piecewise-linear transformation functions is contrast stretching." }, { "code": null, "e": 3628, "s": 3600, "text": "Contrast can be defined as:" }, { "code": null, "e": 3672, "s": 3628, "text": "Contrast = (I_max - I_min)/(I_max + I_min)" }, { "code": null, "e": 3869, "s": 3672, "text": "This process expands the range of intensity levels in an image so that it spans the full intensity of the camera/display. The figure below shows the graph corresponding to the contrast stretching." }, { "code": null, "e": 4285, "s": 3869, "text": "With (r1, s1), (r2, s2) as parameters, the function stretches the intensity levels by essentially decreasing the intensity of the dark pixels and increasing the intensity of the light pixels. If r1 = s1 = 0 and r2 = s2 = L-1, the function becomes a straight dotted line in the graph (which gives no effect). The function is monotonically increasing so that the order of intensity levels between pixels is preserved." }, { "code": null, "e": 4342, "s": 4285, "text": "Below is the Python code to perform contrast stretching." }, { "code": "import cv2import numpy as np # Function to map each intensity level to output intensity level.def pixelVal(pix, r1, s1, r2, s2): if (0 <= pix and pix <= r1): return (s1 / r1)*pix elif (r1 < pix and pix <= r2): return ((s2 - s1)/(r2 - r1)) * (pix - r1) + s1 else: return ((255 - s2)/(255 - r2)) * (pix - r2) + s2 # Open the image.img = cv2.imread('sample.jpg') # Define parameters.r1 = 70s1 = 0r2 = 140s2 = 255 # Vectorize the function to apply it to each value in the Numpy array.pixelVal_vec = np.vectorize(pixelVal) # Apply contrast stretching.contrast_stretched = pixelVal_vec(img, r1, s1, r2, s2) # Save edited image.cv2.imwrite('contrast_stretch.jpg', contrast_stretched)", "e": 5055, "s": 4342, "text": null }, { "code": null, "e": 5063, "s": 5055, "text": "Output:" }, { "code": null, "e": 5080, "s": 5063, "text": "Image-Processing" }, { "code": null, "e": 5087, "s": 5080, "text": "OpenCV" }, { "code": null, "e": 5094, "s": 5087, "text": "Python" }, { "code": null, "e": 5192, "s": 5094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5210, "s": 5192, "text": "Python Dictionary" }, { "code": null, "e": 5252, "s": 5210, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5274, "s": 5252, "text": "Enumerate() in Python" }, { "code": null, "e": 5309, "s": 5274, "text": "Read a file line by line in Python" }, { "code": null, "e": 5335, "s": 5309, "text": "Python String | replace()" }, { "code": null, "e": 5367, "s": 5335, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5396, "s": 5367, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5426, "s": 5396, "text": "Iterate over a list in Python" }, { "code": null, "e": 5453, "s": 5426, "text": "Python Classes and Objects" } ]
What is the use of ini_set() in PHP?
PHP allows the user to modify some of its settings mentioned in php.ini using ini_set(). This function requires two string arguments. The first one is the name of the setting to be modified and the second one is the new value to be assigned to it. Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix. The new value for the option. <?php ini_set('display_errors', '1'); ?> Given the line of code will enable the display_error setting for the script if it’s disabled. We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini.
[ { "code": null, "e": 1435, "s": 1187, "text": "PHP allows the user to modify some of its settings mentioned in php.ini using ini_set(). This function requires two string arguments. The first one is the name of the setting to be modified and the second one is the new value to be assigned to it." }, { "code": null, "e": 1555, "s": 1435, "text": "Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix." }, { "code": null, "e": 1585, "s": 1555, "text": "The new value for the option." }, { "code": null, "e": 1629, "s": 1585, "text": "<?php\n ini_set('display_errors', '1');\n?>" }, { "code": null, "e": 1981, "s": 1629, "text": "Given the line of code will enable the display_error setting for the script if it’s disabled. We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini." } ]
SQL | With Ties Clause
21 Mar, 2018 This post is a continuation of SQL Offset-Fetch Clause Now, we understand that how to use the Fetch Clause in Oracle Database, along with the Specified Offset and we also understand that Fetch clause is the newly added clause in the Oracle Database 12c or it is the new feature added in the Oracle database 12c. Now consider the below example: Suppose we a have a table named myTable with below data: ID NAME SALARY ----------------------------- 1 Geeks 10000 4 Finch 10000 2 RR 6000 3 Dhoni 16000 5 Karthik 7000 6 Watson 10000 Now, suppose we want the first three rows to be Ordered by Salary in descending order, then the below query must be executed: Query: SELECT * from myTable order by salary desc fetch first 3 rows only; Output: We got only first 3 rows order by Salary in Descending Order ID NAME SALARY -------------------------- 3 Dhoni 16000 1 Geeks 10000 4 Finch 10000 Note: In the above result we got first 3 rows, ordered by Salary in Descending Order, but we have one more row with same salary i.e, the row with name Watson and Salary 10000, but it didn’t came up, because we restricted our output to first three rows only. But this is not optimal, because most of the time in live applications we will be required to display the tied rows also. Real Life Example – Suppose we have 10 Racers running, and we have only 3 prizes i.e, first, second, third, but suppose, Racers 3 and 4 finished the race together in same time, so in this case we have a tie between 3 and 4 and that’s why both are holder of Position 3. With Ties So, to overcome the above problem, Oracle introduces a clause known as With Ties clause. Now, let’s see our previous example using With Ties clause. Query: SELECT * from myTable order by salary desc fetch first 3 rows With Ties; Output: See we get only first 3 rows order by Salary in Descending Order along with Tied Row also ID NAME SALARY -------------------------- 3 Dhoni 16000 1 Geeks 10000 6 Watson 10000 // We get Tied Row also 4 Finch 10000 Now, see we got the tied row also, which we were not getting previously. Note: We get the tied row in our output, only when we use the order by clause in our Select statement. Suppose, if we won’t use order by clause, and still we are using with ties clause, then we won’t get the tied row in our output and the query behaves same as, if we are using ONLY clause instead of With Ties clause. Example – Suppose we execute the below query(without using order by clause) : Query: SELECT * from myTable fetch first 3 rows With Ties; Output: See we won't get the tied row because we didn't use order by clause ID NAME SALARY -------------------------- 1 Geeks 10000 4 Finch 10000 2 RR 6000 In the above result we won’t get the tied row and we get only first 3 rows. So With Ties is tied with order by clause, i.e, we get the tied row in output if and only if we use With Ties along with Order by clause. Note: Please make sure that, you run these queries in Oracle Database 12c, because Fetch clause is the newly added feature in Oracle 12c, also With Ties, runs only in Oracle Database 12c, these queries won’t run in below versions of 12c like 10g or 11g. References: About Fetch Clause as well as With Ties Clause, Performing SQL Queries Online SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? Difference between DELETE, DROP and TRUNCATE Window functions in SQL Difference between DELETE and TRUNCATE MySQL | Group_CONCAT() Function MySQL | Regular expressions (Regexp) SQL Correlated Subqueries SQL | DDL, DML, TCL and DCL
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Mar, 2018" }, { "code": null, "e": 107, "s": 52, "text": "This post is a continuation of SQL Offset-Fetch Clause" }, { "code": null, "e": 364, "s": 107, "text": "Now, we understand that how to use the Fetch Clause in Oracle Database, along with the Specified Offset and we also understand that Fetch clause is the newly added clause in the Oracle Database 12c or it is the new feature added in the Oracle database 12c." }, { "code": null, "e": 396, "s": 364, "text": "Now consider the below example:" }, { "code": null, "e": 453, "s": 396, "text": "Suppose we a have a table named myTable with below data:" }, { "code": null, "e": 638, "s": 453, "text": "ID NAME SALARY\n-----------------------------\n1 Geeks 10000\n4 Finch 10000\n2 RR 6000\n3 Dhoni 16000\n5 Karthik 7000\n6 Watson 10000" }, { "code": null, "e": 764, "s": 638, "text": "Now, suppose we want the first three rows to be Ordered by Salary in descending order, then the below query must be executed:" }, { "code": null, "e": 1023, "s": 764, "text": "\nQuery:\nSELECT * from myTable \norder by salary desc \nfetch first 3 rows only;\n\nOutput: \nWe got only first 3 rows order by Salary in Descending Order\n\nID NAME SALARY\n--------------------------\n3 Dhoni 16000\n1 Geeks 10000\n4 Finch 10000\n" }, { "code": null, "e": 1403, "s": 1023, "text": "Note: In the above result we got first 3 rows, ordered by Salary in Descending Order, but we have one more row with same salary i.e, the row with name Watson and Salary 10000, but it didn’t came up, because we restricted our output to first three rows only. But this is not optimal, because most of the time in live applications we will be required to display the tied rows also." }, { "code": null, "e": 1672, "s": 1403, "text": "Real Life Example – Suppose we have 10 Racers running, and we have only 3 prizes i.e, first, second, third, but suppose, Racers 3 and 4 finished the race together in same time, so in this case we have a tie between 3 and 4 and that’s why both are holder of Position 3." }, { "code": null, "e": 1682, "s": 1672, "text": "With Ties" }, { "code": null, "e": 1831, "s": 1682, "text": "So, to overcome the above problem, Oracle introduces a clause known as With Ties clause. Now, let’s see our previous example using With Ties clause." }, { "code": null, "e": 2173, "s": 1831, "text": "Query:\nSELECT * from myTable \norder by salary desc \nfetch first 3 rows With Ties;\n\nOutput:\nSee we get only first 3 rows order by Salary in Descending Order along with Tied Row also\n\nID NAME SALARY\n--------------------------\n3 Dhoni 16000\n1 Geeks 10000\n6 Watson 10000 // We get Tied Row also\n4 Finch 10000\n" }, { "code": null, "e": 2246, "s": 2173, "text": "Now, see we got the tied row also, which we were not getting previously." }, { "code": null, "e": 2565, "s": 2246, "text": "Note: We get the tied row in our output, only when we use the order by clause in our Select statement. Suppose, if we won’t use order by clause, and still we are using with ties clause, then we won’t get the tied row in our output and the query behaves same as, if we are using ONLY clause instead of With Ties clause." }, { "code": null, "e": 2643, "s": 2565, "text": "Example – Suppose we execute the below query(without using order by clause) :" }, { "code": null, "e": 2891, "s": 2643, "text": "Query:\nSELECT * from myTable \nfetch first 3 rows With Ties;\n\nOutput:\nSee we won't get the tied row because we didn't use order by clause\n\nID NAME SALARY\n--------------------------\n1 Geeks 10000\n4 Finch 10000\n2 RR 6000\n" }, { "code": null, "e": 3105, "s": 2891, "text": "In the above result we won’t get the tied row and we get only first 3 rows. So With Ties is tied with order by clause, i.e, we get the tied row in output if and only if we use With Ties along with Order by clause." }, { "code": null, "e": 3359, "s": 3105, "text": "Note: Please make sure that, you run these queries in Oracle Database 12c, because Fetch clause is the newly added feature in Oracle 12c, also With Ties, runs only in Oracle Database 12c, these queries won’t run in below versions of 12c like 10g or 11g." }, { "code": null, "e": 3449, "s": 3359, "text": "References: About Fetch Clause as well as With Ties Clause, Performing SQL Queries Online" }, { "code": null, "e": 3471, "s": 3449, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 3475, "s": 3471, "text": "SQL" }, { "code": null, "e": 3479, "s": 3475, "text": "SQL" }, { "code": null, "e": 3577, "s": 3479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3588, "s": 3577, "text": "CTE in SQL" }, { "code": null, "e": 3612, "s": 3588, "text": "SQL Interview Questions" }, { "code": null, "e": 3678, "s": 3612, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3723, "s": 3678, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 3747, "s": 3723, "text": "Window functions in SQL" }, { "code": null, "e": 3786, "s": 3747, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 3818, "s": 3786, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 3855, "s": 3818, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 3881, "s": 3855, "text": "SQL Correlated Subqueries" } ]
Java Program to Get CPU Serial Number for Windows Machine
09 Jul, 2021 CPU Serial Number (or Processor Serial Number) is a software-readable unique serial number that Intel has stamped into its Pentium 3 microprocessor. Intel offers this as a feature that can be optionally used to provide certain network management and e-commerce benefits. Basically, it lets a program identify individual PCs. We can get the CPU Serial number of a Windows machine in 2 ways: By running the command on Windows PowerShell.Using FileWriter class in java By running the command on Windows PowerShell. Using FileWriter class in java Way 1: Running PowerShell command It is a similar way to what we say running commands on terminals on Mac. For windows, it’s CMD for which we do have a one-liner pred-defined command below. You simply need to write it as ities or copy the same from here which is given below as follows: Syntax: WMIC BIOS GET SERIALNUMBER This pop-up window will appear letting us revealing the CPU serial number for the windows machine. Way 2: Using FileWriter class Java FileWriter class of java.io package is used to write data in character form to file. This class inherits from OutputStreamWriter class which in turn inherits from the Writer class. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream. FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream. FileWriter creates the output file if it is not present already. Example Java // Java Program to get CPU Serial Number of Windows Machine// using FileWriter class // Importing required classesimport java.io.BufferedReader;import java.io.File;import java.io.FileWriter;import java.io.InputStreamReader; // Main class// WindowsCpuSerialNumberpublic class GFG { // Method 1 // To get CPU serial number private static String getWindowsCPU_SerialNumber() { // Initially declaring and initializing an empty // string String result = ""; // Try block to check for exceptions try { // Creating an object of File class File file = File.createTempFile("realhowto", ".vbs"); // Deleting file while exiting file.deleteOnExit(); // Creating an object of FileWriter class to // write on FileWriter fw = new java.io.FileWriter(file); // Remember the command String vbs1 = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n" + "Set colItems = objWMIService.ExecQuery _ \n" + " (\"Select * from Win32_Processor\") \n" + "For Each objItem in colItems \n" + " Wscript.Echo objItem.ProcessorId \n" + " exit for ' do the first cpu only! \n" + "Next \n"; // Writing on file fw.write(vbs1); // Closing all file connections to // release memory spaces fw.close(); Process p = Runtime.getRuntime().exec( "cscript //NoLogo " + file.getPath()); BufferedReader input = new BufferedReader( new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { result += line; } input.close(); } // Catch block to handle the exceptions catch (Exception E) { // Print the exception along with the message System.err.println("Windows CPU Exp : " + E.getMessage()); } return result.trim(); } // Method 2 // Main driver method public static void main(String[] args) { String cpuSerialNumber = getWindowsCPU_SerialNumber(); // Calling the method1 to retrieve CPU serial number // and printing the same System.out.println( "CPU Serial Number of my Windows Machine: " + cpuSerialNumber); }} Output: Below is the hard-coded output when run on a Windows machine with the help of FileWriter class. Note: In addition to this if these programs are windows specific and should not be run on other operating systems. Approach 1 will not work and for approach 2 that is the above approach been laid via FileWriter class if, on Mac the output is as follows. It is because ‘cscript’ cant be run on the terminal. sooda367 saurabh1990aror Picked 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": "\n09 Jul, 2021" }, { "code": null, "e": 353, "s": 28, "text": "CPU Serial Number (or Processor Serial Number) is a software-readable unique serial number that Intel has stamped into its Pentium 3 microprocessor. Intel offers this as a feature that can be optionally used to provide certain network management and e-commerce benefits. Basically, it lets a program identify individual PCs." }, { "code": null, "e": 418, "s": 353, "text": "We can get the CPU Serial number of a Windows machine in 2 ways:" }, { "code": null, "e": 494, "s": 418, "text": "By running the command on Windows PowerShell.Using FileWriter class in java" }, { "code": null, "e": 540, "s": 494, "text": "By running the command on Windows PowerShell." }, { "code": null, "e": 571, "s": 540, "text": "Using FileWriter class in java" }, { "code": null, "e": 605, "s": 571, "text": "Way 1: Running PowerShell command" }, { "code": null, "e": 858, "s": 605, "text": "It is a similar way to what we say running commands on terminals on Mac. For windows, it’s CMD for which we do have a one-liner pred-defined command below. You simply need to write it as ities or copy the same from here which is given below as follows:" }, { "code": null, "e": 867, "s": 858, "text": "Syntax: " }, { "code": null, "e": 895, "s": 867, "text": "WMIC BIOS GET SERIALNUMBER " }, { "code": null, "e": 995, "s": 895, "text": "This pop-up window will appear letting us revealing the CPU serial number for the windows machine. " }, { "code": null, "e": 1026, "s": 995, "text": "Way 2: Using FileWriter class " }, { "code": null, "e": 1116, "s": 1026, "text": "Java FileWriter class of java.io package is used to write data in character form to file." }, { "code": null, "e": 1212, "s": 1116, "text": "This class inherits from OutputStreamWriter class which in turn inherits from the Writer class." }, { "code": null, "e": 1424, "s": 1212, "text": "The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream." }, { "code": null, "e": 1548, "s": 1424, "text": "FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream." }, { "code": null, "e": 1613, "s": 1548, "text": "FileWriter creates the output file if it is not present already." }, { "code": null, "e": 1621, "s": 1613, "text": "Example" }, { "code": null, "e": 1626, "s": 1621, "text": "Java" }, { "code": "// Java Program to get CPU Serial Number of Windows Machine// using FileWriter class // Importing required classesimport java.io.BufferedReader;import java.io.File;import java.io.FileWriter;import java.io.InputStreamReader; // Main class// WindowsCpuSerialNumberpublic class GFG { // Method 1 // To get CPU serial number private static String getWindowsCPU_SerialNumber() { // Initially declaring and initializing an empty // string String result = \"\"; // Try block to check for exceptions try { // Creating an object of File class File file = File.createTempFile(\"realhowto\", \".vbs\"); // Deleting file while exiting file.deleteOnExit(); // Creating an object of FileWriter class to // write on FileWriter fw = new java.io.FileWriter(file); // Remember the command String vbs1 = \"Set objWMIService = GetObject(\\\"winmgmts:\\\\\\\\.\\\\root\\\\cimv2\\\")\\n\" + \"Set colItems = objWMIService.ExecQuery _ \\n\" + \" (\\\"Select * from Win32_Processor\\\") \\n\" + \"For Each objItem in colItems \\n\" + \" Wscript.Echo objItem.ProcessorId \\n\" + \" exit for ' do the first cpu only! \\n\" + \"Next \\n\"; // Writing on file fw.write(vbs1); // Closing all file connections to // release memory spaces fw.close(); Process p = Runtime.getRuntime().exec( \"cscript //NoLogo \" + file.getPath()); BufferedReader input = new BufferedReader( new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { result += line; } input.close(); } // Catch block to handle the exceptions catch (Exception E) { // Print the exception along with the message System.err.println(\"Windows CPU Exp : \" + E.getMessage()); } return result.trim(); } // Method 2 // Main driver method public static void main(String[] args) { String cpuSerialNumber = getWindowsCPU_SerialNumber(); // Calling the method1 to retrieve CPU serial number // and printing the same System.out.println( \"CPU Serial Number of my Windows Machine: \" + cpuSerialNumber); }}", "e": 4187, "s": 1626, "text": null }, { "code": null, "e": 4195, "s": 4187, "text": "Output:" }, { "code": null, "e": 4291, "s": 4195, "text": "Below is the hard-coded output when run on a Windows machine with the help of FileWriter class." }, { "code": null, "e": 4598, "s": 4291, "text": "Note: In addition to this if these programs are windows specific and should not be run on other operating systems. Approach 1 will not work and for approach 2 that is the above approach been laid via FileWriter class if, on Mac the output is as follows. It is because ‘cscript’ cant be run on the terminal." }, { "code": null, "e": 4607, "s": 4598, "text": "sooda367" }, { "code": null, "e": 4623, "s": 4607, "text": "saurabh1990aror" }, { "code": null, "e": 4630, "s": 4623, "text": "Picked" }, { "code": null, "e": 4635, "s": 4630, "text": "Java" }, { "code": null, "e": 4649, "s": 4635, "text": "Java Programs" }, { "code": null, "e": 4654, "s": 4649, "text": "Java" }, { "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": 4767, "s": 4752, "text": "Stream In Java" }, { "code": null, "e": 4788, "s": 4767, "text": "Introduction to Java" }, { "code": null, "e": 4809, "s": 4788, "text": "Constructors in Java" }, { "code": null, "e": 4828, "s": 4809, "text": "Exceptions in Java" }, { "code": null, "e": 4845, "s": 4828, "text": "Generics in Java" }, { "code": null, "e": 4871, "s": 4845, "text": "Java Programming Examples" }, { "code": null, "e": 4905, "s": 4871, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4952, "s": 4905, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4990, "s": 4952, "text": "Factory method design pattern in Java" } ]
jQuery | chaining() - GeeksforGeeks
27 Apr, 2020 jQuery is a very powerful framework of JavaScript. With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element.We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short. This way, browsers do not have to find the same element(s) more than once. Advantage:While using method chaining in jQuery, it ensures that there is no need to use the same selector more than once. Over-using a selector can seriously slow down your code, as every time you call on a selector you are forcing the browser to go looking for it. By combining or “chaining” multiple methods, you can seriously cut down on the number of times you make your browser look for the same elements without having to set any variables. Implementation of chaining() using JavaScript and jQuery for better understanding:Code #1: Using Slide up and slide down method functions for chaining- <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <p id="para">Chaining method in jQuery</p> <button>Click me</button> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { //assigning the color blue $("#para").css("color", "blue") //using slide up method .slideUp(2000) //using slide down method .slideDown(2000). slideUp(2000). slideDown(4000); }); }); </script></body> </html> Output: Code #2: Using animate function in jQuery for chaining effect- <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> </head> <body> <p id="para">Chaining method in jQuery</p> <button>Click me</button> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("#para").css("color", "blue").animate({ width: "100%" }) //it adds animation to the program by styling it .animate({ fontSize: "46px" }) .animate({ borderWidth: 30 }); }); }); </script></body> </html> Output: AnweshanTheProgrammer jQuery-Basics JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26264, "s": 26236, "text": "\n27 Apr, 2020" }, { "code": null, "e": 26649, "s": 26264, "text": "jQuery is a very powerful framework of JavaScript. With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element.We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short. This way, browsers do not have to find the same element(s) more than once." }, { "code": null, "e": 27097, "s": 26649, "text": "Advantage:While using method chaining in jQuery, it ensures that there is no need to use the same selector more than once. Over-using a selector can seriously slow down your code, as every time you call on a selector you are forcing the browser to go looking for it. By combining or “chaining” multiple methods, you can seriously cut down on the number of times you make your browser look for the same elements without having to set any variables." }, { "code": null, "e": 27249, "s": 27097, "text": "Implementation of chaining() using JavaScript and jQuery for better understanding:Code #1: Using Slide up and slide down method functions for chaining-" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <p id=\"para\">Chaining method in jQuery</p> <button>Click me</button> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { //assigning the color blue $(\"#para\").css(\"color\", \"blue\") //using slide up method .slideUp(2000) //using slide down method .slideDown(2000). slideUp(2000). slideDown(4000); }); }); </script></body> </html>", "e": 27963, "s": 27249, "text": null }, { "code": null, "e": 27971, "s": 27963, "text": "Output:" }, { "code": null, "e": 28034, "s": 27971, "text": "Code #2: Using animate function in jQuery for chaining effect-" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> </head> <body> <p id=\"para\">Chaining method in jQuery</p> <button>Click me</button> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { $(\"#para\").css(\"color\", \"blue\").animate({ width: \"100%\" }) //it adds animation to the program by styling it .animate({ fontSize: \"46px\" }) .animate({ borderWidth: 30 }); }); }); </script></body> </html>", "e": 28713, "s": 28034, "text": null }, { "code": null, "e": 28721, "s": 28713, "text": "Output:" }, { "code": null, "e": 28743, "s": 28721, "text": "AnweshanTheProgrammer" }, { "code": null, "e": 28757, "s": 28743, "text": "jQuery-Basics" }, { "code": null, "e": 28768, "s": 28757, "text": "JavaScript" }, { "code": null, "e": 28775, "s": 28768, "text": "JQuery" }, { "code": null, "e": 28873, "s": 28775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28913, "s": 28873, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28958, "s": 28913, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29019, "s": 28958, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29091, "s": 29019, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29143, "s": 29091, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29189, "s": 29143, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 29218, "s": 29189, "text": "Form validation using jQuery" }, { "code": null, "e": 29281, "s": 29218, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 29358, "s": 29281, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
How to get emails using PHP and IMAP ? - GeeksforGeeks
15 Oct, 2020 Reading emails from the Gmail account using PHP will be an enriching task for web developers for its simplicity of code through IMAP (Internet Message Access Protocol). Sometimes there can be a requirement in web projects or from a client that needs the complete management of inbox emails or access to email contents from his Gmail account. This feature can also be useful in email marketing or email newsletters that will be sent automatically on a particular schedule. So while researching Gmail account access, one should try listing emails from the Gmail account using PHP and its IMAP functions extension. IMAP is an internet standard protocol used by clients to get emails from a mail server over a TCP/IP connection with SSL security. The IMAP extension available in PHP libraries provides efficient processing of its email structure and access to email messages via communicating with the email servers. We use PHP code to connect to the Gmail server and use standard IMAP functions to open up the Gmail account and access or fetch emails based on certain criteria. Basic requirements: The following are needed for the development of the functionality. PHP5 or latest PHP version.Enable the IMAP Extension in PHP installation.In Gmail account settings, IMAP should be enabled. PHP5 or latest PHP version. Enable the IMAP Extension in PHP installation. In Gmail account settings, IMAP should be enabled. Steps to Enable IMAP in XAMPP: Go to php.ini configuration fileSearch for “;extension=php_imap.dll”Remove the beginning of semicolon and it should be “extension=php_imap.dll”Also edit max_execution_time = 4000 Go to php.ini configuration file Search for “;extension=php_imap.dll” Remove the beginning of semicolon and it should be “extension=php_imap.dll” Also edit max_execution_time = 4000 Steps to Enable IMAP in Gmail Account: Open Gmail.Click Settings.Select the Forwarding and POP/IMAP blue tab.Select “IMAP Access:” section and Enable IMAP radio button.Click Save Changes.Don’t forget to turn on access for less secure apps for Gmail account. Open Gmail. Click Settings. Select the Forwarding and POP/IMAP blue tab. Select “IMAP Access:” section and Enable IMAP radio button. Click Save Changes. Don’t forget to turn on access for less secure apps for Gmail account. Note: For normal applications, an IMAP server listens on 143 port number. PHP Code: The following is the HTML and PHP code to list emails from Gmail account. To connect to Gmail, the developer needs the individual’s “username” and “password” to be set in the code. Once connected, we search for all emails or emails based on certain criteria by using the imap_search() function. The emails are sorted in a reverse manner so that the latest mails are available on the top using the PHP rsort() function. This PHP function sorts an array in descending order. For every email returned, the subject, from, partial content, and date-time messages are captured. The imap_fetchbody() function fetches a particular section of the email body. So to get the plain text part of the email, we can use “1.1” option as the third parameter. HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="style.css"> <script> function getEmails() { document.getElementById('dataDivID') .style.display = "block"; } </script></head> <body> <h2>List Emails from Gmail using PHP and IMAP</h2> <div id="btnContainer"> <button class="btn active" onclick="getEmails()"> <i class="fa fa-bars"></i>Click to get gmail mails </button> </div> <br> <div id="dataDivID" class="form-container" style="display:none;"> <?php /* gmail connection,with port number 993 */ $host = '{imap.gmail.com:993/imap/ssl/ novalidate-cert/norsh}INBOX'; /* Your gmail credentials */ $user = 'YOUR-EMAIL@GMAIL.COM'; $password = 'YOUR-PASSWORD'; /* Establish a IMAP connection */ $conn = imap_open($host, $user, $password) or die('unable to connect Gmail: ' . imap_last_error()); /* Search emails from gmail inbox*/ $mails = imap_search($conn, 'SUBJECT "Comment"'); /* loop through each email id mails are available. */ if ($mails) { /* Mail output variable starts*/ $mailOutput = ''; $mailOutput.= '<table><tr><th>Subject </th><th> From </th> <th> Date Time </th> <th> Content </th></tr>'; /* rsort is used to display the latest emails on top */ rsort($mails); /* For each email */ foreach ($mails as $email_number) { /* Retrieve specific email information*/ $headers = imap_fetch_overview($conn, $email_number, 0); /* Returns a particular section of the body*/ $message = imap_fetchbody($conn, $email_number, '1'); $subMessage = substr($message, 0, 150); $finalMessage = trim(quoted_printable_decode($subMessage)); $mailOutput.= '<div class="row">'; /* Gmail MAILS header information */ $mailOutput.= '<td><span class="columnClass">' . $headers[0]->subject . '</span></td> '; $mailOutput.= '<td><span class="columnClass">' . $headers[0]->from . '</span></td>'; $mailOutput.= '<td><span class="columnClass">' . $headers[0]->date . '</span></td>'; $mailOutput.= '</div>'; /* Mail body is returned */ $mailOutput.= '<td><span class="column">' . $finalMessage . '</span></td></tr></div>'; }// End foreach $mailOutput.= '</table>'; echo $mailOutput; }//endif /* imap connection is closed */ imap_close($conn); ?> </div></body> </html> CSS code: The following is the code for the file “style.css” used in the above code. CSS body { font-family: Arial; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } tr:nth-child(even) { background-color: #dddddd; } td, th { padding: 8px; width:100px; border: 1px solid #dddddd; text-align: left; } .form-container { padding: 20px; background: #F0F0F0; border: #e0dfdf 1px solid; border-radius: 2px; } * { box-sizing: border-box; } .columnClass { float: left; padding: 10px; } .row:after { content: ""; display: table; clear: both; } .btn { background: #333; border: #1d1d1d 1px solid; color: #f0f0f0; font-size: 0.9em; width: 200px; border-radius: 2px; background-color: #f1f1f1; cursor: pointer; } .btn:hover { background-color: #ddd; } .btn.active { background-color: #666; color: white; } Output: The following is the output shown for emails retrieved with subject “Comment”. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc PHP-Misc CSS HTML PHP Web Technologies HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25915, "s": 25887, "text": "\n15 Oct, 2020" }, { "code": null, "e": 26527, "s": 25915, "text": "Reading emails from the Gmail account using PHP will be an enriching task for web developers for its simplicity of code through IMAP (Internet Message Access Protocol). Sometimes there can be a requirement in web projects or from a client that needs the complete management of inbox emails or access to email contents from his Gmail account. This feature can also be useful in email marketing or email newsletters that will be sent automatically on a particular schedule. So while researching Gmail account access, one should try listing emails from the Gmail account using PHP and its IMAP functions extension." }, { "code": null, "e": 26990, "s": 26527, "text": "IMAP is an internet standard protocol used by clients to get emails from a mail server over a TCP/IP connection with SSL security. The IMAP extension available in PHP libraries provides efficient processing of its email structure and access to email messages via communicating with the email servers. We use PHP code to connect to the Gmail server and use standard IMAP functions to open up the Gmail account and access or fetch emails based on certain criteria." }, { "code": null, "e": 27077, "s": 26990, "text": "Basic requirements: The following are needed for the development of the functionality." }, { "code": null, "e": 27201, "s": 27077, "text": "PHP5 or latest PHP version.Enable the IMAP Extension in PHP installation.In Gmail account settings, IMAP should be enabled." }, { "code": null, "e": 27229, "s": 27201, "text": "PHP5 or latest PHP version." }, { "code": null, "e": 27276, "s": 27229, "text": "Enable the IMAP Extension in PHP installation." }, { "code": null, "e": 27327, "s": 27276, "text": "In Gmail account settings, IMAP should be enabled." }, { "code": null, "e": 27358, "s": 27327, "text": "Steps to Enable IMAP in XAMPP:" }, { "code": null, "e": 27537, "s": 27358, "text": "Go to php.ini configuration fileSearch for “;extension=php_imap.dll”Remove the beginning of semicolon and it should be “extension=php_imap.dll”Also edit max_execution_time = 4000" }, { "code": null, "e": 27570, "s": 27537, "text": "Go to php.ini configuration file" }, { "code": null, "e": 27607, "s": 27570, "text": "Search for “;extension=php_imap.dll”" }, { "code": null, "e": 27683, "s": 27607, "text": "Remove the beginning of semicolon and it should be “extension=php_imap.dll”" }, { "code": null, "e": 27719, "s": 27683, "text": "Also edit max_execution_time = 4000" }, { "code": null, "e": 27758, "s": 27719, "text": "Steps to Enable IMAP in Gmail Account:" }, { "code": null, "e": 27977, "s": 27758, "text": "Open Gmail.Click Settings.Select the Forwarding and POP/IMAP blue tab.Select “IMAP Access:” section and Enable IMAP radio button.Click Save Changes.Don’t forget to turn on access for less secure apps for Gmail account." }, { "code": null, "e": 27989, "s": 27977, "text": "Open Gmail." }, { "code": null, "e": 28005, "s": 27989, "text": "Click Settings." }, { "code": null, "e": 28050, "s": 28005, "text": "Select the Forwarding and POP/IMAP blue tab." }, { "code": null, "e": 28110, "s": 28050, "text": "Select “IMAP Access:” section and Enable IMAP radio button." }, { "code": null, "e": 28130, "s": 28110, "text": "Click Save Changes." }, { "code": null, "e": 28201, "s": 28130, "text": "Don’t forget to turn on access for less secure apps for Gmail account." }, { "code": null, "e": 28275, "s": 28201, "text": "Note: For normal applications, an IMAP server listens on 143 port number." }, { "code": null, "e": 29029, "s": 28275, "text": "PHP Code: The following is the HTML and PHP code to list emails from Gmail account. To connect to Gmail, the developer needs the individual’s “username” and “password” to be set in the code. Once connected, we search for all emails or emails based on certain criteria by using the imap_search() function. The emails are sorted in a reverse manner so that the latest mails are available on the top using the PHP rsort() function. This PHP function sorts an array in descending order. For every email returned, the subject, from, partial content, and date-time messages are captured. The imap_fetchbody() function fetches a particular section of the email body. So to get the plain text part of the email, we can use “1.1” option as the third parameter. " }, { "code": null, "e": 29034, "s": 29029, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <link rel=\"stylesheet\" href=\"style.css\"> <script> function getEmails() { document.getElementById('dataDivID') .style.display = \"block\"; } </script></head> <body> <h2>List Emails from Gmail using PHP and IMAP</h2> <div id=\"btnContainer\"> <button class=\"btn active\" onclick=\"getEmails()\"> <i class=\"fa fa-bars\"></i>Click to get gmail mails </button> </div> <br> <div id=\"dataDivID\" class=\"form-container\" style=\"display:none;\"> <?php /* gmail connection,with port number 993 */ $host = '{imap.gmail.com:993/imap/ssl/ novalidate-cert/norsh}INBOX'; /* Your gmail credentials */ $user = 'YOUR-EMAIL@GMAIL.COM'; $password = 'YOUR-PASSWORD'; /* Establish a IMAP connection */ $conn = imap_open($host, $user, $password) or die('unable to connect Gmail: ' . imap_last_error()); /* Search emails from gmail inbox*/ $mails = imap_search($conn, 'SUBJECT \"Comment\"'); /* loop through each email id mails are available. */ if ($mails) { /* Mail output variable starts*/ $mailOutput = ''; $mailOutput.= '<table><tr><th>Subject </th><th> From </th> <th> Date Time </th> <th> Content </th></tr>'; /* rsort is used to display the latest emails on top */ rsort($mails); /* For each email */ foreach ($mails as $email_number) { /* Retrieve specific email information*/ $headers = imap_fetch_overview($conn, $email_number, 0); /* Returns a particular section of the body*/ $message = imap_fetchbody($conn, $email_number, '1'); $subMessage = substr($message, 0, 150); $finalMessage = trim(quoted_printable_decode($subMessage)); $mailOutput.= '<div class=\"row\">'; /* Gmail MAILS header information */ $mailOutput.= '<td><span class=\"columnClass\">' . $headers[0]->subject . '</span></td> '; $mailOutput.= '<td><span class=\"columnClass\">' . $headers[0]->from . '</span></td>'; $mailOutput.= '<td><span class=\"columnClass\">' . $headers[0]->date . '</span></td>'; $mailOutput.= '</div>'; /* Mail body is returned */ $mailOutput.= '<td><span class=\"column\">' . $finalMessage . '</span></td></tr></div>'; }// End foreach $mailOutput.= '</table>'; echo $mailOutput; }//endif /* imap connection is closed */ imap_close($conn); ?> </div></body> </html>", "e": 32218, "s": 29034, "text": null }, { "code": null, "e": 32303, "s": 32218, "text": "CSS code: The following is the code for the file “style.css” used in the above code." }, { "code": null, "e": 32307, "s": 32303, "text": "CSS" }, { "code": "body { font-family: Arial; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } tr:nth-child(even) { background-color: #dddddd; } td, th { padding: 8px; width:100px; border: 1px solid #dddddd; text-align: left; } .form-container { padding: 20px; background: #F0F0F0; border: #e0dfdf 1px solid; border-radius: 2px; } * { box-sizing: border-box; } .columnClass { float: left; padding: 10px; } .row:after { content: \"\"; display: table; clear: both; } .btn { background: #333; border: #1d1d1d 1px solid; color: #f0f0f0; font-size: 0.9em; width: 200px; border-radius: 2px; background-color: #f1f1f1; cursor: pointer; } .btn:hover { background-color: #ddd; } .btn.active { background-color: #666; color: white; }", "e": 33202, "s": 32307, "text": null }, { "code": null, "e": 33289, "s": 33202, "text": "Output: The following is the output shown for emails retrieved with subject “Comment”." }, { "code": null, "e": 33426, "s": 33289, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33435, "s": 33426, "text": "CSS-Misc" }, { "code": null, "e": 33445, "s": 33435, "text": "HTML-Misc" }, { "code": null, "e": 33454, "s": 33445, "text": "PHP-Misc" }, { "code": null, "e": 33458, "s": 33454, "text": "CSS" }, { "code": null, "e": 33463, "s": 33458, "text": "HTML" }, { "code": null, "e": 33467, "s": 33463, "text": "PHP" }, { "code": null, "e": 33484, "s": 33467, "text": "Web Technologies" }, { "code": null, "e": 33489, "s": 33484, "text": "HTML" }, { "code": null, "e": 33493, "s": 33489, "text": "PHP" }, { "code": null, "e": 33591, "s": 33493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33646, "s": 33591, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 33683, "s": 33646, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 33747, "s": 33683, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 33784, "s": 33747, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33845, "s": 33784, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 33905, "s": 33845, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33958, "s": 33905, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34019, "s": 33958, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 34069, "s": 34019, "text": "How to Insert Form Data into Database using PHP ?" } ]
C# | Math.Floor() Method - GeeksforGeeks
31 Jan, 2019 In C#, Math.Floor() is a Math class method. This method is used to find the largest integer, which is less than or equal to the passed argument. The floor method operates both functionalities in decimal and double. This method can be overload by passing different arguments to it. Math.Floor(Decimal) Method Math.Floor(Double) Method This method is used to returns the largest integer less than or equal to the specified decimal number in the argument list. Syntax: public static decimal Floor(decimal d) Parameter: Decimal d: It is the decimal number of type System.Decimal. Return Type: This function return the largest integer which will be less than or equal to d. The type of this method is System.Decimal. Examples: Input : 12.9 Output : 12 Input : -12.9 Output : -13 Program : To demonstrate the Math.Floor(Decimal) method. // C# program to illustrate the// Math.Floor(Decimal) functionusing System; public class GFG { // Main method static public void Main() { // Different numbers list to find // its floor values Console.WriteLine(Math.Floor(0.2018)); Console.WriteLine(Math.Floor(123.123)); Console.WriteLine(Math.Floor(-0.2)); Console.WriteLine(Math.Floor(0.0)); Console.WriteLine(Math.Floor(34.67M)); }} Output: 0 123 -1 0 34 This method is used to returns the largest integer less than or equal to the specified double-precision floating-point number in the argument list. Syntax: public static double Floor(double d) Parameter: Double d: It is the double number of type System.Double. Return Type: This method returns the largest integer less than or equal to d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The type of this method is System.Double. Examples: Input : 987654321.012 Output : 987654321 Input : -99999 Output : -100000 Program : To demonstrate the Math.Floor(Double) method. // C# program to illustrate the// Math.Floor(Double) functionusing System;class GFG { // Main method static void Main() { // Two values. double n1 = 0.2018; double n2 = 123.123; double n3 = -2.2; double n4 = -123.123; // Take floors of these values. double floor1 = Math.Floor(n1); double floor2 = Math.Floor(n2); double floor3 = Math.Floor(n3); double floor4 = Math.Floor(n4); // Print First values and floor Console.WriteLine("value n1 = " + n1); Console.WriteLine("Floor1 values is = " + floor1); // Print 2nd values and floor Console.WriteLine("value n2 = " + n2); Console.WriteLine("Floor2 values is = " + floor2); // Print 3rd values and floor Console.WriteLine("value n3 = " + n3); Console.WriteLine("Floor3 values is = " + floor3); // Print 4th values and floor Console.WriteLine("value n4 = " + n4); Console.WriteLine("Floor4 values is = " + floor4); }} Output: value n1 = 0.2018 Floor1 values is = 0 value n2 = 123.123 Floor2 values is = 123 value n3 = -2.2 Floor3 values is = -3 value n4 = -123.123 Floor4 values is = -124 Reference: https://msdn.microsoft.com/en-us/library/system.math.floor(v=vs.110).aspx CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 C# | Constructors
[ { "code": null, "e": 25777, "s": 25749, "text": "\n31 Jan, 2019" }, { "code": null, "e": 26058, "s": 25777, "text": "In C#, Math.Floor() is a Math class method. This method is used to find the largest integer, which is less than or equal to the passed argument. The floor method operates both functionalities in decimal and double. This method can be overload by passing different arguments to it." }, { "code": null, "e": 26085, "s": 26058, "text": "Math.Floor(Decimal) Method" }, { "code": null, "e": 26111, "s": 26085, "text": "Math.Floor(Double) Method" }, { "code": null, "e": 26235, "s": 26111, "text": "This method is used to returns the largest integer less than or equal to the specified decimal number in the argument list." }, { "code": null, "e": 26243, "s": 26235, "text": "Syntax:" }, { "code": null, "e": 26283, "s": 26243, "text": "public static decimal Floor(decimal d)\n" }, { "code": null, "e": 26294, "s": 26283, "text": "Parameter:" }, { "code": null, "e": 26354, "s": 26294, "text": "Decimal d: It is the decimal number of type System.Decimal." }, { "code": null, "e": 26490, "s": 26354, "text": "Return Type: This function return the largest integer which will be less than or equal to d. The type of this method is System.Decimal." }, { "code": null, "e": 26500, "s": 26490, "text": "Examples:" }, { "code": null, "e": 26556, "s": 26500, "text": "Input : 12.9\nOutput : 12\n\nInput : -12.9\nOutput : -13\n" }, { "code": null, "e": 26613, "s": 26556, "text": "Program : To demonstrate the Math.Floor(Decimal) method." }, { "code": "// C# program to illustrate the// Math.Floor(Decimal) functionusing System; public class GFG { // Main method static public void Main() { // Different numbers list to find // its floor values Console.WriteLine(Math.Floor(0.2018)); Console.WriteLine(Math.Floor(123.123)); Console.WriteLine(Math.Floor(-0.2)); Console.WriteLine(Math.Floor(0.0)); Console.WriteLine(Math.Floor(34.67M)); }}", "e": 27065, "s": 26613, "text": null }, { "code": null, "e": 27073, "s": 27065, "text": "Output:" }, { "code": null, "e": 27088, "s": 27073, "text": "0\n123\n-1\n0\n34\n" }, { "code": null, "e": 27236, "s": 27088, "text": "This method is used to returns the largest integer less than or equal to the specified double-precision floating-point number in the argument list." }, { "code": null, "e": 27244, "s": 27236, "text": "Syntax:" }, { "code": null, "e": 27282, "s": 27244, "text": "public static double Floor(double d)\n" }, { "code": null, "e": 27293, "s": 27282, "text": "Parameter:" }, { "code": null, "e": 27350, "s": 27293, "text": "Double d: It is the double number of type System.Double." }, { "code": null, "e": 27555, "s": 27350, "text": "Return Type: This method returns the largest integer less than or equal to d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The type of this method is System.Double." }, { "code": null, "e": 27565, "s": 27555, "text": "Examples:" }, { "code": null, "e": 27643, "s": 27565, "text": "Input : 987654321.012 \nOutput : 987654321\n\nInput : -99999\nOutput : -100000\n" }, { "code": null, "e": 27699, "s": 27643, "text": "Program : To demonstrate the Math.Floor(Double) method." }, { "code": "// C# program to illustrate the// Math.Floor(Double) functionusing System;class GFG { // Main method static void Main() { // Two values. double n1 = 0.2018; double n2 = 123.123; double n3 = -2.2; double n4 = -123.123; // Take floors of these values. double floor1 = Math.Floor(n1); double floor2 = Math.Floor(n2); double floor3 = Math.Floor(n3); double floor4 = Math.Floor(n4); // Print First values and floor Console.WriteLine(\"value n1 = \" + n1); Console.WriteLine(\"Floor1 values is = \" + floor1); // Print 2nd values and floor Console.WriteLine(\"value n2 = \" + n2); Console.WriteLine(\"Floor2 values is = \" + floor2); // Print 3rd values and floor Console.WriteLine(\"value n3 = \" + n3); Console.WriteLine(\"Floor3 values is = \" + floor3); // Print 4th values and floor Console.WriteLine(\"value n4 = \" + n4); Console.WriteLine(\"Floor4 values is = \" + floor4); }}", "e": 28751, "s": 27699, "text": null }, { "code": null, "e": 28759, "s": 28751, "text": "Output:" }, { "code": null, "e": 28923, "s": 28759, "text": "value n1 = 0.2018\nFloor1 values is = 0\nvalue n2 = 123.123\nFloor2 values is = 123\nvalue n3 = -2.2\nFloor3 values is = -3\nvalue n4 = -123.123\nFloor4 values is = -124\n" }, { "code": null, "e": 29008, "s": 28923, "text": "Reference: https://msdn.microsoft.com/en-us/library/system.math.floor(v=vs.110).aspx" }, { "code": null, "e": 29020, "s": 29008, "text": "CSharp-Math" }, { "code": null, "e": 29034, "s": 29020, "text": "CSharp-method" }, { "code": null, "e": 29037, "s": 29034, "text": "C#" }, { "code": null, "e": 29135, "s": 29037, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29163, "s": 29135, "text": "C# Dictionary with examples" }, { "code": null, "e": 29178, "s": 29163, "text": "C# | Delegates" }, { "code": null, "e": 29201, "s": 29178, "text": "C# | Method Overriding" }, { "code": null, "e": 29223, "s": 29201, "text": "C# | Abstract Classes" }, { "code": null, "e": 29269, "s": 29223, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29292, "s": 29269, "text": "Extension Method in C#" }, { "code": null, "e": 29314, "s": 29292, "text": "C# | Class and Object" }, { "code": null, "e": 29336, "s": 29314, "text": "C# | Replace() Method" }, { "code": null, "e": 29376, "s": 29336, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Extract column from list in R - GeeksforGeeks
26 Mar, 2021 In this article, we are going to create a list of elements and access those columns in R. We are first creating a list with matrix and vectors and access those columns using R. Approach Create a list Syntax: list_name=list(var1, var2, varn..) Assign names to list elements as columns names. We can give names using names() function Syntax: names(list_name)=c(var1, var2, varn) Access those columns and elements. Method 1: Using indices In this method, we simply have to pass the index of the column with the name of the list to extract that specific column. Example: R # Create a list that can hold a vector, and a matrixlist1 <- list(c("sravan", "sudheer", "vani", "radha"), matrix(c(98, 87, 78, 87))) # assign names to the elements in the list.names(list1) <- c("names", "percentage") # access the column 1print(list1[1]) # access the column 2print(list1[2]) Output: Method2: Using $ operator. In this method, the name of the column to be retrieved has to be passed with its name and name of the list separated by the dollar sign($). Syntax: list_name$column_name Example: R # Create a list that can hold a vector, and a matrixlist1 <- list(c("sravan", "sudheer", "vani", "radha"), matrix(c(98, 87, 78, 87))) # assign names to the elements in the list.names(list1) <- c("names", "percentage") # access the column 1print(list1$names) # access the column 2print(list1$percentage) Output: A list can contain a matrix, vector, and a list as arguments to a list but to access them the method remains the same and it has been discussed in the code below. Example: R # Create a list that can hold a vector, and a matrix and a listlist1 <- list(c("sravan", "sudheer", "vani", "radha"), matrix(c(98, 87, 78, 87)), list('vignan', 'vit', 'vvit', 'rvrjc')) # assign names to the elements in the list.names(list1) <- c("names", "percentage", "college") print("Method 1") # access the column 1print(list1[1]) # access the column 2print(list1[2]) # access the column 3print(list1[3]) print("Method 2") # access the column 1print(list1$names) # access the column 2print(list1$percentage) # access the column 3print(list1$college) Output: It is possible to access nested elements using [[]] operator. Syntax: list_name[[value]][[value]]... Example: R # Create a list that can hold a vector, and a # matrix and a listlist1 <- list(c("sravan", "sudheer", "vani", "radha"), matrix(c(98, 87, 78, 87)), list('vignan', 'vit', 'vvit', 'rvrjc')) # access 2nd column first elementprint(list1[[2]][[1]]) # access 2nd column print(list1[[2]]) # access 3rd column third elementprint(list1[[3]][[3]]) Output: Picked R-List 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n26 Mar, 2021" }, { "code": null, "e": 26664, "s": 26487, "text": "In this article, we are going to create a list of elements and access those columns in R. We are first creating a list with matrix and vectors and access those columns using R." }, { "code": null, "e": 26673, "s": 26664, "text": "Approach" }, { "code": null, "e": 26687, "s": 26673, "text": "Create a list" }, { "code": null, "e": 26695, "s": 26687, "text": "Syntax:" }, { "code": null, "e": 26730, "s": 26695, "text": "list_name=list(var1, var2, varn..)" }, { "code": null, "e": 26819, "s": 26730, "text": "Assign names to list elements as columns names. We can give names using names() function" }, { "code": null, "e": 26827, "s": 26819, "text": "Syntax:" }, { "code": null, "e": 26864, "s": 26827, "text": "names(list_name)=c(var1, var2, varn)" }, { "code": null, "e": 26899, "s": 26864, "text": "Access those columns and elements." }, { "code": null, "e": 26923, "s": 26899, "text": "Method 1: Using indices" }, { "code": null, "e": 27045, "s": 26923, "text": "In this method, we simply have to pass the index of the column with the name of the list to extract that specific column." }, { "code": null, "e": 27054, "s": 27045, "text": "Example:" }, { "code": null, "e": 27056, "s": 27054, "text": "R" }, { "code": "# Create a list that can hold a vector, and a matrixlist1 <- list(c(\"sravan\", \"sudheer\", \"vani\", \"radha\"), matrix(c(98, 87, 78, 87))) # assign names to the elements in the list.names(list1) <- c(\"names\", \"percentage\") # access the column 1print(list1[1]) # access the column 2print(list1[2])", "e": 27365, "s": 27056, "text": null }, { "code": null, "e": 27373, "s": 27365, "text": "Output:" }, { "code": null, "e": 27400, "s": 27373, "text": "Method2: Using $ operator." }, { "code": null, "e": 27540, "s": 27400, "text": "In this method, the name of the column to be retrieved has to be passed with its name and name of the list separated by the dollar sign($)." }, { "code": null, "e": 27548, "s": 27540, "text": "Syntax:" }, { "code": null, "e": 27570, "s": 27548, "text": "list_name$column_name" }, { "code": null, "e": 27579, "s": 27570, "text": "Example:" }, { "code": null, "e": 27581, "s": 27579, "text": "R" }, { "code": "# Create a list that can hold a vector, and a matrixlist1 <- list(c(\"sravan\", \"sudheer\", \"vani\", \"radha\"), matrix(c(98, 87, 78, 87))) # assign names to the elements in the list.names(list1) <- c(\"names\", \"percentage\") # access the column 1print(list1$names) # access the column 2print(list1$percentage)", "e": 27901, "s": 27581, "text": null }, { "code": null, "e": 27909, "s": 27901, "text": "Output:" }, { "code": null, "e": 28072, "s": 27909, "text": "A list can contain a matrix, vector, and a list as arguments to a list but to access them the method remains the same and it has been discussed in the code below." }, { "code": null, "e": 28082, "s": 28072, "text": "Example: " }, { "code": null, "e": 28084, "s": 28082, "text": "R" }, { "code": "# Create a list that can hold a vector, and a matrix and a listlist1 <- list(c(\"sravan\", \"sudheer\", \"vani\", \"radha\"), matrix(c(98, 87, 78, 87)), list('vignan', 'vit', 'vvit', 'rvrjc')) # assign names to the elements in the list.names(list1) <- c(\"names\", \"percentage\", \"college\") print(\"Method 1\") # access the column 1print(list1[1]) # access the column 2print(list1[2]) # access the column 3print(list1[3]) print(\"Method 2\") # access the column 1print(list1$names) # access the column 2print(list1$percentage) # access the column 3print(list1$college)", "e": 28674, "s": 28084, "text": null }, { "code": null, "e": 28682, "s": 28674, "text": "Output:" }, { "code": null, "e": 28744, "s": 28682, "text": "It is possible to access nested elements using [[]] operator." }, { "code": null, "e": 28752, "s": 28744, "text": "Syntax:" }, { "code": null, "e": 28783, "s": 28752, "text": "list_name[[value]][[value]]..." }, { "code": null, "e": 28792, "s": 28783, "text": "Example:" }, { "code": null, "e": 28794, "s": 28792, "text": "R" }, { "code": "# Create a list that can hold a vector, and a # matrix and a listlist1 <- list(c(\"sravan\", \"sudheer\", \"vani\", \"radha\"), matrix(c(98, 87, 78, 87)), list('vignan', 'vit', 'vvit', 'rvrjc')) # access 2nd column first elementprint(list1[[2]][[1]]) # access 2nd column print(list1[[2]]) # access 3rd column third elementprint(list1[[3]][[3]])", "e": 29161, "s": 28794, "text": null }, { "code": null, "e": 29169, "s": 29161, "text": "Output:" }, { "code": null, "e": 29176, "s": 29169, "text": "Picked" }, { "code": null, "e": 29183, "s": 29176, "text": "R-List" }, { "code": null, "e": 29194, "s": 29183, "text": "R Language" }, { "code": null, "e": 29205, "s": 29194, "text": "R Programs" }, { "code": null, "e": 29303, "s": 29205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29355, "s": 29303, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29390, "s": 29355, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29428, "s": 29390, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29486, "s": 29428, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29529, "s": 29486, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29587, "s": 29529, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29630, "s": 29587, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29679, "s": 29630, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29729, "s": 29679, "text": "How to filter R dataframe by multiple conditions?" } ]
Set all odd bits of a number - GeeksforGeeks
03 May, 2021 Given a number, the task is to set all odd bits of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). Position of LSB is considered as 1. Examples : Input : 20 Output : 21 Explanation : Binary representation of 20 is 10100. Setting all odd bits make the number 10101 which is binary representation of 21. Input : 10 Output : 15 Method 1 (Using OR) 1. First generate a number that contains odd position bits. 2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1. Let’s understand this approach with below code. C++ Java Python3 C# PHP Javascript // CPP code Set all odd bits// of a number#include <iostream>using namespace std; // set all odd bitint oddbitsetnumber(int n){ int count = 0; // res for store 010101.. number int res = 0; // generate number form of 010101.....till // temp size for (int temp = n; temp > 0; temp >>= 1) { // if bit is odd, then generate // number and or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res);} // Driver codeint main(){ int n = 10; cout << oddbitsetnumber(n); return 0;} // Java code to Set all odd// bits of a number class GFG{ // set all odd bit static int oddbitsetnumber(int n) { int count = 0; // res for store 010101.. number int res = 0; // generate number form of // 010101.....till temp size for (int temp = n; temp > 0; temp >>= 1) { // if bit is odd, then generate // number and or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res); } // Driver code public static void main(String[] args) { int n = 10; System.out.println(oddbitsetnumber(n)); }} // This code is contributed// by prerna saini ''' Python3 code Set all odd bits of a number''' # set all odd bitdef oddbitsetnumber(n): count = 0 # res for store 010101.. number res = 0 # generate number form of 010101.....till # temp size temp = n while temp > 0: # if bit is odd, then generate # number and or with res if count % 2 == 0: res |= (1 << count) count += 1 temp >>= 1 return (n | res) n = 10print (oddbitsetnumber(n)) #This code is contributed by Shreyanshi Arun. // C# code to Set all odd// bits of a numberusing System; class GFG{ static int oddbitsetnumber(int n) { int count = 0; // res for store 010101.. number int res = 0; // generate number form of // 010101.....till temp size for (int temp = n; temp > 0; temp >>= 1) { // if bit is odd, then // generate number and // or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res); } // Driver Code static public void Main () { int n = 10; Console.WriteLine(oddbitsetnumber(n)); }} // This code is contributed// by prerna ajit <?php// php code Set all odd// bits of a number // set all odd bitfunction oddbitsetnumber($n){ $count = 0; // res for store 010101.. // number $res = 0; // generate number form of // 010101... till temp size for ($temp = $n; $temp > 0; $temp >>= 1) { // if bit is odd, then generate // number and or with res if ($count % 2 == 0) $res |= (1 << $count); $count++; } return ($n | $res);} // Driver code $n = 10; echo oddbitsetnumber($n); // This code is contributed by mits?> <script> // JavaScript Program to Set all odd// bits of a number // set all odd bit function oddbitsetnumber(n) { let count = 0; // res for store 010101.. number let res = 0; // generate number form of // 010101.....till temp size for (let temp = n; temp > 0; temp >>= 1) { // if bit is odd, then generate // number and or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res); } // Driver Code let n = 10; document.write(oddbitsetnumber(n)); // This code is contributed by chinmoy1997pal.</script> Output: 15 Method 2 (A O(1) solution for 32 bit numbers) C++ Java Python3 C# PHP Javascript // Efficient CPP program to set all// odd bits number#include <iostream>using namespace std; // return MSB set numberint getmsb(int n){ // set all bits including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return MSB return (n + 1) >> 1;} // Returns a number of same size (MSB at// same position) as n and all odd bits// set.int getevenbits(int n){ n = getmsb(n); // generate odd bits like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is even then shift by 1 if ((n&1) == 0) n = n >> 1; // return odd set bits number return n; } // set all odd bits hereint setalloddbits(int n){ // take OR with odd set bits number return n | getevenbits(n); } // Driver codeint main(){ int n = 10; cout << setalloddbits(n); return 0;} // Efficient Java program to set// all odd bits numberclass GFG { // return MSB set number static int getmsb(int n) { // set all bits including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return MSB return (n + 1) >> 1; } // Returns a number of same // size (MSB at same position) // as n and all odd bits set. static int getevenbits(int n) { n = getmsb(n); // generate odd bits // like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is even // then shift by 1 if ((n & 1) == 0) n = n >> 1; // return odd set bits number return n; } // set all odd bits here static int setalloddbits(int n) { // take OR with odd // set bits number return n | getevenbits(n); } // Driver code public static void main(String[] args) { int n = 10; System.out.println(setalloddbits(n)); }} // This code is contributed// by prerna saini # Efficient python3 program to # set all odd bits numberimport math # return MSB set numberdef getmsb( n): # set all bits including MSB. n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # return MSB return (n + 1) >> 1 # Returns a number of same# size (MSB at same position)# as n and all odd bits set.def getevenbits(n): n = getmsb(n) # generate odd bits # like 010101.. n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # if bits is even # then shift by 1 if ((n & 1) == 0): n = n >> 1 # return odd set bits number return n # set all odd bits heredef setalloddbits( n): # take OR with odd # set bits number return n | getevenbits(n) # Driver Programn = 10print(setalloddbits(n)) # This code is contributed# by Gitanjali. // Efficient C# program to// set all odd bits numberusing System; class GFG{ // return MSB set number static int getmsb(int n) { // set all bits // including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return MSB return (n + 1) >> 1; } // Returns a number of same // size (MSB at same position) // as n and all odd bits set. static int getevenbits(int n) { n = getmsb(n); // generate odd bits // like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is even // then shift by 1 if ((n & 1) == 0) n = n >> 1; // return odd // set bits number return n; } // set all odd bits here static int setalloddbits(int n) { // take OR with odd // set bits number return n | getevenbits(n); } // Driver Code static public void Main () { int n = 10; Console.WriteLine(setalloddbits(n)); }} // This code is contributed ajit <?php// Efficient php program to// set all odd bits number // return MSB set numberfunction getmsb($n){ // set all bits // including MSB. $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // return MSB return ($n + 1) >> 1;} // Returns a number of// same size (MSB at// same position) as n// and all odd bits setfunction getevenbits($n){ $n = getmsb($n); // generate odd bits // like 010101.. $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // if bits is even // then shift by 1 if (($n&1) == 0) $n = $n >> 1; // return odd set // bits number return $n;} // set all odd bits herefunction setalloddbits($n){ // take OR with odd // set bits number return $n | getevenbits($n);} // Driver code $n = 10; echo setalloddbits($n); // This code is contributed by mits?> <script> // Efficient Javascript program to// set all odd bits number // Return MSB set numberfunction getmsb(n){ // Set all bits // including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Return MSB return (n + 1) >> 1;} // Returns a number of same// size (MSB at same position)// as n and all odd bits set.function getevenbits(n){ n = getmsb(n); // Generate odd bits // like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // If bits is even // then shift by 1 if ((n & 1) == 0) n = n >> 1; // Return odd // set bits number return n;} // Set all odd bits herefunction setalloddbits(n){ // Take OR with odd // set bits number return n | getevenbits(n);} // Driver Codelet n = 10;document.write(setalloddbits(n)); // This code is contributed by decode2207 </script> Output: 15 Mithun Kumar jit_t rdaniellivingston chinmoy1997pal decode2207 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Write an Efficient Method to Check if a Number is Multiple of 3 Swap two nibbles in a byte Highest power of 2 less than or equal to given number Swap bits in a given number Check for Integer Overflow Reverse actual bits of the given number Find one extra character in a string Bit Tricks for Competitive Programming Count total bits in a number
[ { "code": null, "e": 26277, "s": 26249, "text": "\n03 May, 2021" }, { "code": null, "e": 26468, "s": 26277, "text": "Given a number, the task is to set all odd bits of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). Position of LSB is considered as 1." }, { "code": null, "e": 26480, "s": 26468, "text": "Examples : " }, { "code": null, "e": 26660, "s": 26480, "text": "Input : 20\nOutput : 21\nExplanation : Binary representation of 20\nis 10100. Setting all odd\nbits make the number 10101 which is binary\nrepresentation of 21.\n\nInput : 10\nOutput : 15" }, { "code": null, "e": 26812, "s": 26660, "text": "Method 1 (Using OR) 1. First generate a number that contains odd position bits. 2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1." }, { "code": null, "e": 26862, "s": 26812, "text": "Let’s understand this approach with below code. " }, { "code": null, "e": 26866, "s": 26862, "text": "C++" }, { "code": null, "e": 26871, "s": 26866, "text": "Java" }, { "code": null, "e": 26879, "s": 26871, "text": "Python3" }, { "code": null, "e": 26882, "s": 26879, "text": "C#" }, { "code": null, "e": 26886, "s": 26882, "text": "PHP" }, { "code": null, "e": 26897, "s": 26886, "text": "Javascript" }, { "code": "// CPP code Set all odd bits// of a number#include <iostream>using namespace std; // set all odd bitint oddbitsetnumber(int n){ int count = 0; // res for store 010101.. number int res = 0; // generate number form of 010101.....till // temp size for (int temp = n; temp > 0; temp >>= 1) { // if bit is odd, then generate // number and or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res);} // Driver codeint main(){ int n = 10; cout << oddbitsetnumber(n); return 0;}", "e": 27468, "s": 26897, "text": null }, { "code": "// Java code to Set all odd// bits of a number class GFG{ // set all odd bit static int oddbitsetnumber(int n) { int count = 0; // res for store 010101.. number int res = 0; // generate number form of // 010101.....till temp size for (int temp = n; temp > 0; temp >>= 1) { // if bit is odd, then generate // number and or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res); } // Driver code public static void main(String[] args) { int n = 10; System.out.println(oddbitsetnumber(n)); }} // This code is contributed// by prerna saini", "e": 28195, "s": 27468, "text": null }, { "code": "''' Python3 code Set all odd bits of a number''' # set all odd bitdef oddbitsetnumber(n): count = 0 # res for store 010101.. number res = 0 # generate number form of 010101.....till # temp size temp = n while temp > 0: # if bit is odd, then generate # number and or with res if count % 2 == 0: res |= (1 << count) count += 1 temp >>= 1 return (n | res) n = 10print (oddbitsetnumber(n)) #This code is contributed by Shreyanshi Arun.", "e": 28706, "s": 28195, "text": null }, { "code": "// C# code to Set all odd// bits of a numberusing System; class GFG{ static int oddbitsetnumber(int n) { int count = 0; // res for store 010101.. number int res = 0; // generate number form of // 010101.....till temp size for (int temp = n; temp > 0; temp >>= 1) { // if bit is odd, then // generate number and // or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res); } // Driver Code static public void Main () { int n = 10; Console.WriteLine(oddbitsetnumber(n)); }} // This code is contributed// by prerna ajit", "e": 29451, "s": 28706, "text": null }, { "code": "<?php// php code Set all odd// bits of a number // set all odd bitfunction oddbitsetnumber($n){ $count = 0; // res for store 010101.. // number $res = 0; // generate number form of // 010101... till temp size for ($temp = $n; $temp > 0; $temp >>= 1) { // if bit is odd, then generate // number and or with res if ($count % 2 == 0) $res |= (1 << $count); $count++; } return ($n | $res);} // Driver code $n = 10; echo oddbitsetnumber($n); // This code is contributed by mits?>", "e": 30011, "s": 29451, "text": null }, { "code": "<script> // JavaScript Program to Set all odd// bits of a number // set all odd bit function oddbitsetnumber(n) { let count = 0; // res for store 010101.. number let res = 0; // generate number form of // 010101.....till temp size for (let temp = n; temp > 0; temp >>= 1) { // if bit is odd, then generate // number and or with res if (count % 2 == 0) res |= (1 << count); count++; } return (n | res); } // Driver Code let n = 10; document.write(oddbitsetnumber(n)); // This code is contributed by chinmoy1997pal.</script>", "e": 30707, "s": 30011, "text": null }, { "code": null, "e": 30716, "s": 30707, "text": "Output: " }, { "code": null, "e": 30719, "s": 30716, "text": "15" }, { "code": null, "e": 30766, "s": 30719, "text": "Method 2 (A O(1) solution for 32 bit numbers) " }, { "code": null, "e": 30770, "s": 30766, "text": "C++" }, { "code": null, "e": 30775, "s": 30770, "text": "Java" }, { "code": null, "e": 30783, "s": 30775, "text": "Python3" }, { "code": null, "e": 30786, "s": 30783, "text": "C#" }, { "code": null, "e": 30790, "s": 30786, "text": "PHP" }, { "code": null, "e": 30801, "s": 30790, "text": "Javascript" }, { "code": "// Efficient CPP program to set all// odd bits number#include <iostream>using namespace std; // return MSB set numberint getmsb(int n){ // set all bits including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return MSB return (n + 1) >> 1;} // Returns a number of same size (MSB at// same position) as n and all odd bits// set.int getevenbits(int n){ n = getmsb(n); // generate odd bits like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is even then shift by 1 if ((n&1) == 0) n = n >> 1; // return odd set bits number return n; } // set all odd bits hereint setalloddbits(int n){ // take OR with odd set bits number return n | getevenbits(n); } // Driver codeint main(){ int n = 10; cout << setalloddbits(n); return 0;}", "e": 31667, "s": 30801, "text": null }, { "code": "// Efficient Java program to set// all odd bits numberclass GFG { // return MSB set number static int getmsb(int n) { // set all bits including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return MSB return (n + 1) >> 1; } // Returns a number of same // size (MSB at same position) // as n and all odd bits set. static int getevenbits(int n) { n = getmsb(n); // generate odd bits // like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is even // then shift by 1 if ((n & 1) == 0) n = n >> 1; // return odd set bits number return n; } // set all odd bits here static int setalloddbits(int n) { // take OR with odd // set bits number return n | getevenbits(n); } // Driver code public static void main(String[] args) { int n = 10; System.out.println(setalloddbits(n)); }} // This code is contributed// by prerna saini", "e": 32786, "s": 31667, "text": null }, { "code": "# Efficient python3 program to # set all odd bits numberimport math # return MSB set numberdef getmsb( n): # set all bits including MSB. n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # return MSB return (n + 1) >> 1 # Returns a number of same# size (MSB at same position)# as n and all odd bits set.def getevenbits(n): n = getmsb(n) # generate odd bits # like 010101.. n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # if bits is even # then shift by 1 if ((n & 1) == 0): n = n >> 1 # return odd set bits number return n # set all odd bits heredef setalloddbits( n): # take OR with odd # set bits number return n | getevenbits(n) # Driver Programn = 10print(setalloddbits(n)) # This code is contributed# by Gitanjali.", "e": 33615, "s": 32786, "text": null }, { "code": "// Efficient C# program to// set all odd bits numberusing System; class GFG{ // return MSB set number static int getmsb(int n) { // set all bits // including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return MSB return (n + 1) >> 1; } // Returns a number of same // size (MSB at same position) // as n and all odd bits set. static int getevenbits(int n) { n = getmsb(n); // generate odd bits // like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is even // then shift by 1 if ((n & 1) == 0) n = n >> 1; // return odd // set bits number return n; } // set all odd bits here static int setalloddbits(int n) { // take OR with odd // set bits number return n | getevenbits(n); } // Driver Code static public void Main () { int n = 10; Console.WriteLine(setalloddbits(n)); }} // This code is contributed ajit", "e": 34747, "s": 33615, "text": null }, { "code": "<?php// Efficient php program to// set all odd bits number // return MSB set numberfunction getmsb($n){ // set all bits // including MSB. $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // return MSB return ($n + 1) >> 1;} // Returns a number of// same size (MSB at// same position) as n// and all odd bits setfunction getevenbits($n){ $n = getmsb($n); // generate odd bits // like 010101.. $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // if bits is even // then shift by 1 if (($n&1) == 0) $n = $n >> 1; // return odd set // bits number return $n;} // set all odd bits herefunction setalloddbits($n){ // take OR with odd // set bits number return $n | getevenbits($n);} // Driver code $n = 10; echo setalloddbits($n); // This code is contributed by mits?>", "e": 35659, "s": 34747, "text": null }, { "code": "<script> // Efficient Javascript program to// set all odd bits number // Return MSB set numberfunction getmsb(n){ // Set all bits // including MSB. n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Return MSB return (n + 1) >> 1;} // Returns a number of same// size (MSB at same position)// as n and all odd bits set.function getevenbits(n){ n = getmsb(n); // Generate odd bits // like 010101.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // If bits is even // then shift by 1 if ((n & 1) == 0) n = n >> 1; // Return odd // set bits number return n;} // Set all odd bits herefunction setalloddbits(n){ // Take OR with odd // set bits number return n | getevenbits(n);} // Driver Codelet n = 10;document.write(setalloddbits(n)); // This code is contributed by decode2207 </script>", "e": 36565, "s": 35659, "text": null }, { "code": null, "e": 36574, "s": 36565, "text": "Output: " }, { "code": null, "e": 36577, "s": 36574, "text": "15" }, { "code": null, "e": 36592, "s": 36579, "text": "Mithun Kumar" }, { "code": null, "e": 36598, "s": 36592, "text": "jit_t" }, { "code": null, "e": 36616, "s": 36598, "text": "rdaniellivingston" }, { "code": null, "e": 36631, "s": 36616, "text": "chinmoy1997pal" }, { "code": null, "e": 36642, "s": 36631, "text": "decode2207" }, { "code": null, "e": 36652, "s": 36642, "text": "Bit Magic" }, { "code": null, "e": 36662, "s": 36652, "text": "Bit Magic" }, { "code": null, "e": 36760, "s": 36662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36811, "s": 36760, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 36875, "s": 36811, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 36902, "s": 36875, "text": "Swap two nibbles in a byte" }, { "code": null, "e": 36956, "s": 36902, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 36984, "s": 36956, "text": "Swap bits in a given number" }, { "code": null, "e": 37011, "s": 36984, "text": "Check for Integer Overflow" }, { "code": null, "e": 37051, "s": 37011, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 37088, "s": 37051, "text": "Find one extra character in a string" }, { "code": null, "e": 37127, "s": 37088, "text": "Bit Tricks for Competitive Programming" } ]
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) - GeeksforGeeks
28 Jan, 2022 We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor.Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. Following is structure of a single-threaded binary tree. C Java Python3 C# Javascript struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded;}; static class Node { int key; Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. boolean isThreaded;}; // This code is contributed by umadevi9616 class Node: def __init__(self): self.Key = 0; self.left = None; self.right = None; # Used to indicate whether the right pointer is a normal right # pointer or a pointer to inorder successor. self.isThreaded = False; # This code is contributed by Rajput-Ji class Node { int key; Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded;}; // This code is contributed by Rajput-Ji class Node{ constructor(item) { // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. let isThreaded; this.data=item; this.left = this.right = null; }} How to convert a Given Binary Tree to Threaded Binary Tree? We basically need to set NULL right pointers to inorder successor. We first do an inorder traversal of the tree and store it in a queue (we can use a simple array also) so that the inorder successor becomes the next node. We again do an inorder traversal and whenever we find a node whose right is NULL, we take the front item from queue and make it the right of current node. We also set isThreaded to true to indicate that the right pointer is a threaded link. Following is the implementation of the above idea. C++ Java Python3 C# Javascript /* C++ program to convert a Binary Tree to Threaded Tree */#include <bits/stdc++.h>using namespace std; /* Structure of a node in threaded binary tree */struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. bool isThreaded;}; // Helper function to put the Nodes in inorder into queuevoid populateQueue(Node* root, std::queue<Node*>* q){ if (root == NULL) return; if (root->left) populateQueue(root->left, q); q->push(root); if (root->right) populateQueue(root->right, q);} // Function to traverse queue, and make tree threadedvoid createThreadedUtil(Node* root, std::queue<Node*>* q){ if (root == NULL) return; if (root->left) createThreadedUtil(root->left, q); q->pop(); if (root->right) createThreadedUtil(root->right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { root->right = q->front(); root->isThreaded = true; }} // This function uses populateQueue() and// createThreadedUtil() to convert a given binary tree// to threaded tree.void createThreaded(Node* root){ // Create a queue to store inorder traversal std::queue<Node*> q; // Store inorder traversal in queue populateQueue(root, &q); // Link NULL right pointers to inorder successor createThreadedUtil(root, &q);} // A utility function to find leftmost node in a binary// tree rooted with 'root'. This function is used in inOrder()Node* leftMost(Node* root){ while (root != NULL && root->left != NULL) root = root->left; return root;} // Function to do inorder traversal of a threaded binary treevoid inOrder(Node* root){ if (root == NULL) return; // Find the leftmost node in Binary Tree Node* cur = leftMost(root); while (cur != NULL) { cout << cur->key << " "; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); }} // A utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp;} // Driver program to test above functionsint main(){ /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << "Inorder traversal of created threaded tree is\n"; inOrder(root); return 0;} // Java program to convert binary tree to threaded treeimport java.util.LinkedList;import java.util.Queue; /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. boolean isThreaded; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; // Helper function to put the Nodes in inorder into queue void populateQueue(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) populateQueue(node.left, q); q.add(node); if (node.right != null) populateQueue(node.right, q); } // Function to traverse queue, and make tree threaded void createThreadedUtil(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) createThreadedUtil(node.left, q); q.remove(); if (node.right != null) createThreadedUtil(node.right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { node.right = q.peek(); node.isThreaded = true; } } // This function uses populateQueue() and // createThreadedUtil() to convert a given binary tree // to threaded tree. void createThreaded(Node node) { // Create a queue to store inorder traversal Queue<Node> q = new LinkedList<Node>(); // Store inorder traversal in queue populateQueue(node, q); // Link NULL right pointers to inorder successor createThreadedUtil(node, q); } // A utility function to find leftmost node in a binary // tree rooted with 'root'. This function is used in inOrder() Node leftMost(Node node) { while (node != null && node.left != null) node = node.left; return node; } // Function to do inorder traversal of a threaded binary tree void inOrder(Node node) { if (node == null) return; // Find the leftmost node in Binary Tree Node cur = leftMost(node); while (cur != null) { System.out.print(" " + cur.data + " "); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded == true) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // Driver program to test for above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.createThreaded(tree.root); System.out.println("Inorder traversal of created threaded tree"); tree.inOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal # Python3 program to convert# a Binary Tree to Threaded Tree # Structure of a node in threaded binary treeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Used to indicate whether the right pointer # is a normal right pointer or a pointer to # inorder successor. self.isThreaded = False # Helper function to put the Nodes# in inorder into queuedef populateQueue(root, q): if root == None: return if root.left: populateQueue(root.left, q) q.append(root) if root.right: populateQueue(root.right, q) # Function to traverse queue,# and make tree threadeddef createThreadedUtil(root, q): if root == None: return if root.left: createThreadedUtil(root.left, q) q.pop(0) if root.right: createThreadedUtil(root.right, q) # If right pointer is None, link it to the # inorder successor and set 'isThreaded' bit. else: if len(q) == 0: root.right = None else: root.right = q[0] root.isThreaded = True # This function uses populateQueue() and# createThreadedUtil() to convert a given# binary tree to threaded tree.def createThreaded(root): # Create a queue to store inorder traversal q = [] # Store inorder traversal in queue populateQueue(root, q) # Link None right pointers to inorder successor createThreadedUtil(root, q) # A utility function to find leftmost node# in a binary tree rooted with 'root'.# This function is used in inOrder()def leftMost(root): while root != None and root.left != None: root = root.left return root # Function to do inorder traversal# of a threaded binary treedef inOrder(root): if root == None: return # Find the leftmost node in Binary Tree cur = leftMost(root) while cur != None: print(cur.key, end = " ") # If this Node is a thread Node, # then go to inorder successor if cur.isThreaded: cur = cur.right # Else go to the leftmost child # in right subtree else: cur = leftMost(cur.right) # Driver Codeif __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) createThreaded(root) print("Inorder traversal of created", "threaded tree is") inOrder(root) # This code is contributed by Rituraj Jain // C# program to convert binary tree to threaded treeusing System;using System.Collections.Generic; /* Class containing left and right child of currentnode and key value*/public class Node { public int data; public Node left, right; // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. public bool isThreaded; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { Node root; // Helper function to put the Nodes in inorder into queue void populateQueue(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) populateQueue(node.left, q); q.Enqueue(node); if (node.right != null) populateQueue(node.right, q); } // Function to traverse queue, and make tree threaded void createThreadedUtil(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) createThreadedUtil(node.left, q); q.Dequeue(); if (node.right != null) createThreadedUtil(node.right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { if (q.Count != 0) node.right = q.Peek(); node.isThreaded = true; } } // This function uses populateQueue() and // createThreadedUtil() to convert a given binary tree // to threaded tree. void createThreaded(Node node) { // Create a queue to store inorder traversal Queue<Node> q = new Queue<Node>(); // Store inorder traversal in queue populateQueue(node, q); // Link NULL right pointers to inorder successor createThreadedUtil(node, q); } // A utility function to find leftmost node in a binary // tree rooted with 'root'. This function is used in inOrder() Node leftMost(Node node) { while (node != null && node.left != null) node = node.left; return node; } // Function to do inorder traversal of a threaded binary tree void inOrder(Node node) { if (node == null) return; // Find the leftmost node in Binary Tree Node cur = leftMost(node); while (cur != null) { Console.Write(" " + cur.data + " "); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded == true) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.createThreaded(tree.root); Console.WriteLine("Inorder traversal of created threaded tree"); tree.inOrder(tree.root); }} // This code has been contributed by 29AjayKumar <script> // JavaScript program to convert// binary tree to threaded tree /* Class containing left and right child of current node and key value*/class Node{ constructor(item) { // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. let isThreaded; this.data=item; this.left = this.right = null; }} let root;// Helper function to put the Nodes in inorder into queuefunction populateQueue(node,q){ if (node == null) return; if (node.left != null) populateQueue(node.left, q); q.push(node); if (node.right != null) populateQueue(node.right, q);} // Function to traverse queue, and make tree threadedfunction createThreadedUtil(node,q){ if (node == null) return; if (node.left != null) createThreadedUtil(node.left, q); q.shift(); if (node.right != null) createThreadedUtil(node.right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { node.right = q[0]; node.isThreaded = true; }} // This function uses populateQueue() and// createThreadedUtil() to convert a given binary tree// to threaded tree.function createThreaded(node){ // Create a queue to store inorder traversal let q = []; // Store inorder traversal in queue populateQueue(node, q); // Link NULL right pointers to inorder successor createThreadedUtil(node, q);} // A utility function to find leftmost node in a binary// tree rooted with 'root'. This function is used in inOrder()function leftMost(node){ while (node != null && node.left != null) node = node.left; return node;} // Function to do inorder traversal of a threaded binary treefunction inOrder(node){ if (node == null) return; // Find the leftmost node in Binary Tree let cur = leftMost(node); while (cur != null) { document.write(" " + cur.data + " "); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded == true) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); }} // Driver program to test for above functionsroot = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); createThreaded(root); document.write( "Inorder traversal of created threaded tree<br>" ); inOrder(root); // This code is contributed by rag2127 </script> Output: Inorder traversal of created threaded tree is 4 2 5 1 6 3 7 YouTubeGeeksforGeeks507K subscribersConvert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:31•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Qjietvp72_Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)This article is contributed by Minhaz. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rituraj_jain 29AjayKumar rag2127 rutvik_56 umadevi9616 Rajput-Ji threaded-binary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
[ { "code": null, "e": 26167, "s": 26139, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26595, "s": 26167, "text": "We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor.Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. " }, { "code": null, "e": 26654, "s": 26595, "text": "Following is structure of a single-threaded binary tree. " }, { "code": null, "e": 26656, "s": 26654, "text": "C" }, { "code": null, "e": 26661, "s": 26656, "text": "Java" }, { "code": null, "e": 26669, "s": 26661, "text": "Python3" }, { "code": null, "e": 26672, "s": 26669, "text": "C#" }, { "code": null, "e": 26683, "s": 26672, "text": "Javascript" }, { "code": "struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded;};", "e": 26871, "s": 26683, "text": null }, { "code": "static class Node { int key; Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. boolean isThreaded;}; // This code is contributed by umadevi9616", "e": 27109, "s": 26871, "text": null }, { "code": "class Node: def __init__(self): self.Key = 0; self.left = None; self.right = None; # Used to indicate whether the right pointer is a normal right # pointer or a pointer to inorder successor. self.isThreaded = False; # This code is contributed by Rajput-Ji", "e": 27423, "s": 27109, "text": null }, { "code": "class Node { int key; Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded;}; // This code is contributed by Rajput-Ji", "e": 27649, "s": 27423, "text": null }, { "code": "class Node{ constructor(item) { // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. let isThreaded; this.data=item; this.left = this.right = null; }}", "e": 27911, "s": 27649, "text": null }, { "code": null, "e": 28486, "s": 27911, "text": "How to convert a Given Binary Tree to Threaded Binary Tree? We basically need to set NULL right pointers to inorder successor. We first do an inorder traversal of the tree and store it in a queue (we can use a simple array also) so that the inorder successor becomes the next node. We again do an inorder traversal and whenever we find a node whose right is NULL, we take the front item from queue and make it the right of current node. We also set isThreaded to true to indicate that the right pointer is a threaded link. Following is the implementation of the above idea. " }, { "code": null, "e": 28490, "s": 28486, "text": "C++" }, { "code": null, "e": 28495, "s": 28490, "text": "Java" }, { "code": null, "e": 28503, "s": 28495, "text": "Python3" }, { "code": null, "e": 28506, "s": 28503, "text": "C#" }, { "code": null, "e": 28517, "s": 28506, "text": "Javascript" }, { "code": "/* C++ program to convert a Binary Tree to Threaded Tree */#include <bits/stdc++.h>using namespace std; /* Structure of a node in threaded binary tree */struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. bool isThreaded;}; // Helper function to put the Nodes in inorder into queuevoid populateQueue(Node* root, std::queue<Node*>* q){ if (root == NULL) return; if (root->left) populateQueue(root->left, q); q->push(root); if (root->right) populateQueue(root->right, q);} // Function to traverse queue, and make tree threadedvoid createThreadedUtil(Node* root, std::queue<Node*>* q){ if (root == NULL) return; if (root->left) createThreadedUtil(root->left, q); q->pop(); if (root->right) createThreadedUtil(root->right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { root->right = q->front(); root->isThreaded = true; }} // This function uses populateQueue() and// createThreadedUtil() to convert a given binary tree// to threaded tree.void createThreaded(Node* root){ // Create a queue to store inorder traversal std::queue<Node*> q; // Store inorder traversal in queue populateQueue(root, &q); // Link NULL right pointers to inorder successor createThreadedUtil(root, &q);} // A utility function to find leftmost node in a binary// tree rooted with 'root'. This function is used in inOrder()Node* leftMost(Node* root){ while (root != NULL && root->left != NULL) root = root->left; return root;} // Function to do inorder traversal of a threaded binary treevoid inOrder(Node* root){ if (root == NULL) return; // Find the leftmost node in Binary Tree Node* cur = leftMost(root); while (cur != NULL) { cout << cur->key << \" \"; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); }} // A utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp;} // Driver program to test above functionsint main(){ /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << \"Inorder traversal of created threaded tree is\\n\"; inOrder(root); return 0;}", "e": 31367, "s": 28517, "text": null }, { "code": "// Java program to convert binary tree to threaded treeimport java.util.LinkedList;import java.util.Queue; /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. boolean isThreaded; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; // Helper function to put the Nodes in inorder into queue void populateQueue(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) populateQueue(node.left, q); q.add(node); if (node.right != null) populateQueue(node.right, q); } // Function to traverse queue, and make tree threaded void createThreadedUtil(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) createThreadedUtil(node.left, q); q.remove(); if (node.right != null) createThreadedUtil(node.right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { node.right = q.peek(); node.isThreaded = true; } } // This function uses populateQueue() and // createThreadedUtil() to convert a given binary tree // to threaded tree. void createThreaded(Node node) { // Create a queue to store inorder traversal Queue<Node> q = new LinkedList<Node>(); // Store inorder traversal in queue populateQueue(node, q); // Link NULL right pointers to inorder successor createThreadedUtil(node, q); } // A utility function to find leftmost node in a binary // tree rooted with 'root'. This function is used in inOrder() Node leftMost(Node node) { while (node != null && node.left != null) node = node.left; return node; } // Function to do inorder traversal of a threaded binary tree void inOrder(Node node) { if (node == null) return; // Find the leftmost node in Binary Tree Node cur = leftMost(node); while (cur != null) { System.out.print(\" \" + cur.data + \" \"); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded == true) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // Driver program to test for above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.createThreaded(tree.root); System.out.println(\"Inorder traversal of created threaded tree\"); tree.inOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal", "e": 34625, "s": 31367, "text": null }, { "code": "# Python3 program to convert# a Binary Tree to Threaded Tree # Structure of a node in threaded binary treeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Used to indicate whether the right pointer # is a normal right pointer or a pointer to # inorder successor. self.isThreaded = False # Helper function to put the Nodes# in inorder into queuedef populateQueue(root, q): if root == None: return if root.left: populateQueue(root.left, q) q.append(root) if root.right: populateQueue(root.right, q) # Function to traverse queue,# and make tree threadeddef createThreadedUtil(root, q): if root == None: return if root.left: createThreadedUtil(root.left, q) q.pop(0) if root.right: createThreadedUtil(root.right, q) # If right pointer is None, link it to the # inorder successor and set 'isThreaded' bit. else: if len(q) == 0: root.right = None else: root.right = q[0] root.isThreaded = True # This function uses populateQueue() and# createThreadedUtil() to convert a given# binary tree to threaded tree.def createThreaded(root): # Create a queue to store inorder traversal q = [] # Store inorder traversal in queue populateQueue(root, q) # Link None right pointers to inorder successor createThreadedUtil(root, q) # A utility function to find leftmost node# in a binary tree rooted with 'root'.# This function is used in inOrder()def leftMost(root): while root != None and root.left != None: root = root.left return root # Function to do inorder traversal# of a threaded binary treedef inOrder(root): if root == None: return # Find the leftmost node in Binary Tree cur = leftMost(root) while cur != None: print(cur.key, end = \" \") # If this Node is a thread Node, # then go to inorder successor if cur.isThreaded: cur = cur.right # Else go to the leftmost child # in right subtree else: cur = leftMost(cur.right) # Driver Codeif __name__ == \"__main__\": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) createThreaded(root) print(\"Inorder traversal of created\", \"threaded tree is\") inOrder(root) # This code is contributed by Rituraj Jain", "e": 37155, "s": 34625, "text": null }, { "code": "// C# program to convert binary tree to threaded treeusing System;using System.Collections.Generic; /* Class containing left and right child of currentnode and key value*/public class Node { public int data; public Node left, right; // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. public bool isThreaded; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { Node root; // Helper function to put the Nodes in inorder into queue void populateQueue(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) populateQueue(node.left, q); q.Enqueue(node); if (node.right != null) populateQueue(node.right, q); } // Function to traverse queue, and make tree threaded void createThreadedUtil(Node node, Queue<Node> q) { if (node == null) return; if (node.left != null) createThreadedUtil(node.left, q); q.Dequeue(); if (node.right != null) createThreadedUtil(node.right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { if (q.Count != 0) node.right = q.Peek(); node.isThreaded = true; } } // This function uses populateQueue() and // createThreadedUtil() to convert a given binary tree // to threaded tree. void createThreaded(Node node) { // Create a queue to store inorder traversal Queue<Node> q = new Queue<Node>(); // Store inorder traversal in queue populateQueue(node, q); // Link NULL right pointers to inorder successor createThreadedUtil(node, q); } // A utility function to find leftmost node in a binary // tree rooted with 'root'. This function is used in inOrder() Node leftMost(Node node) { while (node != null && node.left != null) node = node.left; return node; } // Function to do inorder traversal of a threaded binary tree void inOrder(Node node) { if (node == null) return; // Find the leftmost node in Binary Tree Node cur = leftMost(node); while (cur != null) { Console.Write(\" \" + cur.data + \" \"); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded == true) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.createThreaded(tree.root); Console.WriteLine(\"Inorder traversal of created threaded tree\"); tree.inOrder(tree.root); }} // This code has been contributed by 29AjayKumar", "e": 40432, "s": 37155, "text": null }, { "code": "<script> // JavaScript program to convert// binary tree to threaded tree /* Class containing left and right child of current node and key value*/class Node{ constructor(item) { // Used to indicate whether the right pointer is a normal // right pointer or a pointer to inorder successor. let isThreaded; this.data=item; this.left = this.right = null; }} let root;// Helper function to put the Nodes in inorder into queuefunction populateQueue(node,q){ if (node == null) return; if (node.left != null) populateQueue(node.left, q); q.push(node); if (node.right != null) populateQueue(node.right, q);} // Function to traverse queue, and make tree threadedfunction createThreadedUtil(node,q){ if (node == null) return; if (node.left != null) createThreadedUtil(node.left, q); q.shift(); if (node.right != null) createThreadedUtil(node.right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { node.right = q[0]; node.isThreaded = true; }} // This function uses populateQueue() and// createThreadedUtil() to convert a given binary tree// to threaded tree.function createThreaded(node){ // Create a queue to store inorder traversal let q = []; // Store inorder traversal in queue populateQueue(node, q); // Link NULL right pointers to inorder successor createThreadedUtil(node, q);} // A utility function to find leftmost node in a binary// tree rooted with 'root'. This function is used in inOrder()function leftMost(node){ while (node != null && node.left != null) node = node.left; return node;} // Function to do inorder traversal of a threaded binary treefunction inOrder(node){ if (node == null) return; // Find the leftmost node in Binary Tree let cur = leftMost(node); while (cur != null) { document.write(\" \" + cur.data + \" \"); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded == true) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); }} // Driver program to test for above functionsroot = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); createThreaded(root); document.write( \"Inorder traversal of created threaded tree<br>\" ); inOrder(root); // This code is contributed by rag2127 </script>", "e": 43317, "s": 40432, "text": null }, { "code": null, "e": 43327, "s": 43317, "text": "Output: " }, { "code": null, "e": 43387, "s": 43327, "text": "Inorder traversal of created threaded tree is\n4 2 5 1 6 3 7" }, { "code": null, "e": 44255, "s": 43389, "text": "YouTubeGeeksforGeeks507K subscribersConvert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:31•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Qjietvp72_Q\" 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": 44484, "s": 44255, "text": "Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)This article is contributed by Minhaz. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 44497, "s": 44484, "text": "rituraj_jain" }, { "code": null, "e": 44509, "s": 44497, "text": "29AjayKumar" }, { "code": null, "e": 44517, "s": 44509, "text": "rag2127" }, { "code": null, "e": 44527, "s": 44517, "text": "rutvik_56" }, { "code": null, "e": 44539, "s": 44527, "text": "umadevi9616" }, { "code": null, "e": 44549, "s": 44539, "text": "Rajput-Ji" }, { "code": null, "e": 44570, "s": 44549, "text": "threaded-binary-tree" }, { "code": null, "e": 44575, "s": 44570, "text": "Tree" }, { "code": null, "e": 44580, "s": 44575, "text": "Tree" }, { "code": null, "e": 44678, "s": 44580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44721, "s": 44678, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 44762, "s": 44721, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 44795, "s": 44762, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 44809, "s": 44795, "text": "Decision Tree" }, { "code": null, "e": 44859, "s": 44809, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 44917, "s": 44859, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 44953, "s": 44917, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 45001, "s": 44953, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
MRI Image Segmentation in MATLAB - GeeksforGeeks
16 Nov, 2021 In the domain of digital image processing, sometimes we need to separate the main object from the image for clear observation. Image segmentation is the process that enables this partitioning. In this method, each pixel is assigned a label, and pixels that share some characteristics are assigned the same label number. This technique is widely used in the medical domain to locate the object of interest. It is a technique to partition a digital image into multiple segments. This process is widely used in medical diagnosis. Here in this article, we have used morphological operations to segment the brain part from the MRI image. The segmentation is carried out in order to facilitate the analysis of the segmented images. This term refers to the technique which medical professionals use to view inside the human body in order to diagnose, monitor, and treat. There are various techniques available in the modern scientific age. MRI: Magnetic resonance imaging CT Scan: Computed Tomography Scan X-Ray: Using electromagnetic waves called X-rays. Ultrasound: Uses sound waves to create pictures of inner body tissues. It does not use any radiation. There exist many types of image segmentation. Thresholding Segmentation Edge-Based Segmentation Region-Based Segmentation Watershed Segmentation In this article, we are working on separating the brain part of the MRI image. Open: It converts small white portions or a bunch of bright pixels into dark portions without changing the size of a larger dark portion. Close: It converts small black portions or a bunch of dark pixels into bright portions without changing the size of the larger white portion. imread( ) inbuilt-function is used to read the image. imtool( ) inbuilt-function is used to display the image. graythresh( ) inbuilt-function is used to calculate the Ostu threshold for converting grayscale image into binary. im2bw( ) inbuilt-function is used to convert grayscale image into binary. strel( ) inbuilt-function is used to define the structuring element. imopen( ) inbuilt-function is used to apply opening morphological operation. bwlabel( ) inbuilt-function is used to assign the label to each pixel of image. imclose( ) inbuilt-function is used to apply closing morphological operation. double( ) inbuilt-function is used to convert unit8 object into double format. Read the MRI image. Convert it into binary. Apply opening operation. Apply connected component analysis. Identify the brain part and separate it out. Display different images in intermediate steps. Example: Matlab % MATLAB code for % Separate the brain part from MRI image. % read the mri image.k=imread("mrii.jpg"); % display the image.imtool(k,[]); % convert it into binary image.k1=im2bw(k,graythresh(k)); % display the binary image.imtool(k1); % Make the brain largest connected component.% We need to apply opening operation.% define the structuring element.SE=strel('disk',7,4); % apply the opening operation.k2=imopen(k1,SE); % display the image now.imtool(k2); % apply connected component analysis.b=bwlabel(k2); % display the colored map image.imtool(b,[]); % brain is component labeled as 9.% set all other component as 0 except brain.b(b~=9)=0; % display the brain part.imtool(b); % inside the brain part, black portion is there.% close the black pixels inside brain part.k3=imclose(b,strel('disk',18)); % display the brain part.imtool(k3); % extract the brain from original image.k4=k3.*double(k); % display the real brain from original image.imtool(k4,[]); Output: Figure 1: Original image Figure 2: Binary image Figure 3:After applying to open Figure 4:ColourMap image Figure 5:Biggest connected component Figure 6: After applying to close on the brain part Figure 7:Brain extracted from the original image Code explanation: k=imread(“mrii.jpg”); this line reads the mri image k1=im2bw(k,graythresh(k)); this line converts image into binary image SE=strel(‘disk’,7,4); this line defines the structuring element. k2=imopen(k1,SE); this line applys the opening operation b=bwlabel(k2); this line applys connected component analysis b(b~=9)=0; this line sets all other component as 0 except brain, since brain is labeled as 9. k3=imclose(b,strel(‘disk’,18)); this line closes the black pixels inside brain part for Inside the brain part, black portion is there. k4=k3.*double(k); this line extracts the brain from original image MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to swap elements in the matrix in MATLAB? How Can Be Randomly Shuffle Rows in MATLAB Matrix? How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? How to Normalize a Histogram in MATLAB? How to Iterate through each element in N-Dimensional matrix in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB How to extract numbers from cell array in MATLAB? MATLAB Syntax How to Find the Position of a Number in an Array in MATLAB? Solving Initial Value 2nd Order Differential Equation Problem using Laplace Transform in MATLAB
[ { "code": null, "e": 25887, "s": 25859, "text": "\n16 Nov, 2021" }, { "code": null, "e": 26293, "s": 25887, "text": "In the domain of digital image processing, sometimes we need to separate the main object from the image for clear observation. Image segmentation is the process that enables this partitioning. In this method, each pixel is assigned a label, and pixels that share some characteristics are assigned the same label number. This technique is widely used in the medical domain to locate the object of interest." }, { "code": null, "e": 26614, "s": 26293, "text": "It is a technique to partition a digital image into multiple segments. This process is widely used in medical diagnosis. Here in this article, we have used morphological operations to segment the brain part from the MRI image. The segmentation is carried out in order to facilitate the analysis of the segmented images. " }, { "code": null, "e": 26821, "s": 26614, "text": "This term refers to the technique which medical professionals use to view inside the human body in order to diagnose, monitor, and treat. There are various techniques available in the modern scientific age." }, { "code": null, "e": 26853, "s": 26821, "text": "MRI: Magnetic resonance imaging" }, { "code": null, "e": 26887, "s": 26853, "text": "CT Scan: Computed Tomography Scan" }, { "code": null, "e": 26937, "s": 26887, "text": "X-Ray: Using electromagnetic waves called X-rays." }, { "code": null, "e": 27039, "s": 26937, "text": "Ultrasound: Uses sound waves to create pictures of inner body tissues. It does not use any radiation." }, { "code": null, "e": 27086, "s": 27039, "text": "There exist many types of image segmentation. " }, { "code": null, "e": 27112, "s": 27086, "text": "Thresholding Segmentation" }, { "code": null, "e": 27136, "s": 27112, "text": "Edge-Based Segmentation" }, { "code": null, "e": 27162, "s": 27136, "text": "Region-Based Segmentation" }, { "code": null, "e": 27185, "s": 27162, "text": "Watershed Segmentation" }, { "code": null, "e": 27265, "s": 27185, "text": "In this article, we are working on separating the brain part of the MRI image. " }, { "code": null, "e": 27403, "s": 27265, "text": "Open: It converts small white portions or a bunch of bright pixels into dark portions without changing the size of a larger dark portion." }, { "code": null, "e": 27546, "s": 27403, "text": "Close: It converts small black portions or a bunch of dark pixels into bright portions without changing the size of the larger white portion. " }, { "code": null, "e": 27600, "s": 27546, "text": "imread( ) inbuilt-function is used to read the image." }, { "code": null, "e": 27657, "s": 27600, "text": "imtool( ) inbuilt-function is used to display the image." }, { "code": null, "e": 27772, "s": 27657, "text": "graythresh( ) inbuilt-function is used to calculate the Ostu threshold for converting grayscale image into binary." }, { "code": null, "e": 27846, "s": 27772, "text": "im2bw( ) inbuilt-function is used to convert grayscale image into binary." }, { "code": null, "e": 27915, "s": 27846, "text": "strel( ) inbuilt-function is used to define the structuring element." }, { "code": null, "e": 27992, "s": 27915, "text": "imopen( ) inbuilt-function is used to apply opening morphological operation." }, { "code": null, "e": 28072, "s": 27992, "text": "bwlabel( ) inbuilt-function is used to assign the label to each pixel of image." }, { "code": null, "e": 28150, "s": 28072, "text": "imclose( ) inbuilt-function is used to apply closing morphological operation." }, { "code": null, "e": 28229, "s": 28150, "text": "double( ) inbuilt-function is used to convert unit8 object into double format." }, { "code": null, "e": 28249, "s": 28229, "text": "Read the MRI image." }, { "code": null, "e": 28273, "s": 28249, "text": "Convert it into binary." }, { "code": null, "e": 28298, "s": 28273, "text": "Apply opening operation." }, { "code": null, "e": 28334, "s": 28298, "text": "Apply connected component analysis." }, { "code": null, "e": 28379, "s": 28334, "text": "Identify the brain part and separate it out." }, { "code": null, "e": 28427, "s": 28379, "text": "Display different images in intermediate steps." }, { "code": null, "e": 28436, "s": 28427, "text": "Example:" }, { "code": null, "e": 28443, "s": 28436, "text": "Matlab" }, { "code": "% MATLAB code for % Separate the brain part from MRI image. % read the mri image.k=imread(\"mrii.jpg\"); % display the image.imtool(k,[]); % convert it into binary image.k1=im2bw(k,graythresh(k)); % display the binary image.imtool(k1); % Make the brain largest connected component.% We need to apply opening operation.% define the structuring element.SE=strel('disk',7,4); % apply the opening operation.k2=imopen(k1,SE); % display the image now.imtool(k2); % apply connected component analysis.b=bwlabel(k2); % display the colored map image.imtool(b,[]); % brain is component labeled as 9.% set all other component as 0 except brain.b(b~=9)=0; % display the brain part.imtool(b); % inside the brain part, black portion is there.% close the black pixels inside brain part.k3=imclose(b,strel('disk',18)); % display the brain part.imtool(k3); % extract the brain from original image.k4=k3.*double(k); % display the real brain from original image.imtool(k4,[]);", "e": 29417, "s": 28443, "text": null }, { "code": null, "e": 29425, "s": 29417, "text": "Output:" }, { "code": null, "e": 29450, "s": 29425, "text": "Figure 1: Original image" }, { "code": null, "e": 29473, "s": 29450, "text": "Figure 2: Binary image" }, { "code": null, "e": 29505, "s": 29473, "text": "Figure 3:After applying to open" }, { "code": null, "e": 29530, "s": 29505, "text": "Figure 4:ColourMap image" }, { "code": null, "e": 29567, "s": 29530, "text": "Figure 5:Biggest connected component" }, { "code": null, "e": 29619, "s": 29567, "text": "Figure 6: After applying to close on the brain part" }, { "code": null, "e": 29668, "s": 29619, "text": "Figure 7:Brain extracted from the original image" }, { "code": null, "e": 29686, "s": 29668, "text": "Code explanation:" }, { "code": null, "e": 29738, "s": 29686, "text": "k=imread(“mrii.jpg”); this line reads the mri image" }, { "code": null, "e": 29808, "s": 29738, "text": "k1=im2bw(k,graythresh(k)); this line converts image into binary image" }, { "code": null, "e": 29873, "s": 29808, "text": "SE=strel(‘disk’,7,4); this line defines the structuring element." }, { "code": null, "e": 29930, "s": 29873, "text": "k2=imopen(k1,SE); this line applys the opening operation" }, { "code": null, "e": 29991, "s": 29930, "text": "b=bwlabel(k2); this line applys connected component analysis" }, { "code": null, "e": 30085, "s": 29991, "text": "b(b~=9)=0; this line sets all other component as 0 except brain, since brain is labeled as 9." }, { "code": null, "e": 30221, "s": 30085, "text": "k3=imclose(b,strel(‘disk’,18)); this line closes the black pixels inside brain part for Inside the brain part, black portion is there." }, { "code": null, "e": 30288, "s": 30221, "text": "k4=k3.*double(k); this line extracts the brain from original image" }, { "code": null, "e": 30314, "s": 30290, "text": "MATLAB image-processing" }, { "code": null, "e": 30321, "s": 30314, "text": "MATLAB" }, { "code": null, "e": 30419, "s": 30321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30465, "s": 30419, "text": "How to swap elements in the matrix in MATLAB?" }, { "code": null, "e": 30516, "s": 30465, "text": "How Can Be Randomly Shuffle Rows in MATLAB Matrix?" }, { "code": null, "e": 30589, "s": 30516, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 30629, "s": 30589, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 30700, "s": 30629, "text": "How to Iterate through each element in N-Dimensional matrix in MATLAB?" }, { "code": null, "e": 30765, "s": 30700, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 30815, "s": 30765, "text": "How to extract numbers from cell array in MATLAB?" }, { "code": null, "e": 30829, "s": 30815, "text": "MATLAB Syntax" }, { "code": null, "e": 30889, "s": 30829, "text": "How to Find the Position of a Number in an Array in MATLAB?" } ]
Python CuPy - GeeksforGeeks
05 Dec, 2019 NumPy surely is the most compatible library for any pythonic code to process large amounts of data in the form of numpy.ndarray(n-dimensional matrix array). However, as soon as we increase the size of data processed to a significant amount the multicore CPU cannot process data as efficiently as required because Numpy is only running on CPU (mostly having 4-8 cores on consumer end) having the limited parallel processing power. This is where a new nice python library comes in CuPy. CuPy is a NumPy compatible library for GPU. CuPy is an open-source matrix library accelerated with NVIDIA CUDA. It also uses CUDA-related libraries including cuBLAS, cuDNN, cuRand, cuSolver, cuSPARSE, cuFFT, and NCCL to make full use of the GPU architecture. It is an implementation of a NumPy-compatible multi-dimensional array on CUDA. CuPy consists of cupy.ndarray, the core multi-dimensional array class, and many functions on it. It supports a subset of numpy.ndarray interface. And it can also accelerate the existing NumPy code through GPU and CUDA libraries. pip python 3 Anaconda(optional) CUDA X.0 (depending upon the hardware) CPU: 2x Intel Xeon E5–2698 v4 @ 2.20GHz Main memory: 1 TB GPU: NVIDIA Tesla V100 32 GB OS – Windows/Linux InstallationDownload the compatible version of the CUDA setup on your device and install it. To install it open the terminal and enter pip install cupy-cuda(version) where version will be the version of CUDA installed on your device. For example-(For CUDA 10.0) pip install cupy-cuda100 If your device does not support CUDA then you can install CuPy in Anaconda and use it for CPU based computing. Alternatively, Anaconda works fine with CUDA too. To install it on Anaconda – Open the Anaconda prompt and enterconda install -c anaconda cupyOrUse Anaconda navigator(GUI) to directly install cupy library. Open the Anaconda prompt and enterconda install -c anaconda cupyOr conda install -c anaconda cupy Or Use Anaconda navigator(GUI) to directly install cupy library. Basics of cupy.ndarray Importing – In the following code, cp is an abbreviation of cupy, as np is numpy as is customarily done.import numpy as np import cupy as cp Just like Numpy, CuPy also have a ndarray class cupy.ndarray which is compatible GPU alternative of numpy.ndarray.x_gpu = cp.array([1, 2, 3]) x_gpu in the above example is an instance of cupy.ndarray. You can see its creation of identical to NumPy’s one, except that numpy is replaced with cupy. Importing – In the following code, cp is an abbreviation of cupy, as np is numpy as is customarily done.import numpy as np import cupy as cp import numpy as np import cupy as cp Just like Numpy, CuPy also have a ndarray class cupy.ndarray which is compatible GPU alternative of numpy.ndarray.x_gpu = cp.array([1, 2, 3]) x_gpu in the above example is an instance of cupy.ndarray. You can see its creation of identical to NumPy’s one, except that numpy is replaced with cupy. x_gpu = cp.array([1, 2, 3]) x_gpu in the above example is an instance of cupy.ndarray. You can see its creation of identical to NumPy’s one, except that numpy is replaced with cupy. Example – Take the Euclidean norm (a.k.a L2 norm). import cupy as cpimport numpy as np x_cpu = np.array([1, 2, 3])x_gpu = cp.array([1, 2, 3]) l2_cpu = np.linalg.norm(x_cpu)l2_gpu = cp.linalg.norm(x_gpu) print("Using Numpy: ", l2_cpu)print("\nUsing Cupy: ", l2_gpu) Using Numpy: 3.7416573867739413 Using Cupy: array(3.74165739) CuPy is a NumPy compatible library for GPU. It is more efficient as compared to numpy because array operations with NVIDIA GPUs can provide considerable speedups over CPU computing. Note- The configurations used here are for CPU is intel i7-7700 HQ and GPU is Geforce GTX 1050 4GB using CUDA 9.0. # Python program to # demonstrate speed comparison# between cupy and numpy # Importing modulesimport cupy as cpimport numpy as npimport time # NumPy and CPU Runtimes = time.time()x_cpu = np.ones((1000, 1000, 100))e = time.time()print("Time consumed by numpy: ", e - s) # CuPy and GPU Runtimes = time.time()x_gpu = cp.ones((1000, 1000, 100))e = time.time()print("\nTime consumed by cupy: "e - s) Time consumed by numpy: 0.4238910675048828 Time consumed by cupy: 0.0010099411010742188 Here, we can see that CuPy could work way faster than NumPy. CuPy implements many functions on cupy.ndarray objects. See the reference for the supported subset of NumPy API. Understanding NumPy might help utilizing most features of CuPy. So, it is recommend you to read the NumPy documentation. References – https://cupy.chainer.org/ sid779 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25493, "s": 25465, "text": "\n05 Dec, 2019" }, { "code": null, "e": 25923, "s": 25493, "text": "NumPy surely is the most compatible library for any pythonic code to process large amounts of data in the form of numpy.ndarray(n-dimensional matrix array). However, as soon as we increase the size of data processed to a significant amount the multicore CPU cannot process data as efficiently as required because Numpy is only running on CPU (mostly having 4-8 cores on consumer end) having the limited parallel processing power." }, { "code": null, "e": 26022, "s": 25923, "text": "This is where a new nice python library comes in CuPy. CuPy is a NumPy compatible library for GPU." }, { "code": null, "e": 26237, "s": 26022, "text": "CuPy is an open-source matrix library accelerated with NVIDIA CUDA. It also uses CUDA-related libraries including cuBLAS, cuDNN, cuRand, cuSolver, cuSPARSE, cuFFT, and NCCL to make full use of the GPU architecture." }, { "code": null, "e": 26545, "s": 26237, "text": "It is an implementation of a NumPy-compatible multi-dimensional array on CUDA. CuPy consists of cupy.ndarray, the core multi-dimensional array class, and many functions on it. It supports a subset of numpy.ndarray interface. And it can also accelerate the existing NumPy code through GPU and CUDA libraries." }, { "code": null, "e": 26549, "s": 26545, "text": "pip" }, { "code": null, "e": 26558, "s": 26549, "text": "python 3" }, { "code": null, "e": 26577, "s": 26558, "text": "Anaconda(optional)" }, { "code": null, "e": 26616, "s": 26577, "text": "CUDA X.0 (depending upon the hardware)" }, { "code": null, "e": 26656, "s": 26616, "text": "CPU: 2x Intel Xeon E5–2698 v4 @ 2.20GHz" }, { "code": null, "e": 26674, "s": 26656, "text": "Main memory: 1 TB" }, { "code": null, "e": 26703, "s": 26674, "text": "GPU: NVIDIA Tesla V100 32 GB" }, { "code": null, "e": 26722, "s": 26703, "text": "OS – Windows/Linux" }, { "code": null, "e": 26857, "s": 26722, "text": "InstallationDownload the compatible version of the CUDA setup on your device and install it. To install it open the terminal and enter" }, { "code": null, "e": 26888, "s": 26857, "text": "pip install cupy-cuda(version)" }, { "code": null, "e": 26984, "s": 26888, "text": "where version will be the version of CUDA installed on your device. For example-(For CUDA 10.0)" }, { "code": null, "e": 27009, "s": 26984, "text": "pip install cupy-cuda100" }, { "code": null, "e": 27170, "s": 27009, "text": "If your device does not support CUDA then you can install CuPy in Anaconda and use it for CPU based computing. Alternatively, Anaconda works fine with CUDA too." }, { "code": null, "e": 27198, "s": 27170, "text": "To install it on Anaconda –" }, { "code": null, "e": 27326, "s": 27198, "text": "Open the Anaconda prompt and enterconda install -c anaconda cupyOrUse Anaconda navigator(GUI) to directly install cupy library." }, { "code": null, "e": 27393, "s": 27326, "text": "Open the Anaconda prompt and enterconda install -c anaconda cupyOr" }, { "code": null, "e": 27424, "s": 27393, "text": "conda install -c anaconda cupy" }, { "code": null, "e": 27427, "s": 27424, "text": "Or" }, { "code": null, "e": 27489, "s": 27427, "text": "Use Anaconda navigator(GUI) to directly install cupy library." }, { "code": null, "e": 27512, "s": 27489, "text": "Basics of cupy.ndarray" }, { "code": null, "e": 27949, "s": 27512, "text": "Importing – In the following code, cp is an abbreviation of cupy, as np is numpy as is customarily done.import numpy as np\nimport cupy as cp\nJust like Numpy, CuPy also have a ndarray class cupy.ndarray which is compatible GPU alternative of numpy.ndarray.x_gpu = cp.array([1, 2, 3])\nx_gpu in the above example is an instance of cupy.ndarray. You can see its creation of identical to NumPy’s one, except that numpy is replaced with cupy." }, { "code": null, "e": 28091, "s": 27949, "text": "Importing – In the following code, cp is an abbreviation of cupy, as np is numpy as is customarily done.import numpy as np\nimport cupy as cp\n" }, { "code": null, "e": 28129, "s": 28091, "text": "import numpy as np\nimport cupy as cp\n" }, { "code": null, "e": 28425, "s": 28129, "text": "Just like Numpy, CuPy also have a ndarray class cupy.ndarray which is compatible GPU alternative of numpy.ndarray.x_gpu = cp.array([1, 2, 3])\nx_gpu in the above example is an instance of cupy.ndarray. You can see its creation of identical to NumPy’s one, except that numpy is replaced with cupy." }, { "code": null, "e": 28454, "s": 28425, "text": "x_gpu = cp.array([1, 2, 3])\n" }, { "code": null, "e": 28608, "s": 28454, "text": "x_gpu in the above example is an instance of cupy.ndarray. You can see its creation of identical to NumPy’s one, except that numpy is replaced with cupy." }, { "code": null, "e": 28659, "s": 28608, "text": "Example – Take the Euclidean norm (a.k.a L2 norm)." }, { "code": "import cupy as cpimport numpy as np x_cpu = np.array([1, 2, 3])x_gpu = cp.array([1, 2, 3]) l2_cpu = np.linalg.norm(x_cpu)l2_gpu = cp.linalg.norm(x_gpu) print(\"Using Numpy: \", l2_cpu)print(\"\\nUsing Cupy: \", l2_gpu)", "e": 28876, "s": 28659, "text": null }, { "code": null, "e": 28939, "s": 28876, "text": "Using Numpy: 3.7416573867739413\n\nUsing Cupy: array(3.74165739)" }, { "code": null, "e": 29121, "s": 28939, "text": "CuPy is a NumPy compatible library for GPU. It is more efficient as compared to numpy because array operations with NVIDIA GPUs can provide considerable speedups over CPU computing." }, { "code": null, "e": 29236, "s": 29121, "text": "Note- The configurations used here are for CPU is intel i7-7700 HQ and GPU is Geforce GTX 1050 4GB using CUDA 9.0." }, { "code": "# Python program to # demonstrate speed comparison# between cupy and numpy # Importing modulesimport cupy as cpimport numpy as npimport time # NumPy and CPU Runtimes = time.time()x_cpu = np.ones((1000, 1000, 100))e = time.time()print(\"Time consumed by numpy: \", e - s) # CuPy and GPU Runtimes = time.time()x_gpu = cp.ones((1000, 1000, 100))e = time.time()print(\"\\nTime consumed by cupy: \"e - s)", "e": 29634, "s": 29236, "text": null }, { "code": null, "e": 29723, "s": 29634, "text": "Time consumed by numpy: 0.4238910675048828\nTime consumed by cupy: 0.0010099411010742188\n" }, { "code": null, "e": 29784, "s": 29723, "text": "Here, we can see that CuPy could work way faster than NumPy." }, { "code": null, "e": 30018, "s": 29784, "text": "CuPy implements many functions on cupy.ndarray objects. See the reference for the supported subset of NumPy API. Understanding NumPy might help utilizing most features of CuPy. So, it is recommend you to read the NumPy documentation." }, { "code": null, "e": 30057, "s": 30018, "text": "References – https://cupy.chainer.org/" }, { "code": null, "e": 30064, "s": 30057, "text": "sid779" }, { "code": null, "e": 30079, "s": 30064, "text": "python-utility" }, { "code": null, "e": 30086, "s": 30079, "text": "Python" }, { "code": null, "e": 30184, "s": 30086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30202, "s": 30184, "text": "Python Dictionary" }, { "code": null, "e": 30237, "s": 30202, "text": "Read a file line by line in Python" }, { "code": null, "e": 30269, "s": 30237, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30291, "s": 30269, "text": "Enumerate() in Python" }, { "code": null, "e": 30333, "s": 30291, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30363, "s": 30333, "text": "Iterate over a list in Python" }, { "code": null, "e": 30389, "s": 30363, "text": "Python String | replace()" }, { "code": null, "e": 30418, "s": 30389, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30462, "s": 30418, "text": "Reading and Writing to text files in Python" } ]
Python VLC Instance - Creating MediaPlayer Instance - GeeksforGeeks
29 Aug, 2020 In this article we will see how we can create a MediaPlayer instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. Media player object is used play a single or multiple media. In order to do this we will use media_player_new method with the Instance object Syntax : instance.media_player_new() Argument : It takes no argument but it can take uri as optional argument Return : It returns MediaPlayer object Below is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new("death_note.mkv") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Another exampleBelow is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new("1.mp4") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Python vlc-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25829, "s": 25801, "text": "\n29 Aug, 2020" }, { "code": null, "e": 26383, "s": 25829, "text": "In this article we will see how we can create a MediaPlayer instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. Media player object is used play a single or multiple media." }, { "code": null, "e": 26464, "s": 26383, "text": "In order to do this we will use media_player_new method with the Instance object" }, { "code": null, "e": 26501, "s": 26464, "text": "Syntax : instance.media_player_new()" }, { "code": null, "e": 26574, "s": 26501, "text": "Argument : It takes no argument but it can take uri as optional argument" }, { "code": null, "e": 26613, "s": 26574, "text": "Return : It returns MediaPlayer object" }, { "code": null, "e": 26641, "s": 26613, "text": "Below is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new(\"death_note.mkv\") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)", "e": 27134, "s": 26641, "text": null }, { "code": null, "e": 27143, "s": 27134, "text": "Output :" }, { "code": null, "e": 27186, "s": 27143, "text": "Another exampleBelow is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new(\"1.mp4\") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)", "e": 27670, "s": 27186, "text": null }, { "code": null, "e": 27679, "s": 27670, "text": "Output :" }, { "code": null, "e": 27698, "s": 27679, "text": "Python vlc-library" }, { "code": null, "e": 27705, "s": 27698, "text": "Python" }, { "code": null, "e": 27803, "s": 27705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27821, "s": 27803, "text": "Python Dictionary" }, { "code": null, "e": 27856, "s": 27821, "text": "Read a file line by line in Python" }, { "code": null, "e": 27888, "s": 27856, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27910, "s": 27888, "text": "Enumerate() in Python" }, { "code": null, "e": 27952, "s": 27910, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27982, "s": 27952, "text": "Iterate over a list in Python" }, { "code": null, "e": 28008, "s": 27982, "text": "Python String | replace()" }, { "code": null, "e": 28037, "s": 28008, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28081, "s": 28037, "text": "Reading and Writing to text files in Python" } ]
Comparing two dates in PHP - GeeksforGeeks
31 Jul, 2021 Given two dates (date1 and date2) and the task is to compare the given dates. Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. Example: <?php// PHP program to compare dates // Declare two dates and // initialize it$date1 = "1998-11-24";$date2 = "1997-03-26"; // Use comparison operator to // compare datesif ($date1 > $date2) echo "$date1 is latest than $date2";else echo "$date1 is older than $date2"; ?> 1998-11-24 is latest than 1997-03-26 Method 2: If both of the given dates are in different formats then use strtotime() function to convert the given dates into the corresponding timestamp format and lastly compare these numerical timestamps to get the desired result. Example: <?php// PHP program to compare dates // Declare two dates in different// format$date1 = "12-03-26";$date2 = "2011-10-24"; // Use strtotime() function to convert// date into dateTimestamp$dateTimestamp1 = strtotime($date1);$dateTimestamp2 = strtotime($date2); // Compare the timestamp date if ($dateTimestamp1 > $dateTimestamp2) echo "$date1 is latest than $date2";else echo "$date1 is older than $date2"; ?> 12-03-26 is latest than 2011-10-24 Method 3: Using DateTime class to compare two dates. Example: <?php// PHP program to compare dates // Declare two dates in different// format and use DateTime() function// to convert date into DateTime$date1 = new DateTime("12-11-24");$date2 = new DateTime("2011-03-26"); // Compare the datesif ($date1 > $date2) echo $date1->format("Y-m-d") . " is latest than " . $date2->format("Y-m-d");else echo $date1->format("Y-m-d") . " is older than " . $date2->format("Y-m-d"); ?> 2012-11-24 is latest than 2011-03-26 PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP Download file from URL using PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP How to get parameters from a URL string in PHP?
[ { "code": null, "e": 25671, "s": 25643, "text": "\n31 Jul, 2021" }, { "code": null, "e": 25895, "s": 25671, "text": "Given two dates (date1 and date2) and the task is to compare the given dates. Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format." }, { "code": null, "e": 26007, "s": 25895, "text": "Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates." }, { "code": null, "e": 26016, "s": 26007, "text": "Example:" }, { "code": "<?php// PHP program to compare dates // Declare two dates and // initialize it$date1 = \"1998-11-24\";$date2 = \"1997-03-26\"; // Use comparison operator to // compare datesif ($date1 > $date2) echo \"$date1 is latest than $date2\";else echo \"$date1 is older than $date2\"; ?>", "e": 26295, "s": 26016, "text": null }, { "code": null, "e": 26333, "s": 26295, "text": "1998-11-24 is latest than 1997-03-26\n" }, { "code": null, "e": 26565, "s": 26333, "text": "Method 2: If both of the given dates are in different formats then use strtotime() function to convert the given dates into the corresponding timestamp format and lastly compare these numerical timestamps to get the desired result." }, { "code": null, "e": 26574, "s": 26565, "text": "Example:" }, { "code": "<?php// PHP program to compare dates // Declare two dates in different// format$date1 = \"12-03-26\";$date2 = \"2011-10-24\"; // Use strtotime() function to convert// date into dateTimestamp$dateTimestamp1 = strtotime($date1);$dateTimestamp2 = strtotime($date2); // Compare the timestamp date if ($dateTimestamp1 > $dateTimestamp2) echo \"$date1 is latest than $date2\";else echo \"$date1 is older than $date2\"; ?>", "e": 26992, "s": 26574, "text": null }, { "code": null, "e": 27028, "s": 26992, "text": "12-03-26 is latest than 2011-10-24\n" }, { "code": null, "e": 27081, "s": 27028, "text": "Method 3: Using DateTime class to compare two dates." }, { "code": null, "e": 27090, "s": 27081, "text": "Example:" }, { "code": "<?php// PHP program to compare dates // Declare two dates in different// format and use DateTime() function// to convert date into DateTime$date1 = new DateTime(\"12-11-24\");$date2 = new DateTime(\"2011-03-26\"); // Compare the datesif ($date1 > $date2) echo $date1->format(\"Y-m-d\") . \" is latest than \" . $date2->format(\"Y-m-d\");else echo $date1->format(\"Y-m-d\") . \" is older than \" . $date2->format(\"Y-m-d\"); ?>", "e": 27533, "s": 27090, "text": null }, { "code": null, "e": 27571, "s": 27533, "text": "2012-11-24 is latest than 2011-03-26\n" }, { "code": null, "e": 27740, "s": 27571, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 27747, "s": 27740, "text": "Picked" }, { "code": null, "e": 27751, "s": 27747, "text": "PHP" }, { "code": null, "e": 27764, "s": 27751, "text": "PHP Programs" }, { "code": null, "e": 27781, "s": 27764, "text": "Web Technologies" }, { "code": null, "e": 27785, "s": 27781, "text": "PHP" }, { "code": null, "e": 27883, "s": 27785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27923, "s": 27883, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27968, "s": 27923, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28010, "s": 27968, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 28062, "s": 28010, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 28095, "s": 28062, "text": "Download file from URL using PHP" }, { "code": null, "e": 28135, "s": 28095, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28187, "s": 28135, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28229, "s": 28187, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 28281, "s": 28229, "text": "Split a comma delimited string into an array in PHP" } ]
How to Deobfuscate an Android Stacktrace using a Mapping File? - GeeksforGeeks
19 Nov, 2021 In general, the stack traces we do receive can be of ANR (Application not responding) issues, Android services logs for e.g. broadcast receivers, Intent services, and many more. On the development side, tracing those error logs will be a major burden. In this article, we go through some specific techniques for retracing stack traces obtained from Google Play crash reports, Firebase crash reports, or any crash report analytics tool. So we’ll start with the steps below to retrace it. Recognize the stack trace error reportExamine the mapping fileTo retrace it, use the (proguardgui) tool Recognize the stack trace error report Examine the mapping file To retrace it, use the (proguardgui) tool Step #1: Reading the Stack-trace So let’s commence this article by checking a sample stacktrace, to help understand better how it really works! Image #1. Looking on the Stacktrace. Step #2: Reading the Map File Now the next step is to get the mapping file, to do that follow the steps below: <your_project_name_here>app/build/outputs/mapping/FLAVOR/release/mapping.txt Step #3: Opening the Gradle GUI Once you have completed the previous steps, now you have to open the gradle GUI, to do that browse to <your_system_name>/AppData/Local/Android/SDK/tools/proguard/lib and then find an executable, named ‘proguardgui.exe’, double click that to open it, a window like this would open: Image #2. The Proguard GUI window. When you arrive at this window, just browse your mapping.txt file from the above URL indicated in Step 01, put your stack trace error logs in the obfuscated stack trace window, and lastly click on the ReTrace button to receive the DeObfuscated error report. Step #4: Using Play Store Developer Console Log in to your Play Developer Account using your login credentials.Choose an app.Select Android vitals > Deobfuscation files from the left menu.Click Upload next to a version of your software.Upload the ProGuard mapping file for your app’s version. Log in to your Play Developer Account using your login credentials. Choose an app. Select Android vitals > Deobfuscation files from the left menu. Click Upload next to a version of your software. Upload the ProGuard mapping file for your app’s version. Step #5: Using The Terminal on the Mac If you are using the terminal on the mac, the whole process gets easier, you simply need to do the following: java -jar /Users/<your computer name>/Library/Android/sdk/tools/proguard/lib/proguardgui.jar All of the preceding processes are carried out locally on your development side and they necessitate some work, and that brings us to the end of this Geeks for Geeks article, hope this helps you deobfuscate your code with ease! Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Android Listview in Java with Example How to Save Data to the Firebase Realtime Database in Android? Flexbox-Layout in Android How to Change the Background Color After Clicking the Button in Android?
[ { "code": null, "e": 26381, "s": 26353, "text": "\n19 Nov, 2021" }, { "code": null, "e": 26868, "s": 26381, "text": "In general, the stack traces we do receive can be of ANR (Application not responding) issues, Android services logs for e.g. broadcast receivers, Intent services, and many more. On the development side, tracing those error logs will be a major burden. In this article, we go through some specific techniques for retracing stack traces obtained from Google Play crash reports, Firebase crash reports, or any crash report analytics tool. So we’ll start with the steps below to retrace it." }, { "code": null, "e": 26972, "s": 26868, "text": "Recognize the stack trace error reportExamine the mapping fileTo retrace it, use the (proguardgui) tool" }, { "code": null, "e": 27011, "s": 26972, "text": "Recognize the stack trace error report" }, { "code": null, "e": 27036, "s": 27011, "text": "Examine the mapping file" }, { "code": null, "e": 27078, "s": 27036, "text": "To retrace it, use the (proguardgui) tool" }, { "code": null, "e": 27111, "s": 27078, "text": "Step #1: Reading the Stack-trace" }, { "code": null, "e": 27222, "s": 27111, "text": "So let’s commence this article by checking a sample stacktrace, to help understand better how it really works!" }, { "code": null, "e": 27259, "s": 27222, "text": "Image #1. Looking on the Stacktrace." }, { "code": null, "e": 27289, "s": 27259, "text": "Step #2: Reading the Map File" }, { "code": null, "e": 27370, "s": 27289, "text": "Now the next step is to get the mapping file, to do that follow the steps below:" }, { "code": null, "e": 27447, "s": 27370, "text": "<your_project_name_here>app/build/outputs/mapping/FLAVOR/release/mapping.txt" }, { "code": null, "e": 27479, "s": 27447, "text": "Step #3: Opening the Gradle GUI" }, { "code": null, "e": 27581, "s": 27479, "text": "Once you have completed the previous steps, now you have to open the gradle GUI, to do that browse to" }, { "code": null, "e": 27645, "s": 27581, "text": "<your_system_name>/AppData/Local/Android/SDK/tools/proguard/lib" }, { "code": null, "e": 27760, "s": 27645, "text": "and then find an executable, named ‘proguardgui.exe’, double click that to open it, a window like this would open:" }, { "code": null, "e": 27795, "s": 27760, "text": "Image #2. The Proguard GUI window." }, { "code": null, "e": 28053, "s": 27795, "text": "When you arrive at this window, just browse your mapping.txt file from the above URL indicated in Step 01, put your stack trace error logs in the obfuscated stack trace window, and lastly click on the ReTrace button to receive the DeObfuscated error report." }, { "code": null, "e": 28097, "s": 28053, "text": "Step #4: Using Play Store Developer Console" }, { "code": null, "e": 28346, "s": 28097, "text": "Log in to your Play Developer Account using your login credentials.Choose an app.Select Android vitals > Deobfuscation files from the left menu.Click Upload next to a version of your software.Upload the ProGuard mapping file for your app’s version." }, { "code": null, "e": 28414, "s": 28346, "text": "Log in to your Play Developer Account using your login credentials." }, { "code": null, "e": 28429, "s": 28414, "text": "Choose an app." }, { "code": null, "e": 28493, "s": 28429, "text": "Select Android vitals > Deobfuscation files from the left menu." }, { "code": null, "e": 28542, "s": 28493, "text": "Click Upload next to a version of your software." }, { "code": null, "e": 28599, "s": 28542, "text": "Upload the ProGuard mapping file for your app’s version." }, { "code": null, "e": 28638, "s": 28599, "text": "Step #5: Using The Terminal on the Mac" }, { "code": null, "e": 28748, "s": 28638, "text": "If you are using the terminal on the mac, the whole process gets easier, you simply need to do the following:" }, { "code": null, "e": 28841, "s": 28748, "text": "java -jar /Users/<your computer name>/Library/Android/sdk/tools/proguard/lib/proguardgui.jar" }, { "code": null, "e": 29069, "s": 28841, "text": "All of the preceding processes are carried out locally on your development side and they necessitate some work, and that brings us to the end of this Geeks for Geeks article, hope this helps you deobfuscate your code with ease!" }, { "code": null, "e": 29076, "s": 29069, "text": "Picked" }, { "code": null, "e": 29084, "s": 29076, "text": "Android" }, { "code": null, "e": 29092, "s": 29084, "text": "Android" }, { "code": null, "e": 29190, "s": 29092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29228, "s": 29190, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29267, "s": 29228, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29317, "s": 29267, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29368, "s": 29317, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 29410, "s": 29368, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29450, "s": 29410, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 29488, "s": 29450, "text": "Android Listview in Java with Example" }, { "code": null, "e": 29551, "s": 29488, "text": "How to Save Data to the Firebase Realtime Database in Android?" }, { "code": null, "e": 29577, "s": 29551, "text": "Flexbox-Layout in Android" } ]
GridView Using BaseAdapter in Android with Example - GeeksforGeeks
29 Oct, 2020 Here, we are designing an android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that is group views in a two-dimensional scrolling grid of rows and columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable and we don’t need to use ScrollView. An example of GridView is your default Gallery. Attributes Description The number of columns to display. It can be an integer or auto_fit which will display as many possible columns to fill the screen of the device. If they don’t specify this attribute then the grid view will behave like a listview. horizontalSpacing property is used to define the default horizontal spacing between columns. This could be in pixel(px),density pixel(dp) or scale independent pixel(sp). Vertical spacing property used to define the default vertical spacing between rows. This should be in px, dp or sp. An Adapter is a connection between the UI components eg (TextView, ImageView,) and data source. An adapter helps fill the UI element with the appropriate data. In android commonly used adapters which fill data in GridView are: ArrayAdapterBaseAdapterCustom ArrayAdapter ArrayAdapter BaseAdapter Custom ArrayAdapter This tutorial will be using the BaseAdapter, following is the structure of the class which extends the base adapter. Java public class MyAdapter extends BaseAdapter { @Override public int getCount() { return 0; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { return null; }} Method Description: getCount(): this method returns the count of the total elements to be displayed. getItem(int i): this method takes in an index and returns an object. getItemId(int i): this method takes in an index and returns the id of the item being displayed in the GridView. getView(int I, View view, ViewGroup group): this is the most important method which returns a view that is displayed in the grid view. The int i is the index, the view can be (ImageView or TextView), and the view group is the container that hosts the View e.g LinearLayout, RelativeLayout, etc. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Open the activity_main.xml file and insert a GridView component in it. The Layout will look blank initially but will be inflated by the custom adapter class during runtime. Below is the code for the activity_main.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:id="@+id/ImageGrid" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <GridView android:id="@+id/grid_view" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="auto_fit" android:horizontalSpacing="10dp" android:verticalSpacing="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Creating a new layout XML file Creating a new file named grid_layout.xml in the same folder as the activity_main.xml file. This Custom View will host an ImageView. The main reason to use custom adapters is to display complex views in the GridView or ListView instead of some simple text. The custom view is named as grid_layout.xml with the LinearLayout as its root and a simple ImageView. Below is the code for the grid_layout.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="center" tools:srcCompat="@tools:sample/avatars" /> </LinearLayout> Step 4: Creating a Custom Adapter class Will name this class MyBaseAdapter which will extend BaseAdapter class and inherit the methods shown above. The main method we need to walk through is the getView method. Java @Overridepublic View getView(int i, View view, ViewGroup viewGroup){ if (view == null) { LayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.grid_layout, viewGroup); } ImageView imageView = view.findViewById(R.id.imageView); imageView.setImageResource(items[i]); return view;} The LayoutInflator is what is responsible for parsing our custom grid_layout.xml file. do note that this operation is expensive and should only be performed when needed. hence its place inside an if statement. Finally, we get a reference to the layout and store it in the view variable. then using that we can initialize the image view and set the image and return the view. In this example, the view shown is quite simple but we can have a more completed view like displaying the id of a person who can have a custom view of the Image, TextView, etc. The entire code of the MyBaseAdapter.java is given below. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView; public class MyBaseAdapter extends BaseAdapter { Context c; int items[]; MyBaseAdapter(Context c, int arr[]) { this.c = c; items = arr; } @Override public int getCount() { return items.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { if (view == null) { LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.grid_layout, null); } ImageView imageView = view.findViewById(R.id.imageView); imageView.setImageResource(items[i]); return view; }} Step 5: Working with the MainActivity.java file The data will use using are images of different android studio logos saved in the drawable folder. To use these images we need to store them in an array and pass it to the custom adapter. Java int[] itemsarray = new int[] { R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5, R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5}; Notice that the same 5 images are repeated. Now setting up the custom base adapter in the MainActivity.java file. Java GridView gridView = findViewById(R.id.grid_view); // create a object of myBaseAdapterMyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray);gridView.setAdapter(baseAdapter); First, we get a reference of the grid layout from the XML file using the fineViewById() method, then we create the object of myBaseAdapter which takes two arguments Context, and the items array. Finally, we set the adapter. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.GridView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { int[] itemsarray = new int[]{ R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5, R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView gridView = findViewById(R.id.grid_view); // create a object of myBaseAdapter MyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray); gridView.setAdapter(baseAdapter); }} android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 25865, "s": 25837, "text": "\n29 Oct, 2020" }, { "code": null, "e": 26236, "s": 25865, "text": "Here, we are designing an android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that is group views in a two-dimensional scrolling grid of rows and columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable and we don’t need to use ScrollView. An example of GridView is your default Gallery." }, { "code": null, "e": 26247, "s": 26236, "text": "Attributes" }, { "code": null, "e": 26259, "s": 26247, "text": "Description" }, { "code": null, "e": 26333, "s": 26259, "text": "The number of columns to display. It can be an integer or auto_fit which " }, { "code": null, "e": 26406, "s": 26333, "text": "will display as many possible columns to fill the screen of the device. " }, { "code": null, "e": 26491, "s": 26406, "text": "If they don’t specify this attribute then the grid view will behave like a listview." }, { "code": null, "e": 26560, "s": 26491, "text": "horizontalSpacing property is used to define the default horizontal " }, { "code": null, "e": 26631, "s": 26560, "text": "spacing between columns. This could be in pixel(px),density pixel(dp) " }, { "code": null, "e": 26663, "s": 26631, "text": "or scale independent pixel(sp)." }, { "code": null, "e": 26733, "s": 26663, "text": "Vertical spacing property used to define the default vertical spacing" }, { "code": null, "e": 26780, "s": 26733, "text": " between rows. This should be in px, dp or sp." }, { "code": null, "e": 27007, "s": 26780, "text": "An Adapter is a connection between the UI components eg (TextView, ImageView,) and data source. An adapter helps fill the UI element with the appropriate data. In android commonly used adapters which fill data in GridView are:" }, { "code": null, "e": 27050, "s": 27007, "text": "ArrayAdapterBaseAdapterCustom ArrayAdapter" }, { "code": null, "e": 27063, "s": 27050, "text": "ArrayAdapter" }, { "code": null, "e": 27075, "s": 27063, "text": "BaseAdapter" }, { "code": null, "e": 27095, "s": 27075, "text": "Custom ArrayAdapter" }, { "code": null, "e": 27213, "s": 27095, "text": "This tutorial will be using the BaseAdapter, following is the structure of the class which extends the base adapter. " }, { "code": null, "e": 27218, "s": 27213, "text": "Java" }, { "code": "public class MyAdapter extends BaseAdapter { @Override public int getCount() { return 0; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { return null; }}", "e": 27574, "s": 27218, "text": null }, { "code": null, "e": 27595, "s": 27574, "text": "Method Description: " }, { "code": null, "e": 27676, "s": 27595, "text": "getCount(): this method returns the count of the total elements to be displayed." }, { "code": null, "e": 27745, "s": 27676, "text": "getItem(int i): this method takes in an index and returns an object." }, { "code": null, "e": 27857, "s": 27745, "text": "getItemId(int i): this method takes in an index and returns the id of the item being displayed in the GridView." }, { "code": null, "e": 28152, "s": 27857, "text": "getView(int I, View view, ViewGroup group): this is the most important method which returns a view that is displayed in the grid view. The int i is the index, the view can be (ImageView or TextView), and the view group is the container that hosts the View e.g LinearLayout, RelativeLayout, etc." }, { "code": null, "e": 28317, "s": 28152, "text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 28346, "s": 28317, "text": "Step 1: Create a New Project" }, { "code": null, "e": 28508, "s": 28346, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 28556, "s": 28508, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 28730, "s": 28556, "text": "Open the activity_main.xml file and insert a GridView component in it. The Layout will look blank initially but will be inflated by the custom adapter class during runtime. " }, { "code": null, "e": 28780, "s": 28730, "text": "Below is the code for the activity_main.xml file." }, { "code": null, "e": 28784, "s": 28780, "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:id=\"@+id/ImageGrid\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <GridView android:id=\"@+id/grid_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:numColumns=\"auto_fit\" android:horizontalSpacing=\"10dp\" android:verticalSpacing=\"10dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 29704, "s": 28784, "text": null }, { "code": null, "e": 29744, "s": 29704, "text": "Step 3: Creating a new layout XML file " }, { "code": null, "e": 30103, "s": 29744, "text": "Creating a new file named grid_layout.xml in the same folder as the activity_main.xml file. This Custom View will host an ImageView. The main reason to use custom adapters is to display complex views in the GridView or ListView instead of some simple text. The custom view is named as grid_layout.xml with the LinearLayout as its root and a simple ImageView." }, { "code": null, "e": 30151, "s": 30103, "text": "Below is the code for the grid_layout.xml file." }, { "code": null, "e": 30155, "s": 30151, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:scaleType=\"center\" tools:srcCompat=\"@tools:sample/avatars\" /> </LinearLayout>", "e": 30677, "s": 30155, "text": null }, { "code": null, "e": 30718, "s": 30677, "text": "Step 4: Creating a Custom Adapter class " }, { "code": null, "e": 30890, "s": 30718, "text": "Will name this class MyBaseAdapter which will extend BaseAdapter class and inherit the methods shown above. The main method we need to walk through is the getView method. " }, { "code": null, "e": 30895, "s": 30890, "text": "Java" }, { "code": "@Overridepublic View getView(int i, View view, ViewGroup viewGroup){ if (view == null) { LayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.grid_layout, viewGroup); } ImageView imageView = view.findViewById(R.id.imageView); imageView.setImageResource(items[i]); return view;}", "e": 31279, "s": 30895, "text": null }, { "code": null, "e": 31890, "s": 31279, "text": "The LayoutInflator is what is responsible for parsing our custom grid_layout.xml file. do note that this operation is expensive and should only be performed when needed. hence its place inside an if statement. Finally, we get a reference to the layout and store it in the view variable. then using that we can initialize the image view and set the image and return the view. In this example, the view shown is quite simple but we can have a more completed view like displaying the id of a person who can have a custom view of the Image, TextView, etc. The entire code of the MyBaseAdapter.java is given below." }, { "code": null, "e": 31895, "s": 31890, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView; public class MyBaseAdapter extends BaseAdapter { Context c; int items[]; MyBaseAdapter(Context c, int arr[]) { this.c = c; items = arr; } @Override public int getCount() { return items.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { if (view == null) { LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.grid_layout, null); } ImageView imageView = view.findViewById(R.id.imageView); imageView.setImageResource(items[i]); return view; }}", "e": 32917, "s": 31895, "text": null }, { "code": null, "e": 32965, "s": 32917, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 33065, "s": 32965, "text": "The data will use using are images of different android studio logos saved in the drawable folder. " }, { "code": null, "e": 33154, "s": 33065, "text": "To use these images we need to store them in an array and pass it to the custom adapter." }, { "code": null, "e": 33159, "s": 33154, "text": "Java" }, { "code": "int[] itemsarray = new int[] { R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5, R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5};", "e": 33426, "s": 33159, "text": null }, { "code": null, "e": 33540, "s": 33426, "text": "Notice that the same 5 images are repeated. Now setting up the custom base adapter in the MainActivity.java file." }, { "code": null, "e": 33545, "s": 33540, "text": "Java" }, { "code": "GridView gridView = findViewById(R.id.grid_view); // create a object of myBaseAdapterMyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray);gridView.setAdapter(baseAdapter);", "e": 33729, "s": 33545, "text": null }, { "code": null, "e": 34086, "s": 33729, "text": "First, we get a reference of the grid layout from the XML file using the fineViewById() method, then we create the object of myBaseAdapter which takes two arguments Context, and the items array. Finally, we set the adapter. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 34091, "s": 34086, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.GridView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { int[] itemsarray = new int[]{ R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5, R.drawable.android_1, R.drawable.android_2, R.drawable.android_3, R.drawable.android_4, R.drawable.android_5 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView gridView = findViewById(R.id.grid_view); // create a object of myBaseAdapter MyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray); gridView.setAdapter(baseAdapter); }}", "e": 34950, "s": 34091, "text": null }, { "code": null, "e": 34958, "s": 34950, "text": "android" }, { "code": null, "e": 34966, "s": 34958, "text": "Android" }, { "code": null, "e": 34971, "s": 34966, "text": "Java" }, { "code": null, "e": 34976, "s": 34971, "text": "Java" }, { "code": null, "e": 34984, "s": 34976, "text": "Android" }, { "code": null, "e": 35082, "s": 34984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35140, "s": 35082, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 35183, "s": 35140, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 35221, "s": 35183, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35254, "s": 35221, "text": "Services in Android with Example" }, { "code": null, "e": 35285, "s": 35254, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 35300, "s": 35285, "text": "Arrays in Java" }, { "code": null, "e": 35344, "s": 35300, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35366, "s": 35344, "text": "For-each loop in Java" }, { "code": null, "e": 35417, "s": 35366, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
JavaScript Function.prototype.bind() Method - GeeksforGeeks
08 Dec, 2021 A function is a set of statements that take inputs, do some specific computation, and produce output. There are various scenarios in programming in which we need to pre-configure this keyword or function arguments and we can easily do that in JavaScript with the help of the bind() method. The bind() method creates a new function based on the function on which it is called. Using the bind() method, we can pre-configure this keyword and arguments for the function using the syntax shown below. Syntax: const newFunction = oldFunction.bind(thisArg, arg1, ag2, ..., argN) Using the above syntax, a new function is created based on the old function with this keyword set to thisArg, and function arguments are preconfigured as arg1, agr2, and so on. The example mentioned below demonstrates the use of the bind() method with the help of an example. Example: Javascript <script> const car = { brand: 'Lamborghini', }; // As of now, 'this' keyword refers // to 'window' object. const printDetail = function (model, topSpeed) { console.log(`${this.brand} ${model} has a top speed of ${topSpeed} mph`); }; // Calling the function without using bind which // means 'this' still refers to 'window' object // so accessing this.brand will give undefined printDetail('Diablo Coatl', 239); // Creating a new function based on printDetail // with 'this' keyword referring to car object // so accessing this.brand will give 'Lamborgini' const lamboPrintDetail = printDetail.bind(car); lamboPrintDetail('Diablo VTTT', 222); // Creating another function based on printDetail // with it's arguments pre-configured and 'this' // keyword referring to car object const reventonPrintDetail = printDetail.bind(car, 'Reventon', 221); // Since the arguments are preconfigured so we don't // need to pass any argument to call this function reventonPrintDetail();</script> Output: undefined Diablo Coatl has a top speed of 239 mph Lamborghini Diablo VTTT has a top speed of 222 mph Lamborghini Reventon has a top speed of 221 mph varshagumber28 JavaScript-Methods Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n08 Dec, 2021" }, { "code": null, "e": 27041, "s": 26545, "text": "A function is a set of statements that take inputs, do some specific computation, and produce output. There are various scenarios in programming in which we need to pre-configure this keyword or function arguments and we can easily do that in JavaScript with the help of the bind() method. The bind() method creates a new function based on the function on which it is called. Using the bind() method, we can pre-configure this keyword and arguments for the function using the syntax shown below." }, { "code": null, "e": 27049, "s": 27041, "text": "Syntax:" }, { "code": null, "e": 27117, "s": 27049, "text": "const newFunction = oldFunction.bind(thisArg, arg1, ag2, ..., argN)" }, { "code": null, "e": 27393, "s": 27117, "text": "Using the above syntax, a new function is created based on the old function with this keyword set to thisArg, and function arguments are preconfigured as arg1, agr2, and so on. The example mentioned below demonstrates the use of the bind() method with the help of an example." }, { "code": null, "e": 27402, "s": 27393, "text": "Example:" }, { "code": null, "e": 27413, "s": 27402, "text": "Javascript" }, { "code": "<script> const car = { brand: 'Lamborghini', }; // As of now, 'this' keyword refers // to 'window' object. const printDetail = function (model, topSpeed) { console.log(`${this.brand} ${model} has a top speed of ${topSpeed} mph`); }; // Calling the function without using bind which // means 'this' still refers to 'window' object // so accessing this.brand will give undefined printDetail('Diablo Coatl', 239); // Creating a new function based on printDetail // with 'this' keyword referring to car object // so accessing this.brand will give 'Lamborgini' const lamboPrintDetail = printDetail.bind(car); lamboPrintDetail('Diablo VTTT', 222); // Creating another function based on printDetail // with it's arguments pre-configured and 'this' // keyword referring to car object const reventonPrintDetail = printDetail.bind(car, 'Reventon', 221); // Since the arguments are preconfigured so we don't // need to pass any argument to call this function reventonPrintDetail();</script>", "e": 28492, "s": 27413, "text": null }, { "code": null, "e": 28500, "s": 28492, "text": "Output:" }, { "code": null, "e": 28649, "s": 28500, "text": "undefined Diablo Coatl has a top speed of 239 mph\nLamborghini Diablo VTTT has a top speed of 222 mph\nLamborghini Reventon has a top speed of 221 mph" }, { "code": null, "e": 28664, "s": 28649, "text": "varshagumber28" }, { "code": null, "e": 28683, "s": 28664, "text": "JavaScript-Methods" }, { "code": null, "e": 28690, "s": 28683, "text": "Picked" }, { "code": null, "e": 28701, "s": 28690, "text": "JavaScript" }, { "code": null, "e": 28718, "s": 28701, "text": "Web Technologies" }, { "code": null, "e": 28816, "s": 28718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28856, "s": 28816, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28917, "s": 28856, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28958, "s": 28917, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28980, "s": 28958, "text": "JavaScript | Promises" }, { "code": null, "e": 29034, "s": 28980, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29074, "s": 29034, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29107, "s": 29074, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29150, "s": 29107, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29200, "s": 29150, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program for Rotate a Matrix by 180 degree - GeeksforGeeks
13 Jan, 2022 Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. Examples : Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that to rotate a matrix by 180 degrees we can easily follow that step Matrix = a00 a01 a02 a10 a11 a12 a20 a21 a22 when we rotate it by 90 degree then matrix is Matrix = a02 a12 a22 a01 a11 a21 a00 a10 a20 when we rotate it by again 90 degree then matrix is Matrix = a22 a21 a20 a12 a11 a10 a02 a01 a00 From the above illustration, we get that simply to rotate the matrix by 180 degrees then we will have to print the given matrix in a reverse manner. Java // Java program to rotate a// matrix by 180 degreesimport java.util.*; class GFG { static int N = 3; // Function to Rotate the // matrix by 180 degree static void rotateMatrix(int mat[][]) { // Simply print from last // cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) System.out.print(mat[i][j] + " "); System.out.println(); } } // Driver Code public static void main(String[] args) { int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); }} // This code is contributed by ChitraNayal Output : 9 8 7 6 5 4 3 2 1 Time complexity: O(N*N) Auxiliary Space: O(1) Method : 2(In-place rotation) There are four steps : 1- Find transpose of a matrix. 2- Reverse columns of the transpose. 3- Find transpose of a matrix. 4- Reverse columns of the transpose Let the given matrix be 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 First we find transpose. 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 Then we reverse elements of every column. 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 then transpose again 4 3 2 1 8 7 6 5 12 11 10 9 16 15 14 13 Then we reverse elements of every column again 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Java // Java program for left// rotation of matrix by 180import java.util.*; class GFG { static int R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree static void reverseColumns(int arr[][]) { for (int i = 0; i < C; i++) { for (int j = 0, k = C - 1; j < k; j++, k--) { t = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = t; } } } // Function for transpose of matrix static void transpose(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = i; j < C; j++) { t = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = t; } } } // Function for display the matrix static void printMatrix(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } // Function to anticlockwise // rotate matrix by 180 degree static void rotate180(int arr[][]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); }} // This code is contributed by ChitraNayal Output : 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Time complexity : O(R*C) Auxiliary Space : O(1)In the code above, the transpose of the matrix has to be found twice, and also, columns have to be reversed twice. So, we can have a better solution. Method : 3 (Position swapping)Here, we swap the values in the respective positions. Java public class GFG { /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ private static void reverseRow(int[][] data, int index) { int cols = data[index].length; for (int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ private static void printMatrix(int[][] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + " "); } System.out.println(""); } } /** * Rotate Matrix by 180 degrees * @param data matrix */ private static void rotateMatrix180(int[][] data) { int rows = data.length; int cols = data[0].length; if (rows % 2 != 0) { //If N is odd reverse the middle row in the matrix reverseRow(data, data.length / 2); } //Swap the value of matrix [i][j] with [rows - i - 1][cols - j - 1] for half the rows size. for (int i = 0; i <= (rows/2) - 1; i++) { for (int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } public static void main(String[] args) { int[][] data = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; //Rotate Matrix rotateMatrix180(data); //Print Matrix printMatrix(data); }} Output : 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Time complexity : O(R*C) Auxiliary Space : O(1) Please refer complete article on Rotate a Matrix by 180 degree for more details! Nvidia rotation Java Java Programs Mathematical Matrix Nvidia Mathematical Matrix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25303, "s": 25275, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25432, "s": 25303, "text": "Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. " }, { "code": null, "e": 25444, "s": 25432, "text": "Examples : " }, { "code": null, "e": 25686, "s": 25444, "text": "Input : 1 2 3\n 4 5 6\n 7 8 9\nOutput : 9 8 7 \n 6 5 4 \n 3 2 1\n\nInput : 1 2 3 4 \n 5 6 7 8 \n 9 0 1 2 \n 3 4 5 6 \nOutput : 6 5 4 3 \n 2 1 0 9 \n 8 7 6 5 \n 4 3 2 1" }, { "code": null, "e": 25828, "s": 25686, "text": "Method: 1 (Only prints rotated matrix) The solution of this problem is that to rotate a matrix by 180 degrees we can easily follow that step " }, { "code": null, "e": 26125, "s": 25828, "text": "Matrix = a00 a01 a02\n a10 a11 a12\n a20 a21 a22\n\nwhen we rotate it by 90 degree\nthen matrix is\nMatrix = a02 a12 a22\n a01 a11 a21\n a00 a10 a20\n \nwhen we rotate it by again 90 \ndegree then matrix is \nMatrix = a22 a21 a20\n a12 a11 a10\n a02 a01 a00 " }, { "code": null, "e": 26274, "s": 26125, "text": "From the above illustration, we get that simply to rotate the matrix by 180 degrees then we will have to print the given matrix in a reverse manner." }, { "code": null, "e": 26279, "s": 26274, "text": "Java" }, { "code": "// Java program to rotate a// matrix by 180 degreesimport java.util.*; class GFG { static int N = 3; // Function to Rotate the // matrix by 180 degree static void rotateMatrix(int mat[][]) { // Simply print from last // cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) System.out.print(mat[i][j] + \" \"); System.out.println(); } } // Driver Code public static void main(String[] args) { int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); }} // This code is contributed by ChitraNayal", "e": 26993, "s": 26279, "text": null }, { "code": null, "e": 27003, "s": 26993, "text": "Output : " }, { "code": null, "e": 27028, "s": 27003, "text": " 9 8 7 \n 6 5 4 \n 3 2 1 " }, { "code": null, "e": 27074, "s": 27028, "text": "Time complexity: O(N*N) Auxiliary Space: O(1)" }, { "code": null, "e": 27262, "s": 27074, "text": "Method : 2(In-place rotation) There are four steps : 1- Find transpose of a matrix. 2- Reverse columns of the transpose. 3- Find transpose of a matrix. 4- Reverse columns of the transpose" }, { "code": null, "e": 27635, "s": 27262, "text": "Let the given matrix be\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n\nFirst we find transpose.\n1 5 9 13\n2 6 10 14\n3 7 11 15\n4 8 12 16\n\nThen we reverse elements of every column.\n4 8 12 16\n3 7 11 15\n2 6 10 14\n1 5 9 13\n\nthen transpose again \n4 3 2 1 \n8 7 6 5 \n12 11 10 9\n16 15 14 13 \n\nThen we reverse elements of every column again\n16 15 14 13 \n12 11 10 9 \n8 7 6 5 \n4 3 2 1" }, { "code": null, "e": 27640, "s": 27635, "text": "Java" }, { "code": "// Java program for left// rotation of matrix by 180import java.util.*; class GFG { static int R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree static void reverseColumns(int arr[][]) { for (int i = 0; i < C; i++) { for (int j = 0, k = C - 1; j < k; j++, k--) { t = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = t; } } } // Function for transpose of matrix static void transpose(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = i; j < C; j++) { t = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = t; } } } // Function for display the matrix static void printMatrix(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) System.out.print(arr[i][j] + \" \"); System.out.println(); } } // Function to anticlockwise // rotate matrix by 180 degree static void rotate180(int arr[][]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); }} // This code is contributed by ChitraNayal", "e": 29180, "s": 27640, "text": null }, { "code": null, "e": 29190, "s": 29180, "text": "Output : " }, { "code": null, "e": 29236, "s": 29190, "text": " 16 15 14 13 \n 12 11 10 9 \n 8 7 6 5 \n 4 3 2 1" }, { "code": null, "e": 29433, "s": 29236, "text": "Time complexity : O(R*C) Auxiliary Space : O(1)In the code above, the transpose of the matrix has to be found twice, and also, columns have to be reversed twice. So, we can have a better solution." }, { "code": null, "e": 29518, "s": 29433, "text": "Method : 3 (Position swapping)Here, we swap the values in the respective positions. " }, { "code": null, "e": 29523, "s": 29518, "text": "Java" }, { "code": "public class GFG { /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ private static void reverseRow(int[][] data, int index) { int cols = data[index].length; for (int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ private static void printMatrix(int[][] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + \" \"); } System.out.println(\"\"); } } /** * Rotate Matrix by 180 degrees * @param data matrix */ private static void rotateMatrix180(int[][] data) { int rows = data.length; int cols = data[0].length; if (rows % 2 != 0) { //If N is odd reverse the middle row in the matrix reverseRow(data, data.length / 2); } //Swap the value of matrix [i][j] with [rows - i - 1][cols - j - 1] for half the rows size. for (int i = 0; i <= (rows/2) - 1; i++) { for (int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } public static void main(String[] args) { int[][] data = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; //Rotate Matrix rotateMatrix180(data); //Print Matrix printMatrix(data); }}", "e": 31376, "s": 29523, "text": null }, { "code": null, "e": 31386, "s": 31376, "text": "Output : " }, { "code": null, "e": 31457, "s": 31386, "text": "25 24 23 22 21 \n20 19 18 17 16 \n15 14 13 12 11 \n10 9 8 7 6 \n5 4 3 2 1 " }, { "code": null, "e": 31506, "s": 31457, "text": "Time complexity : O(R*C) Auxiliary Space : O(1) " }, { "code": null, "e": 31587, "s": 31506, "text": "Please refer complete article on Rotate a Matrix by 180 degree for more details!" }, { "code": null, "e": 31594, "s": 31587, "text": "Nvidia" }, { "code": null, "e": 31603, "s": 31594, "text": "rotation" }, { "code": null, "e": 31608, "s": 31603, "text": "Java" }, { "code": null, "e": 31622, "s": 31608, "text": "Java Programs" }, { "code": null, "e": 31635, "s": 31622, "text": "Mathematical" }, { "code": null, "e": 31642, "s": 31635, "text": "Matrix" }, { "code": null, "e": 31649, "s": 31642, "text": "Nvidia" }, { "code": null, "e": 31662, "s": 31649, "text": "Mathematical" }, { "code": null, "e": 31669, "s": 31662, "text": "Matrix" }, { "code": null, "e": 31674, "s": 31669, "text": "Java" }, { "code": null, "e": 31772, "s": 31674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31787, "s": 31772, "text": "Stream In Java" }, { "code": null, "e": 31808, "s": 31787, "text": "Constructors in Java" }, { "code": null, "e": 31827, "s": 31808, "text": "Exceptions in Java" }, { "code": null, "e": 31857, "s": 31827, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31903, "s": 31857, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31929, "s": 31903, "text": "Java Programming Examples" }, { "code": null, "e": 31963, "s": 31929, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 32010, "s": 31963, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 32042, "s": 32010, "text": "How to Iterate HashMap in Java?" } ]
C++ Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack - GeeksforGeeks
14 Dec, 2021 Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp. Example: Input: exp = “[()]{}{[()()]()}” Output: Balanced Input: exp = “[(])” Output: Not Balanced Algorithm: Declare a character stack S. Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. After complete traversal, if there is some starting bracket left in stack then “not balanced” Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ // CPP program to check for balanced brackets.#include <bits/stdc++.h>using namespace std; // function to check if brackets are balancedbool areBracketsBalanced(string expr){ stack<char> s; char x; // Traversing the Expression for (int i = 0; i < expr.length(); i++) { if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') { // Push the element in the stack s.push(expr[i]); continue; } // IF current current character is not opening // bracket, then it must be closing. So stack // cannot be empty at this point. if (s.empty()) return false; switch (expr[i]) { case ')': // Store the top element in a x = s.top(); s.pop(); if (x == '{' || x == '[') return false; break; case '}': // Store the top element in b x = s.top(); s.pop(); if (x == '(' || x == '[') return false; break; case ']': // Store the top element in c x = s.top(); s.pop(); if (x == '(' || x == '{') return false; break; } } // Check Empty Stack return (s.empty());} // Driver codeint main(){ string expr = "{()}[]"; // Function call if (areBracketsBalanced(expr)) cout << "Balanced"; else cout << "Not Balanced"; return 0;} Balanced Time Complexity: O(n) Auxiliary Space: O(n) for stack. Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details! Amazon Hike Oracle Parentheses-Problems Snapdeal Walmart Wipro Yatra.com Zoho C++ Programs Stack Strings Zoho Amazon Snapdeal Hike Oracle Walmart Wipro Yatra.com Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 25851, "s": 25823, "text": "\n14 Dec, 2021" }, { "code": null, "e": 25995, "s": 25851, "text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp." }, { "code": null, "e": 26005, "s": 25995, "text": "Example: " }, { "code": null, "e": 26054, "s": 26005, "text": "Input: exp = “[()]{}{[()()]()}” Output: Balanced" }, { "code": null, "e": 26096, "s": 26054, "text": "Input: exp = “[(])” Output: Not Balanced " }, { "code": null, "e": 26108, "s": 26096, "text": "Algorithm: " }, { "code": null, "e": 26137, "s": 26108, "text": "Declare a character stack S." }, { "code": null, "e": 26455, "s": 26137, "text": "Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 26733, "s": 26455, "text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 26823, "s": 26733, "text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack." }, { "code": null, "e": 27012, "s": 26823, "text": "If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 27106, "s": 27012, "text": "After complete traversal, if there is some starting bracket left in stack then “not balanced”" }, { "code": null, "e": 27154, "s": 27106, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 27205, "s": 27154, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27209, "s": 27205, "text": "C++" }, { "code": "// CPP program to check for balanced brackets.#include <bits/stdc++.h>using namespace std; // function to check if brackets are balancedbool areBracketsBalanced(string expr){ stack<char> s; char x; // Traversing the Expression for (int i = 0; i < expr.length(); i++) { if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') { // Push the element in the stack s.push(expr[i]); continue; } // IF current current character is not opening // bracket, then it must be closing. So stack // cannot be empty at this point. if (s.empty()) return false; switch (expr[i]) { case ')': // Store the top element in a x = s.top(); s.pop(); if (x == '{' || x == '[') return false; break; case '}': // Store the top element in b x = s.top(); s.pop(); if (x == '(' || x == '[') return false; break; case ']': // Store the top element in c x = s.top(); s.pop(); if (x == '(' || x == '{') return false; break; } } // Check Empty Stack return (s.empty());} // Driver codeint main(){ string expr = \"{()}[]\"; // Function call if (areBracketsBalanced(expr)) cout << \"Balanced\"; else cout << \"Not Balanced\"; return 0;}", "e": 28744, "s": 27209, "text": null }, { "code": null, "e": 28753, "s": 28744, "text": "Balanced" }, { "code": null, "e": 28809, "s": 28753, "text": "Time Complexity: O(n) Auxiliary Space: O(n) for stack. " }, { "code": null, "e": 28935, "s": 28809, "text": "Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!" }, { "code": null, "e": 28942, "s": 28935, "text": "Amazon" }, { "code": null, "e": 28947, "s": 28942, "text": "Hike" }, { "code": null, "e": 28954, "s": 28947, "text": "Oracle" }, { "code": null, "e": 28975, "s": 28954, "text": "Parentheses-Problems" }, { "code": null, "e": 28984, "s": 28975, "text": "Snapdeal" }, { "code": null, "e": 28992, "s": 28984, "text": "Walmart" }, { "code": null, "e": 28998, "s": 28992, "text": "Wipro" }, { "code": null, "e": 29008, "s": 28998, "text": "Yatra.com" }, { "code": null, "e": 29013, "s": 29008, "text": "Zoho" }, { "code": null, "e": 29026, "s": 29013, "text": "C++ Programs" }, { "code": null, "e": 29032, "s": 29026, "text": "Stack" }, { "code": null, "e": 29040, "s": 29032, "text": "Strings" }, { "code": null, "e": 29045, "s": 29040, "text": "Zoho" }, { "code": null, "e": 29052, "s": 29045, "text": "Amazon" }, { "code": null, "e": 29061, "s": 29052, "text": "Snapdeal" }, { "code": null, "e": 29066, "s": 29061, "text": "Hike" }, { "code": null, "e": 29073, "s": 29066, "text": "Oracle" }, { "code": null, "e": 29081, "s": 29073, "text": "Walmart" }, { "code": null, "e": 29087, "s": 29081, "text": "Wipro" }, { "code": null, "e": 29097, "s": 29087, "text": "Yatra.com" }, { "code": null, "e": 29105, "s": 29097, "text": "Strings" }, { "code": null, "e": 29111, "s": 29105, "text": "Stack" }, { "code": null, "e": 29209, "s": 29111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29250, "s": 29209, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 29309, "s": 29250, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 29330, "s": 29309, "text": "Const keyword in C++" }, { "code": null, "e": 29342, "s": 29330, "text": "cout in C++" }, { "code": null, "e": 29363, "s": 29342, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 29411, "s": 29363, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 29431, "s": 29411, "text": "Stack Class in Java" }, { "code": null, "e": 29447, "s": 29431, "text": "Stack in Python" }, { "code": null, "e": 29522, "s": 29447, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python Program to Rotate Matrix Elements - GeeksforGeeks
28 Dec, 2021 Given a matrix, clockwise rotate elements in it. Examples: Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12 The idea is to use loops similar to the program for printing a matrix in spiral form. One by one rotate all rings of elements, starting from the outermost. To rotate a ring, we need to do following. 1) Move elements of top row. 2) Move elements of last column. 3) Move elements of bottom row. 4) Move elements of first column. Repeat above steps for inner ring while there is an inner ring. Below is the implementation of above idea. Thanks to Gaurav Ahirwar for suggesting below solution. Python # Python program to rotate a matrix # Function to rotate a matrixdef rotateMatrix(mat): if not len(mat): return """ top : starting row index bottom : ending row index left : starting column index right : ending column index """ top = 0 bottom = len(mat)-1 left = 0 right = len(mat[0])-1 while left < right and top < bottom: # Store the first element of next row, # this element will replace first element of # current row prev = mat[top+1][left] # Move elements of top row one step right for i in range(left, right+1): curr = mat[top][i] mat[top][i] = prev prev = curr top += 1 # Move elements of rightmost column one step downwards for i in range(top, bottom+1): curr = mat[i][right] mat[i][right] = prev prev = curr right -= 1 # Move elements of bottom row one step left for i in range(right, left-1, -1): curr = mat[bottom][i] mat[bottom][i] = prev prev = curr bottom -= 1 # Move elements of leftmost column one step upwards for i in range(bottom, top-1, -1): curr = mat[i][left] mat[i][left] = prev prev = curr left += 1 return mat # Utility Functiondef printMatrix(mat): for row in mat: print row # Test case 1matrix =[ [1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]# Test case 2"""matrix =[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]""" matrix = rotateMatrix(matrix)# Print modified matrixprintMatrix(matrix) Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12 Please refer complete article on Rotate Matrix Elements for more details! Amazon rotation Zoho Matrix Python Python Programs Zoho Amazon Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26159, "s": 26131, "text": "\n28 Dec, 2021" }, { "code": null, "e": 26208, "s": 26159, "text": "Given a matrix, clockwise rotate elements in it." }, { "code": null, "e": 26218, "s": 26208, "text": "Examples:" }, { "code": null, "e": 26480, "s": 26218, "text": "Input\n1 2 3\n4 5 6\n7 8 9\n\nOutput:\n4 1 2\n7 5 3\n8 9 6\n\nFor 4*4 matrix\nInput:\n1 2 3 4 \n5 6 7 8\n9 10 11 12\n13 14 15 16\n\nOutput:\n5 1 2 3\n9 10 6 4\n13 11 7 8\n14 15 16 12" }, { "code": null, "e": 26887, "s": 26480, "text": "The idea is to use loops similar to the program for printing a matrix in spiral form. One by one rotate all rings of elements, starting from the outermost. To rotate a ring, we need to do following. 1) Move elements of top row. 2) Move elements of last column. 3) Move elements of bottom row. 4) Move elements of first column. Repeat above steps for inner ring while there is an inner ring." }, { "code": null, "e": 26987, "s": 26887, "text": "Below is the implementation of above idea. Thanks to Gaurav Ahirwar for suggesting below solution. " }, { "code": null, "e": 26994, "s": 26987, "text": "Python" }, { "code": "# Python program to rotate a matrix # Function to rotate a matrixdef rotateMatrix(mat): if not len(mat): return \"\"\" top : starting row index bottom : ending row index left : starting column index right : ending column index \"\"\" top = 0 bottom = len(mat)-1 left = 0 right = len(mat[0])-1 while left < right and top < bottom: # Store the first element of next row, # this element will replace first element of # current row prev = mat[top+1][left] # Move elements of top row one step right for i in range(left, right+1): curr = mat[top][i] mat[top][i] = prev prev = curr top += 1 # Move elements of rightmost column one step downwards for i in range(top, bottom+1): curr = mat[i][right] mat[i][right] = prev prev = curr right -= 1 # Move elements of bottom row one step left for i in range(right, left-1, -1): curr = mat[bottom][i] mat[bottom][i] = prev prev = curr bottom -= 1 # Move elements of leftmost column one step upwards for i in range(bottom, top-1, -1): curr = mat[i][left] mat[i][left] = prev prev = curr left += 1 return mat # Utility Functiondef printMatrix(mat): for row in mat: print row # Test case 1matrix =[ [1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]# Test case 2\"\"\"matrix =[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]\"\"\" matrix = rotateMatrix(matrix)# Print modified matrixprintMatrix(matrix)", "e": 28778, "s": 26994, "text": null }, { "code": null, "e": 28787, "s": 28778, "text": "Output: " }, { "code": null, "e": 28826, "s": 28787, "text": "5 1 2 3\n9 10 6 4\n13 11 7 8\n14 15 16 12" }, { "code": null, "e": 28900, "s": 28826, "text": "Please refer complete article on Rotate Matrix Elements for more details!" }, { "code": null, "e": 28907, "s": 28900, "text": "Amazon" }, { "code": null, "e": 28916, "s": 28907, "text": "rotation" }, { "code": null, "e": 28921, "s": 28916, "text": "Zoho" }, { "code": null, "e": 28928, "s": 28921, "text": "Matrix" }, { "code": null, "e": 28935, "s": 28928, "text": "Python" }, { "code": null, "e": 28951, "s": 28935, "text": "Python Programs" }, { "code": null, "e": 28956, "s": 28951, "text": "Zoho" }, { "code": null, "e": 28963, "s": 28956, "text": "Amazon" }, { "code": null, "e": 28970, "s": 28963, "text": "Matrix" }, { "code": null, "e": 29068, "s": 28970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29130, "s": 29068, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 29201, "s": 29130, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 29234, "s": 29201, "text": "Program to multiply two matrices" }, { "code": null, "e": 29255, "s": 29234, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 29297, "s": 29255, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 29325, "s": 29297, "text": "Read JSON file using Python" }, { "code": null, "e": 29375, "s": 29325, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29397, "s": 29375, "text": "Python map() function" } ]
CPU Scheduling in Operating Systems using priority queue with gantt chart - GeeksforGeeks
22 Apr, 2020 Prerequisite: CPU Scheduling in Operating SystemsDifferent Scheduling Algorithms: First Come First Serve CPU Scheduling:Simplest scheduling algorithm that schedules according to arrival times of processes. First come first serve scheduling algorithm states that the process that requests the CPU first is allocated the CPU first. It is implemented by using the FIFO queue. When a process enters the ready queue, its PCB is linked onto the tail of the queue. When the CPU is free, it is allocated to the process at the head of the queue. The running process is then removed from the queue. FCFS is a non-preemptive scheduling algorithm.Shortest Job First(Preemptive):In Preemptive Shortest Job First Scheduling, jobs are put into the ready queue as they arrive, but as a process with short burst time arrives, the existing process is preempted or removed from execution, and the shorter job is executed first.Shortest Job First(Non-Preemptive):In Non-Preemptive Shortest Job First, a process which has the shortest burst time is scheduled first. If two processes have the same bust time then FCFS is used to break the tie.Longest Job First(Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the largest burst time remaining.Longest Job First(Non-Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the longest burst time. This is non-preemptive in nature i.e., when any process starts executing, can’t be interrupted before complete execution.Round Robin Scheduling:To implement Round Robin scheduling, we keep the ready queue as a FIFO queue of processes. New processes are added to the tail of the ready queue. The CPU scheduler picks the first process from the ready queue, sets a timer to interrupt after 1-time quantum, and dispatches the process. One of two things will then happen. The process may have a CPU burst of less than 1-time quantum. In this case, the process itself will release the CPU voluntarily. The scheduler will then proceed to the next process in the ready queue. Otherwise, if the CPU burst of the currently running process is longer than 1-time quantum, the timer will go off and will cause an interrupt to the operating system. A context switch will be executed, and the process will be put at the tail of the ready queue. The CPU scheduler will then select the next process in the ready queue.Priority Based(Preemptive) Scheduling:In Preemptive Priority Scheduling, at the time of arrival of a process in the ready queue, its priority is compared with the priority of the other processes present in the ready queue as well as with the one which is being executed by the CPU at that point of time. The One with the highest priority among all the available processes will be given the CPU next. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority.Priority Based(Non-Preemptive) Scheduling:In the Non Preemptive Priority scheduling, The Processes are scheduled according to the priority number assigned to them. Once the process gets scheduled, it will run till the completion. Generally, the lower the priority number, the higher is the priority of the process. The people might get confused with the priority numbers, hence in the GATE, there clearly mention which one is the highest priority and which one is the lowest one. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority.Highest Response Ratio Next(HRRN) Scheduling:Highest Response Ratio Next (HRRN) is one of the most optimal scheduling algorithms. This is a non-preemptive algorithm in which, the scheduling is done on the basis of an extra parameter called Response Ratio. A Response Ratio is calculated for each of the available jobs and the Job with the highest response ratio is given priority over the others. First Come First Serve CPU Scheduling:Simplest scheduling algorithm that schedules according to arrival times of processes. First come first serve scheduling algorithm states that the process that requests the CPU first is allocated the CPU first. It is implemented by using the FIFO queue. When a process enters the ready queue, its PCB is linked onto the tail of the queue. When the CPU is free, it is allocated to the process at the head of the queue. The running process is then removed from the queue. FCFS is a non-preemptive scheduling algorithm. Shortest Job First(Preemptive):In Preemptive Shortest Job First Scheduling, jobs are put into the ready queue as they arrive, but as a process with short burst time arrives, the existing process is preempted or removed from execution, and the shorter job is executed first. Shortest Job First(Non-Preemptive):In Non-Preemptive Shortest Job First, a process which has the shortest burst time is scheduled first. If two processes have the same bust time then FCFS is used to break the tie. Longest Job First(Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the largest burst time remaining. Longest Job First(Non-Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the longest burst time. This is non-preemptive in nature i.e., when any process starts executing, can’t be interrupted before complete execution. Round Robin Scheduling:To implement Round Robin scheduling, we keep the ready queue as a FIFO queue of processes. New processes are added to the tail of the ready queue. The CPU scheduler picks the first process from the ready queue, sets a timer to interrupt after 1-time quantum, and dispatches the process. One of two things will then happen. The process may have a CPU burst of less than 1-time quantum. In this case, the process itself will release the CPU voluntarily. The scheduler will then proceed to the next process in the ready queue. Otherwise, if the CPU burst of the currently running process is longer than 1-time quantum, the timer will go off and will cause an interrupt to the operating system. A context switch will be executed, and the process will be put at the tail of the ready queue. The CPU scheduler will then select the next process in the ready queue. Priority Based(Preemptive) Scheduling:In Preemptive Priority Scheduling, at the time of arrival of a process in the ready queue, its priority is compared with the priority of the other processes present in the ready queue as well as with the one which is being executed by the CPU at that point of time. The One with the highest priority among all the available processes will be given the CPU next. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority. Priority Based(Non-Preemptive) Scheduling:In the Non Preemptive Priority scheduling, The Processes are scheduled according to the priority number assigned to them. Once the process gets scheduled, it will run till the completion. Generally, the lower the priority number, the higher is the priority of the process. The people might get confused with the priority numbers, hence in the GATE, there clearly mention which one is the highest priority and which one is the lowest one. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority. Highest Response Ratio Next(HRRN) Scheduling:Highest Response Ratio Next (HRRN) is one of the most optimal scheduling algorithms. This is a non-preemptive algorithm in which, the scheduling is done on the basis of an extra parameter called Response Ratio. A Response Ratio is calculated for each of the available jobs and the Job with the highest response ratio is given priority over the others. Consider the following table: Below is the implementation of the above algorithms using a priority queue: FCFS SJF-P SJF-NP LJF-P LJF-NP RR PB-P PB-NP HRRN // C++ implementation of the FCFS algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std; class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } // Function to set starting Arrival Time // Because arrival time gets updated // when you push process in ready queue again // in preemptive algorithms void P_set() { start_AT = AT; BT_left = BT; } // Function to set Response Time void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement FCFS algorithmpriority_queue<process> FCFS_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; // Till ready queue is not empty while (!ready_queue.empty()) { // While clock is less than // Arrival Time while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = ready_queue.top(); ready_queue.pop(); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); // Update the Gantt Chart (*gantt).push(p); p.temp_BT = 0; // Update the completion time to // the queue completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion Queue and// all the timevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; // For 1st row of gantt chart while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; // For process no. in 2nd row while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << (string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-')) << "+"; spaces.pop(); } spaces = gantt; cout << "\n0";//For 3rd row of gantt chart while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << (string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ')) << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue; priority_queue<process> completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call for completion data completion_queue = FCFS_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 4 | 4 | 0 | 0 | | 2 | 1 | 2 | 6 | 5 | 3 | 3 | | 3 | 2 | 3 | 9 | 7 | 4 | 4 | | 4 | 3 | 5 | 14 | 11 | 6 | 6 | | 5 | 4 | 1 | 15 | 11 | 10 | 10 | | 6 | 5 | 4 | 19 | 14 | 10 | 10 | | 7 | 6 | 6 | 25 | 19 | 13 | 13 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 92 Average completion time :- 13.1429 Total turnaround time :- 71 Average turnaround time :- 10.1429 Total waiting time :- 46 Average waiting time :- 6.57143 Total response time :- 46 Average response time :- 6.57143 Gantt Chart (IS indicates ideal state) :- +----------+------+--------+------------+----+----------+--------------+ | P1 | P2 | P3 | P4 | P5 | P6 | P7 | +----------+------+--------+------------+----+----------+--------------+ 0 4 6 9 14 15 19 25 // C++ implementation of the SJF preemptive algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std; class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;}time_t min_BT(priority_queue<process> main_queue, time_t clock){ time_t min = 0; while (!main_queue.empty() && main_queue.top().AT <= clock) { if (min == 0 || min > main_queue.top().BT_left) min = main_queue.top().BT_left; main_queue.pop(); } return min;}int min_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t min = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (min == 0 || main_queue.top().BT_left < min) { min = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement SJF preemptive algorithmpriority_queue<process> SJF_P_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, min_BT_index(ready_queue, clock)); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.BT_left <= min_BT(ready_queue, clock))) { p.BT_left--; p.temp_BT++; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion Queue// and all the timevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialize Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call for completion data completion_queue = SJF_P_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 7 | 7 | 3 | 0 | | 2 | 1 | 2 | 3 | 2 | 0 | 0 | | 3 | 2 | 3 | 10 | 8 | 5 | 5 | | 4 | 3 | 5 | 19 | 16 | 11 | 11 | | 5 | 4 | 1 | 5 | 1 | 0 | 0 | | 6 | 5 | 4 | 14 | 9 | 5 | 5 | | 7 | 6 | 6 | 25 | 19 | 13 | 13 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 83 Average completion time :- 11.8571 Total turnaround time :- 62 Average turnaround time :- 8.85714 Total waiting time :- 37 Average waiting time :- 5.28571 Total response time :- 34 Average response time :- 4.85714 Gantt Chart (IS indicates ideal state) :- +----+------+----+----+------+--------+----------+------------+--------------+ | P1 | P2 | P1 | P5 | P1 | P3 | P6 | P4 | P7 | +----+------+----+----+------+--------+----------+------------+--------------+ 0 1 3 4 5 7 10 14 19 25 // C++ implementation of the SJF(Non-preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implementation pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to find index of process//with minimum BTint min_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t min = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (min == 0 || main_queue.top().BT_left < min) { min = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement SJF(Non-preemptive)priority_queue<process> SJF_NP_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, min_BT_index(ready_queue, clock)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;}//Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display the queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = SJF_NP_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 4 | 4 | 0 | 0 | | 2 | 1 | 2 | 7 | 6 | 4 | 4 | | 3 | 2 | 3 | 10 | 8 | 5 | 5 | | 4 | 3 | 5 | 19 | 16 | 11 | 11 | | 5 | 4 | 1 | 5 | 1 | 0 | 0 | | 6 | 5 | 4 | 14 | 9 | 5 | 5 | | 7 | 6 | 6 | 25 | 19 | 13 | 13 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 84 Average completion time :- 12 Total turnaround time :- 63 Average turnaround time :- 9 Total waiting time :- 38 Average waiting time :- 5.42857 Total response time :- 38 Average response time :- 5.42857 Gantt Chart (IS indicates ideal state) :- +----------+----+------+--------+----------+------------+--------------+ | P1 | P5 | P2 | P3 | P6 | P4 | P7 | +----------+----+------+--------+----------+------------+--------------+ 0 4 5 7 10 14 19 25 // C++ implementation of the LJF(Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implementation pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to implement maximum Burst Timetime_t max_BT(priority_queue<process> main_queue, time_t limit){ time_t max = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().BT_left > max) max = main_queue.top().BT_left; main_queue.pop(); } return max;} // Function to implement maximum BT index w.r.t given clock limitint max_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t max = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().BT_left > max) { max = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement LJF(Preemptive) algorithmpriority_queue<process> LJF_P_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_BT_index(ready_queue, clock)); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.BT_left >= max_BT(ready_queue, clock))) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion Queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = LJF_P_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 23 | 23 | 19 | 0 | | 2 | 1 | 2 | 22 | 21 | 19 | 12 | | 3 | 2 | 3 | 24 | 22 | 19 | 0 | | 4 | 3 | 5 | 19 | 16 | 11 | 0 | | 5 | 4 | 1 | 20 | 16 | 15 | 15 | | 6 | 5 | 4 | 21 | 16 | 12 | 0 | | 7 | 6 | 6 | 25 | 19 | 13 | 0 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 154 Average completion time :- 22 Total turnaround time :- 133 Average turnaround time :- 19 Total waiting time :- 108 Average waiting time :- 15.4286 Total response time :- 27 Average response time :- 3.85714 Gantt Chart (IS indicates ideal state) :- +------+----+------+----+----------+----+------+----+----+----+----+------+----+----+----+----+----+----+ | P1 | P3 | P4 | P6 | P7 | P4 | P6 | P2 | P1 | P3 | P7 | P4 | P5 | P6 | P2 | P1 | P3 | P7 | +------+----+------+----+----------+----+------+----+----+----+----+------+----+----+----+----+----+----+ 0 2 3 5 6 10 11 13 14 15 16 17 19 20 21 22 23 24 25 // C++ implementation of the LJF(Non-Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to find maximum Burst Time Index w.r.t clock limitint max_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t max = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().BT_left > max) { max = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement LJF(Non-Preemptive) Algorithmpriority_queue<process> LJF_NP_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.set_CT(clock); (*gantt).push(p); } p = pop_index(&ready_queue, max_BT_index(ready_queue, clock)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = LJF_NP_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 4 | 4 | 0 | 0 | | 2 | 1 | 2 | 24 | 23 | 21 | 21 | | 3 | 2 | 3 | 22 | 20 | 17 | 17 | | 4 | 3 | 5 | 9 | 6 | 1 | 1 | | 5 | 4 | 1 | 25 | 21 | 20 | 20 | | 6 | 5 | 4 | 19 | 14 | 10 | 10 | | 7 | 6 | 6 | 15 | 9 | 3 | 3 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 118 Average completion time :- 16.8571 Total turnaround time :- 97 Average turnaround time :- 13.8571 Total waiting time :- 72 Average waiting time :- 10.2857 Total response time :- 72 Average response time :- 10.2857 Gantt Chart (IS indicates ideal state) :- +----------+------------+--------------+----------+--------+------+----+ | P1 | P4 | P7 | P6 | P3 | P2 | P5 | +----------+------------+--------------+----------+--------+------+----+ 0 4 9 15 19 22 24 25 // C++ implementation of the Round Robin algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement Round Robin algorithmpriority_queue<process> RR_run(priority_queue<process> ready_queue, time_t Time_Slice, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = ready_queue.top(); ready_queue.pop(); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (p.temp_BT < Time_Slice || ready_queue.empty() || clock < ready_queue.top().AT)) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; // Time quantum for round robin int tq = 2; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = RR_run(ready_queue, tq, &gantt); // Display Completion Queue disp(completion_queue, false); cout << "\nTime Quantum for round robin :- " << tq << endl; // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 8 | 8 | 4 | 0 | | 2 | 1 | 2 | 4 | 3 | 1 | 1 | | 3 | 2 | 3 | 16 | 14 | 11 | 2 | | 4 | 3 | 5 | 23 | 20 | 15 | 5 | | 5 | 4 | 1 | 11 | 7 | 6 | 6 | | 6 | 5 | 4 | 20 | 15 | 11 | 6 | | 7 | 6 | 6 | 25 | 19 | 13 | 7 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 107 Average completion time :- 15.2857 Total turnaround time :- 86 Average turnaround time :- 12.2857 Total waiting time :- 61 Average waiting time :- 8.71429 Total response time :- 27 Average response time :- 3.85714 Time Quantum for round robin :- 2 Gantt Chart (IS indicates ideal state) :- +------+------+------+------+------+----+------+------+----+------+------+------+----+------+ | P1 | P2 | P3 | P1 | P4 | P5 | P6 | P7 | P3 | P4 | P6 | P7 | P4 | P7 | +------+------+------+------+------+----+------+------+----+------+------+------+----+------+ 0 2 4 6 8 10 11 13 15 16 18 20 22 23 25 // C++ implementation of the Priority Based(Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to implement maximum priority w.r.t//priority and also 2nd argument has boolean//variable because we need to specify// True=highest number as highest priority// False=lowest number as highest priorityint max_priority(priority_queue<process> main_priority_queue, int limit, bool high){ int max = -1; if (high == 1) { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (main_priority_queue.top().priority > max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } else { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (max == -1 || main_priority_queue.top().priority < max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } return max;} // Function to implement maximum priority indexint max_priority_index(priority_queue<process> main_queue, int limit, bool high){ int max = -1, i = 0, index = 0; if (high == 1) { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().priority > max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } else { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (max == -1 || main_queue.top().priority < max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } return index;} // Function to implement priority based Preemptive schedulingpriority_queue<process> Priority_P_run(priority_queue<process> ready_queue, queue<process>* gantt, bool high){ int temp; priority_queue<process> completion_queue; process p; time_t clock = 0; if (high == 1) { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.priority >= max_priority(ready_queue, clock, high))) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } } else { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); if (p.AT == p.start_AT) p.set_RT(clock); temp = max_priority(ready_queue, clock, high); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.priority <= max_priority(ready_queue, clock, high))) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display main queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data//3rd argument has true passed becuase we have set//highest number = highest priority completion_queue = Priority_P_run(ready_queue, &gantt, true); // Display Completion Queue as true in//2nd argument to display priority disp(completion_queue, true); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | Priority | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+ | 1 | 0 | 4 | 25 | 25 | 21 | 0 | 2 | | 2 | 1 | 2 | 22 | 21 | 19 | 0 | 4 | | 3 | 2 | 3 | 21 | 19 | 16 | 0 | 6 | | 4 | 3 | 5 | 12 | 9 | 4 | 0 | 10 | | 5 | 4 | 1 | 19 | 15 | 14 | 14 | 8 | | 6 | 5 | 4 | 9 | 4 | 0 | 0 | 12 | | 7 | 6 | 6 | 18 | 12 | 6 | 6 | 9 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+ Total completion time :- 126 Average completion time :- 18 Total turnaround time :- 105 Average turnaround time :- 15 Total waiting time :- 80 Average waiting time :- 11.4286 Total response time :- 20 Average response time :- 2.85714 Gantt Chart (IS indicates ideal state) :- +----+----+----+------+----------+--------+--------------+----+------+----+--------+ | P1 | P2 | P3 | P4 | P6 | P4 | P7 | P5 | P3 | P2 | P1 | +----+----+----+------+----------+--------+--------------+----+------+----+--------+ 0 1 2 3 5 9 12 18 19 21 22 25 // C++ implementation of the Priority Based(Non-Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} //Function to implement maximum priority w.r.t clock limit// and 3rd parameter as bool because we need true = highest//number as highest and false as lowest number as highest priorityint max_priority(priority_queue<process> main_priority_queue, int limit, bool high){ int max = -1; if (high == 1) { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (main_priority_queue.top().priority > max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } else { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (max == -1 || main_priority_queue.top().priority < max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } return max;} // Function to implement maximum priority indexint max_priority_index(priority_queue<process> main_queue, int limit, bool high){ int max = -1, i = 0, index = 0; if (high == 1) { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().priority > max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } else { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (max == -1 || main_queue.top().priority < max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } return index;} // Function to implement priority based Preemptive schedulingpriority_queue<process> Priority_NP_run(priority_queue<process> ready_queue, queue<process>* gantt, bool high){ priority_queue<process> completion_queue; process p; time_t clock = 0; if (high == 1) { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } } else { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display main queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data//and true is passed as 3rd argument because we//are considering highest number as highest priority completion_queue = Priority_NP_run(ready_queue, &gantt, true); // Display Completion Queue disp(completion_queue, true); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | Priority | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+ | 1 | 0 | 4 | 4 | 4 | 0 | 0 | 2 | | 2 | 1 | 2 | 25 | 24 | 22 | 22 | 4 | | 3 | 2 | 3 | 23 | 21 | 18 | 18 | 6 | | 4 | 3 | 5 | 9 | 6 | 1 | 1 | 10 | | 5 | 4 | 1 | 20 | 16 | 15 | 15 | 8 | | 6 | 5 | 4 | 13 | 8 | 4 | 4 | 12 | | 7 | 6 | 6 | 19 | 13 | 7 | 7 | 9 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+ Total completion time :- 113 Average completion time :- 16.1429 Total turnaround time :- 92 Average turnaround time :- 13.1429 Total waiting time :- 67 Average waiting time :- 9.57143 Total response time :- 67 Average response time :- 9.57143 Gantt Chart (IS indicates ideal state) :- +----------+------------+----------+--------------+----+--------+------+ | P1 | P4 | P6 | P7 | P5 | P3 | P2 | +----------+------------+----------+--------------+----+--------+------+ 0 4 9 13 19 20 23 25 // C++ implementation of the HRRN Scheduling#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to implement maximum Response Ratio// index w.r.t clock limit for arrival timeint max_response_ratio_index(priority_queue<process> ready_queue, time_t limit){ int index, i = 0; double response_ratio = 0, max = 0; while (!ready_queue.empty() && ready_queue.top().AT <= limit) { response_ratio = ((double)(limit - ready_queue.top().AT) + ready_queue.top().BT_left) / ready_queue.top().BT_left; if (response_ratio > max) { max = response_ratio; index = i; } i++; ready_queue.pop(); } return index;} // Function to implement HRRN Schedulingpriority_queue<process> HRRN_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_response_ratio_index(ready_queue, clock)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display main queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; cout << "| Process No. | Arrival Time "; cout << "| Burst Time | Completion Time "; cout << "| Turnaround Time | Waiting Time | Response Time |"; if (high == true) cout << " Priority |" << endl; else cout << endl; cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << "|\n"; main_queue.pop(); } cout << "+-------------+--------------"; cout << "+------------+-----------------"; cout << "+-----------------+--------------+---------------+"; if (high == true) cout << "----------+"; cout << endl; temp1 = get_total_CT(tempq); cout << "\nTotal completion time :- " << temp1 << endl; cout << "Average completion time :- " << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << "\nTotal turnaround time :- " << temp1 << endl; cout << "Average turnaround time :- " << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << "\nTotal waiting time :- " << temp1 << endl; cout << "Average waiting time :- " << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << "\nTotal response time :- " << temp1 << endl; cout << "Average response time :- " << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << "\n\nGantt Chart (IS indicates ideal state) :- \n\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } cout << "\n|"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << "IS" << string(spaces.front().temp_BT, ' ') << '|'; else cout << "P" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << "\n+"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << "+"; spaces.pop(); } spaces = gantt; cout << "\n0"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << "\n\n";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = HRRN_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;} OUTPUT :- +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ | 1 | 0 | 4 | 4 | 4 | 0 | 0 | | 2 | 1 | 2 | 6 | 5 | 3 | 3 | | 3 | 2 | 3 | 10 | 8 | 5 | 5 | | 4 | 3 | 5 | 15 | 12 | 7 | 7 | | 5 | 4 | 1 | 7 | 3 | 2 | 2 | | 6 | 5 | 4 | 19 | 14 | 10 | 10 | | 7 | 6 | 6 | 25 | 19 | 13 | 13 | +-------------+--------------+------------+-----------------+-----------------+--------------+---------------+ Total completion time :- 86 Average completion time :- 12.2857 Total turnaround time :- 65 Average turnaround time :- 9.28571 Total waiting time :- 40 Average waiting time :- 5.71429 Total response time :- 40 Average response time :- 5.71429 Gantt Chart (IS indicates ideal state) :- +----------+------+----+--------+------------+----------+--------------+ | P1 | P2 | P5 | P3 | P4 | P6 | P7 | +----------+------+----+--------+------------+----------+--------------+ 0 4 6 7 10 15 19 25 jaspreetsinghpal18 cpu-scheduling Data Structures Operating Systems-CPU Scheduling Algorithms Operating Systems Queue Data Structures Operating Systems Queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Types of Operating Systems Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 25943, "s": 25915, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26025, "s": 25943, "text": "Prerequisite: CPU Scheduling in Operating SystemsDifferent Scheduling Algorithms:" }, { "code": null, "e": 29965, "s": 26025, "text": "First Come First Serve CPU Scheduling:Simplest scheduling algorithm that schedules according to arrival times of processes. First come first serve scheduling algorithm states that the process that requests the CPU first is allocated the CPU first. It is implemented by using the FIFO queue. When a process enters the ready queue, its PCB is linked onto the tail of the queue. When the CPU is free, it is allocated to the process at the head of the queue. The running process is then removed from the queue. FCFS is a non-preemptive scheduling algorithm.Shortest Job First(Preemptive):In Preemptive Shortest Job First Scheduling, jobs are put into the ready queue as they arrive, but as a process with short burst time arrives, the existing process is preempted or removed from execution, and the shorter job is executed first.Shortest Job First(Non-Preemptive):In Non-Preemptive Shortest Job First, a process which has the shortest burst time is scheduled first. If two processes have the same bust time then FCFS is used to break the tie.Longest Job First(Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the largest burst time remaining.Longest Job First(Non-Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the longest burst time. This is non-preemptive in nature i.e., when any process starts executing, can’t be interrupted before complete execution.Round Robin Scheduling:To implement Round Robin scheduling, we keep the ready queue as a FIFO queue of processes. New processes are added to the tail of the ready queue. The CPU scheduler picks the first process from the ready queue, sets a timer to interrupt after 1-time quantum, and dispatches the process. One of two things will then happen. The process may have a CPU burst of less than 1-time quantum. In this case, the process itself will release the CPU voluntarily. The scheduler will then proceed to the next process in the ready queue. Otherwise, if the CPU burst of the currently running process is longer than 1-time quantum, the timer will go off and will cause an interrupt to the operating system. A context switch will be executed, and the process will be put at the tail of the ready queue. The CPU scheduler will then select the next process in the ready queue.Priority Based(Preemptive) Scheduling:In Preemptive Priority Scheduling, at the time of arrival of a process in the ready queue, its priority is compared with the priority of the other processes present in the ready queue as well as with the one which is being executed by the CPU at that point of time. The One with the highest priority among all the available processes will be given the CPU next. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority.Priority Based(Non-Preemptive) Scheduling:In the Non Preemptive Priority scheduling, The Processes are scheduled according to the priority number assigned to them. Once the process gets scheduled, it will run till the completion. Generally, the lower the priority number, the higher is the priority of the process. The people might get confused with the priority numbers, hence in the GATE, there clearly mention which one is the highest priority and which one is the lowest one. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority.Highest Response Ratio Next(HRRN) Scheduling:Highest Response Ratio Next (HRRN) is one of the most optimal scheduling algorithms. This is a non-preemptive algorithm in which, the scheduling is done on the basis of an extra parameter called Response Ratio. A Response Ratio is calculated for each of the available jobs and the Job with the highest response ratio is given priority over the others." }, { "code": null, "e": 30519, "s": 29965, "text": "First Come First Serve CPU Scheduling:Simplest scheduling algorithm that schedules according to arrival times of processes. First come first serve scheduling algorithm states that the process that requests the CPU first is allocated the CPU first. It is implemented by using the FIFO queue. When a process enters the ready queue, its PCB is linked onto the tail of the queue. When the CPU is free, it is allocated to the process at the head of the queue. The running process is then removed from the queue. FCFS is a non-preemptive scheduling algorithm." }, { "code": null, "e": 30793, "s": 30519, "text": "Shortest Job First(Preemptive):In Preemptive Shortest Job First Scheduling, jobs are put into the ready queue as they arrive, but as a process with short burst time arrives, the existing process is preempted or removed from execution, and the shorter job is executed first." }, { "code": null, "e": 31007, "s": 30793, "text": "Shortest Job First(Non-Preemptive):In Non-Preemptive Shortest Job First, a process which has the shortest burst time is scheduled first. If two processes have the same bust time then FCFS is used to break the tie." }, { "code": null, "e": 31191, "s": 31007, "text": "Longest Job First(Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the largest burst time remaining." }, { "code": null, "e": 31491, "s": 31191, "text": "Longest Job First(Non-Preemptive):It is similar to an SJF scheduling algorithm. But, in this scheduling algorithm, we give priority to the process having the longest burst time. This is non-preemptive in nature i.e., when any process starts executing, can’t be interrupted before complete execution." }, { "code": null, "e": 32372, "s": 31491, "text": "Round Robin Scheduling:To implement Round Robin scheduling, we keep the ready queue as a FIFO queue of processes. New processes are added to the tail of the ready queue. The CPU scheduler picks the first process from the ready queue, sets a timer to interrupt after 1-time quantum, and dispatches the process. One of two things will then happen. The process may have a CPU burst of less than 1-time quantum. In this case, the process itself will release the CPU voluntarily. The scheduler will then proceed to the next process in the ready queue. Otherwise, if the CPU burst of the currently running process is longer than 1-time quantum, the timer will go off and will cause an interrupt to the operating system. A context switch will be executed, and the process will be put at the tail of the ready queue. The CPU scheduler will then select the next process in the ready queue." }, { "code": null, "e": 32904, "s": 32372, "text": "Priority Based(Preemptive) Scheduling:In Preemptive Priority Scheduling, at the time of arrival of a process in the ready queue, its priority is compared with the priority of the other processes present in the ready queue as well as with the one which is being executed by the CPU at that point of time. The One with the highest priority among all the available processes will be given the CPU next. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority." }, { "code": null, "e": 33516, "s": 32904, "text": "Priority Based(Non-Preemptive) Scheduling:In the Non Preemptive Priority scheduling, The Processes are scheduled according to the priority number assigned to them. Once the process gets scheduled, it will run till the completion. Generally, the lower the priority number, the higher is the priority of the process. The people might get confused with the priority numbers, hence in the GATE, there clearly mention which one is the highest priority and which one is the lowest one. In this program, we have both options, whether to consider highest number as highest priority or lowest number as highest priority." }, { "code": null, "e": 33913, "s": 33516, "text": "Highest Response Ratio Next(HRRN) Scheduling:Highest Response Ratio Next (HRRN) is one of the most optimal scheduling algorithms. This is a non-preemptive algorithm in which, the scheduling is done on the basis of an extra parameter called Response Ratio. A Response Ratio is calculated for each of the available jobs and the Job with the highest response ratio is given priority over the others." }, { "code": null, "e": 33943, "s": 33913, "text": "Consider the following table:" }, { "code": null, "e": 34019, "s": 33943, "text": "Below is the implementation of the above algorithms using a priority queue:" }, { "code": null, "e": 34024, "s": 34019, "text": "FCFS" }, { "code": null, "e": 34030, "s": 34024, "text": "SJF-P" }, { "code": null, "e": 34037, "s": 34030, "text": "SJF-NP" }, { "code": null, "e": 34043, "s": 34037, "text": "LJF-P" }, { "code": null, "e": 34050, "s": 34043, "text": "LJF-NP" }, { "code": null, "e": 34053, "s": 34050, "text": "RR" }, { "code": null, "e": 34058, "s": 34053, "text": "PB-P" }, { "code": null, "e": 34064, "s": 34058, "text": "PB-NP" }, { "code": null, "e": 34069, "s": 34064, "text": "HRRN" }, { "code": "// C++ implementation of the FCFS algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std; class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } // Function to set starting Arrival Time // Because arrival time gets updated // when you push process in ready queue again // in preemptive algorithms void P_set() { start_AT = AT; BT_left = BT; } // Function to set Response Time void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement FCFS algorithmpriority_queue<process> FCFS_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; // Till ready queue is not empty while (!ready_queue.empty()) { // While clock is less than // Arrival Time while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = ready_queue.top(); ready_queue.pop(); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); // Update the Gantt Chart (*gantt).push(p); p.temp_BT = 0; // Update the completion time to // the queue completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion Queue and// all the timevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; // For 1st row of gantt chart while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; // For process no. in 2nd row while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << (string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-')) << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\";//For 3rd row of gantt chart while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << (string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ')) << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue; priority_queue<process> completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call for completion data completion_queue = FCFS_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 43992, "s": 34069, "text": null }, { "code": null, "e": 44002, "s": 43992, "text": "OUTPUT :-" }, { "code": null, "e": 45811, "s": 44002, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 4 | 4 | 0 | 0 |\n| 2 | 1 | 2 | 6 | 5 | 3 | 3 |\n| 3 | 2 | 3 | 9 | 7 | 4 | 4 |\n| 4 | 3 | 5 | 14 | 11 | 6 | 6 |\n| 5 | 4 | 1 | 15 | 11 | 10 | 10 |\n| 6 | 5 | 4 | 19 | 14 | 10 | 10 |\n| 7 | 6 | 6 | 25 | 19 | 13 | 13 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 92\nAverage completion time :- 13.1429\n\nTotal turnaround time :- 71\nAverage turnaround time :- 10.1429\n\nTotal waiting time :- 46\nAverage waiting time :- 6.57143\n\nTotal response time :- 46\nAverage response time :- 6.57143\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----------+------+--------+------------+----+----------+--------------+\n| P1 | P2 | P3 | P4 | P5 | P6 | P7 |\n+----------+------+--------+------------+----+----------+--------------+\n0 4 6 9 14 15 19 25\n\n\n\n" }, { "code": "// C++ implementation of the SJF preemptive algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std; class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;}time_t min_BT(priority_queue<process> main_queue, time_t clock){ time_t min = 0; while (!main_queue.empty() && main_queue.top().AT <= clock) { if (min == 0 || min > main_queue.top().BT_left) min = main_queue.top().BT_left; main_queue.pop(); } return min;}int min_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t min = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (min == 0 || main_queue.top().BT_left < min) { min = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement SJF preemptive algorithmpriority_queue<process> SJF_P_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, min_BT_index(ready_queue, clock)); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.BT_left <= min_BT(ready_queue, clock))) { p.BT_left--; p.temp_BT++; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion Queue// and all the timevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialize Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call for completion data completion_queue = SJF_P_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 56728, "s": 45811, "text": null }, { "code": null, "e": 56738, "s": 56728, "text": "OUTPUT :-" }, { "code": null, "e": 58571, "s": 56738, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 7 | 7 | 3 | 0 |\n| 2 | 1 | 2 | 3 | 2 | 0 | 0 |\n| 3 | 2 | 3 | 10 | 8 | 5 | 5 |\n| 4 | 3 | 5 | 19 | 16 | 11 | 11 |\n| 5 | 4 | 1 | 5 | 1 | 0 | 0 |\n| 6 | 5 | 4 | 14 | 9 | 5 | 5 |\n| 7 | 6 | 6 | 25 | 19 | 13 | 13 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 83\nAverage completion time :- 11.8571\n\nTotal turnaround time :- 62\nAverage turnaround time :- 8.85714\n\nTotal waiting time :- 37\nAverage waiting time :- 5.28571\n\nTotal response time :- 34\nAverage response time :- 4.85714\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----+------+----+----+------+--------+----------+------------+--------------+\n| P1 | P2 | P1 | P5 | P1 | P3 | P6 | P4 | P7 |\n+----+------+----+----+------+--------+----------+------------+--------------+\n0 1 3 4 5 7 10 14 19 25\n\n\n\n" }, { "code": "// C++ implementation of the SJF(Non-preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implementation pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to find index of process//with minimum BTint min_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t min = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (min == 0 || main_queue.top().BT_left < min) { min = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement SJF(Non-preemptive)priority_queue<process> SJF_NP_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, min_BT_index(ready_queue, clock)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;}//Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display the queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = SJF_NP_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 68830, "s": 58571, "text": null }, { "code": null, "e": 68840, "s": 68830, "text": "OUTPUT :-" }, { "code": null, "e": 70637, "s": 68840, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 4 | 4 | 0 | 0 |\n| 2 | 1 | 2 | 7 | 6 | 4 | 4 |\n| 3 | 2 | 3 | 10 | 8 | 5 | 5 |\n| 4 | 3 | 5 | 19 | 16 | 11 | 11 |\n| 5 | 4 | 1 | 5 | 1 | 0 | 0 |\n| 6 | 5 | 4 | 14 | 9 | 5 | 5 |\n| 7 | 6 | 6 | 25 | 19 | 13 | 13 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 84\nAverage completion time :- 12\n\nTotal turnaround time :- 63\nAverage turnaround time :- 9\n\nTotal waiting time :- 38\nAverage waiting time :- 5.42857\n\nTotal response time :- 38\nAverage response time :- 5.42857\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----------+----+------+--------+----------+------------+--------------+\n| P1 | P5 | P2 | P3 | P6 | P4 | P7 |\n+----------+----+------+--------+----------+------------+--------------+\n0 4 5 7 10 14 19 25\n\n\n" }, { "code": "// C++ implementation of the LJF(Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implementation pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to implement maximum Burst Timetime_t max_BT(priority_queue<process> main_queue, time_t limit){ time_t max = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().BT_left > max) max = main_queue.top().BT_left; main_queue.pop(); } return max;} // Function to implement maximum BT index w.r.t given clock limitint max_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t max = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().BT_left > max) { max = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement LJF(Preemptive) algorithmpriority_queue<process> LJF_P_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_BT_index(ready_queue, clock)); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.BT_left >= max_BT(ready_queue, clock))) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion Queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = LJF_P_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 81600, "s": 70637, "text": null }, { "code": null, "e": 81610, "s": 81600, "text": "OUTPUT :-" }, { "code": null, "e": 83543, "s": 81610, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 23 | 23 | 19 | 0 |\n| 2 | 1 | 2 | 22 | 21 | 19 | 12 |\n| 3 | 2 | 3 | 24 | 22 | 19 | 0 |\n| 4 | 3 | 5 | 19 | 16 | 11 | 0 |\n| 5 | 4 | 1 | 20 | 16 | 15 | 15 |\n| 6 | 5 | 4 | 21 | 16 | 12 | 0 |\n| 7 | 6 | 6 | 25 | 19 | 13 | 0 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 154\nAverage completion time :- 22\n\nTotal turnaround time :- 133\nAverage turnaround time :- 19\n\nTotal waiting time :- 108\nAverage waiting time :- 15.4286\n\nTotal response time :- 27\nAverage response time :- 3.85714\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+------+----+------+----+----------+----+------+----+----+----+----+------+----+----+----+----+----+----+\n| P1 | P3 | P4 | P6 | P7 | P4 | P6 | P2 | P1 | P3 | P7 | P4 | P5 | P6 | P2 | P1 | P3 | P7 |\n+------+----+------+----+----------+----+------+----+----+----+----+------+----+----+----+----+----+----+\n0 2 3 5 6 10 11 13 14 15 16 17 19 20 21 22 23 24 25\n\n\n" }, { "code": "// C++ implementation of the LJF(Non-Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to find maximum Burst Time Index w.r.t clock limitint max_BT_index(priority_queue<process> main_queue, time_t limit){ int index, i = 0; time_t max = 0; while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().BT_left > max) { max = main_queue.top().BT_left; index = i; } main_queue.pop(); i++; } return index;} // Function to implement LJF(Non-Preemptive) Algorithmpriority_queue<process> LJF_NP_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.set_CT(clock); (*gantt).push(p); } p = pop_index(&ready_queue, max_BT_index(ready_queue, clock)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = LJF_NP_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 93814, "s": 83543, "text": null }, { "code": null, "e": 93824, "s": 93814, "text": "OUTPUT :-" }, { "code": null, "e": 95633, "s": 93824, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 4 | 4 | 0 | 0 |\n| 2 | 1 | 2 | 24 | 23 | 21 | 21 |\n| 3 | 2 | 3 | 22 | 20 | 17 | 17 |\n| 4 | 3 | 5 | 9 | 6 | 1 | 1 |\n| 5 | 4 | 1 | 25 | 21 | 20 | 20 |\n| 6 | 5 | 4 | 19 | 14 | 10 | 10 |\n| 7 | 6 | 6 | 15 | 9 | 3 | 3 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 118\nAverage completion time :- 16.8571\n\nTotal turnaround time :- 97\nAverage turnaround time :- 13.8571\n\nTotal waiting time :- 72\nAverage waiting time :- 10.2857\n\nTotal response time :- 72\nAverage response time :- 10.2857\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----------+------------+--------------+----------+--------+------+----+\n| P1 | P4 | P7 | P6 | P3 | P2 | P5 |\n+----------+------------+--------------+----------+--------+------+----+\n0 4 9 15 19 22 24 25\n\n\n" }, { "code": "// C++ implementation of the Round Robin algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement Round Robin algorithmpriority_queue<process> RR_run(priority_queue<process> ready_queue, time_t Time_Slice, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = ready_queue.top(); ready_queue.pop(); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (p.temp_BT < Time_Slice || ready_queue.empty() || clock < ready_queue.top().AT)) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display Completion queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; // Time quantum for round robin int tq = 2; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = RR_run(ready_queue, tq, &gantt); // Display Completion Queue disp(completion_queue, false); cout << \"\\nTime Quantum for round robin :- \" << tq << endl; // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 105319, "s": 95633, "text": null }, { "code": null, "e": 105329, "s": 105319, "text": "OUTPUT :-" }, { "code": null, "e": 107257, "s": 105329, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 8 | 8 | 4 | 0 |\n| 2 | 1 | 2 | 4 | 3 | 1 | 1 |\n| 3 | 2 | 3 | 16 | 14 | 11 | 2 |\n| 4 | 3 | 5 | 23 | 20 | 15 | 5 |\n| 5 | 4 | 1 | 11 | 7 | 6 | 6 |\n| 6 | 5 | 4 | 20 | 15 | 11 | 6 |\n| 7 | 6 | 6 | 25 | 19 | 13 | 7 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 107\nAverage completion time :- 15.2857\n\nTotal turnaround time :- 86\nAverage turnaround time :- 12.2857\n\nTotal waiting time :- 61\nAverage waiting time :- 8.71429\n\nTotal response time :- 27\nAverage response time :- 3.85714\n\nTime Quantum for round robin :- 2\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+------+------+------+------+------+----+------+------+----+------+------+------+----+------+\n| P1 | P2 | P3 | P1 | P4 | P5 | P6 | P7 | P3 | P4 | P6 | P7 | P4 | P7 |\n+------+------+------+------+------+----+------+------+----+------+------+------+----+------+\n0 2 4 6 8 10 11 13 15 16 18 20 22 23 25\n\n\n" }, { "code": "// C++ implementation of the Priority Based(Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to implement maximum priority w.r.t//priority and also 2nd argument has boolean//variable because we need to specify// True=highest number as highest priority// False=lowest number as highest priorityint max_priority(priority_queue<process> main_priority_queue, int limit, bool high){ int max = -1; if (high == 1) { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (main_priority_queue.top().priority > max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } else { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (max == -1 || main_priority_queue.top().priority < max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } return max;} // Function to implement maximum priority indexint max_priority_index(priority_queue<process> main_queue, int limit, bool high){ int max = -1, i = 0, index = 0; if (high == 1) { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().priority > max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } else { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (max == -1 || main_queue.top().priority < max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } return index;} // Function to implement priority based Preemptive schedulingpriority_queue<process> Priority_P_run(priority_queue<process> ready_queue, queue<process>* gantt, bool high){ int temp; priority_queue<process> completion_queue; process p; time_t clock = 0; if (high == 1) { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); if (p.AT == p.start_AT) p.set_RT(clock); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.priority >= max_priority(ready_queue, clock, high))) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } } else { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); if (p.AT == p.start_AT) p.set_RT(clock); temp = max_priority(ready_queue, clock, high); while (p.BT_left > 0 && (ready_queue.empty() || clock < ready_queue.top().AT || p.priority <= max_priority(ready_queue, clock, high))) { p.temp_BT++; p.BT_left--; clock++; } if (p.BT_left == 0) { p.AT = p.start_AT; p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } else { p.AT = clock; p.CT = clock; (*gantt).push(p); p.temp_BT = 0; ready_queue.push(p); } } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display main queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data//3rd argument has true passed becuase we have set//highest number = highest priority completion_queue = Priority_P_run(ready_queue, &gantt, true); // Display Completion Queue as true in//2nd argument to display priority disp(completion_queue, true); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 120863, "s": 107257, "text": null }, { "code": null, "e": 120873, "s": 120863, "text": "OUTPUT :-" }, { "code": null, "e": 122841, "s": 120873, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | Priority |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+\n| 1 | 0 | 4 | 25 | 25 | 21 | 0 | 2 |\n| 2 | 1 | 2 | 22 | 21 | 19 | 0 | 4 |\n| 3 | 2 | 3 | 21 | 19 | 16 | 0 | 6 |\n| 4 | 3 | 5 | 12 | 9 | 4 | 0 | 10 |\n| 5 | 4 | 1 | 19 | 15 | 14 | 14 | 8 |\n| 6 | 5 | 4 | 9 | 4 | 0 | 0 | 12 |\n| 7 | 6 | 6 | 18 | 12 | 6 | 6 | 9 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+\n\nTotal completion time :- 126\nAverage completion time :- 18\n\nTotal turnaround time :- 105\nAverage turnaround time :- 15\n\nTotal waiting time :- 80\nAverage waiting time :- 11.4286\n\nTotal response time :- 20\nAverage response time :- 2.85714\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----+----+----+------+----------+--------+--------------+----+------+----+--------+\n| P1 | P2 | P3 | P4 | P6 | P4 | P7 | P5 | P3 | P2 | P1 |\n+----+----+----+------+----------+--------+--------------+----+------+----+--------+\n0 1 2 3 5 9 12 18 19 21 22 25\n\n" }, { "code": "// C++ implementation of the Priority Based(Non-Preemptive) algorithm#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} //Function to implement maximum priority w.r.t clock limit// and 3rd parameter as bool because we need true = highest//number as highest and false as lowest number as highest priorityint max_priority(priority_queue<process> main_priority_queue, int limit, bool high){ int max = -1; if (high == 1) { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (main_priority_queue.top().priority > max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } else { while (!main_priority_queue.empty() && main_priority_queue.top().AT <= limit) { if (max == -1 || main_priority_queue.top().priority < max) max = main_priority_queue.top().priority; main_priority_queue.pop(); } } return max;} // Function to implement maximum priority indexint max_priority_index(priority_queue<process> main_queue, int limit, bool high){ int max = -1, i = 0, index = 0; if (high == 1) { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (main_queue.top().priority > max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } else { while (!main_queue.empty() && main_queue.top().AT <= limit) { if (max == -1 || main_queue.top().priority < max) { max = main_queue.top().priority; index = i; } main_queue.pop(); i++; } } return index;} // Function to implement priority based Preemptive schedulingpriority_queue<process> Priority_NP_run(priority_queue<process> ready_queue, queue<process>* gantt, bool high){ priority_queue<process> completion_queue; process p; time_t clock = 0; if (high == 1) { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } } else { while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_priority_index(ready_queue, clock, high)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display main queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data//and true is passed as 3rd argument because we//are considering highest number as highest priority completion_queue = Priority_NP_run(ready_queue, &gantt, true); // Display Completion Queue disp(completion_queue, true); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 135401, "s": 122841, "text": null }, { "code": null, "e": 135411, "s": 135401, "text": "OUTPUT :-" }, { "code": null, "e": 137341, "s": 135411, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time | Priority |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+\n| 1 | 0 | 4 | 4 | 4 | 0 | 0 | 2 |\n| 2 | 1 | 2 | 25 | 24 | 22 | 22 | 4 |\n| 3 | 2 | 3 | 23 | 21 | 18 | 18 | 6 |\n| 4 | 3 | 5 | 9 | 6 | 1 | 1 | 10 |\n| 5 | 4 | 1 | 20 | 16 | 15 | 15 | 8 |\n| 6 | 5 | 4 | 13 | 8 | 4 | 4 | 12 |\n| 7 | 6 | 6 | 19 | 13 | 7 | 7 | 9 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+----------+\n\nTotal completion time :- 113\nAverage completion time :- 16.1429\n\nTotal turnaround time :- 92\nAverage turnaround time :- 13.1429\n\nTotal waiting time :- 67\nAverage waiting time :- 9.57143\n\nTotal response time :- 67\nAverage response time :- 9.57143\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----------+------------+----------+--------------+----+--------+------+\n| P1 | P4 | P6 | P7 | P5 | P3 | P2 |\n+----------+------------+----------+--------------+----+--------+------+\n0 4 9 13 19 20 23 25\n\n\n" }, { "code": "// C++ implementation of the HRRN Scheduling#include <cstdlib>#include <iostream>#include <queue>using namespace std;class process {public: pid_t p_no = 0; time_t start_AT = 0, AT = 0, BT_left = 0, BT = 0, temp_BT = 0, CT = 0, TAT = 0, WT = 0, RT = 0; int priority = 0; // Function for completion time void set_CT(time_t time) { CT = time; set_TAT(); set_WT(); } // Function for Turn Around Time void set_TAT() { TAT = CT - start_AT; } // Function for Waiting Time void set_WT() { WT = TAT - BT; } void P_set() { start_AT = AT; BT_left = BT; } void set_RT(time_t time) { RT = time - start_AT; } // Overload operator '<' w.r.t arrival // time because arrival time is the // first priority even greater than // priority of process and priority_queue // pops out the greatest value first // so we need to replace '<' with '>' inorder // to pop out smallest value friend bool operator<(const process& a, const process& b) { return a.AT > b.AT; }}; // Function to implement pop_index()process pop_index(priority_queue<process>* main_queue, int index){ priority_queue<process> rm_index; int i; process p; switch (index) { case 0: p = (*main_queue).top(); (*main_queue).pop(); break; default: for (i = 0; i < index; i++) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } p = (*main_queue).top(); (*main_queue).pop(); while (!(*main_queue).empty()) { rm_index.push((*main_queue).top()); (*main_queue).pop(); } (*main_queue) = rm_index; break; } return p;} // Function to implement maximum Response Ratio// index w.r.t clock limit for arrival timeint max_response_ratio_index(priority_queue<process> ready_queue, time_t limit){ int index, i = 0; double response_ratio = 0, max = 0; while (!ready_queue.empty() && ready_queue.top().AT <= limit) { response_ratio = ((double)(limit - ready_queue.top().AT) + ready_queue.top().BT_left) / ready_queue.top().BT_left; if (response_ratio > max) { max = response_ratio; index = i; } i++; ready_queue.pop(); } return index;} // Function to implement HRRN Schedulingpriority_queue<process> HRRN_run(priority_queue<process> ready_queue, queue<process>* gantt){ priority_queue<process> completion_queue; process p; time_t clock = 0; while (!ready_queue.empty()) { while (clock < ready_queue.top().AT) { p.temp_BT++; clock++; } if (p.temp_BT > 0) { p.p_no = -1; p.CT = clock; (*gantt).push(p); } p = pop_index(&ready_queue, max_response_ratio_index(ready_queue, clock)); p.set_RT(clock); while (p.BT_left > 0) { p.temp_BT++; p.BT_left--; clock++; } p.set_CT(clock); (*gantt).push(p); p.temp_BT = 0; completion_queue.push(p); } return completion_queue;} // Set data on the basis of given tablepriority_queue<process> set_sample_data(){ priority_queue<process> ready_queue; process temp; temp.AT = 0; temp.BT = 4; temp.priority = 2; temp.p_no = 1; temp.P_set(); ready_queue.push(temp); temp.AT = 1; temp.BT = 2; temp.priority = 4; temp.p_no = 2; temp.P_set(); ready_queue.push(temp); temp.AT = 2; temp.BT = 3; temp.priority = 6; temp.p_no = 3; temp.P_set(); ready_queue.push(temp); temp.AT = 3; temp.BT = 5; temp.priority = 10; temp.p_no = 4; temp.P_set(); ready_queue.push(temp); temp.AT = 4; temp.BT = 1; temp.priority = 8; temp.p_no = 5; temp.P_set(); ready_queue.push(temp); temp.AT = 5; temp.BT = 4; temp.priority = 12; temp.p_no = 6; temp.P_set(); ready_queue.push(temp); temp.AT = 6; temp.BT = 6; temp.priority = 9; temp.p_no = 7; temp.P_set(); ready_queue.push(temp); return ready_queue;} // Function to get total Waiting Timedouble get_total_WT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().WT; processes.pop(); } return total;} // Function to get total Turn Around Timedouble get_total_TAT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().TAT; processes.pop(); } return total;} // Function to get total Completion Timedouble get_total_CT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().CT; processes.pop(); } return total;} // Function to get total Response Timedouble get_total_RT(priority_queue<process> processes){ double total = 0; while (!processes.empty()) { total += processes.top().RT; processes.pop(); } return total;} // Function to display main queuevoid disp(priority_queue<process> main_queue, bool high){ int i = 0, temp, size = main_queue.size(); priority_queue<process> tempq = main_queue; double temp1; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; cout << \"| Process No. | Arrival Time \"; cout << \"| Burst Time | Completion Time \"; cout << \"| Turnaround Time | Waiting Time | Response Time |\"; if (high == true) cout << \" Priority |\" << endl; else cout << endl; cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\" << endl; else cout << endl; while (!main_queue.empty()) { temp = to_string(main_queue.top().p_no).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().p_no << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().start_AT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().start_AT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().BT).length(); cout << '|' << string(6 - temp / 2 - temp % 2, ' ') << main_queue.top().BT << string(6 - temp / 2, ' '); temp = to_string(main_queue.top().CT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().CT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().TAT).length(); cout << '|' << string(8 - temp / 2 - temp % 2, ' ') << main_queue.top().TAT << string(9 - temp / 2, ' '); temp = to_string(main_queue.top().WT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().WT << string(7 - temp / 2, ' '); temp = to_string(main_queue.top().RT).length(); cout << '|' << string(7 - temp / 2 - temp % 2, ' ') << main_queue.top().RT << string(8 - temp / 2, ' '); if (high == true) { temp = to_string(main_queue.top().priority).length(); cout << '|' << string(5 - temp / 2 - temp % 2, ' ') << main_queue.top().priority << string(5 - temp / 2, ' '); } cout << \"|\\n\"; main_queue.pop(); } cout << \"+-------------+--------------\"; cout << \"+------------+-----------------\"; cout << \"+-----------------+--------------+---------------+\"; if (high == true) cout << \"----------+\"; cout << endl; temp1 = get_total_CT(tempq); cout << \"\\nTotal completion time :- \" << temp1 << endl; cout << \"Average completion time :- \" << temp1 / size << endl; temp1 = get_total_TAT(tempq); cout << \"\\nTotal turnaround time :- \" << temp1 << endl; cout << \"Average turnaround time :- \" << temp1 / size << endl; temp1 = get_total_WT(tempq); cout << \"\\nTotal waiting time :- \" << temp1 << endl; cout << \"Average waiting time :- \" << temp1 / size << endl; temp1 = get_total_RT(tempq); cout << \"\\nTotal response time :- \" << temp1 << endl; cout << \"Average response time :- \" << temp1 / size << endl;} // Function to display Gantt Chartvoid disp_gantt_chart(queue<process> gantt){ int temp, prev = 0; queue<process> spaces = gantt; cout << \"\\n\\nGantt Chart (IS indicates ideal state) :- \\n\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } cout << \"\\n|\"; spaces = gantt; while (!spaces.empty()) { cout << string(spaces.front().temp_BT, ' '); if (spaces.front().p_no == -1) cout << \"IS\" << string(spaces.front().temp_BT, ' ') << '|'; else cout << \"P\" << spaces.front().p_no << string(spaces.front().temp_BT, ' ') << '|'; spaces.pop(); } spaces = gantt; cout << \"\\n+\"; while (!spaces.empty()) { cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT, '-') << \"+\"; spaces.pop(); } spaces = gantt; cout << \"\\n0\"; while (!spaces.empty()) { temp = to_string(spaces.front().CT).length(); cout << string(to_string(spaces.front().p_no).length() + (spaces.front().p_no != -1) + 2 * spaces.front().temp_BT - temp / 2 - prev, ' ') << spaces.front().CT; prev = temp / 2 - temp % 2 == 0; spaces.pop(); } cout << \"\\n\\n\";} // Driver Codeint main(){ // Initialise Ready and Completion Queue priority_queue<process> ready_queue, completion_queue; // queue for Gantt Chart queue<process> gantt; ready_queue = set_sample_data(); // Function call to find completion data completion_queue = HRRN_run(ready_queue, &gantt); // Display Completion Queue disp(completion_queue, false); // Display Gantt Chart disp_gantt_chart(gantt); return 0;}", "e": 147817, "s": 137341, "text": null }, { "code": null, "e": 147827, "s": 147817, "text": "OUTPUT :-" }, { "code": null, "e": 149634, "s": 147827, "text": "+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| Process No. | Arrival Time | Burst Time | Completion Time | Turnaround Time | Waiting Time | Response Time |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n| 1 | 0 | 4 | 4 | 4 | 0 | 0 |\n| 2 | 1 | 2 | 6 | 5 | 3 | 3 |\n| 3 | 2 | 3 | 10 | 8 | 5 | 5 |\n| 4 | 3 | 5 | 15 | 12 | 7 | 7 |\n| 5 | 4 | 1 | 7 | 3 | 2 | 2 |\n| 6 | 5 | 4 | 19 | 14 | 10 | 10 |\n| 7 | 6 | 6 | 25 | 19 | 13 | 13 |\n+-------------+--------------+------------+-----------------+-----------------+--------------+---------------+\n\nTotal completion time :- 86\nAverage completion time :- 12.2857\n\nTotal turnaround time :- 65\nAverage turnaround time :- 9.28571\n\nTotal waiting time :- 40\nAverage waiting time :- 5.71429\n\nTotal response time :- 40\nAverage response time :- 5.71429\n\n\nGantt Chart (IS indicates ideal state) :- \n\n+----------+------+----+--------+------------+----------+--------------+\n| P1 | P2 | P5 | P3 | P4 | P6 | P7 |\n+----------+------+----+--------+------------+----------+--------------+\n0 4 6 7 10 15 19 25\n\n" }, { "code": null, "e": 149653, "s": 149634, "text": "jaspreetsinghpal18" }, { "code": null, "e": 149668, "s": 149653, "text": "cpu-scheduling" }, { "code": null, "e": 149684, "s": 149668, "text": "Data Structures" }, { "code": null, "e": 149717, "s": 149684, "text": "Operating Systems-CPU Scheduling" }, { "code": null, "e": 149728, "s": 149717, "text": "Algorithms" }, { "code": null, "e": 149746, "s": 149728, "text": "Operating Systems" }, { "code": null, "e": 149752, "s": 149746, "text": "Queue" }, { "code": null, "e": 149768, "s": 149752, "text": "Data Structures" }, { "code": null, "e": 149786, "s": 149768, "text": "Operating Systems" }, { "code": null, "e": 149792, "s": 149786, "text": "Queue" }, { "code": null, "e": 149803, "s": 149792, "text": "Algorithms" }, { "code": null, "e": 149901, "s": 149803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 149926, "s": 149901, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 149953, "s": 149926, "text": "How to Start Learning DSA?" }, { "code": null, "e": 150006, "s": 149953, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 150040, "s": 150006, "text": "K means Clustering - Introduction" }, { "code": null, "e": 150107, "s": 150040, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 150134, "s": 150107, "text": "Types of Operating Systems" }, { "code": null, "e": 150173, "s": 150134, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 150222, "s": 150173, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 150262, "s": 150222, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Program to print all the numbers divisible by 3 and 5 for a given number - GeeksforGeeks
17 May, 2021 Given the integer N, the task is to print all the numbers less than N, which are divisible by 3 and 5.Examples : Input : 50 Output : 0 15 30 45 Input : 100 Output : 0 15 30 45 60 75 90 Approach : For example, let’s take N = 20 as a limit, then the program should print all numbers less than 20 which are divisible by both 3 and 5. For this divide each number from 0 to N by both 3 and 5 and check their remainder. If remainder is 0 in both cases then simply print that number.Below is the implementation : C++ Java Python3 C# PHP Javascript // C++ program to print all the numbers// divisible by 3 and 5 for a given number#include <iostream>using namespace std; // Result function with Nvoid result(int N){ // iterate from 0 to N for (int num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) cout << num << " "; }} // Driver codeint main(){ // input goes here int N = 100; // Calling function result(N); return 0;} // This code is contributed by Manish Shaw// (manishshaw1) // Java program to print all the numbers// divisible by 3 and 5 for a given number class GFG{ // Result function with N static void result(int N) { // iterate from 0 to N for (int num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) System.out.print(num + " "); } } // Driver code public static void main(String []args) { // input goes here int N = 100; // Calling function result(N); }} # Python program to print all the numbers# divisible by 3 and 5 for a given number # Result function with Ndef result(N): # iterate from 0 to N for num in range(N): # Short-circuit operator is used if num % 3 == 0 and num % 5 == 0: print(str(num) + " ", end = "") else: pass # Driver codeif __name__ == "__main__": # input goes here N = 100 # Calling function result(N) // C# program to print all the numbers// divisible by 3 and 5 for a given numberusing System;public class GFG{ // Result function with N static void result(int N) { // iterate from 0 to N for (int num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) Console.Write(num + " "); } } // Driver code static public void Main (){ // input goes here int N = 100; // Calling function result(N); }//This code is contributed by ajit. } <?php// PHP program to print all the numbers// divisible by 3 and 5 for a given number // Result function with Nfunction result($N){ // iterate from 0 to N for ($num = 0; $num < $N; $num++) { // Short-circuit operator is used if ($num % 3 == 0 && $num % 5 == 0) echo $num, " "; }} // Driver code // input goes here$N = 100; // Calling functionresult($N); // This code is contributed by ajit?> <script> // Javascript program to// print all the numbers// divisible by 3 and 5// for a given number // Result function with Nfunction result(N){ // iterate from 0 to N for (let num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) document.write( num+ " "); }} // Driver code // input goes herelet N = 100; // Calling functionresult(N); // This code is contributed by Bobby </script> Output : 0 15 30 45 60 75 90 manishshaw1 ukasp jit_t arorakashish0911 divisibility Python Python Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26559, "s": 26531, "text": "\n17 May, 2021" }, { "code": null, "e": 26674, "s": 26559, "text": "Given the integer N, the task is to print all the numbers less than N, which are divisible by 3 and 5.Examples : " }, { "code": null, "e": 26749, "s": 26674, "text": "Input : 50\nOutput : 0 15 30 45 \n\nInput : 100\nOutput : 0 15 30 45 60 75 90 " }, { "code": null, "e": 27074, "s": 26751, "text": "Approach : For example, let’s take N = 20 as a limit, then the program should print all numbers less than 20 which are divisible by both 3 and 5. For this divide each number from 0 to N by both 3 and 5 and check their remainder. If remainder is 0 in both cases then simply print that number.Below is the implementation : " }, { "code": null, "e": 27078, "s": 27074, "text": "C++" }, { "code": null, "e": 27083, "s": 27078, "text": "Java" }, { "code": null, "e": 27091, "s": 27083, "text": "Python3" }, { "code": null, "e": 27094, "s": 27091, "text": "C#" }, { "code": null, "e": 27098, "s": 27094, "text": "PHP" }, { "code": null, "e": 27109, "s": 27098, "text": "Javascript" }, { "code": "// C++ program to print all the numbers// divisible by 3 and 5 for a given number#include <iostream>using namespace std; // Result function with Nvoid result(int N){ // iterate from 0 to N for (int num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) cout << num << \" \"; }} // Driver codeint main(){ // input goes here int N = 100; // Calling function result(N); return 0;} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 27653, "s": 27109, "text": null }, { "code": "// Java program to print all the numbers// divisible by 3 and 5 for a given number class GFG{ // Result function with N static void result(int N) { // iterate from 0 to N for (int num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) System.out.print(num + \" \"); } } // Driver code public static void main(String []args) { // input goes here int N = 100; // Calling function result(N); }}", "e": 28229, "s": 27653, "text": null }, { "code": "# Python program to print all the numbers# divisible by 3 and 5 for a given number # Result function with Ndef result(N): # iterate from 0 to N for num in range(N): # Short-circuit operator is used if num % 3 == 0 and num % 5 == 0: print(str(num) + \" \", end = \"\") else: pass # Driver codeif __name__ == \"__main__\": # input goes here N = 100 # Calling function result(N)", "e": 28721, "s": 28229, "text": null }, { "code": "// C# program to print all the numbers// divisible by 3 and 5 for a given numberusing System;public class GFG{ // Result function with N static void result(int N) { // iterate from 0 to N for (int num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) Console.Write(num + \" \"); } } // Driver code static public void Main (){ // input goes here int N = 100; // Calling function result(N); }//This code is contributed by ajit. }", "e": 29322, "s": 28721, "text": null }, { "code": "<?php// PHP program to print all the numbers// divisible by 3 and 5 for a given number // Result function with Nfunction result($N){ // iterate from 0 to N for ($num = 0; $num < $N; $num++) { // Short-circuit operator is used if ($num % 3 == 0 && $num % 5 == 0) echo $num, \" \"; }} // Driver code // input goes here$N = 100; // Calling functionresult($N); // This code is contributed by ajit?>", "e": 29756, "s": 29322, "text": null }, { "code": "<script> // Javascript program to// print all the numbers// divisible by 3 and 5// for a given number // Result function with Nfunction result(N){ // iterate from 0 to N for (let num = 0; num < N; num++) { // Short-circuit operator is used if (num % 3 == 0 && num % 5 == 0) document.write( num+ \" \"); }} // Driver code // input goes herelet N = 100; // Calling functionresult(N); // This code is contributed by Bobby </script>", "e": 30225, "s": 29756, "text": null }, { "code": null, "e": 30235, "s": 30225, "text": "Output : " }, { "code": null, "e": 30256, "s": 30235, "text": "0 15 30 45 60 75 90 " }, { "code": null, "e": 30270, "s": 30258, "text": "manishshaw1" }, { "code": null, "e": 30276, "s": 30270, "text": "ukasp" }, { "code": null, "e": 30282, "s": 30276, "text": "jit_t" }, { "code": null, "e": 30299, "s": 30282, "text": "arorakashish0911" }, { "code": null, "e": 30312, "s": 30299, "text": "divisibility" }, { "code": null, "e": 30319, "s": 30312, "text": "Python" }, { "code": null, "e": 30335, "s": 30319, "text": "Python Programs" }, { "code": null, "e": 30354, "s": 30335, "text": "School Programming" }, { "code": null, "e": 30452, "s": 30354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30470, "s": 30452, "text": "Python Dictionary" }, { "code": null, "e": 30505, "s": 30470, "text": "Read a file line by line in Python" }, { "code": null, "e": 30537, "s": 30505, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30559, "s": 30537, "text": "Enumerate() in Python" }, { "code": null, "e": 30601, "s": 30559, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30644, "s": 30601, "text": "Python program to convert a list to string" }, { "code": null, "e": 30666, "s": 30644, "text": "Defaultdict in Python" }, { "code": null, "e": 30705, "s": 30666, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 30751, "s": 30705, "text": "Python | Split string into list of characters" } ]
Advantages and Disadvantages of Using Stored Procedures - SQL - GeeksforGeeks
05 Jun, 2020 A Stored Procedure is a type of code in SQL that can be stored for later use and can be used many times. So, whenever you need to execute the query, instead of calling it you can just call the stored procedure. You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter values that is passed. Syntax : CREATE PROCEDURE procedure_name AS sql_statement GO; To execute a stored procedure – EXEC procedure_name; Example : CREATE PROCEDURE SelectAllGeeks AS SELECT * FROM Geeks GO; Advantages :The main advantages of stored procedure are given below: Better Performance –The procedure calls are quick and efficient as stored procedures are compiled once and stored in executable form.Hence the response is quick. The executable code is automatically cached, hence lowers the memory requirements.Higher Productivity –Since the same piece of code is used again and again so, it results in higher productivity.Ease of Use –To create a stored procedure, one can use any Java Integrated Development Environment (IDE). Then, they can be deployed on any tier of network architecture.Scalability –Stored procedures increase scalability by isolating application processing on the server.Maintainability –Maintaining a procedure on a server is much easier then maintaining copies on various client machines, this is because scripts are in one location.Security –Access to the Oracle data can be restricted by allowing users to manipulate the data only through stored procedures that execute with their definer’s privileges. Better Performance –The procedure calls are quick and efficient as stored procedures are compiled once and stored in executable form.Hence the response is quick. The executable code is automatically cached, hence lowers the memory requirements. Higher Productivity –Since the same piece of code is used again and again so, it results in higher productivity. Ease of Use –To create a stored procedure, one can use any Java Integrated Development Environment (IDE). Then, they can be deployed on any tier of network architecture. Scalability –Stored procedures increase scalability by isolating application processing on the server. Maintainability –Maintaining a procedure on a server is much easier then maintaining copies on various client machines, this is because scripts are in one location. Security –Access to the Oracle data can be restricted by allowing users to manipulate the data only through stored procedures that execute with their definer’s privileges. Disadvantages :The main disadvantages of stored procedures are given below: Testing –Testing of a logic which is encapsulated inside a stored procedure is very difficult. Any data errors in handling stored procedures are not generated until runtime.Debugging –Depending on the database technology, debugging stored procedures will either be very difficult or not possible at all. Some relational databases such as SQL Server have some debugging capabilities.Versioning –Version control is not supported by the stored procedure.Cost –An extra developer in the form of DBA is required to access the SQL and write a better stored procedure. This will automatically incur added cost.Portability –Complex stored procedures will not always port to upgraded versions of the same database. This is specially true in case of moving from one database type(Oracle) to another database type(MS SQL Server). Testing –Testing of a logic which is encapsulated inside a stored procedure is very difficult. Any data errors in handling stored procedures are not generated until runtime. Debugging –Depending on the database technology, debugging stored procedures will either be very difficult or not possible at all. Some relational databases such as SQL Server have some debugging capabilities. Versioning –Version control is not supported by the stored procedure. Cost –An extra developer in the form of DBA is required to access the SQL and write a better stored procedure. This will automatically incur added cost. Portability –Complex stored procedures will not always port to upgraded versions of the same database. This is specially true in case of moving from one database type(Oracle) to another database type(MS SQL Server). DBMS-SQL Picked DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS What is Temporary Table in SQL? Conflict Serializability in DBMS KDD Process in Data Mining SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 25574, "s": 25546, "text": "\n05 Jun, 2020" }, { "code": null, "e": 25920, "s": 25574, "text": "A Stored Procedure is a type of code in SQL that can be stored for later use and can be used many times. So, whenever you need to execute the query, instead of calling it you can just call the stored procedure. You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter values that is passed." }, { "code": null, "e": 25929, "s": 25920, "text": "Syntax :" }, { "code": null, "e": 25983, "s": 25929, "text": "CREATE PROCEDURE procedure_name\nAS\nsql_statement\nGO; " }, { "code": null, "e": 26015, "s": 25983, "text": "To execute a stored procedure –" }, { "code": null, "e": 26036, "s": 26015, "text": "EXEC procedure_name;" }, { "code": null, "e": 26046, "s": 26036, "text": "Example :" }, { "code": null, "e": 26107, "s": 26046, "text": "CREATE PROCEDURE SelectAllGeeks\nAS\nSELECT * \nFROM Geeks\nGO; " }, { "code": null, "e": 26176, "s": 26107, "text": "Advantages :The main advantages of stored procedure are given below:" }, { "code": null, "e": 27139, "s": 26176, "text": "Better Performance –The procedure calls are quick and efficient as stored procedures are compiled once and stored in executable form.Hence the response is quick. The executable code is automatically cached, hence lowers the memory requirements.Higher Productivity –Since the same piece of code is used again and again so, it results in higher productivity.Ease of Use –To create a stored procedure, one can use any Java Integrated Development Environment (IDE). Then, they can be deployed on any tier of network architecture.Scalability –Stored procedures increase scalability by isolating application processing on the server.Maintainability –Maintaining a procedure on a server is much easier then maintaining copies on various client machines, this is because scripts are in one location.Security –Access to the Oracle data can be restricted by allowing users to manipulate the data only through stored procedures that execute with their definer’s privileges." }, { "code": null, "e": 27384, "s": 27139, "text": "Better Performance –The procedure calls are quick and efficient as stored procedures are compiled once and stored in executable form.Hence the response is quick. The executable code is automatically cached, hence lowers the memory requirements." }, { "code": null, "e": 27497, "s": 27384, "text": "Higher Productivity –Since the same piece of code is used again and again so, it results in higher productivity." }, { "code": null, "e": 27667, "s": 27497, "text": "Ease of Use –To create a stored procedure, one can use any Java Integrated Development Environment (IDE). Then, they can be deployed on any tier of network architecture." }, { "code": null, "e": 27770, "s": 27667, "text": "Scalability –Stored procedures increase scalability by isolating application processing on the server." }, { "code": null, "e": 27935, "s": 27770, "text": "Maintainability –Maintaining a procedure on a server is much easier then maintaining copies on various client machines, this is because scripts are in one location." }, { "code": null, "e": 28107, "s": 27935, "text": "Security –Access to the Oracle data can be restricted by allowing users to manipulate the data only through stored procedures that execute with their definer’s privileges." }, { "code": null, "e": 28183, "s": 28107, "text": "Disadvantages :The main disadvantages of stored procedures are given below:" }, { "code": null, "e": 29002, "s": 28183, "text": "Testing –Testing of a logic which is encapsulated inside a stored procedure is very difficult. Any data errors in handling stored procedures are not generated until runtime.Debugging –Depending on the database technology, debugging stored procedures will either be very difficult or not possible at all. Some relational databases such as SQL Server have some debugging capabilities.Versioning –Version control is not supported by the stored procedure.Cost –An extra developer in the form of DBA is required to access the SQL and write a better stored procedure. This will automatically incur added cost.Portability –Complex stored procedures will not always port to upgraded versions of the same database. This is specially true in case of moving from one database type(Oracle) to another database type(MS SQL Server)." }, { "code": null, "e": 29176, "s": 29002, "text": "Testing –Testing of a logic which is encapsulated inside a stored procedure is very difficult. Any data errors in handling stored procedures are not generated until runtime." }, { "code": null, "e": 29386, "s": 29176, "text": "Debugging –Depending on the database technology, debugging stored procedures will either be very difficult or not possible at all. Some relational databases such as SQL Server have some debugging capabilities." }, { "code": null, "e": 29456, "s": 29386, "text": "Versioning –Version control is not supported by the stored procedure." }, { "code": null, "e": 29609, "s": 29456, "text": "Cost –An extra developer in the form of DBA is required to access the SQL and write a better stored procedure. This will automatically incur added cost." }, { "code": null, "e": 29825, "s": 29609, "text": "Portability –Complex stored procedures will not always port to upgraded versions of the same database. This is specially true in case of moving from one database type(Oracle) to another database type(MS SQL Server)." }, { "code": null, "e": 29834, "s": 29825, "text": "DBMS-SQL" }, { "code": null, "e": 29841, "s": 29834, "text": "Picked" }, { "code": null, "e": 29846, "s": 29841, "text": "DBMS" }, { "code": null, "e": 29850, "s": 29846, "text": "SQL" }, { "code": null, "e": 29855, "s": 29850, "text": "DBMS" }, { "code": null, "e": 29859, "s": 29855, "text": "SQL" }, { "code": null, "e": 29957, "s": 29859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29974, "s": 29957, "text": "Deadlock in DBMS" }, { "code": null, "e": 30015, "s": 29974, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 30047, "s": 30015, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 30080, "s": 30047, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 30107, "s": 30080, "text": "KDD Process in Data Mining" }, { "code": null, "e": 30149, "s": 30107, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 30193, "s": 30149, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 30214, "s": 30193, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 30280, "s": 30214, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Print the Kth Digit | Practice | GeeksforGeeks
Given two numbers A and B, find Kth digit from right of AB. Example 1: Input: A = 3 B = 3 K = 1 Output: 7 Explanation: 33 = 27 and 1st digit from right is 7 Example 2: Input: A = 5 B = 2 K = 2 Output: 2 Explanation: 52 = 25 and second digit from right is 2. Your Task: You don't need to read input or print anything. Your task is to complete the function kthDigit() which takes integers A, B, K as input parameters and returns Kth Digit of AB from right side. Expected Time Complexity: O(log AB) Expected Space Complexity: O(1) Constraints: 1 <= A,B <= 15 1 <=K<= digits in AB 0 sakesai305 days ago class Solution{ static long kthDigit(int A,int B,int K){ long result = (long)Math.pow(A,B); if(K==1) return result%10; long mama = result/((long)Math.pow(10,K-1)); return mama%10; }} 0 shivamranageu20236 days ago class Solution{public: int kthDigit(int A,int B,int K){ // code here long long int b= pow(A,B); long long int c = pow(10,K); return (int)((b%c)/(c/10)); }}; 0 mohdraza2 weeks ago class Solution{ static long kthDigit(int A,int B,int K){ // code here long a =(long)Math.pow(A,B); String st=Long.toString(a); long ch=st.charAt(st.length()-K)-'0'; return ch; }} +1 rapuriteja3 weeks ago def kthDigit(self, A, B, K): num = A**B return str(num)[-K] 0 mayank180919994 weeks ago int kthDigit(int A,int B,int K){ // code her long long int N=pow(A,B); int digit; while(K>0){ digit=N%10; N=N/10; K--; } return digit; } 0 giridharsonu1231 month ago JavaScript Solution let n=0; let rem=0; let ans=Math.pow(A,B); while(ans > 0){ n++; rem=ans%10; if(K==n){ return Math.floor(rem); } ans/=10; } 0 asifsaba5812 months ago class Solution{ public: int kthDigit(int A,int B,int K){ long long int value=pow(A,B); long long int count=0; long long int k_th_Digit=0; while(value>0){ k_th_Digit=value%10; count++; if(count==K){ return k_th_Digit; } value=value/10; } return 0; } }; 0 bhanujggandhi2 months ago Using pow() function in C++ int kthDigit(int A,int B,int K){ long long int num = pow(A, B); long long int truncate_num = num/pow(10,K-1); return truncate_num%10; } 0 gupta2411sumit2 months ago int kthDigit(int A,int B,int K){ // code here long long int num = pow( A , B ) ; // int ans = 0 ; while(K>0) { ans = num%10 ; num = num/10 ; K-- ; } return ans ; } 0 chechipresh2 months ago class Solution{ public: int kthDigit(int A,int B,int K){ // code here long int p=pow(A,B); int d; while (1){ d=p%10; K--; if (K==0) return d; p/=10; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 300, "s": 238, "text": "Given two numbers A and B, find Kth digit from right of AB.\n " }, { "code": null, "e": 311, "s": 300, "text": "Example 1:" }, { "code": null, "e": 399, "s": 311, "text": "Input:\nA = 3\nB = 3\nK = 1\nOutput:\n7\nExplanation:\n33 = 27 and 1st\ndigit from right is \n7\n" }, { "code": null, "e": 410, "s": 399, "text": "Example 2:" }, { "code": null, "e": 501, "s": 410, "text": "Input:\nA = 5\nB = 2\nK = 2\nOutput:\n2\nExplanation:\n52 = 25 and second\ndigit from right is\n2.\n" }, { "code": null, "e": 706, "s": 501, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function kthDigit() which takes integers A, B, K as input parameters and returns Kth Digit of AB from right side.\n " }, { "code": null, "e": 776, "s": 706, "text": "Expected Time Complexity: O(log AB)\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 827, "s": 776, "text": "Constraints:\n1 <= A,B <= 15\n1 <=K<= digits in AB\n " }, { "code": null, "e": 829, "s": 827, "text": "0" }, { "code": null, "e": 849, "s": 829, "text": "sakesai305 days ago" }, { "code": null, "e": 1056, "s": 849, "text": "class Solution{ static long kthDigit(int A,int B,int K){ long result = (long)Math.pow(A,B); if(K==1) return result%10; long mama = result/((long)Math.pow(10,K-1)); return mama%10; }}" }, { "code": null, "e": 1058, "s": 1056, "text": "0" }, { "code": null, "e": 1086, "s": 1058, "text": "shivamranageu20236 days ago" }, { "code": null, "e": 1271, "s": 1086, "text": "class Solution{public: int kthDigit(int A,int B,int K){ // code here long long int b= pow(A,B); long long int c = pow(10,K); return (int)((b%c)/(c/10)); }};" }, { "code": null, "e": 1273, "s": 1271, "text": "0" }, { "code": null, "e": 1293, "s": 1273, "text": "mohdraza2 weeks ago" }, { "code": null, "e": 1506, "s": 1293, "text": "class Solution{ static long kthDigit(int A,int B,int K){ // code here long a =(long)Math.pow(A,B); String st=Long.toString(a); long ch=st.charAt(st.length()-K)-'0'; return ch; }}" }, { "code": null, "e": 1509, "s": 1506, "text": "+1" }, { "code": null, "e": 1531, "s": 1509, "text": "rapuriteja3 weeks ago" }, { "code": null, "e": 1603, "s": 1531, "text": "def kthDigit(self, A, B, K): num = A**B return str(num)[-K]" }, { "code": null, "e": 1605, "s": 1603, "text": "0" }, { "code": null, "e": 1631, "s": 1605, "text": "mayank180919994 weeks ago" }, { "code": null, "e": 1857, "s": 1631, "text": " int kthDigit(int A,int B,int K){\n // code her\n long long int N=pow(A,B);\n int digit;\n while(K>0){\n digit=N%10;\n N=N/10;\n K--;\n }\n return digit;\n }" }, { "code": null, "e": 1859, "s": 1857, "text": "0" }, { "code": null, "e": 1886, "s": 1859, "text": "giridharsonu1231 month ago" }, { "code": null, "e": 2114, "s": 1886, "text": "JavaScript Solution let n=0; let rem=0; let ans=Math.pow(A,B); while(ans > 0){ n++; rem=ans%10; if(K==n){ return Math.floor(rem); } ans/=10; } " }, { "code": null, "e": 2116, "s": 2114, "text": "0" }, { "code": null, "e": 2140, "s": 2116, "text": "asifsaba5812 months ago" }, { "code": null, "e": 2625, "s": 2140, "text": "class Solution{\npublic:\n int kthDigit(int A,int B,int K){\n \n long long int value=pow(A,B);\n \n long long int count=0;\n \n long long int k_th_Digit=0;\n \n while(value>0){\n \n k_th_Digit=value%10;\n \n count++;\n \n if(count==K){\n \n return k_th_Digit;\n }\n \n value=value/10;\n }\n \n return 0; \n }\n \n \n};" }, { "code": null, "e": 2627, "s": 2625, "text": "0" }, { "code": null, "e": 2653, "s": 2627, "text": "bhanujggandhi2 months ago" }, { "code": null, "e": 2681, "s": 2653, "text": "Using pow() function in C++" }, { "code": null, "e": 2854, "s": 2681, "text": "int kthDigit(int A,int B,int K){\n long long int num = pow(A, B);\n \n long long int truncate_num = num/pow(10,K-1);\n return truncate_num%10;\n }" }, { "code": null, "e": 2856, "s": 2854, "text": "0" }, { "code": null, "e": 2883, "s": 2856, "text": "gupta2411sumit2 months ago" }, { "code": null, "e": 3169, "s": 2883, "text": "int kthDigit(int A,int B,int K){ // code here long long int num = pow( A , B ) ; // int ans = 0 ; while(K>0) { ans = num%10 ; num = num/10 ; K-- ; } return ans ; }" }, { "code": null, "e": 3171, "s": 3169, "text": "0" }, { "code": null, "e": 3195, "s": 3171, "text": "chechipresh2 months ago" }, { "code": null, "e": 3458, "s": 3195, "text": "class Solution{\npublic:\n int kthDigit(int A,int B,int K){\n // code here \n long int p=pow(A,B);\n int d;\n while (1){\n d=p%10;\n K--;\n if (K==0)\n return d;\n p/=10;\n }\n };" }, { "code": null, "e": 3604, "s": 3458, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3640, "s": 3604, "text": " Login to access your submissions. " }, { "code": null, "e": 3650, "s": 3640, "text": "\nProblem\n" }, { "code": null, "e": 3660, "s": 3650, "text": "\nContest\n" }, { "code": null, "e": 3723, "s": 3660, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3871, "s": 3723, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4079, "s": 3871, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4185, "s": 4079, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Difference between Console.Write and Console.WriteLine in C# - GeeksforGeeks
26 May, 2020 In C#, to print the data on the console output screen the following method are used – Console.Write() and Console.WriteLine() method. Console is a predefined class of System namespace. While Write() and WriteLine() both are the Console Class methods. The only difference between the Write() and WriteLine() is that Console.Write is used to print data without printing the new line, while Console.WriteLine is used to print data along with printing the new line. Program 1: Example of Console.Write() in C#. C# // C# program to show the difference// between Console.Write and // Console.WriteLine using System; public class GFG{ static void Main(string[] args) { // use of Write() method Console.Write("Geeks"); Console.Write("For"); Console.Write("Geeks"); }} Output: GeeksForGeeks Program 2: Example of Console.WriteLine() in C#. C# // C# program to show the difference// between Console.Write and // Console.WriteLine using System; public class GFG{ static void Main(string[] args) { // use of WriteLine() method Console.WriteLine("Geeks"); Console.WriteLine("For"); Console.WriteLine("Geeks"); }} Output: Geeks For Geeks In the above code, program 1 shows the output without including the newline in the each console output and program 2 shows the output including the newline in the each console output. C# Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25657, "s": 25629, "text": "\n26 May, 2020" }, { "code": null, "e": 25908, "s": 25657, "text": "In C#, to print the data on the console output screen the following method are used – Console.Write() and Console.WriteLine() method. Console is a predefined class of System namespace. While Write() and WriteLine() both are the Console Class methods." }, { "code": null, "e": 26120, "s": 25908, "text": "The only difference between the Write() and WriteLine() is that Console.Write is used to print data without printing the new line, while Console.WriteLine is used to print data along with printing the new line." }, { "code": null, "e": 26165, "s": 26120, "text": "Program 1: Example of Console.Write() in C#." }, { "code": null, "e": 26168, "s": 26165, "text": "C#" }, { "code": "// C# program to show the difference// between Console.Write and // Console.WriteLine using System; public class GFG{ static void Main(string[] args) { // use of Write() method Console.Write(\"Geeks\"); Console.Write(\"For\"); Console.Write(\"Geeks\"); }}", "e": 26463, "s": 26168, "text": null }, { "code": null, "e": 26471, "s": 26463, "text": "Output:" }, { "code": null, "e": 26486, "s": 26471, "text": "GeeksForGeeks\n" }, { "code": null, "e": 26535, "s": 26486, "text": "Program 2: Example of Console.WriteLine() in C#." }, { "code": null, "e": 26538, "s": 26535, "text": "C#" }, { "code": "// C# program to show the difference// between Console.Write and // Console.WriteLine using System; public class GFG{ static void Main(string[] args) { // use of WriteLine() method Console.WriteLine(\"Geeks\"); Console.WriteLine(\"For\"); Console.WriteLine(\"Geeks\"); }}", "e": 26849, "s": 26538, "text": null }, { "code": null, "e": 26857, "s": 26849, "text": "Output:" }, { "code": null, "e": 26874, "s": 26857, "text": "Geeks\nFor\nGeeks\n" }, { "code": null, "e": 27058, "s": 26874, "text": "In the above code, program 1 shows the output without including the newline in the each console output and program 2 shows the output including the newline in the each console output." }, { "code": null, "e": 27061, "s": 27058, "text": "C#" }, { "code": null, "e": 27080, "s": 27061, "text": "Difference Between" }, { "code": null, "e": 27178, "s": 27080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27201, "s": 27178, "text": "Extension Method in C#" }, { "code": null, "e": 27229, "s": 27201, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27246, "s": 27229, "text": "C# | Inheritance" }, { "code": null, "e": 27268, "s": 27246, "text": "Partial Classes in C#" }, { "code": null, "e": 27297, "s": 27268, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27328, "s": 27297, "text": "Difference between BFS and DFS" }, { "code": null, "e": 27368, "s": 27328, "text": "Class method vs Static method in Python" }, { "code": null, "e": 27400, "s": 27368, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27461, "s": 27400, "text": "Difference between var, let and const keywords in JavaScript" } ]
Find the angle between tangents drawn from a given external point to a Circle - GeeksforGeeks
25 May, 2021 Given a positive integers R representing the radius of the circle and the center of the circle (X1, Y1) and another point (X2, Y2) in the cartesian plane, the task is to find the angle between the pair of tangents drawn from the point (X2, Y2) to the circle. Examples: Input: R = 6, (X1, Y1) = (5, 1), (X2, Y2) = (6, 9)Output: 96.1851 Input: R = 4, (X1, Y1) = (7, 12), (X2, Y2) = (3, 4)Output: 53.1317 Approach: The given problem can be solved based on the following observations: The radius makes an angle of 90 degrees with the tangent at the point of contact of the tangent and circle. Also, the angle subtended by the pair of tangents (θ) is bisected by the line joining the center of the circle and the exterior point. Therefore, the distance between the center and the exterior point can be calculated using the distance formula as: Distance = Now, consider d as the distance between the two given points, then In the right-angled triangle OAB, => => => => Therefore, using the above formula, the angle between the pair of tangents drawn from the point (X2, Y2) to the circle can be calculated. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <cmath>#include <iostream>using namespace std; // Function to find the distance between// center and the exterior pointdouble point_distance(int x1, int y1, int x2, int y2){ // Find the difference between // the x and y coordinates int p = (x2 - x1); int q = (y2 - y1); // Using the distance formula double distance = sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle.void tangentAngle(int x1, int y1, int x2, int y2, double radius){ // Calculate the distance between // the center and exterior point double distance = point_distance( x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { cout << -1; } // Find the angle using the formula double result = 2 * asin(radius / distance) * 180 / 3.1415; // Print the resultant angle cout << result << " degrees";} // Driver Codeint main(){ int radius = 4; int x1 = 7, y1 = 12; int x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius); return 0;} // java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to find the distance between// center and the exterior pointstatic double point_distance(int x1, int y1, int x2, int y2){ // Find the difference between // the x and y coordinates int p = (x2 - x1); int q = (y2 - y1); // Using the distance formula double distance = Math.sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle.static void tangentAngle(int x1, int y1, int x2, int y2, double radius){ // Calculate the distance between // the center and exterior point double distance = point_distance( x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { System.out.println(-1); } // Find the angle using the formula double result = 2 * Math.asin(radius / distance) * 180 / 3.1415; // Print the resultant angle System.out.println(String.format("%.4f", result) + " degrees");} // Driver Code public static void main(String[] args) { int radius = 4; int x1 = 7, y1 = 12; int x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius); }} // This code is contributed by susmitakundugoaldanga. # Python 3 program for the above approachimport math # Function to find the distance between# center and the exterior pointdef point_distance(x1, y1, x2, y2): # Find the difference between # the x and y coordinates p = (x2 - x1) q = (y2 - y1) # Using the distance formula distance = math.sqrt(p * p + q * q) return distance # Function to find the angle between# the pair of tangents drawn from the# point (X2, Y2) to the circle.def tangentAngle(x1, y1, x2, y2, radius): # Calculate the distance between # the center and exterior point distance = point_distance( x1, y1, x2, y2) # Invalid Case if (radius / distance > 1 or radius / distance < -1): print(-1) # Find the angle using the formula result = 2 * math.asin(radius / distance) * 180 / 3.1415 # Print the resultant angle print(result, " degrees") # Driver Codeif __name__ == "__main__": radius = 4 x1 = 7 y1 = 12 x2 = 3 y2 = 4 tangentAngle(x1, y1, x2, y2, radius) # This code is contributed by ukasp. // C# program for the above approachusing System; class GFG{ // Function to find the distance between// center and the exterior pointstatic double point_distance(int x1, int y1, int x2, int y2){ // Find the difference between // the x and y coordinates int p = (x2 - x1); int q = (y2 - y1); // Using the distance formula double distance = Math.Sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle.static void tangentAngle(int x1, int y1, int x2, int y2, double radius){ // Calculate the distance between // the center and exterior point double distance = point_distance(x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { Console.WriteLine(-1); } // Find the angle using the formula double result = 2 * Math.Asin( radius / distance) * 180 / 3.1415; // Print the resultant angle Console.WriteLine( String.Format("{0:0.0000}", result) + " degrees");} // Driver codestatic void Main(){ int radius = 4; int x1 = 7, y1 = 12; int x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius);}} // This code is contributed by abhinavjain194 <script> // JavaScript program for the above approach // Function to find the distance between// center and the exterior pointfunction point_distance( x1, y1, x2, y2){ // Find the difference between // the x and y coordinates var p = (x2 - x1); var q = (y2 - y1); // Using the distance formula var distance = Math.sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle. function tangentAngle( x1, y1, x2, y2, radius){ // Calculate the distance between // the center and exterior point var distance = point_distance(x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { document.write(-1 + "<br>"); } // Find the angle using the formula var result = 2 * Math.asin( radius / distance) * 180 / 3.1415; // Print the resultant angle document.write( result.toFixed(4) + " degrees"); } // Driver code var radius = 4; var x1 = 7, y1 = 12; var x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius); </script> 53.1317 degrees Time Complexity: O(1)Auxiliary Space: O(1) ukasp susmitakundugoaldanga abhinavjain194 bunnyram19 circle Circles Geometric-Lines Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull using Divide and Conquer Algorithm Equation of circle when three points on the circle are given Circle and Lattice Points Orientation of 3 ordered points Program to find slope of a line Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25354, "s": 25326, "text": "\n25 May, 2021" }, { "code": null, "e": 25613, "s": 25354, "text": "Given a positive integers R representing the radius of the circle and the center of the circle (X1, Y1) and another point (X2, Y2) in the cartesian plane, the task is to find the angle between the pair of tangents drawn from the point (X2, Y2) to the circle." }, { "code": null, "e": 25623, "s": 25613, "text": "Examples:" }, { "code": null, "e": 25689, "s": 25623, "text": "Input: R = 6, (X1, Y1) = (5, 1), (X2, Y2) = (6, 9)Output: 96.1851" }, { "code": null, "e": 25756, "s": 25689, "text": "Input: R = 4, (X1, Y1) = (7, 12), (X2, Y2) = (3, 4)Output: 53.1317" }, { "code": null, "e": 25835, "s": 25756, "text": "Approach: The given problem can be solved based on the following observations:" }, { "code": null, "e": 26078, "s": 25835, "text": "The radius makes an angle of 90 degrees with the tangent at the point of contact of the tangent and circle. Also, the angle subtended by the pair of tangents (θ) is bisected by the line joining the center of the circle and the exterior point." }, { "code": null, "e": 26193, "s": 26078, "text": "Therefore, the distance between the center and the exterior point can be calculated using the distance formula as:" }, { "code": null, "e": 26205, "s": 26193, "text": "Distance = " }, { "code": null, "e": 26306, "s": 26205, "text": "Now, consider d as the distance between the two given points, then In the right-angled triangle OAB," }, { "code": null, "e": 26310, "s": 26306, "text": "=> " }, { "code": null, "e": 26314, "s": 26310, "text": "=> " }, { "code": null, "e": 26318, "s": 26314, "text": "=> " }, { "code": null, "e": 26322, "s": 26318, "text": "=> " }, { "code": null, "e": 26460, "s": 26322, "text": "Therefore, using the above formula, the angle between the pair of tangents drawn from the point (X2, Y2) to the circle can be calculated." }, { "code": null, "e": 26511, "s": 26460, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26515, "s": 26511, "text": "C++" }, { "code": null, "e": 26520, "s": 26515, "text": "Java" }, { "code": null, "e": 26528, "s": 26520, "text": "Python3" }, { "code": null, "e": 26531, "s": 26528, "text": "C#" }, { "code": null, "e": 26542, "s": 26531, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <cmath>#include <iostream>using namespace std; // Function to find the distance between// center and the exterior pointdouble point_distance(int x1, int y1, int x2, int y2){ // Find the difference between // the x and y coordinates int p = (x2 - x1); int q = (y2 - y1); // Using the distance formula double distance = sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle.void tangentAngle(int x1, int y1, int x2, int y2, double radius){ // Calculate the distance between // the center and exterior point double distance = point_distance( x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { cout << -1; } // Find the angle using the formula double result = 2 * asin(radius / distance) * 180 / 3.1415; // Print the resultant angle cout << result << \" degrees\";} // Driver Codeint main(){ int radius = 4; int x1 = 7, y1 = 12; int x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius); return 0;}", "e": 27800, "s": 26542, "text": null }, { "code": "// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to find the distance between// center and the exterior pointstatic double point_distance(int x1, int y1, int x2, int y2){ // Find the difference between // the x and y coordinates int p = (x2 - x1); int q = (y2 - y1); // Using the distance formula double distance = Math.sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle.static void tangentAngle(int x1, int y1, int x2, int y2, double radius){ // Calculate the distance between // the center and exterior point double distance = point_distance( x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { System.out.println(-1); } // Find the angle using the formula double result = 2 * Math.asin(radius / distance) * 180 / 3.1415; // Print the resultant angle System.out.println(String.format(\"%.4f\", result) + \" degrees\");} // Driver Code public static void main(String[] args) { int radius = 4; int x1 = 7, y1 = 12; int x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius); }} // This code is contributed by susmitakundugoaldanga.", "e": 29239, "s": 27800, "text": null }, { "code": "# Python 3 program for the above approachimport math # Function to find the distance between# center and the exterior pointdef point_distance(x1, y1, x2, y2): # Find the difference between # the x and y coordinates p = (x2 - x1) q = (y2 - y1) # Using the distance formula distance = math.sqrt(p * p + q * q) return distance # Function to find the angle between# the pair of tangents drawn from the# point (X2, Y2) to the circle.def tangentAngle(x1, y1, x2, y2, radius): # Calculate the distance between # the center and exterior point distance = point_distance( x1, y1, x2, y2) # Invalid Case if (radius / distance > 1 or radius / distance < -1): print(-1) # Find the angle using the formula result = 2 * math.asin(radius / distance) * 180 / 3.1415 # Print the resultant angle print(result, \" degrees\") # Driver Codeif __name__ == \"__main__\": radius = 4 x1 = 7 y1 = 12 x2 = 3 y2 = 4 tangentAngle(x1, y1, x2, y2, radius) # This code is contributed by ukasp.", "e": 30376, "s": 29239, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the distance between// center and the exterior pointstatic double point_distance(int x1, int y1, int x2, int y2){ // Find the difference between // the x and y coordinates int p = (x2 - x1); int q = (y2 - y1); // Using the distance formula double distance = Math.Sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle.static void tangentAngle(int x1, int y1, int x2, int y2, double radius){ // Calculate the distance between // the center and exterior point double distance = point_distance(x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { Console.WriteLine(-1); } // Find the angle using the formula double result = 2 * Math.Asin( radius / distance) * 180 / 3.1415; // Print the resultant angle Console.WriteLine( String.Format(\"{0:0.0000}\", result) + \" degrees\");} // Driver codestatic void Main(){ int radius = 4; int x1 = 7, y1 = 12; int x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius);}} // This code is contributed by abhinavjain194", "e": 31738, "s": 30376, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the distance between// center and the exterior pointfunction point_distance( x1, y1, x2, y2){ // Find the difference between // the x and y coordinates var p = (x2 - x1); var q = (y2 - y1); // Using the distance formula var distance = Math.sqrt(p * p + q * q); return distance;} // Function to find the angle between// the pair of tangents drawn from the// point (X2, Y2) to the circle. function tangentAngle( x1, y1, x2, y2, radius){ // Calculate the distance between // the center and exterior point var distance = point_distance(x1, y1, x2, y2); // Invalid Case if (radius / distance > 1 || radius / distance < -1) { document.write(-1 + \"<br>\"); } // Find the angle using the formula var result = 2 * Math.asin( radius / distance) * 180 / 3.1415; // Print the resultant angle document.write( result.toFixed(4) + \" degrees\"); } // Driver code var radius = 4; var x1 = 7, y1 = 12; var x2 = 3, y2 = 4; tangentAngle(x1, y1, x2, y2, radius); </script>", "e": 32905, "s": 31738, "text": null }, { "code": null, "e": 32921, "s": 32905, "text": "53.1317 degrees" }, { "code": null, "e": 32966, "s": 32923, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 32972, "s": 32966, "text": "ukasp" }, { "code": null, "e": 32994, "s": 32972, "text": "susmitakundugoaldanga" }, { "code": null, "e": 33009, "s": 32994, "text": "abhinavjain194" }, { "code": null, "e": 33020, "s": 33009, "text": "bunnyram19" }, { "code": null, "e": 33027, "s": 33020, "text": "circle" }, { "code": null, "e": 33035, "s": 33027, "text": "Circles" }, { "code": null, "e": 33051, "s": 33035, "text": "Geometric-Lines" }, { "code": null, "e": 33061, "s": 33051, "text": "Geometric" }, { "code": null, "e": 33074, "s": 33061, "text": "Mathematical" }, { "code": null, "e": 33087, "s": 33074, "text": "Mathematical" }, { "code": null, "e": 33097, "s": 33087, "text": "Geometric" }, { "code": null, "e": 33195, "s": 33097, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33204, "s": 33195, "text": "Comments" }, { "code": null, "e": 33217, "s": 33204, "text": "Old Comments" }, { "code": null, "e": 33264, "s": 33217, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 33325, "s": 33264, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 33351, "s": 33325, "text": "Circle and Lattice Points" }, { "code": null, "e": 33383, "s": 33351, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 33415, "s": 33383, "text": "Program to find slope of a line" }, { "code": null, "e": 33445, "s": 33415, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33505, "s": 33445, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33520, "s": 33505, "text": "C++ Data Types" }, { "code": null, "e": 33563, "s": 33520, "text": "Set in C++ Standard Template Library (STL)" } ]
Dynamic SQL - GeeksforGeeks
08 Sep, 2020 Prerequisite – Difference between Static and Dynamic SQL Dynamic SQL is a programming technique that could be used to write SQL queries during runtime. Dynamic SQL could be used to create general and flexible SQL queries. Syntax for dynamic SQL is to make it string as below : 'SELECT statement'; To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : EXEC sp_executesql N'SELECT statement'; Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string.Steps to use Dynamic SQL : Declare two variables, @var1 for holding the name of the table and @var 2 for holding the dynamic SQL :DECLARE @var1 NVARCHAR(MAX), @var2 NVARCHAR(MAX);Set the value of the @var1 variable to table_name :SET @var1 = N'table_name';Create the dynamic SQL by adding the SELECT statement to the table name parameter :SET @var2= N'SELECT * FROM ' + @var1;Run the sp_executesql stored procedure by using the @var2 parameter :EXEC sp_executesql @var2; Declare two variables, @var1 for holding the name of the table and @var 2 for holding the dynamic SQL :DECLARE @var1 NVARCHAR(MAX), @var2 NVARCHAR(MAX); DECLARE @var1 NVARCHAR(MAX), @var2 NVARCHAR(MAX); Set the value of the @var1 variable to table_name :SET @var1 = N'table_name'; SET @var1 = N'table_name'; Create the dynamic SQL by adding the SELECT statement to the table name parameter :SET @var2= N'SELECT * FROM ' + @var1; SET @var2= N'SELECT * FROM ' + @var1; Run the sp_executesql stored procedure by using the @var2 parameter :EXEC sp_executesql @var2; EXEC sp_executesql @var2; Example – SELECT * from geek; Table – Geek Using Dynamic SQL : DECLARE @tab NVARCHAR(128), @st NVARCHAR(MAX); SET @tab = N'geektable'; SET @st = N'SELECT * FROM ' + @tab; EXEC sp_executesql @st; Table – Geek DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL | Subquery SQL Query to Convert VARCHAR to INT SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n08 Sep, 2020" }, { "code": null, "e": 25570, "s": 25513, "text": "Prerequisite – Difference between Static and Dynamic SQL" }, { "code": null, "e": 25735, "s": 25570, "text": "Dynamic SQL is a programming technique that could be used to write SQL queries during runtime. Dynamic SQL could be used to create general and flexible SQL queries." }, { "code": null, "e": 25790, "s": 25735, "text": "Syntax for dynamic SQL is to make it string as below :" }, { "code": null, "e": 25810, "s": 25790, "text": "'SELECT statement';" }, { "code": null, "e": 25898, "s": 25810, "text": "To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below :" }, { "code": null, "e": 25938, "s": 25898, "text": "EXEC sp_executesql N'SELECT statement';" }, { "code": null, "e": 26040, "s": 25938, "text": "Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string.Steps to use Dynamic SQL :" }, { "code": null, "e": 26487, "s": 26040, "text": "Declare two variables, @var1 for holding the name of the table and @var 2 for holding the dynamic SQL :DECLARE \n@var1 NVARCHAR(MAX), \n@var2 NVARCHAR(MAX);Set the value of the @var1 variable to table_name :SET @var1 = N'table_name';Create the dynamic SQL by adding the SELECT statement to the table name parameter :SET @var2= N'SELECT * \nFROM ' + @var1;Run the sp_executesql stored procedure by using the @var2 parameter :EXEC sp_executesql @var2;" }, { "code": null, "e": 26642, "s": 26487, "text": "Declare two variables, @var1 for holding the name of the table and @var 2 for holding the dynamic SQL :DECLARE \n@var1 NVARCHAR(MAX), \n@var2 NVARCHAR(MAX);" }, { "code": null, "e": 26694, "s": 26642, "text": "DECLARE \n@var1 NVARCHAR(MAX), \n@var2 NVARCHAR(MAX);" }, { "code": null, "e": 26772, "s": 26694, "text": "Set the value of the @var1 variable to table_name :SET @var1 = N'table_name';" }, { "code": null, "e": 26799, "s": 26772, "text": "SET @var1 = N'table_name';" }, { "code": null, "e": 26921, "s": 26799, "text": "Create the dynamic SQL by adding the SELECT statement to the table name parameter :SET @var2= N'SELECT * \nFROM ' + @var1;" }, { "code": null, "e": 26960, "s": 26921, "text": "SET @var2= N'SELECT * \nFROM ' + @var1;" }, { "code": null, "e": 27055, "s": 26960, "text": "Run the sp_executesql stored procedure by using the @var2 parameter :EXEC sp_executesql @var2;" }, { "code": null, "e": 27081, "s": 27055, "text": "EXEC sp_executesql @var2;" }, { "code": null, "e": 27091, "s": 27081, "text": "Example –" }, { "code": null, "e": 27112, "s": 27091, "text": "SELECT * \nfrom geek;" }, { "code": null, "e": 27125, "s": 27112, "text": "Table – Geek" }, { "code": null, "e": 27145, "s": 27125, "text": "Using Dynamic SQL :" }, { "code": null, "e": 27280, "s": 27145, "text": "DECLARE \n@tab NVARCHAR(128), \n@st NVARCHAR(MAX);\nSET @tab = N'geektable';\nSET @st = N'SELECT * \nFROM ' + @tab;\nEXEC sp_executesql @st;" }, { "code": null, "e": 27293, "s": 27280, "text": "Table – Geek" }, { "code": null, "e": 27302, "s": 27293, "text": "DBMS-SQL" }, { "code": null, "e": 27306, "s": 27302, "text": "SQL" }, { "code": null, "e": 27310, "s": 27306, "text": "SQL" }, { "code": null, "e": 27408, "s": 27310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27474, "s": 27408, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27531, "s": 27474, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27563, "s": 27531, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27578, "s": 27563, "text": "SQL | Subquery" }, { "code": null, "e": 27614, "s": 27578, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27692, "s": 27614, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27709, "s": 27692, "text": "SQL using Python" }, { "code": null, "e": 27775, "s": 27709, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27837, "s": 27775, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Product of all pairwise consecutive elements in an Array - GeeksforGeeks
23 Apr, 2021 Given an array of integers of N elements. The task is to print the product of all of the pairwise consecutive elements.Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all ranging from 0 to N-2Examples: Input : arr[] = {8, 5, 4, 3, 15, 20} Output : 40, 20, 12, 45, 300 Input : arr[] = {5, 10, 15, 20} Output : 50, 150, 300 The solution is to traverse the array and calculate and print the product of every pair (arr[i], arr[i+1]).Below is the implementation of this approach: C++ Java Python 3 C# PHP Javascript // C++ program to print the// product of the consecutive elements.#include <iostream>using namespace std; // Function to print pairwise// consecutive productvoid pairwiseProduct(int arr[], int n){ int prod = 1; for (int i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; printf(" %d ", prod); }} // Driver Codeint main(){ int arr[] = { 4, 10, 15, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pairwiseProduct(arr, n); return 0;} // Java program to print the product// of the consecutive elements.import java .io.*; class GFG{// Function to print pairwise// consecutive productstatic void pairwiseProduct(int[] arr, int n){ int prod = 1; for (int i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; System.out.print(prod + " "); }} // Driver Codepublic static void main(String[] args){ int[] arr = { 4, 10, 15, 5, 6 }; int n = arr.length; pairwiseProduct(arr, n);}} // This code is contributed// by anuj_67.. # Python 3 program to print the# product of the consecutive elements. # Function to print pairwise# consecutive productdef pairwiseProduct( arr, n): prod = 1 for i in range(n - 1) : # multiply the alternate numbers prod = arr[i] * arr[i + 1] print(prod, end = " ") # Driver Codeif __name__=="__main__": arr = [ 4, 10, 15, 5, 6 ] n = len(arr) pairwiseProduct(arr, n) # This code is contributed# by ChitraNayal // C# program to print the product// of the consecutive elements.using System; class GFG{// Function to print pairwise// consecutive productstatic void pairwiseProduct(int[] arr, int n){ int prod = 1; for (int i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; Console.Write(prod + " "); }} // Driver Codepublic static void Main(){ int[] arr = { 4, 10, 15, 5, 6 }; int n = arr.Length; pairwiseProduct(arr, n);}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to print the// product of the consecutive elements. // Function to print pairwise// consecutive productfunction pairwiseProduct(&$arr, $n){ $prod = 1; for ($i = 0; $i < $n - 1; $i++) { // multiply the alternate numbers $prod = $arr[$i] * $arr[$i + 1]; echo ($prod); echo (" "); }} // Driver Code$arr = array(4, 10, 15, 5, 6 );$n = sizeof($arr); pairwiseProduct($arr, $n); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program to print the// product of the consecutive elements. // Function to print pairwise// consecutive productfunction pairwiseProduct( arr, n){ let prod = 1; for (let i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; document.write(prod + " ");; }} // driver code let arr = [ 4, 10, 15, 5, 6 ]; let n = arr.length; pairwiseProduct(arr, n); // This code is contributed by jana_sayantan.</script> 40 150 75 30 Time complexity : O(n) Shivi_Aggarwal Akanksha_Rai vt_m ukasp VishalBachchas jana_sayantan Technical Scripter 2018 Arrays School Programming Technical Scripter Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Find duplicates in O(n) time and O(1) extra space | Set 1 Reversal algorithm for array rotation Next Greater Element Python Dictionary Inheritance in C++ Reverse a string in Java Interfaces in Java C++ Classes and Objects
[ { "code": null, "e": 24821, "s": 24793, "text": "\n23 Apr, 2021" }, { "code": null, "e": 25049, "s": 24821, "text": "Given an array of integers of N elements. The task is to print the product of all of the pairwise consecutive elements.Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all ranging from 0 to N-2Examples: " }, { "code": null, "e": 25172, "s": 25049, "text": "Input : arr[] = {8, 5, 4, 3, 15, 20}\nOutput : 40, 20, 12, 45, 300\n\nInput : arr[] = {5, 10, 15, 20}\nOutput : 50, 150, 300" }, { "code": null, "e": 25329, "s": 25174, "text": "The solution is to traverse the array and calculate and print the product of every pair (arr[i], arr[i+1]).Below is the implementation of this approach: " }, { "code": null, "e": 25333, "s": 25329, "text": "C++" }, { "code": null, "e": 25338, "s": 25333, "text": "Java" }, { "code": null, "e": 25347, "s": 25338, "text": "Python 3" }, { "code": null, "e": 25350, "s": 25347, "text": "C#" }, { "code": null, "e": 25354, "s": 25350, "text": "PHP" }, { "code": null, "e": 25365, "s": 25354, "text": "Javascript" }, { "code": "// C++ program to print the// product of the consecutive elements.#include <iostream>using namespace std; // Function to print pairwise// consecutive productvoid pairwiseProduct(int arr[], int n){ int prod = 1; for (int i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; printf(\" %d \", prod); }} // Driver Codeint main(){ int arr[] = { 4, 10, 15, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pairwiseProduct(arr, n); return 0;}", "e": 25875, "s": 25365, "text": null }, { "code": "// Java program to print the product// of the consecutive elements.import java .io.*; class GFG{// Function to print pairwise// consecutive productstatic void pairwiseProduct(int[] arr, int n){ int prod = 1; for (int i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; System.out.print(prod + \" \"); }} // Driver Codepublic static void main(String[] args){ int[] arr = { 4, 10, 15, 5, 6 }; int n = arr.length; pairwiseProduct(arr, n);}} // This code is contributed// by anuj_67..", "e": 26460, "s": 25875, "text": null }, { "code": "# Python 3 program to print the# product of the consecutive elements. # Function to print pairwise# consecutive productdef pairwiseProduct( arr, n): prod = 1 for i in range(n - 1) : # multiply the alternate numbers prod = arr[i] * arr[i + 1] print(prod, end = \" \") # Driver Codeif __name__==\"__main__\": arr = [ 4, 10, 15, 5, 6 ] n = len(arr) pairwiseProduct(arr, n) # This code is contributed# by ChitraNayal", "e": 26913, "s": 26460, "text": null }, { "code": "// C# program to print the product// of the consecutive elements.using System; class GFG{// Function to print pairwise// consecutive productstatic void pairwiseProduct(int[] arr, int n){ int prod = 1; for (int i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; Console.Write(prod + \" \"); }} // Driver Codepublic static void Main(){ int[] arr = { 4, 10, 15, 5, 6 }; int n = arr.Length; pairwiseProduct(arr, n);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 27489, "s": 26913, "text": null }, { "code": "<?php// PHP program to print the// product of the consecutive elements. // Function to print pairwise// consecutive productfunction pairwiseProduct(&$arr, $n){ $prod = 1; for ($i = 0; $i < $n - 1; $i++) { // multiply the alternate numbers $prod = $arr[$i] * $arr[$i + 1]; echo ($prod); echo (\" \"); }} // Driver Code$arr = array(4, 10, 15, 5, 6 );$n = sizeof($arr); pairwiseProduct($arr, $n); // This code is contributed// by Shivi_Aggarwal?>", "e": 27972, "s": 27489, "text": null }, { "code": "<script> // Javascript program to print the// product of the consecutive elements. // Function to print pairwise// consecutive productfunction pairwiseProduct( arr, n){ let prod = 1; for (let i = 0; i < n - 1; i++) { // multiply the alternate numbers prod = arr[i] * arr[i + 1]; document.write(prod + \" \");; }} // driver code let arr = [ 4, 10, 15, 5, 6 ]; let n = arr.length; pairwiseProduct(arr, n); // This code is contributed by jana_sayantan.</script>", "e": 28481, "s": 27972, "text": null }, { "code": null, "e": 28497, "s": 28481, "text": "40 150 75 30" }, { "code": null, "e": 28523, "s": 28499, "text": "Time complexity : O(n) " }, { "code": null, "e": 28538, "s": 28523, "text": "Shivi_Aggarwal" }, { "code": null, "e": 28551, "s": 28538, "text": "Akanksha_Rai" }, { "code": null, "e": 28556, "s": 28551, "text": "vt_m" }, { "code": null, "e": 28562, "s": 28556, "text": "ukasp" }, { "code": null, "e": 28577, "s": 28562, "text": "VishalBachchas" }, { "code": null, "e": 28591, "s": 28577, "text": "jana_sayantan" }, { "code": null, "e": 28615, "s": 28591, "text": "Technical Scripter 2018" }, { "code": null, "e": 28622, "s": 28615, "text": "Arrays" }, { "code": null, "e": 28641, "s": 28622, "text": "School Programming" }, { "code": null, "e": 28660, "s": 28641, "text": "Technical Scripter" }, { "code": null, "e": 28667, "s": 28660, "text": "Arrays" }, { "code": null, "e": 28765, "s": 28667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28774, "s": 28765, "text": "Comments" }, { "code": null, "e": 28787, "s": 28774, "text": "Old Comments" }, { "code": null, "e": 28812, "s": 28787, "text": "Window Sliding Technique" }, { "code": null, "e": 28861, "s": 28812, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28919, "s": 28861, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 28957, "s": 28919, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28978, "s": 28957, "text": "Next Greater Element" }, { "code": null, "e": 28996, "s": 28978, "text": "Python Dictionary" }, { "code": null, "e": 29015, "s": 28996, "text": "Inheritance in C++" }, { "code": null, "e": 29040, "s": 29015, "text": "Reverse a string in Java" }, { "code": null, "e": 29059, "s": 29040, "text": "Interfaces in Java" } ]
C program to print digital clock with current time - GeeksforGeeks
16 Nov, 2021 The time.h header defines four variable types, two macro and various functions for manipulating date and time. A brief description of the variable types defined in the header time.h is as : size_t : This is the unsigned integral type and is the result of the sizeof keyword. clock_t : This is a type suitable for storing the processor time. time_t is : This is a type suitable for storing the calendar time. struct tm : This is a structure used to hold the time and date. Below is the implementation of digital clock. On executing the program, the output window will show the time when the program was executed. C // C implementation of digital clock#include <stdio.h>#include <time.h> // driver codeint main(){ time_t s, val = 1; struct tm* current_time; // time in seconds s = time(NULL); // to get current time current_time = localtime(&s); // print time in minutes, // hours and seconds printf("%02d:%02d:%02d", current_time->tm_hour, current_time->tm_min, current_time->tm_sec); return 0;} Output : Below is the C program to show the current time inside a rectangular bar. The output window shows the day, month, date, current time and year. C // C program to print digital// clock using graphics#include <graphics.h>#include <time.h> // driver codeint main(){ // DETECT is a macro defined in // "graphics.h" header file int dt = DETECT, gmode, midx, midy; long current_time; char strftime[30]; // initialize graphic mode initgraph(&dt, &gmode, ""); // to find mid value in horizontal // and vertical axis midx = getmaxx() / 2; midy = getmaxy() / 2; // set current colour to white setcolor(WHITE); // make a rectangular box in // the middle of screen rectangle(midx - 200, midy - 40, midx + 200, midy + 40); // fill rectangle with white color floodfill(midx, midy, WHITE); while (!kbhit()) { // get current time in seconds current_time = time(NULL); // store time in string strcpy(strftime, ctime(¤t_time)); // set color of text to red setcolor(RED); // set the text justification settextjustify(CENTER_TEXT, CENTER_TEXT); // to set styling to text settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 3); // locate position to write moveto(midx, midy); // print current time outtext(strftime); } getch(); // deallocate memory for graph closegraph();} Output : References : cprogramforbeginners kalrap615 c-graphics date-time-program C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File UDP Server-Client implementation in C
[ { "code": null, "e": 25587, "s": 25559, "text": "\n16 Nov, 2021" }, { "code": null, "e": 25779, "s": 25587, "text": "The time.h header defines four variable types, two macro and various functions for manipulating date and time. A brief description of the variable types defined in the header time.h is as : " }, { "code": null, "e": 25864, "s": 25779, "text": "size_t : This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 25930, "s": 25864, "text": "clock_t : This is a type suitable for storing the processor time." }, { "code": null, "e": 25997, "s": 25930, "text": "time_t is : This is a type suitable for storing the calendar time." }, { "code": null, "e": 26061, "s": 25997, "text": "struct tm : This is a structure used to hold the time and date." }, { "code": null, "e": 26203, "s": 26061, "text": "Below is the implementation of digital clock. On executing the program, the output window will show the time when the program was executed. " }, { "code": null, "e": 26205, "s": 26203, "text": "C" }, { "code": "// C implementation of digital clock#include <stdio.h>#include <time.h> // driver codeint main(){ time_t s, val = 1; struct tm* current_time; // time in seconds s = time(NULL); // to get current time current_time = localtime(&s); // print time in minutes, // hours and seconds printf(\"%02d:%02d:%02d\", current_time->tm_hour, current_time->tm_min, current_time->tm_sec); return 0;}", "e": 26650, "s": 26205, "text": null }, { "code": null, "e": 26661, "s": 26650, "text": "Output : " }, { "code": null, "e": 26805, "s": 26661, "text": "Below is the C program to show the current time inside a rectangular bar. The output window shows the day, month, date, current time and year. " }, { "code": null, "e": 26807, "s": 26805, "text": "C" }, { "code": "// C program to print digital// clock using graphics#include <graphics.h>#include <time.h> // driver codeint main(){ // DETECT is a macro defined in // \"graphics.h\" header file int dt = DETECT, gmode, midx, midy; long current_time; char strftime[30]; // initialize graphic mode initgraph(&dt, &gmode, \"\"); // to find mid value in horizontal // and vertical axis midx = getmaxx() / 2; midy = getmaxy() / 2; // set current colour to white setcolor(WHITE); // make a rectangular box in // the middle of screen rectangle(midx - 200, midy - 40, midx + 200, midy + 40); // fill rectangle with white color floodfill(midx, midy, WHITE); while (!kbhit()) { // get current time in seconds current_time = time(NULL); // store time in string strcpy(strftime, ctime(¤t_time)); // set color of text to red setcolor(RED); // set the text justification settextjustify(CENTER_TEXT, CENTER_TEXT); // to set styling to text settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 3); // locate position to write moveto(midx, midy); // print current time outtext(strftime); } getch(); // deallocate memory for graph closegraph();}", "e": 28119, "s": 26807, "text": null }, { "code": null, "e": 28130, "s": 28119, "text": "Output : " }, { "code": null, "e": 28165, "s": 28130, "text": "References : cprogramforbeginners " }, { "code": null, "e": 28175, "s": 28165, "text": "kalrap615" }, { "code": null, "e": 28186, "s": 28175, "text": "c-graphics" }, { "code": null, "e": 28204, "s": 28186, "text": "date-time-program" }, { "code": null, "e": 28215, "s": 28204, "text": "C Language" }, { "code": null, "e": 28226, "s": 28215, "text": "C Programs" }, { "code": null, "e": 28324, "s": 28226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28362, "s": 28324, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28388, "s": 28362, "text": "Exception Handling in C++" }, { "code": null, "e": 28410, "s": 28388, "text": "'this' pointer in C++" }, { "code": null, "e": 28430, "s": 28410, "text": "Multithreading in C" }, { "code": null, "e": 28471, "s": 28430, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28484, "s": 28471, "text": "Strings in C" }, { "code": null, "e": 28525, "s": 28484, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28560, "s": 28525, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 28601, "s": 28560, "text": "C Program to read contents of Whole File" } ]
Java Program to Display Transpose Matrix - GeeksforGeeks
07 Jan, 2021 Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Approach: Create a 2-D Array. Insert the values in the array by running two nested loops. The outer ith loop will go till the no.of rows and the inner jth loop will run till the number of columns. For displaying the transpose of the matrix, run the same loop as explained in the above step but print the a[j[i] th element every time we are traversing inside the loop. Example: Java // Java Program to Display Transpose Matrix import java.util.*;public class GFG { public static void main(String args[]) { // initialize the array of 3*3 order int[][] arr = new int[3][3]; System.out.println("enter the elements of matrix"); int k = 1; // get the elements from user for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { arr[i][j] = k++; } } System.out.println("Matrix before Transpose "); // display original matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(" " + arr[i][j]); } System.out.println(); } System.out.println("Matrix After Transpose "); // transpose and print matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(" " + arr[j][i]); } System.out.println(); } }} enter the elements of matrix Matrix before Transpose 1 2 3 4 5 6 7 8 9 Matrix After Transpose 1 4 7 2 5 8 3 6 9 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25373, "s": 25345, "text": "\n07 Jan, 2021" }, { "code": null, "e": 25535, "s": 25373, "text": "Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]." }, { "code": null, "e": 25545, "s": 25535, "text": "Approach:" }, { "code": null, "e": 25565, "s": 25545, "text": "Create a 2-D Array." }, { "code": null, "e": 25732, "s": 25565, "text": "Insert the values in the array by running two nested loops. The outer ith loop will go till the no.of rows and the inner jth loop will run till the number of columns." }, { "code": null, "e": 25903, "s": 25732, "text": "For displaying the transpose of the matrix, run the same loop as explained in the above step but print the a[j[i] th element every time we are traversing inside the loop." }, { "code": null, "e": 25912, "s": 25903, "text": "Example:" }, { "code": null, "e": 25917, "s": 25912, "text": "Java" }, { "code": "// Java Program to Display Transpose Matrix import java.util.*;public class GFG { public static void main(String args[]) { // initialize the array of 3*3 order int[][] arr = new int[3][3]; System.out.println(\"enter the elements of matrix\"); int k = 1; // get the elements from user for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { arr[i][j] = k++; } } System.out.println(\"Matrix before Transpose \"); // display original matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(\" \" + arr[i][j]); } System.out.println(); } System.out.println(\"Matrix After Transpose \"); // transpose and print matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(\" \" + arr[j][i]); } System.out.println(); } }}", "e": 26939, "s": 25917, "text": null }, { "code": null, "e": 27059, "s": 26939, "text": "enter the elements of matrix\nMatrix before Transpose \n 1 2 3\n 4 5 6\n 7 8 9\nMatrix After Transpose \n 1 4 7\n 2 5 8\n 3 6 9" }, { "code": null, "e": 27066, "s": 27059, "text": "Picked" }, { "code": null, "e": 27090, "s": 27066, "text": "Technical Scripter 2020" }, { "code": null, "e": 27095, "s": 27090, "text": "Java" }, { "code": null, "e": 27109, "s": 27095, "text": "Java Programs" }, { "code": null, "e": 27128, "s": 27109, "text": "Technical Scripter" }, { "code": null, "e": 27133, "s": 27128, "text": "Java" }, { "code": null, "e": 27231, "s": 27133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27246, "s": 27231, "text": "Stream In Java" }, { "code": null, "e": 27265, "s": 27246, "text": "Exceptions in Java" }, { "code": null, "e": 27286, "s": 27265, "text": "Constructors in Java" }, { "code": null, "e": 27316, "s": 27286, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27362, "s": 27316, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27388, "s": 27362, "text": "Java Programming Examples" }, { "code": null, "e": 27422, "s": 27388, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27469, "s": 27422, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 27501, "s": 27469, "text": "How to Iterate HashMap in Java?" } ]
isgraph() C library function - GeeksforGeeks
24 Oct, 2017 The C library function isgraph() checks whether a character is a graphic character or not.Characters that have graphical representation are known are graphic characters. For example: ‘:’ ‘;’ ‘?’ ‘@’ etc. Syntax – #include <ctype.h> int isgraph(int ch); Return Value – function returns nonzero if ch is any printable character other than a space, else it returns 0. For ASCII environments, printable characters are in the range of 0X21 through 0X7E. Code – // code to check graphical character#include <stdio.h>#include <ctype.h> int main(){ char var1 = 'g'; char var2 = ' '; char var3 = '1'; if (isgraph(var1)) printf("var1 = |%c| can be printed\n", var1); else printf("var1 = |%c| can't be printed\n", var1); if (isgraph(var2)) printf("var2 = |%c| can be printed\n", var2); else printf("var2 = |%c| can't be printed\n", var2); if (isgraph(var3)) printf("var3 = |%c| can be printed\n", var3); else printf("var3 = |%c| can't be printed\n", var3); return (0);} Output – var1 = |g| can be printed var2 = | | can't be printed var3 = |1| can be printed Code – // code to print all Graphical Characters#include <stdio.h>#include <ctype.h> int main(){ int i; printf("In C programming All graphic " "characters are: \n"); for (i = 0; i <= 127; ++i) if (isgraph(i) != 0) printf("%c ", i); return 0;} Output – In C programming All graphic characters are: ! " # $ % & ' ( ) * +, - . / 0 1 2 3 4 5 6 7 8 9 : ; ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Library C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Multiple Inheritance in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C How to split a string in C/C++, Python and Java? UDP Server-Client implementation in C
[ { "code": null, "e": 24330, "s": 24302, "text": "\n24 Oct, 2017" }, { "code": null, "e": 24534, "s": 24330, "text": "The C library function isgraph() checks whether a character is a graphic character or not.Characters that have graphical representation are known are graphic characters. For example: ‘:’ ‘;’ ‘?’ ‘@’ etc." }, { "code": null, "e": 24543, "s": 24534, "text": "Syntax –" }, { "code": null, "e": 24584, "s": 24543, "text": "#include <ctype.h>\nint isgraph(int ch);\n" }, { "code": null, "e": 24696, "s": 24584, "text": "Return Value – function returns nonzero if ch is any printable character other than a space, else it returns 0." }, { "code": null, "e": 24780, "s": 24696, "text": "For ASCII environments, printable characters are in the range of 0X21 through 0X7E." }, { "code": null, "e": 24787, "s": 24780, "text": "Code –" }, { "code": "// code to check graphical character#include <stdio.h>#include <ctype.h> int main(){ char var1 = 'g'; char var2 = ' '; char var3 = '1'; if (isgraph(var1)) printf(\"var1 = |%c| can be printed\\n\", var1); else printf(\"var1 = |%c| can't be printed\\n\", var1); if (isgraph(var2)) printf(\"var2 = |%c| can be printed\\n\", var2); else printf(\"var2 = |%c| can't be printed\\n\", var2); if (isgraph(var3)) printf(\"var3 = |%c| can be printed\\n\", var3); else printf(\"var3 = |%c| can't be printed\\n\", var3); return (0);}", "e": 25381, "s": 24787, "text": null }, { "code": null, "e": 25390, "s": 25381, "text": "Output –" }, { "code": null, "e": 25471, "s": 25390, "text": "var1 = |g| can be printed\nvar2 = | | can't be printed\nvar3 = |1| can be printed\n" }, { "code": null, "e": 25478, "s": 25471, "text": "Code –" }, { "code": "// code to print all Graphical Characters#include <stdio.h>#include <ctype.h> int main(){ int i; printf(\"In C programming All graphic \" \"characters are: \\n\"); for (i = 0; i <= 127; ++i) if (isgraph(i) != 0) printf(\"%c \", i); return 0;}", "e": 25766, "s": 25478, "text": null }, { "code": null, "e": 25775, "s": 25766, "text": "Output –" }, { "code": null, "e": 26008, "s": 25775, "text": "In C programming All graphic characters are: \n! \" # $ % & ' ( ) * +, - . / 0 1 2 3 4 5 6 7 8 9 \n: ; ? @ A B C D E F G H I J K L M N O P Q R S T U\n V W X Y Z [ \\ ] ^ _ ` a b c d e f g h i j k l m n\n o p q r s t u v w x y z { | } ~ \n" }, { "code": null, "e": 26313, "s": 26008, "text": "This article is contributed by Shivani Ghughtyal. 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": 26438, "s": 26313, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26448, "s": 26438, "text": "C-Library" }, { "code": null, "e": 26459, "s": 26448, "text": "C Language" }, { "code": null, "e": 26557, "s": 26459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26595, "s": 26557, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26621, "s": 26595, "text": "Exception Handling in C++" }, { "code": null, "e": 26643, "s": 26621, "text": "'this' pointer in C++" }, { "code": null, "e": 26663, "s": 26643, "text": "Multithreading in C" }, { "code": null, "e": 26704, "s": 26663, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26732, "s": 26704, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 26774, "s": 26732, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26810, "s": 26774, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26859, "s": 26810, "text": "How to split a string in C/C++, Python and Java?" } ]
Partial functions in Python. Reduce the complexity of your code. | by Dhanesh Budhrani | Towards Data Science
In this post I’ll be talking about partial functions and how we can use them to make our code cleaner. A partial function allows us to call a second function with fixed values in certain arguments. For instance, we may have a function that computes an exponentiation. Then, we may need to create a new function that assigns a fixed value to either the base or the exponent. We can easily do this by using functool’s partial function, without having to replicate the body of the original function. Let’s go through the implementation of the above example to get a better understanding. First of all, we’ll need the function from which the partial function will be based on. As mentioned before, we’ll implement an exponentiation function: def power(base, exponent): return base ** exponent Now, we may want to implement a function that computes the squared value of a number. If we didn’t have partial functions available in Python, we’d have to replicate (and adapt) our code: def squared(base): return base ** 2 In this case, it wasn’t much of a big deal, since we only had to replicate one line of code. However, in most situations, you’ll have to deal with larger functions. Let’s see how to reuse “power()” with a partial function: from functools import partialdef power(base, exponent): return base ** exponentsquared = partial(power, exponent=2) Finally, we may call “squared()” as simply as follows: squared(3)squared(base=7) That’s it! I hope that partial functions become a useful tool for you and help you reduce complexity in your code!
[ { "code": null, "e": 274, "s": 171, "text": "In this post I’ll be talking about partial functions and how we can use them to make our code cleaner." }, { "code": null, "e": 756, "s": 274, "text": "A partial function allows us to call a second function with fixed values in certain arguments. For instance, we may have a function that computes an exponentiation. Then, we may need to create a new function that assigns a fixed value to either the base or the exponent. We can easily do this by using functool’s partial function, without having to replicate the body of the original function. Let’s go through the implementation of the above example to get a better understanding." }, { "code": null, "e": 909, "s": 756, "text": "First of all, we’ll need the function from which the partial function will be based on. As mentioned before, we’ll implement an exponentiation function:" }, { "code": null, "e": 961, "s": 909, "text": "def power(base, exponent): return base ** exponent" }, { "code": null, "e": 1149, "s": 961, "text": "Now, we may want to implement a function that computes the squared value of a number. If we didn’t have partial functions available in Python, we’d have to replicate (and adapt) our code:" }, { "code": null, "e": 1186, "s": 1149, "text": "def squared(base): return base ** 2" }, { "code": null, "e": 1409, "s": 1186, "text": "In this case, it wasn’t much of a big deal, since we only had to replicate one line of code. However, in most situations, you’ll have to deal with larger functions. Let’s see how to reuse “power()” with a partial function:" }, { "code": null, "e": 1526, "s": 1409, "text": "from functools import partialdef power(base, exponent): return base ** exponentsquared = partial(power, exponent=2)" }, { "code": null, "e": 1581, "s": 1526, "text": "Finally, we may call “squared()” as simply as follows:" }, { "code": null, "e": 1607, "s": 1581, "text": "squared(3)squared(base=7)" } ]
Sort first k values in ascending order and remaining n-k values in descending order - GeeksforGeeks
19 May, 2021 Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order. Examples: Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1 Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6 Algorithm: Store the first k elements in an array and sort that in ascending order.Store the remaining n-k elements in an array and sort that in descending order.Merge the two arrays by adding the elements from the second array in reverse order. Store the first k elements in an array and sort that in ascending order. Store the remaining n-k elements in an array and sort that in descending order. Merge the two arrays by adding the elements from the second array in reverse order. C++ Java Python3 C# PHP Javascript // C++ program to sort first k elements// in increasing order and remaining// n-k elements in decreasing#include <bits/stdc++.h>using namespace std; // Function to sort the arrayvoid printOrder(int arr[], int n, int k){ int len1 = k, len2 = n - k; int arr1[k], arr2[n - k]; // Store the k elements in an array for (int i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k elements in an array for (int i = k; i < n; i++) arr2[i - k] = arr[i]; // sorting the array from 0 to k-1 places sort(arr1, arr1 + len1); // sorting the array from k to n places sort(arr2, arr2 + len2); // storing the values in the final array arr for (int i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // printing the array for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printOrder(arr, n, k); return 0;} // Java program to sort first k elements// in increasing order and remaining// n-k elements in decreasingimport java.util.*; class GFG { // function to print half of the array in // ascending order and the other half in // descending order static void printOrder(int[] arr, int n, int k) { int len1 = k, len2 = n - k; int[] arr1 = new int[k]; int[] arr2 = new int[n - k]; // Store the k elements in an array for (int i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k elements in an array for (int i = k; i < n; i++) arr2[i - k] = arr[i]; // sorting the array from 0 to k-1 places Arrays.sort(arr1, 0, k); // sorting the array from k to n places Arrays.sort(arr2, k, n - k); // storing the values in the final array arr for (int i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // printing the array for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } } // Driver code public static void main(String[] args) { int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = arr.length; printOrder(arr, n, k); }} # Python 3 program to sort first# k elements in increasing order# and remaining n-k elements in# decreasing # Function to sort the arraydef printOrder(arr, n, k): len1 = k len2 = n - k arr1 = [0] * k arr2 = [0] * (n - k) # Store the k elements # in an array for i in range(k): arr1[i] = arr[i] # Store the remaining n-k # elements in an array for i in range(k, n): arr2[i - k] = arr[i] # sorting the array from # 0 to k-1 places arr1.sort() # sorting the array from # k to n places arr2.sort() # storing the values in the # final array arr for i in range(n): if (i < k): arr[i] = arr1[i] else : arr[i] = arr2[len2 - 1] len2 -= 1 # printing the array for i in range(n): print(arr[i], end = " ") # Driver codeif __name__ == "__main__": arr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ] k = 4 n = len(arr) printOrder(arr, n, k) # This code is contributed# by ChitraNayal // C# program to sort first k elements// in increasing order and remaining// n-k elements in decreasingusing System; class GFG { // function to print half of the array in // ascending order and the other half in // descending order static void printOrder(int[] arr, int n, int k) { int len2 = n - k; int[] arr1 = new int[k]; int[] arr2 = new int[n - k]; // Store the k elements in an array for (int i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k // elements in an array for (int i = k; i < n; i++) arr2[i - k] = arr[i]; // sorting the array from // 0 to k-1 places Array.Sort(arr1, 0, k); // sorting the array from k to n places Array.Sort(arr2, 0, n - k); // storing the values in // the final array arr for (int i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // printing the array for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } } // Driver code public static void Main() { int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = arr.Length; printOrder(arr, n, k); }} // This code is contributed by Subhadeep <?php// PHP program to sort first// k elements in increasing order// and remaining n-k elements in// decreasing // Function to sort the arrayfunction printOrder($arr, $n, $k){ $len1 = $k; $len2 = $n - $k; $arr1 = array_fill(0, $k, 0); $arr2 = array_fill(0, ($n - $k), 0); // Store the k elements // in an array for ($i = 0; $i < $k; $i++) $arr1[$i] = $arr[$i]; // Store the remaining n-k // elements in an array for ($i = $k; $i < $n; $i++) $arr2[$i - $k] = $arr[$i]; // sorting the array from // 0 to k-1 places sort($arr1); // sorting the array from // k to n places sort($arr2); // storing the values in the // final array arr for ($i = 0; $i < $n; $i++) if ($i < $k) $arr[$i] = $arr1[$i]; else { $arr[$i] = $arr2[$len2 - 1]; $len2 -= 1; } // printing the array for ($i = 0; $i < $n; $i++) print($arr[$i] . " ");} // Driver code$arr = array( 5, 4, 6, 2, 1, 3, 8, 9, -1 );$k = 4; $n = count($arr); printOrder($arr, $n, $k); // This code is contributed by mits?> <script> // Javascript program to sort first k elements// in increasing order and remaining// n-k elements in decreasing // Function to print half of the array in// ascending order and the other half in// descending orderfunction printOrder(arr, n, k){ let len1 = k, len2 = n - k; let arr1 = new Array(k); let arr2 = new Array(n - k); // Store the k elements in an array for(let i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k // elements in an array for(let i = k; i < n; i++) arr2[i - k] = arr[i]; // Sorting the array from 0 to k-1 places arr1.sort(function(a, b){return a - b;}); // Sorting the array from k to n places arr2.sort(function(a, b){return a - b;}); // Storing the values in the final array arr for(let i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // Printing the array for(let i = 0; i < n; i++) { document.write(arr[i] + " "); }} // Driver codelet arr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ];let k = 4;let n = arr.length; printOrder(arr, n, k); // This code is contributed by rag2127 </script> 2 4 5 6 9 8 3 1 -1 Time Complexity: O(N * log(N))Auxiliary Space: O(N) Efficient Approach: The idea is simple, sort the first k elements in increasing order and remaining n-k elements in decreasing using library function. C++ Java Python3 C# PHP Javascript // C++ program to sort first k elements// in increasing order and remaining// n-k elements in decreasing#include <bits/stdc++.h>using namespace std; // function to sort the arrayvoid printOrder(int arr[], int n, int k){ // Sort first k elements in ascending order sort(arr, arr + k); // Sort remaining n-k elements in descending order sort(arr + k, arr + n, greater<int>());} // Driver codeint main(){ int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printOrder(arr, n, k); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to sort first k elements// in increasing order and remaining// n-k elements in decreasingimport java.util.*; public class SortExample { static void printOrder(Integer[] arr, int k) { int n = arr.length; // Sort first k elements in ascending order Arrays.sort(arr, 0, k); // Sort remaining n-k elements in descending order Arrays.sort(arr, k, n, Collections.reverseOrder()); } public static void main(String[] args) { // Our arr contains 8 elements Integer[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; printOrder(arr, k); System.out.printf("%s", Arrays.toString(arr)); }} # Python3 program to sort first k elements# in increasing order and remaining# n-k elements in decreasing # function to sort the arraydef printOrder(arr, n, k): # Sort first k elements in ascending order a = arr[0:k]; a.sort(); # Sort remaining n-k elements in descending order b = arr[k:n]; b.sort(); b.reverse(); return a + b; # Driver codearr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ];k = 4;n = len(arr); arr = printOrder(arr, n, k); for i in range(n): print(arr[i], end =" "); # This code is contributed by mits // C# program to sort first k elements// in increasing order and remaining// n-k elements in decreasingusing System; public class SortExample { static void printOrder(int[] arr, int k) { int n = arr.Length; // Sort first k elements in ascending order Array.Sort(arr, 0, k); // Sort remaining n-k elements in descending order Array.Sort(arr, k, n - k); Array.Reverse(arr, k, n - k); } // Driver code public static void Main(String[] args) { // Our arr contains 8 elements int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; printOrder(arr, k); Console.Write("{0}", String.Join(" ", arr)); }} // This code contributed by Rajput-Ji <?php// PHP program to sort first k elements// in increasing order and remaining// n-k elements in decreasing // function to sort the arrayfunction printOrder($arr, $n, $k){ // Sort first k elements in ascending order $a= array_slice($arr, 0, $k); sort($a); // Sort remaining n-k elements in descending order $b = array_slice($arr, $k, $n); sort($b); $b = array_reverse($b); unset($arr); $arr = $a; return array_merge($arr, $b);} // Driver code $arr = array( 5, 4, 6, 2, 1, 3, 8, 9, -1 ); $k = 4; $n = count($arr); $arr=printOrder($arr, $n, $k); for ($i = 0; $i < $n; $i++) echo $arr[$i]." "; // This code is contributed by mits?> <script> // Javascript program to sort first k elements// in increasing order and remaining// n-k elements in decreasingfunction printOrder(arr, k){ let n = arr.length; // Sort first k elements in ascending order // Sort remaining n-k elements in descending order arr = arr.slice(0, k).sort( function(a, b){return a - b;}).concat( arr.slice(k, n).sort(function(a, b){return b - a;})); return arr;} // Driver code // Our arr contains 8 elementslet arr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ];let k = 4;arr = printOrder(arr, k); document.write(arr.join(" ")); // This code is contributed by avanitrachhadiya2155 </script> 2 4 5 6 9 8 3 1 -1 Time Complexity: O(N * log(N))Auxiliary Space: O(1) tufan_gupta2000 ukasp Rajput-Ji Mithun Kumar rrlinus rag2127 avanitrachhadiya2155 Reverse Wipro Arrays Sorting Wipro Arrays Sorting Reverse 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array
[ { "code": null, "e": 27310, "s": 27282, "text": "\n19 May, 2021" }, { "code": null, "e": 27449, "s": 27310, "text": "Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order." }, { "code": null, "e": 27460, "s": 27449, "text": "Examples: " }, { "code": null, "e": 27538, "s": 27460, "text": "Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1" }, { "code": null, "e": 27585, "s": 27538, "text": "Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6 " }, { "code": null, "e": 27597, "s": 27585, "text": "Algorithm: " }, { "code": null, "e": 27832, "s": 27597, "text": "Store the first k elements in an array and sort that in ascending order.Store the remaining n-k elements in an array and sort that in descending order.Merge the two arrays by adding the elements from the second array in reverse order." }, { "code": null, "e": 27905, "s": 27832, "text": "Store the first k elements in an array and sort that in ascending order." }, { "code": null, "e": 27985, "s": 27905, "text": "Store the remaining n-k elements in an array and sort that in descending order." }, { "code": null, "e": 28069, "s": 27985, "text": "Merge the two arrays by adding the elements from the second array in reverse order." }, { "code": null, "e": 28073, "s": 28069, "text": "C++" }, { "code": null, "e": 28078, "s": 28073, "text": "Java" }, { "code": null, "e": 28086, "s": 28078, "text": "Python3" }, { "code": null, "e": 28089, "s": 28086, "text": "C#" }, { "code": null, "e": 28093, "s": 28089, "text": "PHP" }, { "code": null, "e": 28104, "s": 28093, "text": "Javascript" }, { "code": "// C++ program to sort first k elements// in increasing order and remaining// n-k elements in decreasing#include <bits/stdc++.h>using namespace std; // Function to sort the arrayvoid printOrder(int arr[], int n, int k){ int len1 = k, len2 = n - k; int arr1[k], arr2[n - k]; // Store the k elements in an array for (int i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k elements in an array for (int i = k; i < n; i++) arr2[i - k] = arr[i]; // sorting the array from 0 to k-1 places sort(arr1, arr1 + len1); // sorting the array from k to n places sort(arr2, arr2 + len2); // storing the values in the final array arr for (int i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // printing the array for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printOrder(arr, n, k); return 0;}", "e": 29209, "s": 28104, "text": null }, { "code": "// Java program to sort first k elements// in increasing order and remaining// n-k elements in decreasingimport java.util.*; class GFG { // function to print half of the array in // ascending order and the other half in // descending order static void printOrder(int[] arr, int n, int k) { int len1 = k, len2 = n - k; int[] arr1 = new int[k]; int[] arr2 = new int[n - k]; // Store the k elements in an array for (int i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k elements in an array for (int i = k; i < n; i++) arr2[i - k] = arr[i]; // sorting the array from 0 to k-1 places Arrays.sort(arr1, 0, k); // sorting the array from k to n places Arrays.sort(arr2, k, n - k); // storing the values in the final array arr for (int i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // printing the array for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } } // Driver code public static void main(String[] args) { int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = arr.length; printOrder(arr, n, k); }}", "e": 30585, "s": 29209, "text": null }, { "code": "# Python 3 program to sort first# k elements in increasing order# and remaining n-k elements in# decreasing # Function to sort the arraydef printOrder(arr, n, k): len1 = k len2 = n - k arr1 = [0] * k arr2 = [0] * (n - k) # Store the k elements # in an array for i in range(k): arr1[i] = arr[i] # Store the remaining n-k # elements in an array for i in range(k, n): arr2[i - k] = arr[i] # sorting the array from # 0 to k-1 places arr1.sort() # sorting the array from # k to n places arr2.sort() # storing the values in the # final array arr for i in range(n): if (i < k): arr[i] = arr1[i] else : arr[i] = arr2[len2 - 1] len2 -= 1 # printing the array for i in range(n): print(arr[i], end = \" \") # Driver codeif __name__ == \"__main__\": arr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ] k = 4 n = len(arr) printOrder(arr, n, k) # This code is contributed# by ChitraNayal", "e": 31608, "s": 30585, "text": null }, { "code": "// C# program to sort first k elements// in increasing order and remaining// n-k elements in decreasingusing System; class GFG { // function to print half of the array in // ascending order and the other half in // descending order static void printOrder(int[] arr, int n, int k) { int len2 = n - k; int[] arr1 = new int[k]; int[] arr2 = new int[n - k]; // Store the k elements in an array for (int i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k // elements in an array for (int i = k; i < n; i++) arr2[i - k] = arr[i]; // sorting the array from // 0 to k-1 places Array.Sort(arr1, 0, k); // sorting the array from k to n places Array.Sort(arr2, 0, n - k); // storing the values in // the final array arr for (int i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // printing the array for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } } // Driver code public static void Main() { int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = arr.Length; printOrder(arr, n, k); }} // This code is contributed by Subhadeep", "e": 33067, "s": 31608, "text": null }, { "code": "<?php// PHP program to sort first// k elements in increasing order// and remaining n-k elements in// decreasing // Function to sort the arrayfunction printOrder($arr, $n, $k){ $len1 = $k; $len2 = $n - $k; $arr1 = array_fill(0, $k, 0); $arr2 = array_fill(0, ($n - $k), 0); // Store the k elements // in an array for ($i = 0; $i < $k; $i++) $arr1[$i] = $arr[$i]; // Store the remaining n-k // elements in an array for ($i = $k; $i < $n; $i++) $arr2[$i - $k] = $arr[$i]; // sorting the array from // 0 to k-1 places sort($arr1); // sorting the array from // k to n places sort($arr2); // storing the values in the // final array arr for ($i = 0; $i < $n; $i++) if ($i < $k) $arr[$i] = $arr1[$i]; else { $arr[$i] = $arr2[$len2 - 1]; $len2 -= 1; } // printing the array for ($i = 0; $i < $n; $i++) print($arr[$i] . \" \");} // Driver code$arr = array( 5, 4, 6, 2, 1, 3, 8, 9, -1 );$k = 4; $n = count($arr); printOrder($arr, $n, $k); // This code is contributed by mits?>", "e": 34183, "s": 33067, "text": null }, { "code": "<script> // Javascript program to sort first k elements// in increasing order and remaining// n-k elements in decreasing // Function to print half of the array in// ascending order and the other half in// descending orderfunction printOrder(arr, n, k){ let len1 = k, len2 = n - k; let arr1 = new Array(k); let arr2 = new Array(n - k); // Store the k elements in an array for(let i = 0; i < k; i++) arr1[i] = arr[i]; // Store the remaining n-k // elements in an array for(let i = k; i < n; i++) arr2[i - k] = arr[i]; // Sorting the array from 0 to k-1 places arr1.sort(function(a, b){return a - b;}); // Sorting the array from k to n places arr2.sort(function(a, b){return a - b;}); // Storing the values in the final array arr for(let i = 0; i < n; i++) { if (i < k) arr[i] = arr1[i]; else { arr[i] = arr2[len2 - 1]; len2--; } } // Printing the array for(let i = 0; i < n; i++) { document.write(arr[i] + \" \"); }} // Driver codelet arr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ];let k = 4;let n = arr.length; printOrder(arr, n, k); // This code is contributed by rag2127 </script>", "e": 35424, "s": 34183, "text": null }, { "code": null, "e": 35443, "s": 35424, "text": "2 4 5 6 9 8 3 1 -1" }, { "code": null, "e": 35497, "s": 35445, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(N)" }, { "code": null, "e": 35648, "s": 35497, "text": "Efficient Approach: The idea is simple, sort the first k elements in increasing order and remaining n-k elements in decreasing using library function." }, { "code": null, "e": 35652, "s": 35648, "text": "C++" }, { "code": null, "e": 35657, "s": 35652, "text": "Java" }, { "code": null, "e": 35665, "s": 35657, "text": "Python3" }, { "code": null, "e": 35668, "s": 35665, "text": "C#" }, { "code": null, "e": 35672, "s": 35668, "text": "PHP" }, { "code": null, "e": 35683, "s": 35672, "text": "Javascript" }, { "code": "// C++ program to sort first k elements// in increasing order and remaining// n-k elements in decreasing#include <bits/stdc++.h>using namespace std; // function to sort the arrayvoid printOrder(int arr[], int n, int k){ // Sort first k elements in ascending order sort(arr, arr + k); // Sort remaining n-k elements in descending order sort(arr + k, arr + n, greater<int>());} // Driver codeint main(){ int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printOrder(arr, n, k); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 36304, "s": 35683, "text": null }, { "code": "// Java program to sort first k elements// in increasing order and remaining// n-k elements in decreasingimport java.util.*; public class SortExample { static void printOrder(Integer[] arr, int k) { int n = arr.length; // Sort first k elements in ascending order Arrays.sort(arr, 0, k); // Sort remaining n-k elements in descending order Arrays.sort(arr, k, n, Collections.reverseOrder()); } public static void main(String[] args) { // Our arr contains 8 elements Integer[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; printOrder(arr, k); System.out.printf(\"%s\", Arrays.toString(arr)); }}", "e": 36988, "s": 36304, "text": null }, { "code": "# Python3 program to sort first k elements# in increasing order and remaining# n-k elements in decreasing # function to sort the arraydef printOrder(arr, n, k): # Sort first k elements in ascending order a = arr[0:k]; a.sort(); # Sort remaining n-k elements in descending order b = arr[k:n]; b.sort(); b.reverse(); return a + b; # Driver codearr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ];k = 4;n = len(arr); arr = printOrder(arr, n, k); for i in range(n): print(arr[i], end =\" \"); # This code is contributed by mits", "e": 37524, "s": 36988, "text": null }, { "code": "// C# program to sort first k elements// in increasing order and remaining// n-k elements in decreasingusing System; public class SortExample { static void printOrder(int[] arr, int k) { int n = arr.Length; // Sort first k elements in ascending order Array.Sort(arr, 0, k); // Sort remaining n-k elements in descending order Array.Sort(arr, k, n - k); Array.Reverse(arr, k, n - k); } // Driver code public static void Main(String[] args) { // Our arr contains 8 elements int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, -1 }; int k = 4; printOrder(arr, k); Console.Write(\"{0}\", String.Join(\" \", arr)); }} // This code contributed by Rajput-Ji", "e": 38257, "s": 37524, "text": null }, { "code": "<?php// PHP program to sort first k elements// in increasing order and remaining// n-k elements in decreasing // function to sort the arrayfunction printOrder($arr, $n, $k){ // Sort first k elements in ascending order $a= array_slice($arr, 0, $k); sort($a); // Sort remaining n-k elements in descending order $b = array_slice($arr, $k, $n); sort($b); $b = array_reverse($b); unset($arr); $arr = $a; return array_merge($arr, $b);} // Driver code $arr = array( 5, 4, 6, 2, 1, 3, 8, 9, -1 ); $k = 4; $n = count($arr); $arr=printOrder($arr, $n, $k); for ($i = 0; $i < $n; $i++) echo $arr[$i].\" \"; // This code is contributed by mits?>", "e": 38947, "s": 38257, "text": null }, { "code": "<script> // Javascript program to sort first k elements// in increasing order and remaining// n-k elements in decreasingfunction printOrder(arr, k){ let n = arr.length; // Sort first k elements in ascending order // Sort remaining n-k elements in descending order arr = arr.slice(0, k).sort( function(a, b){return a - b;}).concat( arr.slice(k, n).sort(function(a, b){return b - a;})); return arr;} // Driver code // Our arr contains 8 elementslet arr = [ 5, 4, 6, 2, 1, 3, 8, 9, -1 ];let k = 4;arr = printOrder(arr, k); document.write(arr.join(\" \")); // This code is contributed by avanitrachhadiya2155 </script>", "e": 39595, "s": 38947, "text": null }, { "code": null, "e": 39614, "s": 39595, "text": "2 4 5 6 9 8 3 1 -1" }, { "code": null, "e": 39668, "s": 39616, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(1)" }, { "code": null, "e": 39684, "s": 39668, "text": "tufan_gupta2000" }, { "code": null, "e": 39690, "s": 39684, "text": "ukasp" }, { "code": null, "e": 39700, "s": 39690, "text": "Rajput-Ji" }, { "code": null, "e": 39713, "s": 39700, "text": "Mithun Kumar" }, { "code": null, "e": 39721, "s": 39713, "text": "rrlinus" }, { "code": null, "e": 39729, "s": 39721, "text": "rag2127" }, { "code": null, "e": 39750, "s": 39729, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39758, "s": 39750, "text": "Reverse" }, { "code": null, "e": 39764, "s": 39758, "text": "Wipro" }, { "code": null, "e": 39771, "s": 39764, "text": "Arrays" }, { "code": null, "e": 39779, "s": 39771, "text": "Sorting" }, { "code": null, "e": 39785, "s": 39779, "text": "Wipro" }, { "code": null, "e": 39792, "s": 39785, "text": "Arrays" }, { "code": null, "e": 39800, "s": 39792, "text": "Sorting" }, { "code": null, "e": 39808, "s": 39800, "text": "Reverse" }, { "code": null, "e": 39906, "s": 39808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39974, "s": 39906, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39997, "s": 39974, "text": "Introduction to Arrays" }, { "code": null, "e": 40029, "s": 39997, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40043, "s": 40029, "text": "Linear Search" } ]
How to create a String object in C#?
To create a string object in C#, use any of the below given method. By assigning a string literal to a String variable By using a String class constructor By using the string concatenation operator (+) By retrieving a property or calling a method that returns a string By calling a formatting method to convert a value or an object to its string representation The following is an example showing different ways to create a string object in C#. Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { //from string literal and string concatenation string fname, lname; fname = "Brad "; lname = "Pitt"; char []letters= { 'W', 'e', 'b'}; string [] sarray={ "Web", "World"}; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //by using string constructor { 'W, 'e', 'b'}; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //methods returning string { "Web", "World" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); } } } Full Name: Brad Pitt Greetings: Web Message: Web World Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
[ { "code": null, "e": 1130, "s": 1062, "text": "To create a string object in C#, use any of the below given method." }, { "code": null, "e": 1181, "s": 1130, "text": "By assigning a string literal to a String variable" }, { "code": null, "e": 1217, "s": 1181, "text": "By using a String class constructor" }, { "code": null, "e": 1264, "s": 1217, "text": "By using the string concatenation operator (+)" }, { "code": null, "e": 1331, "s": 1264, "text": "By retrieving a property or calling a method that returns a string" }, { "code": null, "e": 1423, "s": 1331, "text": "By calling a formatting method to convert a value or an object to its string representation" }, { "code": null, "e": 1507, "s": 1423, "text": "The following is an example showing different ways to create a string object in C#." }, { "code": null, "e": 1518, "s": 1507, "text": " Live Demo" }, { "code": null, "e": 2515, "s": 1518, "text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n //from string literal and string concatenation\n string fname, lname;\n fname = \"Brad \";\n lname = \"Pitt\";\n char []letters= { 'W', 'e', 'b'};\n string [] sarray={ \"Web\", \"World\"};\n string fullname = fname + lname;\n Console.WriteLine(\"Full Name: {0}\", fullname);\n //by using string constructor { 'W, 'e', 'b'};\n string greetings = new string(letters);\n Console.WriteLine(\"Greetings: {0}\", greetings);\n //methods returning string { \"Web\", \"World\" };\n string message = String.Join(\" \", sarray);\n Console.WriteLine(\"Message: {0}\", message);\n //formatting method to convert a value\n DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);\n string chat = String.Format(\"Message sent at {0:t} on {0:D}\", waiting);\n Console.WriteLine(\"Message: {0}\", chat);\n }\n }\n}" }, { "code": null, "e": 2634, "s": 2515, "text": "Full Name: Brad Pitt\nGreetings: Web\nMessage: Web World\nMessage: Message sent at 5:58 PM on Wednesday, October 10, 2012" } ]
Java - String toLowerCase() Method
This method has two variants. The first variant converts all of the characters in this String to lower case using the rules of the given Locale. This is equivalent to calling toLowerCase(Locale.getDefault()). The second variant takes locale as an argument to be used while converting into lower case. Here is the syntax of this method − public String toLowerCase() Here is the detail of parameters − NA NA It returns the String, converted to lowercase. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :"); System.out.println(Str.toLowerCase()); } } This will produce the following result − Return Value :welcome to tutorialspoint.com 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2586, "s": 2377, "text": "This method has two variants. The first variant converts all of the characters in this String to lower case using the rules of the given Locale. This is equivalent to calling toLowerCase(Locale.getDefault())." }, { "code": null, "e": 2678, "s": 2586, "text": "The second variant takes locale as an argument to be used while converting into lower case." }, { "code": null, "e": 2714, "s": 2678, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2743, "s": 2714, "text": "public String toLowerCase()\n" }, { "code": null, "e": 2778, "s": 2743, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2781, "s": 2778, "text": "NA" }, { "code": null, "e": 2784, "s": 2781, "text": "NA" }, { "code": null, "e": 2831, "s": 2784, "text": "It returns the String, converted to lowercase." }, { "code": null, "e": 3073, "s": 2831, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\");\n System.out.println(Str.toLowerCase());\n }\n}" }, { "code": null, "e": 3114, "s": 3073, "text": "This will produce the following result −" }, { "code": null, "e": 3159, "s": 3114, "text": "Return Value :welcome to tutorialspoint.com\n" }, { "code": null, "e": 3192, "s": 3159, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3208, "s": 3192, "text": " Malhar Lathkar" }, { "code": null, "e": 3241, "s": 3208, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3257, "s": 3241, "text": " Malhar Lathkar" }, { "code": null, "e": 3292, "s": 3257, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3306, "s": 3292, "text": " Anadi Sharma" }, { "code": null, "e": 3340, "s": 3306, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3354, "s": 3340, "text": " Tushar Kale" }, { "code": null, "e": 3391, "s": 3354, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3406, "s": 3391, "text": " Monica Mittal" }, { "code": null, "e": 3439, "s": 3406, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3458, "s": 3439, "text": " Arnab Chakraborty" }, { "code": null, "e": 3465, "s": 3458, "text": " Print" }, { "code": null, "e": 3476, "s": 3465, "text": " Add Notes" } ]
How to work with object detection datasets in COCO format | by Eric Hofesmann | Towards Data Science
Microsoft's Common Objects in Context dataset (COCO) is the most popular object detection dataset at the moment. It is widely used to benchmark the performance of computer vision methods. Due to the popularity of the dataset, the format that COCO uses to store annotations is often the go-to format when creating a new custom object detection dataset. While the COCO dataset also supports annotations for other tasks like segmentation, I will leave that to a future blog post. For now, we will focus only on object detection data. The “COCO format” is a specific JSON structure dictating how labels and metadata are saved for an image dataset. Many blog posts exist that describe the basic format of COCO, but they often lack detailed examples of loading and working with your COCO formatted data. This post will walk you through: The COCO file format Converting an existing dataset to COCO format Loading a COCO dataset Visualizing and exploring your dataset Generating predictions from an object detection model Evaluating mAP of a model on your COCO dataset In order to do all of this, I’ll be using the open-source machine learning developer tool, FiftyOne, that I have been working on. It’s designed to let researchers and engineers easily work with and visualize image and video datasets with annotations and model predictions stored in various formats. You can easily install FiftyOne through pip: pip install fiftyone As of 06/29/2021: With support from the COCO team, COCO has been integrated into FiftyOne to make it easy to download and evaluate on the dataset. You can now specify and download the exact subset of the dataset that you want, load your own COCO-formatted data into FiftyOne, and evaluate your models with COCO-style evaluation enhanced by the visualization capabilities of FiftyOne. See this post or this documentation for more details! If you are new to the object detection space and are tasked with creating a new object detection dataset, then following the COCO format is a good choice due to its relative simplicity and widespread usage. This section will explain what the file and folder structure of a COCO formatted object detection dataset actually looks like. At a high level, the COCO format defines exactly how your annotations (bounding boxes, object classes, etc) and image metadata (like height, width, image sources, etc) are stored on disk. The folder structure of a COCO dataset looks like this: <dataset_dir>/ data/ <filename0>.<ext> <filename1>.<ext> ... labels.json The dataset is stored in a directory containing your raw image data and a single json file that contains all of the annotations, metadata, categories, and other information that you could possibly want to store about your dataset. If you have multiple splits of data, they would be stored in different directories with different json files. If you were to download the COCO dataset from their website, this would be the instances_train2017.json and instances_val2017.json files. (Note: The official test set annotations are unavailable to the public) { "info": { "year": "2021", "version": "1.0", "description": "Exported from FiftyOne", "contributor": "Voxel51", "url": "https://fiftyone.ai", "date_created": "2021-01-19T09:48:27" }, "licenses": [ { "url": "http://creativecommons.org/licenses/by-nc-sa/2.0/", "id": 1, "name": "Attribution-NonCommercial-ShareAlike License" }, ... ], "categories": [ ... { "id": 2, "name": "cat", "supercategory": "animal" }, ... ], "images": [ { "id": 0, "license": 1, "file_name": "<filename0>.<ext>", "height": 480, "width": 640, "date_captured": null }, ... ], "annotations": [ { "id": 0, "image_id": 0, "category_id": 2, "bbox": [260, 177, 231, 199], "segmentation": [...], "area": 45969, "iscrowd": 0 }, ... ]} Info — Description and versioning information about your dataset. Licenses — List of licenses with unique IDs to be specified by your images. Categories — Classification categories each with a unique ID. Optionally associated with a supercategory that can span multiple classes. These categories can be whatever you want, but note that if you’d need to follow the COCO classes if you want to use a model pretrained on COCO out of the box (or follow other dataset categories to use other models). Images — List of images in your dataset and relevant metadata including unique image ID, filepath, height, width, and optional attributes like license, URL, date captured, etc. Annotations — List of annotations each with a unique ID and the image ID it relates to. This is where you will store the bounding box information in our case or segmentation/keypoint/other label information for other tasks. This also stores bounding box area and iscrowd indicating a large bounding box surrounding multiple objects of the same category which is used for evaluation. This section will outline how to take your raw or annotated dataset and convert it to the COCO format depending on what data you currently have and the format it is in. In this case, you already have a dataset with images and annotations but want to convert it to the COCO format. If your dataset happens to follow a different common format that is supported by FiftyOne, like CVAT, YOLO, KITTI, Pascal VOC, TF Object detection, or others, then you can load and convert it to COCO format in a single command. # Convert a COCO detection dataset to CVAT image formatfiftyone convert \ --input-dir /path/to/cvat-image-dataset \ --input-type fiftyone.types.CVATImageDataset \ --output-dir /path/to/coco-detection-dataset \ --output-type fiftyone.types.COCODetectionDataset If your data is not stored in a supported format, then it is still easy to load it into FiftyOne using Python and export it in COCO format. The idea is to load each image and associated labels as a FiftyOne Sample and add them to a FiftyOne Dataset: You can then export this dataset in COCO format with one line: And there you have it! /path/to/coco-detection-dataset now contains your images and labels in COCO format. Check out the next section to see how to easily load it back into Python. If you only have unlabeled images, then you will first need to generate object labels. You can generate either ground truth labels with an annotation tool or provider (like CVAT, Labelbox, MTurk, or one of many others) or predicted labels with an existing pretrained model. If, for example, you used CVAT to annotate your raw data, then you can now convert it to COCO format using the FiftyOne command just like in the above section: # Convert a COCO detection dataset to CVAT image formatfiftyone convert \ --input-dir /path/to/cvat-image-dataset \ --input-type fiftyone.types.CVATImageDataset \ --output-dir /path/to/coco-detection-dataset \ --output-type fiftyone.types.COCODetectionDataset Alternatively, if you want to use a model to generate predictions, you can load your unlabeled data into FiftyOne and generate predictions with the FiftyOne Model Zoo, then save your dataset in COCO format. This section assumes that you have gathered images and annotated them, storing your dataset in the COCO format, either following the previous section or manually building the labels JSON through custom scripting. In order to load your COCO formatted dataset, you could write a parser for the JSON labels file, but really you should just use one of the various tools out there that will load it for you. Two of the best tools for this are the official COCO APIs and FiftyOne. There are official COCO APIs for Python, Lua, and Matlab. These APIs are commonly used and provide basic functionality to load and compute dataset-wide evaluation on your dataset. If you are using Python, I would recommend trying out FiftyOne, since it provides similar functionality to the cocoapi, along with a powerful API and GUI designed specifically to make it as easy as possible for you to explore, analyze, and work with your data. If your dataset correctly follows the COCO format outlined in the previous sections, you can load it into a FiftyOne Dataset in Python with a single command: Now that your dataset is in Python, you can use the FiftyOne API to easily access all of the different information and labels associated with your data and visualize it in the App. To visualize your dataset, launch the FiftyOne App: With the API, you can use aggregations to get statistics about your dataset, like the number of detections for each category: The primary way of interacting with your dataset is through views. Every query you make will give you a different view into your dataset, like sorting by samples with the most number of objects: You can also make a view that filters a label field based on a more complex value like small bounding box area: The FiftyOne Brain contains various methods that allow you to analyze the quality of your ground truth data. For example, you can find the most unique samples in your dataset which can help you get a better idea of what kind of additional data you should add: Other Brain methods can help you find possible annotation mistakes and identify hard samples you may want to train on. All of these will assist you in training better models since better models generally stem from better data. The main reason that you want to create a COCO formatted dataset is to use it to train and test models. Most models these days rely on your data being loaded into Python. Especially if you are using TensorFlow or PyTorch since these libraries are primarily Python-based. Using the COCO API or FiftyOne to get your dataset into Python makes it much easier to write up a PyTorch dataloader, for example, than if you had to parse the labels JSON yourself. Actually training a model on your data is out of the scope of this post but there are plenty of examples for both PyTorch object detection training and even a TensorFlow Object Detection API to help you along. If you are just starting and want to see how some pretrained models would behave on your dataset, the easiest way to generate some predictions is with the FiftyOne Model Zoo. It contains over 70 models, many of which are object detection models. fiftyone zoo models list Note: If you’re tired of configuring TensorFlow/PyTorch models to use your GPU, check out my blog post on Conda. Since your data is stored in COCO format, it can be loaded into FiftyOne, model predictions can be generated on it, and then visualized in the App: The primary evaluation metric for object detection models is mean average precision (mAP). This is a fairly complex metric that is explained in more detail in other posts. In summary, it is computed by: Matching predicted detections with ground truth objects if they overlap above some intersection-over-union (IoU) valueComputing the number of true positives, false positives, and false negatives for all detections of each classUsing these TP/FP/FN to generate a precision-recall curveComputing the average precision for each classTaking the mean of all of the classwise average precision values Matching predicted detections with ground truth objects if they overlap above some intersection-over-union (IoU) value Computing the number of true positives, false positives, and false negatives for all detections of each class Using these TP/FP/FN to generate a precision-recall curve Computing the average precision for each class Taking the mean of all of the classwise average precision values The COCO evaluation protocol introduces one additional step: mAPs are averaged across a range of 10 IoU thresholds. Additionally, COCO object detection evaluation also includes calculating the mAP for things like small, medium, and large bounding boxes, and varying thresholds of detections per image. Note: When evaluating an object detection model, the categories of the predictions must match those of the dataset. This means you must either follow the labels of the COCO dataset to use an out-of-the-box model trained on COCO, or you must fine-tune a model on your dataset so it will predict your custom categories. This COCO mAP value can be computed with either the COCO API or with FiftyOne. Assuming you have a dataset in COCO format with model predictions stored in the predictions field of the dataset, the following will compute the COCO mAP in FiftyOne: Even though mAP is the most popular single value to compare model performances, this metric does have drawbacks. If you really want to know how well your model is performing, you need to dig into your data and look at model predictions on individual samples. The best way to build intuition about how your model performs is by looking at predictions that it was confident about but got wrong. With FiftyOne, this is easy. For example, let’s create a view into our dataset looking at the samples with the most false positives: The example above is in this view and shows a crowd of objects with the false positives not annotated in the ground truth! In the COCO format, ground truth objects can have an iscrowd attribute that specifies that the bounding box is drawn around a crowd of objects. This is one of many examples where this iscrowd box is either missing or incorrectly labeled resulting in false positives. This is something that would have been impossible to find just by looking at the mAP of the model and shows the importance of sample-level analysis to understand dataset quality. High-quality, intentionally-curated data is critical to training great computer vision models. At Voxel51, we have over 25 years of CV/ML experience and care deeply about enabling the community to bring their AI solutions to life. That’s why we developed FiftyOne, an open-source tool that helps engineers and scientists to build high-quality datasets and models. Want to learn more? Check us out at fiftyone.ai.
[ { "code": null, "e": 360, "s": 172, "text": "Microsoft's Common Objects in Context dataset (COCO) is the most popular object detection dataset at the moment. It is widely used to benchmark the performance of computer vision methods." }, { "code": null, "e": 703, "s": 360, "text": "Due to the popularity of the dataset, the format that COCO uses to store annotations is often the go-to format when creating a new custom object detection dataset. While the COCO dataset also supports annotations for other tasks like segmentation, I will leave that to a future blog post. For now, we will focus only on object detection data." }, { "code": null, "e": 816, "s": 703, "text": "The “COCO format” is a specific JSON structure dictating how labels and metadata are saved for an image dataset." }, { "code": null, "e": 1003, "s": 816, "text": "Many blog posts exist that describe the basic format of COCO, but they often lack detailed examples of loading and working with your COCO formatted data. This post will walk you through:" }, { "code": null, "e": 1024, "s": 1003, "text": "The COCO file format" }, { "code": null, "e": 1070, "s": 1024, "text": "Converting an existing dataset to COCO format" }, { "code": null, "e": 1093, "s": 1070, "text": "Loading a COCO dataset" }, { "code": null, "e": 1132, "s": 1093, "text": "Visualizing and exploring your dataset" }, { "code": null, "e": 1186, "s": 1132, "text": "Generating predictions from an object detection model" }, { "code": null, "e": 1233, "s": 1186, "text": "Evaluating mAP of a model on your COCO dataset" }, { "code": null, "e": 1532, "s": 1233, "text": "In order to do all of this, I’ll be using the open-source machine learning developer tool, FiftyOne, that I have been working on. It’s designed to let researchers and engineers easily work with and visualize image and video datasets with annotations and model predictions stored in various formats." }, { "code": null, "e": 1577, "s": 1532, "text": "You can easily install FiftyOne through pip:" }, { "code": null, "e": 1598, "s": 1577, "text": "pip install fiftyone" }, { "code": null, "e": 1982, "s": 1598, "text": "As of 06/29/2021: With support from the COCO team, COCO has been integrated into FiftyOne to make it easy to download and evaluate on the dataset. You can now specify and download the exact subset of the dataset that you want, load your own COCO-formatted data into FiftyOne, and evaluate your models with COCO-style evaluation enhanced by the visualization capabilities of FiftyOne." }, { "code": null, "e": 2036, "s": 1982, "text": "See this post or this documentation for more details!" }, { "code": null, "e": 2370, "s": 2036, "text": "If you are new to the object detection space and are tasked with creating a new object detection dataset, then following the COCO format is a good choice due to its relative simplicity and widespread usage. This section will explain what the file and folder structure of a COCO formatted object detection dataset actually looks like." }, { "code": null, "e": 2558, "s": 2370, "text": "At a high level, the COCO format defines exactly how your annotations (bounding boxes, object classes, etc) and image metadata (like height, width, image sources, etc) are stored on disk." }, { "code": null, "e": 2614, "s": 2558, "text": "The folder structure of a COCO dataset looks like this:" }, { "code": null, "e": 2714, "s": 2614, "text": "<dataset_dir>/ data/ <filename0>.<ext> <filename1>.<ext> ... labels.json" }, { "code": null, "e": 3055, "s": 2714, "text": "The dataset is stored in a directory containing your raw image data and a single json file that contains all of the annotations, metadata, categories, and other information that you could possibly want to store about your dataset. If you have multiple splits of data, they would be stored in different directories with different json files." }, { "code": null, "e": 3265, "s": 3055, "text": "If you were to download the COCO dataset from their website, this would be the instances_train2017.json and instances_val2017.json files. (Note: The official test set annotations are unavailable to the public)" }, { "code": null, "e": 4334, "s": 3265, "text": "{ \"info\": { \"year\": \"2021\", \"version\": \"1.0\", \"description\": \"Exported from FiftyOne\", \"contributor\": \"Voxel51\", \"url\": \"https://fiftyone.ai\", \"date_created\": \"2021-01-19T09:48:27\" }, \"licenses\": [ { \"url\": \"http://creativecommons.org/licenses/by-nc-sa/2.0/\", \"id\": 1, \"name\": \"Attribution-NonCommercial-ShareAlike License\" }, ... ], \"categories\": [ ... { \"id\": 2, \"name\": \"cat\", \"supercategory\": \"animal\" }, ... ], \"images\": [ { \"id\": 0, \"license\": 1, \"file_name\": \"<filename0>.<ext>\", \"height\": 480, \"width\": 640, \"date_captured\": null }, ... ], \"annotations\": [ { \"id\": 0, \"image_id\": 0, \"category_id\": 2, \"bbox\": [260, 177, 231, 199], \"segmentation\": [...], \"area\": 45969, \"iscrowd\": 0 }, ... ]}" }, { "code": null, "e": 4400, "s": 4334, "text": "Info — Description and versioning information about your dataset." }, { "code": null, "e": 4476, "s": 4400, "text": "Licenses — List of licenses with unique IDs to be specified by your images." }, { "code": null, "e": 4830, "s": 4476, "text": "Categories — Classification categories each with a unique ID. Optionally associated with a supercategory that can span multiple classes. These categories can be whatever you want, but note that if you’d need to follow the COCO classes if you want to use a model pretrained on COCO out of the box (or follow other dataset categories to use other models)." }, { "code": null, "e": 5007, "s": 4830, "text": "Images — List of images in your dataset and relevant metadata including unique image ID, filepath, height, width, and optional attributes like license, URL, date captured, etc." }, { "code": null, "e": 5390, "s": 5007, "text": "Annotations — List of annotations each with a unique ID and the image ID it relates to. This is where you will store the bounding box information in our case or segmentation/keypoint/other label information for other tasks. This also stores bounding box area and iscrowd indicating a large bounding box surrounding multiple objects of the same category which is used for evaluation." }, { "code": null, "e": 5559, "s": 5390, "text": "This section will outline how to take your raw or annotated dataset and convert it to the COCO format depending on what data you currently have and the format it is in." }, { "code": null, "e": 5671, "s": 5559, "text": "In this case, you already have a dataset with images and annotations but want to convert it to the COCO format." }, { "code": null, "e": 5899, "s": 5671, "text": "If your dataset happens to follow a different common format that is supported by FiftyOne, like CVAT, YOLO, KITTI, Pascal VOC, TF Object detection, or others, then you can load and convert it to COCO format in a single command." }, { "code": null, "e": 6171, "s": 5899, "text": "# Convert a COCO detection dataset to CVAT image formatfiftyone convert \\ --input-dir /path/to/cvat-image-dataset \\ --input-type fiftyone.types.CVATImageDataset \\ --output-dir /path/to/coco-detection-dataset \\ --output-type fiftyone.types.COCODetectionDataset" }, { "code": null, "e": 6421, "s": 6171, "text": "If your data is not stored in a supported format, then it is still easy to load it into FiftyOne using Python and export it in COCO format. The idea is to load each image and associated labels as a FiftyOne Sample and add them to a FiftyOne Dataset:" }, { "code": null, "e": 6484, "s": 6421, "text": "You can then export this dataset in COCO format with one line:" }, { "code": null, "e": 6665, "s": 6484, "text": "And there you have it! /path/to/coco-detection-dataset now contains your images and labels in COCO format. Check out the next section to see how to easily load it back into Python." }, { "code": null, "e": 6939, "s": 6665, "text": "If you only have unlabeled images, then you will first need to generate object labels. You can generate either ground truth labels with an annotation tool or provider (like CVAT, Labelbox, MTurk, or one of many others) or predicted labels with an existing pretrained model." }, { "code": null, "e": 7099, "s": 6939, "text": "If, for example, you used CVAT to annotate your raw data, then you can now convert it to COCO format using the FiftyOne command just like in the above section:" }, { "code": null, "e": 7371, "s": 7099, "text": "# Convert a COCO detection dataset to CVAT image formatfiftyone convert \\ --input-dir /path/to/cvat-image-dataset \\ --input-type fiftyone.types.CVATImageDataset \\ --output-dir /path/to/coco-detection-dataset \\ --output-type fiftyone.types.COCODetectionDataset" }, { "code": null, "e": 7578, "s": 7371, "text": "Alternatively, if you want to use a model to generate predictions, you can load your unlabeled data into FiftyOne and generate predictions with the FiftyOne Model Zoo, then save your dataset in COCO format." }, { "code": null, "e": 7791, "s": 7578, "text": "This section assumes that you have gathered images and annotated them, storing your dataset in the COCO format, either following the previous section or manually building the labels JSON through custom scripting." }, { "code": null, "e": 8053, "s": 7791, "text": "In order to load your COCO formatted dataset, you could write a parser for the JSON labels file, but really you should just use one of the various tools out there that will load it for you. Two of the best tools for this are the official COCO APIs and FiftyOne." }, { "code": null, "e": 8233, "s": 8053, "text": "There are official COCO APIs for Python, Lua, and Matlab. These APIs are commonly used and provide basic functionality to load and compute dataset-wide evaluation on your dataset." }, { "code": null, "e": 8494, "s": 8233, "text": "If you are using Python, I would recommend trying out FiftyOne, since it provides similar functionality to the cocoapi, along with a powerful API and GUI designed specifically to make it as easy as possible for you to explore, analyze, and work with your data." }, { "code": null, "e": 8652, "s": 8494, "text": "If your dataset correctly follows the COCO format outlined in the previous sections, you can load it into a FiftyOne Dataset in Python with a single command:" }, { "code": null, "e": 8833, "s": 8652, "text": "Now that your dataset is in Python, you can use the FiftyOne API to easily access all of the different information and labels associated with your data and visualize it in the App." }, { "code": null, "e": 8885, "s": 8833, "text": "To visualize your dataset, launch the FiftyOne App:" }, { "code": null, "e": 9011, "s": 8885, "text": "With the API, you can use aggregations to get statistics about your dataset, like the number of detections for each category:" }, { "code": null, "e": 9206, "s": 9011, "text": "The primary way of interacting with your dataset is through views. Every query you make will give you a different view into your dataset, like sorting by samples with the most number of objects:" }, { "code": null, "e": 9318, "s": 9206, "text": "You can also make a view that filters a label field based on a more complex value like small bounding box area:" }, { "code": null, "e": 9578, "s": 9318, "text": "The FiftyOne Brain contains various methods that allow you to analyze the quality of your ground truth data. For example, you can find the most unique samples in your dataset which can help you get a better idea of what kind of additional data you should add:" }, { "code": null, "e": 9805, "s": 9578, "text": "Other Brain methods can help you find possible annotation mistakes and identify hard samples you may want to train on. All of these will assist you in training better models since better models generally stem from better data." }, { "code": null, "e": 9909, "s": 9805, "text": "The main reason that you want to create a COCO formatted dataset is to use it to train and test models." }, { "code": null, "e": 10468, "s": 9909, "text": "Most models these days rely on your data being loaded into Python. Especially if you are using TensorFlow or PyTorch since these libraries are primarily Python-based. Using the COCO API or FiftyOne to get your dataset into Python makes it much easier to write up a PyTorch dataloader, for example, than if you had to parse the labels JSON yourself. Actually training a model on your data is out of the scope of this post but there are plenty of examples for both PyTorch object detection training and even a TensorFlow Object Detection API to help you along." }, { "code": null, "e": 10714, "s": 10468, "text": "If you are just starting and want to see how some pretrained models would behave on your dataset, the easiest way to generate some predictions is with the FiftyOne Model Zoo. It contains over 70 models, many of which are object detection models." }, { "code": null, "e": 10739, "s": 10714, "text": "fiftyone zoo models list" }, { "code": null, "e": 10852, "s": 10739, "text": "Note: If you’re tired of configuring TensorFlow/PyTorch models to use your GPU, check out my blog post on Conda." }, { "code": null, "e": 11000, "s": 10852, "text": "Since your data is stored in COCO format, it can be loaded into FiftyOne, model predictions can be generated on it, and then visualized in the App:" }, { "code": null, "e": 11203, "s": 11000, "text": "The primary evaluation metric for object detection models is mean average precision (mAP). This is a fairly complex metric that is explained in more detail in other posts. In summary, it is computed by:" }, { "code": null, "e": 11598, "s": 11203, "text": "Matching predicted detections with ground truth objects if they overlap above some intersection-over-union (IoU) valueComputing the number of true positives, false positives, and false negatives for all detections of each classUsing these TP/FP/FN to generate a precision-recall curveComputing the average precision for each classTaking the mean of all of the classwise average precision values" }, { "code": null, "e": 11717, "s": 11598, "text": "Matching predicted detections with ground truth objects if they overlap above some intersection-over-union (IoU) value" }, { "code": null, "e": 11827, "s": 11717, "text": "Computing the number of true positives, false positives, and false negatives for all detections of each class" }, { "code": null, "e": 11885, "s": 11827, "text": "Using these TP/FP/FN to generate a precision-recall curve" }, { "code": null, "e": 11932, "s": 11885, "text": "Computing the average precision for each class" }, { "code": null, "e": 11997, "s": 11932, "text": "Taking the mean of all of the classwise average precision values" }, { "code": null, "e": 12299, "s": 11997, "text": "The COCO evaluation protocol introduces one additional step: mAPs are averaged across a range of 10 IoU thresholds. Additionally, COCO object detection evaluation also includes calculating the mAP for things like small, medium, and large bounding boxes, and varying thresholds of detections per image." }, { "code": null, "e": 12617, "s": 12299, "text": "Note: When evaluating an object detection model, the categories of the predictions must match those of the dataset. This means you must either follow the labels of the COCO dataset to use an out-of-the-box model trained on COCO, or you must fine-tune a model on your dataset so it will predict your custom categories." }, { "code": null, "e": 12863, "s": 12617, "text": "This COCO mAP value can be computed with either the COCO API or with FiftyOne. Assuming you have a dataset in COCO format with model predictions stored in the predictions field of the dataset, the following will compute the COCO mAP in FiftyOne:" }, { "code": null, "e": 13122, "s": 12863, "text": "Even though mAP is the most popular single value to compare model performances, this metric does have drawbacks. If you really want to know how well your model is performing, you need to dig into your data and look at model predictions on individual samples." }, { "code": null, "e": 13389, "s": 13122, "text": "The best way to build intuition about how your model performs is by looking at predictions that it was confident about but got wrong. With FiftyOne, this is easy. For example, let’s create a view into our dataset looking at the samples with the most false positives:" }, { "code": null, "e": 13779, "s": 13389, "text": "The example above is in this view and shows a crowd of objects with the false positives not annotated in the ground truth! In the COCO format, ground truth objects can have an iscrowd attribute that specifies that the bounding box is drawn around a crowd of objects. This is one of many examples where this iscrowd box is either missing or incorrectly labeled resulting in false positives." }, { "code": null, "e": 13958, "s": 13779, "text": "This is something that would have been impossible to find just by looking at the mAP of the model and shows the importance of sample-level analysis to understand dataset quality." }, { "code": null, "e": 14322, "s": 13958, "text": "High-quality, intentionally-curated data is critical to training great computer vision models. At Voxel51, we have over 25 years of CV/ML experience and care deeply about enabling the community to bring their AI solutions to life. That’s why we developed FiftyOne, an open-source tool that helps engineers and scientists to build high-quality datasets and models." } ]
Change x axes scale in matplotlib
Using plt.xticks, we can change the X-axis scale. Using plt.plot() method, we can create a line with two lists that are passed in its argument. Using plt.plot() method, we can create a line with two lists that are passed in its argument. Add text to the axes. Add the text *s* to the axes at location *x*, *y* in data coordinates, using plt.text() method, where the font size can be customized by changing the font-size value. Add text to the axes. Add the text *s* to the axes at location *x*, *y* in data coordinates, using plt.text() method, where the font size can be customized by changing the font-size value. Using xticks method, get or set the current tick locations and labels of the X-axis. Using xticks method, get or set the current tick locations and labels of the X-axis. To show the figure, use plt.show() method. To show the figure, use plt.show() method. import matplotlib.pyplot as plt plt.plot([1, 2, 4], [1, 2, 4]) plt.text(2, 3, "y=x", color='red', fontsize=20) plt.xticks([1, 2, 3, 4, 5]) # changing x scale by own plt.show()
[ { "code": null, "e": 1112, "s": 1062, "text": "Using plt.xticks, we can change the X-axis scale." }, { "code": null, "e": 1206, "s": 1112, "text": "Using plt.plot() method, we can create a line with two lists that are passed in its argument." }, { "code": null, "e": 1300, "s": 1206, "text": "Using plt.plot() method, we can create a line with two lists that are passed in its argument." }, { "code": null, "e": 1489, "s": 1300, "text": "Add text to the axes. Add the text *s* to the axes at location *x*, *y* in data coordinates, using plt.text() method, where the font size can be customized by changing the font-size value." }, { "code": null, "e": 1678, "s": 1489, "text": "Add text to the axes. Add the text *s* to the axes at location *x*, *y* in data coordinates, using plt.text() method, where the font size can be customized by changing the font-size value." }, { "code": null, "e": 1763, "s": 1678, "text": "Using xticks method, get or set the current tick locations and labels of the X-axis." }, { "code": null, "e": 1848, "s": 1763, "text": "Using xticks method, get or set the current tick locations and labels of the X-axis." }, { "code": null, "e": 1891, "s": 1848, "text": "To show the figure, use plt.show() method." }, { "code": null, "e": 1934, "s": 1891, "text": "To show the figure, use plt.show() method." }, { "code": null, "e": 2117, "s": 1934, "text": "import matplotlib.pyplot as plt\n\nplt.plot([1, 2, 4], [1, 2, 4])\n\nplt.text(2, 3, \"y=x\", color='red', fontsize=20)\n\nplt.xticks([1, 2, 3, 4, 5]) # changing x scale by own\n\nplt.show()" } ]
Possible paths | Practice | GeeksforGeeks
Given a directed graph and two vertices ‘u’ and ‘v’ in it. Find the number of possible walks from ‘u’ to ‘v’ with exactly k edges on the walk modulo 109+7. Note : There can be a cycle in the graph and an edge can be travelled multiple times. Example 1: Input 1: graph = {{0,1,1,1},{0,0,0,1}, {0,0,0,1}, {0,0,0,0}}, u = 0, v = 3, k = 2 Output: 2 Explanation: Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. The output should be 2 as there are two walk from 0 to 3 with exactly 2 edges. The walks are {0, 2, 3} and {0, 1, 3}. Your Task: You don't need to read or print anything. Your task is to complete the function MinimumWalk() which takes graph, u, v and k as input parameter and returns total possible paths from u to v using exactly k edges modulo 109+7. Note: In graph, if graph[i][j] = 1, it means there is an directed edge from vertex i to j. Expected Time Complexity: O(n3) Expected Space Complexity: O(n3) Constraints: 1 ≤ n ≤ 50 1 ≤ k ≤ n 0 ≤ u, v ≤ n-1 +1 aloksinghbais021 week ago C++ solution having time complexity as O(N^3) and space complexity as O(N^3) is as follows :- Execution Time :- 0.03 / 1.26 sec vector<int> adj[51]; int mod = (int)1e9 + 7; long long int dp[51][51]; long long int helper(int node,int des,int k){ if(k == 0){ return node == des ? 1LL : 0; } if(dp[node][k] != -1) return dp[node][k]; long long int cnt = 0; for(auto choice: adj[node]){ cnt = (cnt + 1LL*helper(choice,des,k-1)) % mod; } return (dp[node][k] = cnt); } int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){ int n = graph.size(); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(graph[i][j] == 1){ adj[i].push_back(j); } } } memset(dp,-1,sizeof(dp)); return (int)helper(u,v,k);} 0 aditya048481 month ago # TIME complexity = O(V*K + V*V) # SPACE complexity = O(V*K) from collections import defaultdict class Solution: def helperFunc(self, g, v, curr, p, table): if p == 0: if curr == v: return 1 else: return 0 if (curr, p) not in table: table[(curr, p)] = 0 for x in g[curr]: table[(curr, p)] = (table[(curr, p)] + self.helperFunc(g, v, x, p-1, table )) % 1000000007 return table[(curr, p)] def MinimumWalk(self, graph, u, v, k): g = defaultdict(list) for i in range(len(graph)): for j in range(len(graph[i])): if graph[i][j] == 1: g[i].append(j) table = {} result = self.helperFunc(g, v, u, k, table) % 1000000007 return result 0 belalazam31 month ago int mod=1e9 +7; unordered_map<int,unordered_map<int,int>>dp; int dfs(int u,int v,vector<vector<int>>&graph,int k) { if(u==v and k==0) {return 1;} if(k==0)return 0; if(dp[u][k]!=0)return dp[u][k]; int x=0; for(auto i:graph[u]) { if(i==1)dp[u][k]=(dp[u][k]+dfs(x,v,graph,k-1))%mod; x++; } return dp[u][k]%mod; }int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){ return dfs(u,v,graph,k);} +2 sbh698405 months ago The solution in the editorial is O(n^4) time. I personally solved this using matrix exponentiation in O(n^3 log n) +1 rohitjug19csPremium5 months ago JAVA O(k.n.n) Time complexity , and O(n.k) Space Complexity Solution public int MinimumWalk(int[][] graph, int u, int v, int k) { int m = (int)(Math.pow(10, 9) + 7); int n = graph.length; int dp[][] = new int[n][k+1]; dp[u][0] = 1; for(int j=0; j<k; j++){ for(int i=0; i<n; i++){ if(dp[i][j] > 0){ for(int l=0; l<n; l++) if(graph[i][l]==1)dp[l][j+1] = (dp[l][j+1]+dp[i][j])%m; } } } return dp[v][k]; } +2 ritumodi55 months ago We can solve this using dynamic programming. We start at the source vertex u, and for each neighbor of vertex u, run a dfs from that neighbor with k-1 edges needed. Here's a recursive memoised Java solution: class Solution{ private static final int mod = (int)1e9+7; public int MinimumWalk(int[][] graph, int u, int v, int k){ return helper(graph, u, v, k, new Integer[graph.length][k+1]); } private int helper(int[][] graph, int curr, int dest, int k, Integer[][] memo){ if(k == 0) return curr == dest ? 1 : 0; if(memo[curr][k] != null) return memo[curr][k]; int ans = 0; for(int i = 0; i < graph[0].length; i++) if (graph[curr][i] == 1) ans = (ans + helper(graph, i, dest, k-1, memo)) % mod; return memo[curr][k] = ans % mod; } } 0 rajsonkar36315 months ago 12 +1 ritikraj6120 This comment was deleted. -1 mvanshika5 months ago The allowed time complexity is On3 my code is of On2 yet it is exceeding the time limit ... can anyone suggest what is wrong in my code class Solution{ public int MinimumWalk(int[][] graph, int u, int v, int k) { // Code here int count =0; for(int i=0;i<graph.length;i++) { if(graph[u][i]==1) { count=(count+dfs(graph,i,v,k,1)%1000000007)%1000000007; } } return count; } public int dfs(int[][] graph,int curr, int v, int k, int edge) { if(edge>k) return 0; if(curr==v&&edge==k) return 1; int count=0; for(int i=0;i<graph.length;i++) { if(graph[curr][i]==1) { count=(count+dfs(graph,i,v,k,edge+1)%1000000007)%1000000007; } } return count; }} 0 tushargupta19995 months ago C++ DFS + Caching class Solution { int dfs(vector<vector<int>>&graph, vector<vector<long>>&dp, int cur, int target, int k) { if(dp[cur][k] != -1) { return dp[cur][k]; } dp[cur][k] = 0; for(int i=0; i<graph.size(); i++) { if(graph[cur][i]) { dp[cur][k] = (dp[cur][k] + dfs(graph, dp, i, target, k-1))%int(1e9+7); } } return dp[cur][k]; } public: int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){ vector<vector<long>> dp(graph.size(), vector<long>(k+1, -1)); dp[v][0] = 1; for(int i=0; i<graph.size(); i++) { if(i != v) dp[i][0] = 0; } dfs(graph, dp, u, v, k); return dp[u][k]; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 394, "s": 238, "text": "Given a directed graph and two vertices ‘u’ and ‘v’ in it. Find the number of possible walks from ‘u’ to ‘v’ with exactly k edges on the walk modulo 109+7." }, { "code": null, "e": 480, "s": 394, "text": "Note : There can be a cycle in the graph and an edge can be travelled multiple times." }, { "code": null, "e": 491, "s": 480, "text": "Example 1:" }, { "code": null, "e": 781, "s": 491, "text": "Input 1: graph = {{0,1,1,1},{0,0,0,1}, \n{0,0,0,1}, {0,0,0,0}}, u = 0, v = 3, k = 2\nOutput: 2\nExplanation: Let source ‘u’ be vertex 0, \ndestination ‘v’ be 3 and k be 2. The output \nshould be 2 as there are two walk from 0 to \n3 with exactly 2 edges. The walks are {0, 2, 3}\nand {0, 1, 3}.\n\n" }, { "code": null, "e": 1109, "s": 781, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function MinimumWalk() which takes graph, u, v and k as input parameter and returns total possible paths from u to v using exactly k edges modulo 109+7.\nNote: In graph, if graph[i][j] = 1, it means there is an directed edge from vertex i to j.\n " }, { "code": null, "e": 1176, "s": 1109, "text": "Expected Time Complexity: O(n3)\nExpected Space Complexity: O(n3)\n " }, { "code": null, "e": 1225, "s": 1176, "text": "Constraints:\n1 ≤ n ≤ 50\n1 ≤ k ≤ n\n0 ≤ u, v ≤ n-1" }, { "code": null, "e": 1228, "s": 1225, "text": "+1" }, { "code": null, "e": 1254, "s": 1228, "text": "aloksinghbais021 week ago" }, { "code": null, "e": 1349, "s": 1254, "text": "C++ solution having time complexity as O(N^3) and space complexity as O(N^3) is as follows :- " }, { "code": null, "e": 1386, "s": 1351, "text": "Execution Time :- 0.03 / 1.26 sec " }, { "code": null, "e": 2128, "s": 1388, "text": "vector<int> adj[51]; int mod = (int)1e9 + 7; long long int dp[51][51]; long long int helper(int node,int des,int k){ if(k == 0){ return node == des ? 1LL : 0; } if(dp[node][k] != -1) return dp[node][k]; long long int cnt = 0; for(auto choice: adj[node]){ cnt = (cnt + 1LL*helper(choice,des,k-1)) % mod; } return (dp[node][k] = cnt); } int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){ int n = graph.size(); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(graph[i][j] == 1){ adj[i].push_back(j); } } } memset(dp,-1,sizeof(dp)); return (int)helper(u,v,k);}" }, { "code": null, "e": 2130, "s": 2128, "text": "0" }, { "code": null, "e": 2153, "s": 2130, "text": "aditya048481 month ago" }, { "code": null, "e": 3047, "s": 2153, "text": "# TIME complexity = O(V*K + V*V)\n# SPACE complexity = O(V*K)\n\nfrom collections import defaultdict\n\nclass Solution:\n \n def helperFunc(self, g, v, curr, p, table):\n if p == 0:\n if curr == v:\n return 1\n else:\n return 0\n \n if (curr, p) not in table:\n \n table[(curr, p)] = 0\n for x in g[curr]:\n table[(curr, p)] = (table[(curr, p)] + self.helperFunc(g, v, x, p-1, table )) % 1000000007\n \n \n return table[(curr, p)] \n \n\tdef MinimumWalk(self, graph, u, v, k):\n\t\n\t g = defaultdict(list)\n\t \n\t for i in range(len(graph)):\n\t for j in range(len(graph[i])):\n\t if graph[i][j] == 1:\n\t g[i].append(j)\n\t \n\t table = {}\n\t result = self.helperFunc(g, v, u, k, table) % 1000000007\n\t return result " }, { "code": null, "e": 3049, "s": 3047, "text": "0" }, { "code": null, "e": 3071, "s": 3049, "text": "belalazam31 month ago" }, { "code": null, "e": 3556, "s": 3071, "text": "int mod=1e9 +7; unordered_map<int,unordered_map<int,int>>dp; int dfs(int u,int v,vector<vector<int>>&graph,int k) { if(u==v and k==0) {return 1;} if(k==0)return 0; if(dp[u][k]!=0)return dp[u][k]; int x=0; for(auto i:graph[u]) { if(i==1)dp[u][k]=(dp[u][k]+dfs(x,v,graph,k-1))%mod; x++; } return dp[u][k]%mod; }int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){ return dfs(u,v,graph,k);}" }, { "code": null, "e": 3559, "s": 3556, "text": "+2" }, { "code": null, "e": 3580, "s": 3559, "text": "sbh698405 months ago" }, { "code": null, "e": 3695, "s": 3580, "text": "The solution in the editorial is O(n^4) time. I personally solved this using matrix exponentiation in O(n^3 log n)" }, { "code": null, "e": 3698, "s": 3695, "text": "+1" }, { "code": null, "e": 3730, "s": 3698, "text": "rohitjug19csPremium5 months ago" }, { "code": null, "e": 3799, "s": 3730, "text": "JAVA O(k.n.n) Time complexity , and O(n.k) Space Complexity Solution" }, { "code": null, "e": 4263, "s": 3799, "text": "public int MinimumWalk(int[][] graph, int u, int v, int k)\n {\n int m = (int)(Math.pow(10, 9) + 7);\n int n = graph.length; \n int dp[][] = new int[n][k+1];\n \n dp[u][0] = 1;\n for(int j=0; j<k; j++){\n for(int i=0; i<n; i++){\n if(dp[i][j] > 0){\n for(int l=0; l<n; l++)\n if(graph[i][l]==1)dp[l][j+1] = (dp[l][j+1]+dp[i][j])%m;\n }\n } \n }\n\n return dp[v][k];\n }" }, { "code": null, "e": 4266, "s": 4263, "text": "+2" }, { "code": null, "e": 4288, "s": 4266, "text": "ritumodi55 months ago" }, { "code": null, "e": 4333, "s": 4288, "text": "We can solve this using dynamic programming." }, { "code": null, "e": 4455, "s": 4335, "text": "We start at the source vertex u, and for each neighbor of vertex u, run a dfs from that neighbor with k-1 edges needed." }, { "code": null, "e": 4500, "s": 4457, "text": "Here's a recursive memoised Java solution:" }, { "code": null, "e": 5134, "s": 4502, "text": "class Solution{\n private static final int mod = (int)1e9+7;\n \n public int MinimumWalk(int[][] graph, int u, int v, int k){\n return helper(graph, u, v, k, new Integer[graph.length][k+1]); \n }\n \n private int helper(int[][] graph, int curr, int dest, int k, Integer[][] memo){\n if(k == 0) return curr == dest ? 1 : 0;\n if(memo[curr][k] != null) return memo[curr][k];\n \n int ans = 0;\n for(int i = 0; i < graph[0].length; i++)\n if (graph[curr][i] == 1)\n ans = (ans + helper(graph, i, dest, k-1, memo)) % mod;\n \n return memo[curr][k] = ans % mod;\n }\n}" }, { "code": null, "e": 5136, "s": 5134, "text": "0" }, { "code": null, "e": 5162, "s": 5136, "text": "rajsonkar36315 months ago" }, { "code": null, "e": 5165, "s": 5162, "text": "12" }, { "code": null, "e": 5168, "s": 5165, "text": "+1" }, { "code": null, "e": 5181, "s": 5168, "text": "ritikraj6120" }, { "code": null, "e": 5207, "s": 5181, "text": "This comment was deleted." }, { "code": null, "e": 5210, "s": 5207, "text": "-1" }, { "code": null, "e": 5232, "s": 5210, "text": "mvanshika5 months ago" }, { "code": null, "e": 5368, "s": 5232, "text": "The allowed time complexity is On3 my code is of On2 yet it is exceeding the time limit ... can anyone suggest what is wrong in my code" }, { "code": null, "e": 6078, "s": 5368, "text": "class Solution{ public int MinimumWalk(int[][] graph, int u, int v, int k) { // Code here int count =0; for(int i=0;i<graph.length;i++) { if(graph[u][i]==1) { count=(count+dfs(graph,i,v,k,1)%1000000007)%1000000007; } } return count; } public int dfs(int[][] graph,int curr, int v, int k, int edge) { if(edge>k) return 0; if(curr==v&&edge==k) return 1; int count=0; for(int i=0;i<graph.length;i++) { if(graph[curr][i]==1) { count=(count+dfs(graph,i,v,k,edge+1)%1000000007)%1000000007; } } return count; }}" }, { "code": null, "e": 6080, "s": 6078, "text": "0" }, { "code": null, "e": 6108, "s": 6080, "text": "tushargupta19995 months ago" }, { "code": null, "e": 6126, "s": 6108, "text": "C++ DFS + Caching" }, { "code": null, "e": 6855, "s": 6126, "text": "class Solution {\n int dfs(vector<vector<int>>&graph, vector<vector<long>>&dp, int cur, int target, int k) {\n if(dp[cur][k] != -1) {\n return dp[cur][k];\n }\n dp[cur][k] = 0;\n for(int i=0; i<graph.size(); i++) {\n if(graph[cur][i]) {\n dp[cur][k] = (dp[cur][k] + dfs(graph, dp, i, target, k-1))%int(1e9+7);\n }\n }\n return dp[cur][k];\n }\n public:\n\tint MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){\n\t vector<vector<long>> dp(graph.size(), vector<long>(k+1, -1));\n\t dp[v][0] = 1;\n\t for(int i=0; i<graph.size(); i++) {\n\t if(i != v) dp[i][0] = 0;\n\t }\n\t dfs(graph, dp, u, v, k);\n\t return dp[u][k];\n\t}\n};" }, { "code": null, "e": 7001, "s": 6855, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7037, "s": 7001, "text": " Login to access your submissions. " }, { "code": null, "e": 7047, "s": 7037, "text": "\nProblem\n" }, { "code": null, "e": 7057, "s": 7047, "text": "\nContest\n" }, { "code": null, "e": 7120, "s": 7057, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7268, "s": 7120, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7476, "s": 7268, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7582, "s": 7476, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Check if an array can be split into subsets of K consecutive elements - GeeksforGeeks
21 May, 2021 Given an array arr[] and integer K, the task is to split the array into subsets of size K, such that each subset consists of K consecutive elements. Examples: Input: arr[] = {1, 2, 3, 6, 2, 3, 4, 7, 8}, K = 3 Output: true Explanation: The given array of length 9 can be split into 3 subsets {1, 2, 3}, {2, 3, 4} and {6, 7, 8} such that each subset consists of 3 consecutive elements. Input: arr[] = [1, 2, 3, 4, 5], K = 4 Output: false Explanation: The given array of length 5 cannot be split into subsets of 4. Approach Follow the steps to solve the problem: Store the frequencies of all array elements in a HashMap Traverse the HashMap. For every element present in the HashMap, check if all its occurrences can be grouped in a subsets with its next (K – 1) consecutive elements or not. If so, reduce the frequencies of the elements included in the subsets accordingly in the HashMap and proceed forward. If any element is found which cannot be grouped into a subset of K consecutive elements, print False. Otherwise print True. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to check if a given array can// be split into subsets of K consecutive// elementsbool groupInKConsecutive(vector<int>& arr, int K){ // Stores the frequencies of // array elements map<int, int> count; for (int h : arr) { ++count[h]; } // Traverse the map for (auto c : count) { int cur = c.first; int n = c.second; // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for (int i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.count(cur + i)) { return false; } count[cur + i] -= n; // If it cannot be split into // required number of subsets if (count[cur + i] < 0) return false; } } } return true;} // Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 6, 2, 3, 4, 7, 8 }; int k = 3; if (groupInKConsecutive(arr, k)) { cout << "True"; } else { cout << "False"; }} // Java Program to implement the// above approachimport java.util.*;class GFG{ // Function to check if a given array can// be split into subsets of K consecutive// elementsstatic boolean groupInKConsecutive(int[] arr, int K){ // Stores the frequencies of // array elements HashMap<Integer, Integer> count = new HashMap<Integer, Integer>(); for (int h : arr) { if(count.containsKey(h)) count.put(h, count.get(h) + 1); else count.put(h, 1); } // Traverse the map for (Map.Entry<Integer, Integer> c : count.entrySet()) { int cur = c.getKey(); int n = c.getValue(); // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for (int i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.containsKey(cur + i)) { return false; } count.put(cur + i, count.get(cur + i) - n); // If it cannot be split into // required number of subsets if (count.get(cur + i) < 0) return false; } } } return true;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 6, 2, 3, 4, 7, 8 }; int k = 3; if (groupInKConsecutive(arr, k)) { System.out.print("True"); } else { System.out.print("False"); }}} // This code contributed by sapnasingh4991 # Python3 program to implement the# above approach from collections import defaultdict # Function to check if a given array can# be split into subsets of K consecutive# elementsdef groupInKConsecutive(arr, K): # Stores the frequencies of # array elements count = defaultdict(int) for h in arr: count[h] += 1 # Traverse the map for key, value in count.items(): cur = key n = value # Check if all its occurrences can # be grouped into K subsets if (n > 0): # Traverse next K elements for i in range(1, K): # If the element is not # present in the array if ((cur + i) not in count): return False count[cur + i] -= n # If it cannot be split into # required number of subsets if (count[cur + i] < 0): return False return True # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 3, 6, 2, 3, 4, 7, 8 ] k = 3 if (groupInKConsecutive(arr, k)): print("True") else: print("False") # This code is contributed by chitranayal // C# program to implement the// above approachusing System;using System.Collections;using System.Collections.Generic;using System.Linq; class GFG{ // Function to check if a given array can// be split into subsets of K consecutive// elementsstatic bool groupInKConsecutive(int[] arr, int K){ // Stores the frequencies of // array elements Dictionary<int, int> count = new Dictionary<int, int>(); foreach(int h in arr) { if (count.ContainsKey(h)) count[h]++; else count[h] = 1; } // Traverse the map foreach(int c in count.Keys.ToList()) { int cur = c; int n = count; // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for(int i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.ContainsKey(cur + i)) { return false; } count[cur + i] -= n; // If it cannot be split into // required number of subsets if (count[cur + i] < 0) return false; } } } return true;} // Driver Codepublic static void Main(string[] args){ int[] arr = { 1, 2, 3, 6, 2, 3, 4, 7, 8 }; int k = 3; if (groupInKConsecutive(arr, k)) { Console.Write("True"); } else { Console.Write("False"); }}} // This code is contributed by rutvik_56 <script> // Javascript Program to implement the// above approach // Function to check if a given array can// be split into subsets of K consecutive// elementsfunction groupInKConsecutive(arr, K){ // Stores the frequencies of // array elements var count = new Map(); arr.forEach(element => { if(count.has(element)) count.set(element, count.get(element)+1) else count.set(element, 1) }); // Traverse the map count.forEach((value, key) => { var cur = key; var n = value; // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for (var i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.has(cur + i)) { return false; } count.set(cur + i, count.get(cur+i)-n); // If it cannot be split into // required number of subsets if (count.get(cur + i) < 0) return false; } } }); return true;} // Driver Codevar arr = [1, 2, 3, 6, 2, 3, 4, 7, 8];var k = 3;if (groupInKConsecutive(arr, k)) { document.write( "True");}else { document.write( "False");} </script> True Time Complexity: O(N*log(N)) Auxiliary Space: O(N) ukasp sapnasingh4991 rutvik_56 famously cpp-map frequency-counting subset Arrays Hash Searching Sorting Arrays Searching Hash Sorting subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 24431, "s": 24403, "text": "\n21 May, 2021" }, { "code": null, "e": 24580, "s": 24431, "text": "Given an array arr[] and integer K, the task is to split the array into subsets of size K, such that each subset consists of K consecutive elements." }, { "code": null, "e": 24591, "s": 24580, "text": "Examples: " }, { "code": null, "e": 24816, "s": 24591, "text": "Input: arr[] = {1, 2, 3, 6, 2, 3, 4, 7, 8}, K = 3 Output: true Explanation: The given array of length 9 can be split into 3 subsets {1, 2, 3}, {2, 3, 4} and {6, 7, 8} such that each subset consists of 3 consecutive elements." }, { "code": null, "e": 24946, "s": 24816, "text": "Input: arr[] = [1, 2, 3, 4, 5], K = 4 Output: false Explanation: The given array of length 5 cannot be split into subsets of 4. " }, { "code": null, "e": 24995, "s": 24946, "text": "Approach Follow the steps to solve the problem: " }, { "code": null, "e": 25052, "s": 24995, "text": "Store the frequencies of all array elements in a HashMap" }, { "code": null, "e": 25074, "s": 25052, "text": "Traverse the HashMap." }, { "code": null, "e": 25342, "s": 25074, "text": "For every element present in the HashMap, check if all its occurrences can be grouped in a subsets with its next (K – 1) consecutive elements or not. If so, reduce the frequencies of the elements included in the subsets accordingly in the HashMap and proceed forward." }, { "code": null, "e": 25466, "s": 25342, "text": "If any element is found which cannot be grouped into a subset of K consecutive elements, print False. Otherwise print True." }, { "code": null, "e": 25517, "s": 25466, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25521, "s": 25517, "text": "C++" }, { "code": null, "e": 25526, "s": 25521, "text": "Java" }, { "code": null, "e": 25534, "s": 25526, "text": "Python3" }, { "code": null, "e": 25537, "s": 25534, "text": "C#" }, { "code": null, "e": 25548, "s": 25537, "text": "Javascript" }, { "code": "// C++ Program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to check if a given array can// be split into subsets of K consecutive// elementsbool groupInKConsecutive(vector<int>& arr, int K){ // Stores the frequencies of // array elements map<int, int> count; for (int h : arr) { ++count[h]; } // Traverse the map for (auto c : count) { int cur = c.first; int n = c.second; // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for (int i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.count(cur + i)) { return false; } count[cur + i] -= n; // If it cannot be split into // required number of subsets if (count[cur + i] < 0) return false; } } } return true;} // Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 6, 2, 3, 4, 7, 8 }; int k = 3; if (groupInKConsecutive(arr, k)) { cout << \"True\"; } else { cout << \"False\"; }}", "e": 26856, "s": 25548, "text": null }, { "code": "// Java Program to implement the// above approachimport java.util.*;class GFG{ // Function to check if a given array can// be split into subsets of K consecutive// elementsstatic boolean groupInKConsecutive(int[] arr, int K){ // Stores the frequencies of // array elements HashMap<Integer, Integer> count = new HashMap<Integer, Integer>(); for (int h : arr) { if(count.containsKey(h)) count.put(h, count.get(h) + 1); else count.put(h, 1); } // Traverse the map for (Map.Entry<Integer, Integer> c : count.entrySet()) { int cur = c.getKey(); int n = c.getValue(); // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for (int i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.containsKey(cur + i)) { return false; } count.put(cur + i, count.get(cur + i) - n); // If it cannot be split into // required number of subsets if (count.get(cur + i) < 0) return false; } } } return true;} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 6, 2, 3, 4, 7, 8 }; int k = 3; if (groupInKConsecutive(arr, k)) { System.out.print(\"True\"); } else { System.out.print(\"False\"); }}} // This code contributed by sapnasingh4991", "e": 28581, "s": 26856, "text": null }, { "code": "# Python3 program to implement the# above approach from collections import defaultdict # Function to check if a given array can# be split into subsets of K consecutive# elementsdef groupInKConsecutive(arr, K): # Stores the frequencies of # array elements count = defaultdict(int) for h in arr: count[h] += 1 # Traverse the map for key, value in count.items(): cur = key n = value # Check if all its occurrences can # be grouped into K subsets if (n > 0): # Traverse next K elements for i in range(1, K): # If the element is not # present in the array if ((cur + i) not in count): return False count[cur + i] -= n # If it cannot be split into # required number of subsets if (count[cur + i] < 0): return False return True # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 6, 2, 3, 4, 7, 8 ] k = 3 if (groupInKConsecutive(arr, k)): print(\"True\") else: print(\"False\") # This code is contributed by chitranayal", "e": 29795, "s": 28581, "text": null }, { "code": "// C# program to implement the// above approachusing System;using System.Collections;using System.Collections.Generic;using System.Linq; class GFG{ // Function to check if a given array can// be split into subsets of K consecutive// elementsstatic bool groupInKConsecutive(int[] arr, int K){ // Stores the frequencies of // array elements Dictionary<int, int> count = new Dictionary<int, int>(); foreach(int h in arr) { if (count.ContainsKey(h)) count[h]++; else count[h] = 1; } // Traverse the map foreach(int c in count.Keys.ToList()) { int cur = c; int n = count; // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for(int i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.ContainsKey(cur + i)) { return false; } count[cur + i] -= n; // If it cannot be split into // required number of subsets if (count[cur + i] < 0) return false; } } } return true;} // Driver Codepublic static void Main(string[] args){ int[] arr = { 1, 2, 3, 6, 2, 3, 4, 7, 8 }; int k = 3; if (groupInKConsecutive(arr, k)) { Console.Write(\"True\"); } else { Console.Write(\"False\"); }}} // This code is contributed by rutvik_56", "e": 31511, "s": 29795, "text": null }, { "code": "<script> // Javascript Program to implement the// above approach // Function to check if a given array can// be split into subsets of K consecutive// elementsfunction groupInKConsecutive(arr, K){ // Stores the frequencies of // array elements var count = new Map(); arr.forEach(element => { if(count.has(element)) count.set(element, count.get(element)+1) else count.set(element, 1) }); // Traverse the map count.forEach((value, key) => { var cur = key; var n = value; // Check if all its occurrences can // be grouped into K subsets if (n > 0) { // Traverse next K elements for (var i = 1; i < K; ++i) { // If the element is not // present in the array if (!count.has(cur + i)) { return false; } count.set(cur + i, count.get(cur+i)-n); // If it cannot be split into // required number of subsets if (count.get(cur + i) < 0) return false; } } }); return true;} // Driver Codevar arr = [1, 2, 3, 6, 2, 3, 4, 7, 8];var k = 3;if (groupInKConsecutive(arr, k)) { document.write( \"True\");}else { document.write( \"False\");} </script>", "e": 32878, "s": 31511, "text": null }, { "code": null, "e": 32883, "s": 32878, "text": "True" }, { "code": null, "e": 32937, "s": 32885, "text": "Time Complexity: O(N*log(N)) Auxiliary Space: O(N) " }, { "code": null, "e": 32943, "s": 32937, "text": "ukasp" }, { "code": null, "e": 32958, "s": 32943, "text": "sapnasingh4991" }, { "code": null, "e": 32968, "s": 32958, "text": "rutvik_56" }, { "code": null, "e": 32977, "s": 32968, "text": "famously" }, { "code": null, "e": 32985, "s": 32977, "text": "cpp-map" }, { "code": null, "e": 33004, "s": 32985, "text": "frequency-counting" }, { "code": null, "e": 33011, "s": 33004, "text": "subset" }, { "code": null, "e": 33018, "s": 33011, "text": "Arrays" }, { "code": null, "e": 33023, "s": 33018, "text": "Hash" }, { "code": null, "e": 33033, "s": 33023, "text": "Searching" }, { "code": null, "e": 33041, "s": 33033, "text": "Sorting" }, { "code": null, "e": 33048, "s": 33041, "text": "Arrays" }, { "code": null, "e": 33058, "s": 33048, "text": "Searching" }, { "code": null, "e": 33063, "s": 33058, "text": "Hash" }, { "code": null, "e": 33071, "s": 33063, "text": "Sorting" }, { "code": null, "e": 33078, "s": 33071, "text": "subset" }, { "code": null, "e": 33176, "s": 33078, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33185, "s": 33176, "text": "Comments" }, { "code": null, "e": 33198, "s": 33185, "text": "Old Comments" }, { "code": null, "e": 33219, "s": 33198, "text": "Next Greater Element" }, { "code": null, "e": 33244, "s": 33219, "text": "Window Sliding Technique" }, { "code": null, "e": 33271, "s": 33244, "text": "Count pairs with given sum" }, { "code": null, "e": 33320, "s": 33271, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33358, "s": 33320, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33394, "s": 33358, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 33425, "s": 33394, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 33452, "s": 33425, "text": "Count pairs with given sum" }, { "code": null, "e": 33486, "s": 33452, "text": "Hashing | Set 3 (Open Addressing)" } ]
Difference between strncmp() and strcmp() in C/C++
The function strncmp() is used to compare left string to right string up to a number. It works same as strcmp(). It returns a value greater than zero when the matching character of left string has greater ASCII value than the character of the right string. Returns a value less than zero when the matching character of left string has lesser ASCII value than the character of the right string. Here is the syntax of strncmp() in C language, int strncmp ( const char *leftString, const char *rightString, size_t number ); Here, leftString − The first string which is to be compared with right string. leftString − The first string which is to be compared with right string. rightString − The second string which is used to compare the first string. rightString − The second string which is used to compare the first string. number − Maximum number of characters to compare. number − Maximum number of characters to compare. Here is an example of strncmp() in C language, Live Demo #include<stdio.h> #include<string.h> int main() { char str1[] = "blank"; char str2[] = "Hello World!"; int result = strncmp(str1, str2, 1); if (result==0) printf("Strings are equal"); else printf("Strings are unequal"); printf("\nValue returned by strcmp() is: %d" , result); return 0; } Here is the output Strings are unequal Value returned by strcmp() is: 26 The function strcmp() is a built-in library function and declared in “string.h” header file. This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found. If the first character of both strings are equal, it checks second character and so on. This process will be continued until NULL character is found or both characters are unequal. It returns zero if both strings are identical i.e. characters are same in both strings. It returns a value greater than zero when the matching character of left string has greater ASCII value than the character of the right string. It returns a value less than zero when the matching character of left string has lesser ASCII value than the character of the right string. Here is the syntax of strcmp() in C language, int strcmp(const char *leftString, const char *rightString ); Here, leftString − The first string which is to be compared with right string. leftString − The first string which is to be compared with right string. rightString − The second string which is used to compare the first string. rightString − The second string which is used to compare the first string. Here is an example of strcmp() in C language, Live Demo #include<stdio.h> #include<string.h> int main() { char str1[] = "hello World!"; char str2[] = "Hello World!"; int result = strcmp(str1, str2); if (result==0) printf("Strings are equal"); else printf("Strings are unequal"); printf("\nValue returned by strcmp() is: %d" , result); return 0; } Here is the output: Strings are unequal Value returned by strcmp() is: 32
[ { "code": null, "e": 1456, "s": 1062, "text": "The function strncmp() is used to compare left string to right string up to a number. It works same as strcmp(). It returns a value greater than zero when the matching character of left string has greater ASCII value than the character of the right string. Returns a value less than zero when the matching character of left string has lesser ASCII value than the character of the right string." }, { "code": null, "e": 1503, "s": 1456, "text": "Here is the syntax of strncmp() in C language," }, { "code": null, "e": 1583, "s": 1503, "text": "int strncmp ( const char *leftString, const char *rightString, size_t number );" }, { "code": null, "e": 1589, "s": 1583, "text": "Here," }, { "code": null, "e": 1663, "s": 1589, "text": "leftString − The first string which is to be compared with right string." }, { "code": null, "e": 1737, "s": 1663, "text": "leftString − The first string which is to be compared with right string." }, { "code": null, "e": 1813, "s": 1737, "text": "rightString − The second string which is used to compare the first string." }, { "code": null, "e": 1889, "s": 1813, "text": "rightString − The second string which is used to compare the first string." }, { "code": null, "e": 1939, "s": 1889, "text": "number − Maximum number of characters to compare." }, { "code": null, "e": 1989, "s": 1939, "text": "number − Maximum number of characters to compare." }, { "code": null, "e": 2036, "s": 1989, "text": "Here is an example of strncmp() in C language," }, { "code": null, "e": 2047, "s": 2036, "text": " Live Demo" }, { "code": null, "e": 2365, "s": 2047, "text": "#include<stdio.h>\n#include<string.h>\n\nint main() {\n char str1[] = \"blank\";\n char str2[] = \"Hello World!\";\n int result = strncmp(str1, str2, 1);\n\n if (result==0)\n printf(\"Strings are equal\");\n else\n printf(\"Strings are unequal\");\n\n printf(\"\\nValue returned by strcmp() is: %d\" , result);\n return 0;\n}" }, { "code": null, "e": 2384, "s": 2365, "text": "Here is the output" }, { "code": null, "e": 2438, "s": 2384, "text": "Strings are unequal\nValue returned by strcmp() is: 26" }, { "code": null, "e": 2820, "s": 2438, "text": "The function strcmp() is a built-in library function and declared in “string.h” header file. This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found." }, { "code": null, "e": 3089, "s": 2820, "text": "If the first character of both strings are equal, it checks second character and so on. This process will be continued until NULL character is found or both characters are unequal. It returns zero if both strings are identical i.e. characters are same in both strings." }, { "code": null, "e": 3373, "s": 3089, "text": "It returns a value greater than zero when the matching character of left string has greater ASCII value than the character of the right string. It returns a value less than zero when the matching character of left string has lesser ASCII value than the character of the right string." }, { "code": null, "e": 3419, "s": 3373, "text": "Here is the syntax of strcmp() in C language," }, { "code": null, "e": 3481, "s": 3419, "text": "int strcmp(const char *leftString, const char *rightString );" }, { "code": null, "e": 3487, "s": 3481, "text": "Here," }, { "code": null, "e": 3560, "s": 3487, "text": "leftString − The first string which is to be compared with right string." }, { "code": null, "e": 3633, "s": 3560, "text": "leftString − The first string which is to be compared with right string." }, { "code": null, "e": 3708, "s": 3633, "text": "rightString − The second string which is used to compare the first string." }, { "code": null, "e": 3783, "s": 3708, "text": "rightString − The second string which is used to compare the first string." }, { "code": null, "e": 3829, "s": 3783, "text": "Here is an example of strcmp() in C language," }, { "code": null, "e": 3840, "s": 3829, "text": " Live Demo" }, { "code": null, "e": 4160, "s": 3840, "text": "#include<stdio.h>\n#include<string.h>\nint main() {\n char str1[] = \"hello World!\";\n char str2[] = \"Hello World!\";\n int result = strcmp(str1, str2);\n\n if (result==0)\n printf(\"Strings are equal\");\n else\n printf(\"Strings are unequal\");\n\n printf(\"\\nValue returned by strcmp() is: %d\" , result);\n return 0;\n}" }, { "code": null, "e": 4180, "s": 4160, "text": "Here is the output:" }, { "code": null, "e": 4234, "s": 4180, "text": "Strings are unequal\nValue returned by strcmp() is: 32" } ]
How to Create a Progress Bar using HTML5 ? - GeeksforGeeks
28 May, 2020 In this article, we are creating the progress bar of a task by using a <progress> tag. It is used to represent the progress of a task. It is also defined as how much work is done and how much is left. It is not used to represent the disk space or relevant query. Syntax: <progress attributes...> </progress> Example: <!DOCTYPE html><html> <head> <title> Represent the progress of a task </title></head> <body> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> HTML5: How to represent the progress of a task </h2> Downloading progress for a song: <progress value="57" max="100"> </progress></body> </html> Output: Supported Browsers are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc HTML5 HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet) Form validation using HTML and JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Angular Libraries For Web Developers Convert a string to an integer in JavaScript
[ { "code": null, "e": 25186, "s": 25158, "text": "\n28 May, 2020" }, { "code": null, "e": 25449, "s": 25186, "text": "In this article, we are creating the progress bar of a task by using a <progress> tag. It is used to represent the progress of a task. It is also defined as how much work is done and how much is left. It is not used to represent the disk space or relevant query." }, { "code": null, "e": 25457, "s": 25449, "text": "Syntax:" }, { "code": null, "e": 25494, "s": 25457, "text": "<progress attributes...> </progress>" }, { "code": null, "e": 25503, "s": 25494, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Represent the progress of a task </title></head> <body> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> HTML5: How to represent the progress of a task </h2> Downloading progress for a song: <progress value=\"57\" max=\"100\"> </progress></body> </html> ", "e": 25874, "s": 25503, "text": null }, { "code": null, "e": 25882, "s": 25874, "text": "Output:" }, { "code": null, "e": 25919, "s": 25882, "text": "Supported Browsers are listed below:" }, { "code": null, "e": 25933, "s": 25919, "text": "Google Chrome" }, { "code": null, "e": 25951, "s": 25933, "text": "Internet Explorer" }, { "code": null, "e": 25959, "s": 25951, "text": "Firefox" }, { "code": null, "e": 25965, "s": 25959, "text": "Opera" }, { "code": null, "e": 25972, "s": 25965, "text": "Safari" }, { "code": null, "e": 26109, "s": 25972, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26119, "s": 26109, "text": "HTML-Misc" }, { "code": null, "e": 26125, "s": 26119, "text": "HTML5" }, { "code": null, "e": 26130, "s": 26125, "text": "HTML" }, { "code": null, "e": 26147, "s": 26130, "text": "Web Technologies" }, { "code": null, "e": 26152, "s": 26147, "text": "HTML" }, { "code": null, "e": 26250, "s": 26152, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26259, "s": 26250, "text": "Comments" }, { "code": null, "e": 26272, "s": 26259, "text": "Old Comments" }, { "code": null, "e": 26320, "s": 26272, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26370, "s": 26320, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26394, "s": 26370, "text": "REST API (Introduction)" }, { "code": null, "e": 26431, "s": 26394, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26473, "s": 26431, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26515, "s": 26473, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26548, "s": 26515, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26591, "s": 26548, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26635, "s": 26591, "text": "Top 10 Angular Libraries For Web Developers" } ]
How to create an impressive GUI in Python using Tkinter?
Tkinter is a standard Python GUI library in Python, which gives us an object-oriented interface with Tk GUI Toolkit. It's amazing how quickly one can create some really impressive looking apps. Actions in GUI are usually performed through direct manipulation of graphical elements. We will take a simple "addition" application to show how easy it is to create an impressive GUI in Python using tkinter. GUI is all about widgets and windows and these are available in Tkinter. First, we will import the Tkinter library, then create a window object (class Tk is used to create window object) and create a label widget in which we can show any text or image (used in GUI application). The widget is in the insert window and on executing, we will get the output screen. # Import the required libraries from tkinter import * win=Tk() win.geometry("700x300") def sum(): a=int(entry1.get()) b=int(entry2.get()) c=a+b # insert(index,value) entry3.insert(0,c) def clearing(): # delete(0,END) entry1.delete(0,END) entry2.delete(0,END) entry3.delete(0,END) label1=Label(win, text="Enter number 1:", padx=20, pady=10) label2=Label(win, text="Enter number 2:", padx=20, pady=10) entry1=Entry(win, width=30, borderwidth=2) entry2=Entry(win, width=30, borderwidth=2) entry3=Entry(win, width=30, borderwidth=2) add=Button(win, text="Add", padx=20, pady=10, command=sum) clear=Button(win, text="Clear", padx=20, pady=10, command=clearing) label1.grid(row=0, column=0) label2.grid(row=1, column=0) entry1.grid(row=0, column=1) entry2.grid(row=1, column=1) add.grid(row=2, column=0) entry3.grid(row=3, column=0) clear.grid(row=2, column=1) win.mainloop() If we run the above code, it will display a window with a basic addition widget. Now, insert two numbers (number 1 and number 2) and click the Add button to show the summation of number 1 and number 2 or click the Clear button to refresh the output screen.
[ { "code": null, "e": 1344, "s": 1062, "text": "Tkinter is a standard Python GUI library in Python, which gives us an object-oriented interface with Tk GUI Toolkit. It's amazing how quickly one can create some really impressive looking apps. Actions in GUI are usually performed through direct manipulation of graphical elements." }, { "code": null, "e": 1538, "s": 1344, "text": "We will take a simple \"addition\" application to show how easy it is to create an impressive GUI in Python using tkinter. GUI is all about widgets and windows and these are available in Tkinter." }, { "code": null, "e": 1828, "s": 1538, "text": "First, we will import the Tkinter library, then create a window object (class Tk is used to create window object) and create a label widget in which we can show any text or image (used in GUI application). The widget is in the insert window and on executing, we will get the output screen." }, { "code": null, "e": 2734, "s": 1828, "text": "# Import the required libraries\nfrom tkinter import *\nwin=Tk()\nwin.geometry(\"700x300\")\n\ndef sum():\n a=int(entry1.get())\n b=int(entry2.get())\n c=a+b\n # insert(index,value)\n entry3.insert(0,c)\n\ndef clearing():\n # delete(0,END)\n entry1.delete(0,END)\n entry2.delete(0,END)\n entry3.delete(0,END)\n\nlabel1=Label(win, text=\"Enter number 1:\", padx=20, pady=10)\nlabel2=Label(win, text=\"Enter number 2:\", padx=20, pady=10)\n\nentry1=Entry(win, width=30, borderwidth=2)\nentry2=Entry(win, width=30, borderwidth=2)\nentry3=Entry(win, width=30, borderwidth=2)\n\nadd=Button(win, text=\"Add\", padx=20, pady=10, command=sum)\n\nclear=Button(win, text=\"Clear\", padx=20, pady=10, command=clearing)\n\nlabel1.grid(row=0, column=0)\nlabel2.grid(row=1, column=0)\n\nentry1.grid(row=0, column=1)\nentry2.grid(row=1, column=1)\nadd.grid(row=2, column=0)\nentry3.grid(row=3, column=0)\nclear.grid(row=2, column=1)\n\nwin.mainloop()" }, { "code": null, "e": 2815, "s": 2734, "text": "If we run the above code, it will display a window with a basic addition widget." }, { "code": null, "e": 2991, "s": 2815, "text": "Now, insert two numbers (number 1 and number 2) and click the Add button to show the summation of number 1 and number 2 or click the Clear button to refresh the output screen." } ]
map::clear() in C++ STL
In this article we will be discussing the working, syntax and examples of map::clear() function in C++ STL. Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys. map::clear() function is an inbuilt function in C++ STL, which is defined in header file. clear() is used to remove all the content from the associated map container. This function removes all the values and makes the size of the container as 0. Map_name.clear(); This function accepts no parameter. This function returns nothing map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.clear(); size of the map is: 0 Live Demo #include <bits/stdc++.h> using namespace std; int main() { map<int, string> TP_1, TP_2; //Insert values TP_1[1] = "Tutorials"; TP_1[2] = "Point"; TP_1[3] = "is an"; TP_1[4] = "education portal"; //size of map cout<< "Map size before clear() function: \n"; cout << "Size of map1 = "<<TP_1.size() << endl; cout << "Size of map2 = "<<TP_2.size() << endl; //call clear() to delete the elements TP_1.clear(); TP_2.clear(); //now print the size of maps cout<< "Map size after applying clear() function: \n"; cout << "Size of map1 = "<<TP_1.size() << endl; cout << "Size of map2 = "<<TP_2.size() << endl; return 0; } Map size before clear() function: Size of map1 = 4 Size of map2 = 0 Map size after applying clear() function: Size of map1 = 0 Size of map2 = 0
[ { "code": null, "e": 1170, "s": 1062, "text": "In this article we will be discussing the working, syntax and examples of map::clear() function in C++ STL." }, { "code": null, "e": 1480, "s": 1170, "text": "Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys." }, { "code": null, "e": 1727, "s": 1480, "text": "map::clear() function is an inbuilt function in C++ STL, which is defined in header file. clear() is used to remove all the content from the associated map container. This function removes all the values and makes the size of the container as 0." }, { "code": null, "e": 1745, "s": 1727, "text": "Map_name.clear();" }, { "code": null, "e": 1781, "s": 1745, "text": "This function accepts no parameter." }, { "code": null, "e": 1811, "s": 1781, "text": "This function returns nothing" }, { "code": null, "e": 1901, "s": 1811, "text": "map<char, int> newmap;\nnewmap[‘a’] = 1;\nnewmap[‘b’] = 2;\nnewmap[‘c’] = 3;\nnewmap.clear();" }, { "code": null, "e": 1923, "s": 1901, "text": "size of the map is: 0" }, { "code": null, "e": 1934, "s": 1923, "text": " Live Demo" }, { "code": null, "e": 2598, "s": 1934, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n map<int, string> TP_1, TP_2;\n //Insert values\n TP_1[1] = \"Tutorials\";\n TP_1[2] = \"Point\";\n TP_1[3] = \"is an\";\n TP_1[4] = \"education portal\";\n //size of map\n cout<< \"Map size before clear() function: \\n\";\n cout << \"Size of map1 = \"<<TP_1.size() << endl;\n cout << \"Size of map2 = \"<<TP_2.size() << endl;\n //call clear() to delete the elements\n TP_1.clear();\n TP_2.clear();\n //now print the size of maps\n cout<< \"Map size after applying clear() function: \\n\";\n cout << \"Size of map1 = \"<<TP_1.size() << endl;\n cout << \"Size of map2 = \"<<TP_2.size() << endl;\n return 0;\n}" }, { "code": null, "e": 2742, "s": 2598, "text": "Map size before clear() function:\nSize of map1 = 4\nSize of map2 = 0\nMap size after applying clear() function:\nSize of map1 = 0\nSize of map2 = 0" } ]
What is the difference between custom and built-in functions in JavaScript?
The custom functions in JavaScript are user-defined functions. JavaScript allows us to write our own functions. The following is the syntax − <script> <!-- function functionname(parameter-list) { statements } //--> </script> Bult-in functions are functions already provided by JavaScript library, for example, the following are string functions − The following is an example of a built-in function in JavaScript to concatenate strings − Live Demo <html> <head> <title>JavaScript String concat() Method</title> </head> <body> <script> var str1 = new String( "This is string one" ); var str2 = new String( "This is string two" ); var str3 = str1.concat( str2 ); document.write("Concatenated String :" + str3); </script> </body> </html>
[ { "code": null, "e": 1204, "s": 1062, "text": "The custom functions in JavaScript are user-defined functions. JavaScript allows us to write our own functions. The following is the syntax −" }, { "code": null, "e": 1320, "s": 1204, "text": "<script>\n <!--\n function functionname(parameter-list)\n {\n statements\n }\n //-->\n</script>" }, { "code": null, "e": 1442, "s": 1320, "text": "Bult-in functions are functions already provided by JavaScript library, for example, the following are string functions −" }, { "code": null, "e": 1532, "s": 1442, "text": "The following is an example of a built-in function in JavaScript to concatenate strings −" }, { "code": null, "e": 1543, "s": 1532, "text": " Live Demo" }, { "code": null, "e": 1910, "s": 1543, "text": "<html>\n <head>\n <title>JavaScript String concat() Method</title>\n </head>\n \n <body>\n <script>\n var str1 = new String( \"This is string one\" );\n var str2 = new String( \"This is string two\" );\n var str3 = str1.concat( str2 );\n \n document.write(\"Concatenated String :\" + str3);\n </script>\n </body>\n</html>" } ]
Bootstrap - Images
This chapter covers the Bootstrap support for images. Bootstrap provides three classes that can be used to apply some simple styles to images − .img-rounded − adds border-radius:6px to give the image rounded corners. .img-rounded − adds border-radius:6px to give the image rounded corners. .img-circle − makes the entire image round by adding border-radius:500px. .img-circle − makes the entire image round by adding border-radius:500px. .img-thumbnail − adds a bit of padding and a gray border − .img-thumbnail − adds a bit of padding and a gray border − The following example demonstrates this − <img src = "/bootstrap/images/download.png" class = "img-rounded"> <img src = "/bootstrap/images/download.png" class = "img-circle"> <img src = "/bootstrap/images/download.png" class = "img-thumbnail"> 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3475, "s": 3331, "text": "This chapter covers the Bootstrap support for images. Bootstrap provides three classes that can be used to apply some simple styles to images −" }, { "code": null, "e": 3548, "s": 3475, "text": ".img-rounded − adds border-radius:6px to give the image rounded corners." }, { "code": null, "e": 3621, "s": 3548, "text": ".img-rounded − adds border-radius:6px to give the image rounded corners." }, { "code": null, "e": 3695, "s": 3621, "text": ".img-circle − makes the entire image round by adding border-radius:500px." }, { "code": null, "e": 3769, "s": 3695, "text": ".img-circle − makes the entire image round by adding border-radius:500px." }, { "code": null, "e": 3828, "s": 3769, "text": ".img-thumbnail − adds a bit of padding and a gray border −" }, { "code": null, "e": 3887, "s": 3828, "text": ".img-thumbnail − adds a bit of padding and a gray border −" }, { "code": null, "e": 3929, "s": 3887, "text": "The following example demonstrates this −" }, { "code": null, "e": 4131, "s": 3929, "text": "<img src = \"/bootstrap/images/download.png\" class = \"img-rounded\">\n<img src = \"/bootstrap/images/download.png\" class = \"img-circle\">\n<img src = \"/bootstrap/images/download.png\" class = \"img-thumbnail\">" }, { "code": null, "e": 4164, "s": 4131, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4178, "s": 4164, "text": " Anadi Sharma" }, { "code": null, "e": 4213, "s": 4178, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4230, "s": 4213, "text": " Frahaan Hussain" }, { "code": null, "e": 4267, "s": 4230, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 4295, "s": 4267, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4328, "s": 4295, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 4340, "s": 4328, "text": " Azaz Patel" }, { "code": null, "e": 4375, "s": 4340, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4392, "s": 4375, "text": " Muhammad Ismail" }, { "code": null, "e": 4425, "s": 4392, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 4445, "s": 4425, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4452, "s": 4445, "text": " Print" }, { "code": null, "e": 4463, "s": 4452, "text": " Add Notes" } ]
man - Unix, Linux Command
man it is the interface used to view the system's reference manuals. man [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-m system[,...]] [-M path] [-S list] [-e extension] [-i|-I] [--regex|--wildcard] [--names-only] [-a] [-u] [--no-subpages] [-P pager] [-r prompt] [-7] [-E encoding] [--no-hyphenation] [--no-justification] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] [[section] page ...] ... man -k [apropos options] regexp ... man -K [-w|-W] [-S list] [-i|-I] [--regex] [section] term ... man -f [whatis options] page ... man -l [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-P pager] [-r prompt] [-7] [-E encoding] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] file ... man -w|-W [-C file] [-d] [-D] page ... man -c [-C file] [-d] [-D] page ... man [-hV] man [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-m system[,...]] [-M path] [-S list] [-e extension] [-i|-I] [--regex|--wildcard] [--names-only] [-a] [-u] [--no-subpages] [-P pager] [-r prompt] [-7] [-E encoding] [--no-hyphenation] [--no-justification] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] [[section] page ...] ... man -k [apropos options] regexp ... man -K [-w|-W] [-S list] [-i|-I] [--regex] [section] term ... man -f [whatis options] page ... man -l [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-P pager] [-r prompt] [-7] [-E encoding] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] file ... man is the system's manual pager. Each page argument given to man is normally the name of a program, utility or function. The manual page associated with each of these arguments is then found and displayed. A section, if provided, will direct man to look only in that section of the manual. The default action is to search in all of the available sections, following a pre-defined order and to show only the first page found, even if page exists in several sections. Example-1: To Display the manual page for the item (program) ls : $ man ls output: To Display, in succession, all of the available intro manual pages contained within the manual. It is possible to quit between successive displays or skip any of them: $ man -a intro output: # man -a intro--Man-- next: intro(8) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(3) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(2) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(5) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(4) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(6) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(7) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ] to get to next page press q to quit. Example-3: Format the manual page referenced by `alias', usually a shell manual page, into the default troff or groff format and pipe it to the printer named ps : $ man -t alias | lpr -Pps output: command content will be sent to printer. Example-4: output: # man -k printfprintf (1) - format and print data Example-5: To Lookup the manual pages referenced by mkdir and print out the short descriptions of any found. Equivalent to whatis -r mkdir. $ man -f mkdir output: # man -f mkdirmkdir (1) - make directories Example-6: To invoke the subcommands themselves. For example : $ man -aw git diff output: /usr/share/man/man1/git-diff.1.gz To disable this behaviour, use the --no-subpages option. $ man -aw --no-subpages git diff /usr/share/man/man1/git.1.gz /usr/share/man/man3/Git.3pm.gz /usr/share/man/man1/diff.1.gz 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10646, "s": 10577, "text": "man it is the interface used to view the system's reference manuals." }, { "code": null, "e": 11424, "s": 10646, "text": " man [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-m system[,...]] [-M path] [-S list] [-e extension] \n[-i|-I] [--regex|--wildcard] [--names-only] [-a] [-u] [--no-subpages] [-P pager] [-r prompt] [-7] [-E encoding] [--no-hyphenation] \n[--no-justification] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] [[section] page ...] ... \n man -k [apropos options] regexp ...\n man -K [-w|-W] [-S list] [-i|-I] [--regex] [section] term ...\n man -f [whatis options] page ...\n man -l [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-P pager] [-r prompt] [-7] [-E encoding] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] file ...\n man -w|-W [-C file] [-d] [-D] page ...\n man -c [-C file] [-d] [-D] page ...\n man [-hV] " }, { "code": null, "e": 11791, "s": 11424, "text": " man [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-m system[,...]] [-M path] [-S list] [-e extension] \n[-i|-I] [--regex|--wildcard] [--names-only] [-a] [-u] [--no-subpages] [-P pager] [-r prompt] [-7] [-E encoding] [--no-hyphenation] \n[--no-justification] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] [[section] page ...] ... " }, { "code": null, "e": 11925, "s": 11791, "text": " man -k [apropos options] regexp ...\n man -K [-w|-W] [-S list] [-i|-I] [--regex] [section] term ...\n man -f [whatis options] page ..." }, { "code": null, "e": 12113, "s": 11925, "text": " man -l [-C file] [-d] [-D] [--warnings[=warnings]] [-R encoding] [-L locale] [-P pager] [-r prompt] [-7] [-E encoding] [-p string] [-t] [-T[device]] [-H[browser]] [-X[dpi]] [-Z] file ..." }, { "code": null, "e": 12580, "s": 12113, "text": "man is the system's manual pager. Each page argument given to man is normally the name of a program, utility or function. The manual page associated with each of these arguments is then found and displayed. A section, if provided, will direct man to look only in that section of the manual. The default action is to search in all of the available sections, following a pre-defined order and to show only the first page found, even if page exists in several sections." }, { "code": null, "e": 12591, "s": 12580, "text": "Example-1:" }, { "code": null, "e": 12646, "s": 12591, "text": "To Display the manual page for the item (program) ls :" }, { "code": null, "e": 12655, "s": 12646, "text": "$ man ls" }, { "code": null, "e": 12663, "s": 12655, "text": "output:" }, { "code": null, "e": 12831, "s": 12663, "text": "To Display, in succession, all of the available intro manual pages contained within the manual. It is possible to quit between successive displays or skip any of them:" }, { "code": null, "e": 12846, "s": 12831, "text": "$ man -a intro" }, { "code": null, "e": 12854, "s": 12846, "text": "output:" }, { "code": null, "e": 13373, "s": 12854, "text": "# man -a intro--Man-- next: intro(8) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(3) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(2) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(5) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(4) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(6) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]--Man-- next: intro(7) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]" }, { "code": null, "e": 13410, "s": 13373, "text": "to get to next page press q to quit." }, { "code": null, "e": 13421, "s": 13410, "text": "Example-3:" }, { "code": null, "e": 13573, "s": 13421, "text": "Format the manual page referenced by `alias', usually a shell manual page, into the default troff or groff format and pipe it to the printer named ps :" }, { "code": null, "e": 13599, "s": 13573, "text": "$ man -t alias | lpr -Pps" }, { "code": null, "e": 13607, "s": 13599, "text": "output:" }, { "code": null, "e": 13648, "s": 13607, "text": "command content will be sent to printer." }, { "code": null, "e": 13659, "s": 13648, "text": "Example-4:" }, { "code": null, "e": 13667, "s": 13659, "text": "output:" }, { "code": null, "e": 13727, "s": 13667, "text": "# man -k printfprintf (1) - format and print data" }, { "code": null, "e": 13738, "s": 13727, "text": "Example-5:" }, { "code": null, "e": 13867, "s": 13738, "text": "To Lookup the manual pages referenced by mkdir and print out the short descriptions of any found. Equivalent to whatis -r mkdir." }, { "code": null, "e": 13882, "s": 13867, "text": "$ man -f mkdir" }, { "code": null, "e": 13890, "s": 13882, "text": "output:" }, { "code": null, "e": 13944, "s": 13890, "text": "# man -f mkdirmkdir (1) - make directories" }, { "code": null, "e": 13955, "s": 13944, "text": "Example-6:" }, { "code": null, "e": 14007, "s": 13955, "text": "To invoke the subcommands themselves. For example :" }, { "code": null, "e": 14026, "s": 14007, "text": "$ man -aw git diff" }, { "code": null, "e": 14034, "s": 14026, "text": "output:" }, { "code": null, "e": 14250, "s": 14034, "text": "/usr/share/man/man1/git-diff.1.gz\nTo disable this behaviour, use the --no-subpages option.\n\n$ man -aw --no-subpages git diff\n/usr/share/man/man1/git.1.gz\n/usr/share/man/man3/Git.3pm.gz\n/usr/share/man/man1/diff.1.gz\n" }, { "code": null, "e": 14285, "s": 14250, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14313, "s": 14285, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14347, "s": 14313, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14364, "s": 14347, "text": " Frahaan Hussain" }, { "code": null, "e": 14397, "s": 14364, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14408, "s": 14397, "text": " Pradeep D" }, { "code": null, "e": 14443, "s": 14408, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14459, "s": 14443, "text": " Musab Zayadneh" }, { "code": null, "e": 14492, "s": 14459, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14504, "s": 14492, "text": " GUHARAJANM" }, { "code": null, "e": 14536, "s": 14504, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14544, "s": 14536, "text": " Uplatz" }, { "code": null, "e": 14551, "s": 14544, "text": " Print" }, { "code": null, "e": 14562, "s": 14551, "text": " Add Notes" } ]
MySQL - RAND Function
MySQL has a RAND function that can be invoked to produce random numbers between 0 and 1 − mysql> SELECT RAND( ), RAND( ), RAND( ); +------------------+-----------------+------------------+ | RAND( ) | RAND( ) | RAND( ) | +------------------+-----------------+------------------+ | 0.45464584925645 | 0.1824410643265 | 0.54826780459682 | +------------------+-----------------+------------------+ 1 row in set (0.00 sec) When invoked with an integer argument, RAND( ) uses that value to seed the random number generator. Each time you seed the generator with a given value, RAND( ) will produce a repeatable series of numbers − mysql> SELECT RAND(1), RAND( ), RAND( ); +------------------+------------------+------------------+ | RAND(1 ) | RAND( ) | RAND( ) | +------------------+------------------+------------------+ | 0.18109050223705 | 0.75023211143001 | 0.20788908117254 | +------------------+------------------+------------------+ 1 row in set (0.00 sec) You can use ORDER BY RAND() to randomize a set of rows or values as follows − To understand ORDER BY RAND() function, consider an employee_tbl table, which is having the following records − mysql> SELECT * FROM employee_tbl; +------+------+------------+--------------------+ | id | name | work_date | daily_typing_pages | +------+------+------------+--------------------+ | 1 | John | 2007-01-24 | 250 | | 2 | Ram | 2007-05-27 | 220 | | 3 | Jack | 2007-05-06 | 170 | | 3 | Jack | 2007-04-06 | 100 | | 4 | Jill | 2007-04-06 | 220 | | 5 | Zara | 2007-06-06 | 300 | | 5 | Zara | 2007-02-06 | 350 | +------+------+------------+--------------------+ 7 rows in set (0.00 sec) Now, use the following commands − mysql> SELECT * FROM employee_tbl ORDER BY RAND(); +------+------+------------+--------------------+ | id | name | work_date | daily_typing_pages | +------+------+------------+--------------------+ | 5 | Zara | 2007-02-06 | 350 | | 5 | Zara | 2007-06-06 | 300 | | 3 | Jack | 2007-05-06 | 170 | | 2 | Ram | 2007-05-27 | 220 | | 4 | Jill | 2007-04-06 | 220 | | 5 | Zara | 2007-02-06 | 350 | | 1 | John | 2007-01-24 | 250 | +------+------+------------+--------------------+ 7 rows in set (0.01 sec) mysql> SELECT * FROM employee_tbl ORDER BY RAND(); +------+------+------------+--------------------+ | id | name | work_date | daily_typing_pages | +------+------+------------+--------------------+ | 5 | Zara | 2007-02-06 | 350 | | 5 | Zara | 2007-06-06 | 300 | | 3 | Jack | 2007-05-06 | 170 | | 2 | Ram | 2007-05-27 | 220 | | 4 | Jill | 2007-04-06 | 220 | | 5 | Zara | 2007-02-06 | 350 | | 1 | John | 2007-01-24 | 250 | +------+------+------------+--------------------+ 7 rows in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2423, "s": 2333, "text": "MySQL has a RAND function that can be invoked to produce random numbers between 0 and 1 −" }, { "code": null, "e": 2779, "s": 2423, "text": "mysql> SELECT RAND( ), RAND( ), RAND( );\n+------------------+-----------------+------------------+\n| RAND( ) | RAND( ) | RAND( ) |\n+------------------+-----------------+------------------+\n| 0.45464584925645 | 0.1824410643265 | 0.54826780459682 |\n+------------------+-----------------+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2986, "s": 2779, "text": "When invoked with an integer argument, RAND( ) uses that value to seed the random number generator. Each time you seed the generator with a given value, RAND( ) will produce a repeatable series of numbers −" }, { "code": null, "e": 3347, "s": 2986, "text": "mysql> SELECT RAND(1), RAND( ), RAND( );\n+------------------+------------------+------------------+\n| RAND(1 ) | RAND( ) | RAND( ) |\n+------------------+------------------+------------------+\n| 0.18109050223705 | 0.75023211143001 | 0.20788908117254 |\n+------------------+------------------+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3425, "s": 3347, "text": "You can use ORDER BY RAND() to randomize a set of rows or values as follows −" }, { "code": null, "e": 3537, "s": 3425, "text": "To understand ORDER BY RAND() function, consider an employee_tbl table, which is having the following records −" }, { "code": null, "e": 4147, "s": 3537, "text": "mysql> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 4181, "s": 4147, "text": "Now, use the following commands −" }, { "code": null, "e": 5434, "s": 4181, "text": "mysql> SELECT * FROM employee_tbl ORDER BY RAND();\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 5 | Zara | 2007-02-06 | 350 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-02-06 | 350 |\n| 1 | John | 2007-01-24 | 250 |\n+------+------+------------+--------------------+\n7 rows in set (0.01 sec)\n\nmysql> SELECT * FROM employee_tbl ORDER BY RAND();\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 5 | Zara | 2007-02-06 | 350 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-02-06 | 350 |\n| 1 | John | 2007-01-24 | 250 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 5467, "s": 5434, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5495, "s": 5467, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5530, "s": 5495, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5547, "s": 5530, "text": " Frahaan Hussain" }, { "code": null, "e": 5581, "s": 5547, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5616, "s": 5581, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5650, "s": 5616, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 5678, "s": 5650, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5711, "s": 5678, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5731, "s": 5711, "text": " Harshit Srivastava" }, { "code": null, "e": 5764, "s": 5731, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 5782, "s": 5764, "text": " Trevoir Williams" }, { "code": null, "e": 5789, "s": 5782, "text": " Print" }, { "code": null, "e": 5800, "s": 5789, "text": " Add Notes" } ]
Zend Framework - Forms & Validation
Zend Framework provides a separate component, zend-form to accelerate the form creation and validation process. It connects the model and the view layer. It provides a set of form elements to create full-fledged html form from pre-defined models, an InputFilter class to validate the model against the form and options to bind the data from the form to the model and vice versa. The Zend form component can be installed using the Composer command as specified below − composer require zendframework/zend-form A Zend form framework has three subcomponents to manage the forms. They are as explained below in detail − Elements − Used to define a single html input control mapped to a property in the model. Elements − Used to define a single html input control mapped to a property in the model. Fieldset − Used to group elements and other fieldset in a nested manner. Fieldset − Used to group elements and other fieldset in a nested manner. Form − Used to create an html form and consists of elements and fieldsets. Form − Used to create an html form and consists of elements and fieldsets. Zend Forms are usually created under the module//src/Form directory. Let us now create a simple form to add book into the database. To do this, we should adhere to the following steps − Create the “BookForm.php” under the *myapp/module/Tutorial/src/Form” directory. Add the following changes in the file − <?php namespace Tutorial\Form; use Zend\Form\Form; class BookForm extends Form { public function __construct($name = null) { parent::__construct('book'); $this->add(array( 'name' => 'id', 'type' => 'Hidden', )); $this->add(array( 'name' => 'author', 'type' => 'Text', 'options' => array( 'label' => 'Author', ), )); $this->add(array( 'name' => 'title', 'type' => 'Text', 'options' => array( 'label' => 'Title', ), )); $this->add(array( 'name' => 'submit', 'type' => 'Submit', 'attributes' => array( 'value' => 'Go', 'id' => 'submitbutton', ), )); } } The Form class provides an add method to map the model and its corresponding form details. we have created the BookForm by extending the Form class and added the form details for Book model. Update the model, ‘Book’ with filter and validation as specified below − <?php namespace Tutorial\Model; use Zend\InputFilter\InputFilterInterface; use Zend\InputFilter\InputFilterAwareInterface; use Zend\InputFilter\InputFilter; class Book implements InputFilterAwareInterface { public $id; public $author; public $title; protected $inputFilter; public function setInputFilter(InputFilterInterface $inputFilter) { throw new \Exception("Not used"); } public function getInputFilter() { if (!$this->inputFilter) { $inputFilter = new InputFilter(); $inputFilter->add(array( 'name' => 'id', 'required' => true, 'filters' => array( array('name' => 'Int'), ), )); $inputFilter->add(array( 'name' => 'author', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 1, 'max' => 100, ), ), ), )); $inputFilter->add(array( 'name' => 'title', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 1, 'max' => 100, ), ), ), )); $this->inputFilter = $inputFilter; } return $this->inputFilter; } public function exchangeArray($data) { $this->id = (!empty($data['id'])) ? $data['id'] : null; $this->author = (!empty($data['author'])) ? $data['author'] : null; $this->title = (!empty($data['title'])) ? $data['title'] : null; } } Each model should implement the InputFilterAwareInterface. The InputFilterAwareInterface provides two methods, setInputFilter() and getInputFilter(). The getInputFilter is used to get the validation details of the model. Zend framework provides a rich set of filters and validators to validate the form. Some of the filters and validators used in the book model are as follows − StripTags − Remove unwanted HTML. StripTags − Remove unwanted HTML. StringTrim − Remove unnecessary white space. StringTrim − Remove unnecessary white space. StringLength validator − Ensure that the user does not enter more characters than the specified limit. StringLength validator − Ensure that the user does not enter more characters than the specified limit. Include the saveBook method to add book to the database. BookTable.php <?php namespace Tutorial\Model; use Zend\Db\TableGateway\TableGatewayInterface; class BookTable { protected $tableGateway; public function __construct(TableGatewayInterface $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $resultSet = $this->tableGateway->select(); return $resultSet; } public function getBook($id) { $id = (int) $id; $rowset = $this->tableGateway->select(array('id' => $id)); $row = $rowset->current(); if (!$row) { throw new \Exception("Could not find row $id"); } return $row; } public function saveBook(Book $book) { $data = array ( 'author' => $book->author, 'title' => $book->title, ); $id = (int) $book->id; if ($id == 0) { $this->tableGateway->insert($data); } else { if ($this->getBook($id)) { $this->tableGateway->update($data, array('id' => $id)); } else { throw new \Exception('Book id does not exist'); } } } } Add a new action addAction in the tutorial controller – myapp/module/Tutorial/src/Controller/TutorialController.php. public function addAction() { $form = new BookForm(); $form->get('submit')->setValue('Add'); $request = $this->getRequest(); if ($request->isPost()) { $book = new Book(); $form->setInputFilter($book->getInputFilter()); $form->setData($request->getPost()); if ($form->isValid()) { $book->exchangeArray($form->getData()); $this->bookTable->saveBook($book); // Redirect to list of Tutorial return $this->redirect()->toRoute('tutorial'); } } return array('form' => $form); } The addAction method does the following processes − Gets the request object. Gets the request object. Checks if the request's http method is a post method. Checks if the request's http method is a post method. If request's http method is not post, it just renders the template, add.phtml If request's http method is not post, it just renders the template, add.phtml If the request's http method is not post, then it sets the inputfilter, gets the request data and sets it into the inputfiler. If the request's http method is not post, then it sets the inputfilter, gets the request data and sets it into the inputfiler. Checks whether the form is valid using the isValid() method of Form class. Checks whether the form is valid using the isValid() method of Form class. If the form is not valid, it again renders the template, add.phtml If the form is not valid, it again renders the template, add.phtml If the form is valid, it saves the book into the database and redirects to the home page. If the form is valid, it saves the book into the database and redirects to the home page. Create a template – add.phtml under myapp/module/Tutorial/view/tutorial/tutorial/add.phtml Add.phtml <?php $title = 'Add new Book'; $this->headTitle($title); ?> <h1><?php echo $this->escapeHtml($title); ?></h1> <?php if(!empty($form)) { $form->setAttribute('action', $this->url('tutorial', array('action' => 'add'))); $form->prepare(); echo $this->form()->openTag($form); echo $this->formHidden($form->get('id')); echo $this->formRow($form->get('author'))."<br>"; echo $this->formRow($form->get('title'))."<br>"; echo $this->formSubmit($form->get('submit')); echo $this->form()->closeTag(); } Here, we are rendering the book form using the Form instance, $form. Now, we can run the application – http://localhost:8080/tutorial/add. Form Page Validate Error Page Print Add Notes Bookmark this page
[ { "code": null, "e": 2691, "s": 2312, "text": "Zend Framework provides a separate component, zend-form to accelerate the form creation and validation process. It connects the model and the view layer. It provides a set of form elements to create full-fledged html form from pre-defined models, an InputFilter class to validate the model against the form and options to bind the data from the form to the model and vice versa." }, { "code": null, "e": 2780, "s": 2691, "text": "The Zend form component can be installed using the Composer command as specified below −" }, { "code": null, "e": 2823, "s": 2780, "text": "composer require zendframework/zend-form \n" }, { "code": null, "e": 2930, "s": 2823, "text": "A Zend form framework has three subcomponents to manage the forms. They are as explained below in detail −" }, { "code": null, "e": 3019, "s": 2930, "text": "Elements − Used to define a single html input control mapped to a property in the model." }, { "code": null, "e": 3108, "s": 3019, "text": "Elements − Used to define a single html input control mapped to a property in the model." }, { "code": null, "e": 3181, "s": 3108, "text": "Fieldset − Used to group elements and other fieldset in a nested manner." }, { "code": null, "e": 3254, "s": 3181, "text": "Fieldset − Used to group elements and other fieldset in a nested manner." }, { "code": null, "e": 3329, "s": 3254, "text": "Form − Used to create an html form and consists of elements and fieldsets." }, { "code": null, "e": 3404, "s": 3329, "text": "Form − Used to create an html form and consists of elements and fieldsets." }, { "code": null, "e": 3473, "s": 3404, "text": "Zend Forms are usually created under the module//src/Form directory." }, { "code": null, "e": 3590, "s": 3473, "text": "Let us now create a simple form to add book into the database. To do this, we should adhere to the following steps −" }, { "code": null, "e": 3710, "s": 3590, "text": "Create the “BookForm.php” under the *myapp/module/Tutorial/src/Form” directory. Add the following changes in the file −" }, { "code": null, "e": 4539, "s": 3710, "text": "<?php \nnamespace Tutorial\\Form; \nuse Zend\\Form\\Form; \n\nclass BookForm extends Form {\n \n public function __construct($name = null) { \n parent::__construct('book'); \n $this->add(array( \n 'name' => 'id', \n 'type' => 'Hidden', \n )); \n $this->add(array( \n 'name' => 'author', \n 'type' => 'Text', \n 'options' => array( \n 'label' => 'Author', \n ), \n )); \n $this->add(array( \n 'name' => 'title', \n 'type' => 'Text', \n 'options' => array( \n 'label' => 'Title', \n ), \n )); \n $this->add(array( \n 'name' => 'submit', \n 'type' => 'Submit', \n 'attributes' => array( \n 'value' => 'Go', \n 'id' => 'submitbutton', \n ), \n )); \n } \n}" }, { "code": null, "e": 4730, "s": 4539, "text": "The Form class provides an add method to map the model and its corresponding form details. we have created the BookForm by extending the Form class and added the form details for Book model." }, { "code": null, "e": 4803, "s": 4730, "text": "Update the model, ‘Book’ with filter and validation as specified below −" }, { "code": null, "e": 7039, "s": 4803, "text": "<?php \nnamespace Tutorial\\Model; \nuse Zend\\InputFilter\\InputFilterInterface; \nuse Zend\\InputFilter\\InputFilterAwareInterface; \nuse Zend\\InputFilter\\InputFilter; \n\nclass Book implements InputFilterAwareInterface { \n public $id; \n public $author; \n public $title; \n protected $inputFilter; \n public function setInputFilter(InputFilterInterface $inputFilter) { \n throw new \\Exception(\"Not used\"); \n } \n public function getInputFilter() { \n if (!$this->inputFilter) { \n $inputFilter = new InputFilter(); \n $inputFilter->add(array( \n 'name' => 'id', \n 'required' => true, \n 'filters' => array( \n array('name' => 'Int'), \n ),\n )); \n $inputFilter->add(array( \n 'name' => 'author', \n 'required' => true, \n 'filters' => array( \n array('name' => 'StripTags'), \n array('name' => 'StringTrim'), \n ), \n 'validators' => array( \n array( \n 'name' => 'StringLength', \n 'options' => array( \n 'encoding' => 'UTF-8', \n 'min' => 1, \n 'max' => 100, \n ), \n ), \n ), \n )); \n $inputFilter->add(array( \n 'name' => 'title', \n 'required' => true, \n 'filters' => array( \n array('name' => 'StripTags'), \n array('name' => 'StringTrim'), \n ), \n 'validators' => array( \n array( \n 'name' => 'StringLength', \n 'options' => array( \n 'encoding' => 'UTF-8', \n 'min' => 1, \n 'max' => 100, \n ), \n ),\n ), \n )); \n $this->inputFilter = $inputFilter; \n } \n return $this->inputFilter; \n } \n public function exchangeArray($data) { \n $this->id = (!empty($data['id'])) ? $data['id'] : null; \n $this->author = (!empty($data['author'])) ? $data['author'] : null; \n $this->title = (!empty($data['title'])) ? $data['title'] : null; \n } \n}" }, { "code": null, "e": 7189, "s": 7039, "text": "Each model should implement the InputFilterAwareInterface. The InputFilterAwareInterface provides two methods, setInputFilter() and getInputFilter()." }, { "code": null, "e": 7418, "s": 7189, "text": "The getInputFilter is used to get the validation details of the model. Zend framework provides a rich set of filters and validators to validate the form. Some of the filters and validators used in the book model are as follows −" }, { "code": null, "e": 7452, "s": 7418, "text": "StripTags − Remove unwanted HTML." }, { "code": null, "e": 7486, "s": 7452, "text": "StripTags − Remove unwanted HTML." }, { "code": null, "e": 7531, "s": 7486, "text": "StringTrim − Remove unnecessary white space." }, { "code": null, "e": 7576, "s": 7531, "text": "StringTrim − Remove unnecessary white space." }, { "code": null, "e": 7679, "s": 7576, "text": "StringLength validator − Ensure that the user does not enter more characters than the specified limit." }, { "code": null, "e": 7782, "s": 7679, "text": "StringLength validator − Ensure that the user does not enter more characters than the specified limit." }, { "code": null, "e": 7839, "s": 7782, "text": "Include the saveBook method to add book to the database." }, { "code": null, "e": 7853, "s": 7839, "text": "BookTable.php" }, { "code": null, "e": 8980, "s": 7853, "text": "<?php \nnamespace Tutorial\\Model; \nuse Zend\\Db\\TableGateway\\TableGatewayInterface; \n\nclass BookTable {\n protected $tableGateway; \n public function __construct(TableGatewayInterface $tableGateway) { \n $this->tableGateway = $tableGateway; \n } \n public function fetchAll() { \n $resultSet = $this->tableGateway->select(); \n return $resultSet; \n } \n public function getBook($id) { \n $id = (int) $id; \n $rowset = $this->tableGateway->select(array('id' => $id)); \n $row = $rowset->current(); \n if (!$row) { \n throw new \\Exception(\"Could not find row $id\"); \n } \n return $row; \n } \n public function saveBook(Book $book) { \n $data = array ( \n 'author' => $book->author, \n 'title' => $book->title, \n ); \n $id = (int) $book->id; \n if ($id == 0) { \n $this->tableGateway->insert($data); \n } else {\n if ($this->getBook($id)) { \n $this->tableGateway->update($data, array('id' => $id)); \n } else { \n throw new \\Exception('Book id does not exist'); \n } \n } \n } \n}" }, { "code": null, "e": 9097, "s": 8980, "text": "Add a new action addAction in the tutorial controller – myapp/module/Tutorial/src/Controller/TutorialController.php." }, { "code": null, "e": 9682, "s": 9097, "text": "public function addAction() { \n $form = new BookForm(); \n $form->get('submit')->setValue('Add'); \n $request = $this->getRequest(); \n if ($request->isPost()) { \n $book = new Book(); \n $form->setInputFilter($book->getInputFilter()); \n $form->setData($request->getPost()); \n if ($form->isValid()) { \n $book->exchangeArray($form->getData()); \n $this->bookTable->saveBook($book); \n \n // Redirect to list of Tutorial \n return $this->redirect()->toRoute('tutorial'); \n } \n } \n return array('form' => $form); \n}" }, { "code": null, "e": 9734, "s": 9682, "text": "The addAction method does the following processes −" }, { "code": null, "e": 9759, "s": 9734, "text": "Gets the request object." }, { "code": null, "e": 9784, "s": 9759, "text": "Gets the request object." }, { "code": null, "e": 9838, "s": 9784, "text": "Checks if the request's http method is a post method." }, { "code": null, "e": 9892, "s": 9838, "text": "Checks if the request's http method is a post method." }, { "code": null, "e": 9970, "s": 9892, "text": "If request's http method is not post, it just renders the template, add.phtml" }, { "code": null, "e": 10048, "s": 9970, "text": "If request's http method is not post, it just renders the template, add.phtml" }, { "code": null, "e": 10175, "s": 10048, "text": "If the request's http method is not post, then it sets the inputfilter, gets the request data and sets it into the inputfiler." }, { "code": null, "e": 10302, "s": 10175, "text": "If the request's http method is not post, then it sets the inputfilter, gets the request data and sets it into the inputfiler." }, { "code": null, "e": 10377, "s": 10302, "text": "Checks whether the form is valid using the isValid() method of Form class." }, { "code": null, "e": 10452, "s": 10377, "text": "Checks whether the form is valid using the isValid() method of Form class." }, { "code": null, "e": 10519, "s": 10452, "text": "If the form is not valid, it again renders the template, add.phtml" }, { "code": null, "e": 10586, "s": 10519, "text": "If the form is not valid, it again renders the template, add.phtml" }, { "code": null, "e": 10676, "s": 10586, "text": "If the form is valid, it saves the book into the database and redirects to the home page." }, { "code": null, "e": 10766, "s": 10676, "text": "If the form is valid, it saves the book into the database and redirects to the home page." }, { "code": null, "e": 10857, "s": 10766, "text": "Create a template – add.phtml under myapp/module/Tutorial/view/tutorial/tutorial/add.phtml" }, { "code": null, "e": 10867, "s": 10857, "text": "Add.phtml" }, { "code": null, "e": 11406, "s": 10867, "text": "<?php \n$title = 'Add new Book'; \n$this->headTitle($title); \n?> \n<h1><?php echo $this->escapeHtml($title); ?></h1> \n<?php \nif(!empty($form)) { \n $form->setAttribute('action', $this->url('tutorial', array('action' => 'add'))); \n $form->prepare(); \n echo $this->form()->openTag($form); \n echo $this->formHidden($form->get('id')); \n echo $this->formRow($form->get('author')).\"<br>\"; \n echo $this->formRow($form->get('title')).\"<br>\"; \n echo $this->formSubmit($form->get('submit')); \n echo $this->form()->closeTag(); \n} " }, { "code": null, "e": 11475, "s": 11406, "text": "Here, we are rendering the book form using the Form instance, $form." }, { "code": null, "e": 11545, "s": 11475, "text": "Now, we can run the application – http://localhost:8080/tutorial/add." }, { "code": null, "e": 11555, "s": 11545, "text": "Form Page" }, { "code": null, "e": 11575, "s": 11555, "text": "Validate Error Page" }, { "code": null, "e": 11582, "s": 11575, "text": " Print" }, { "code": null, "e": 11593, "s": 11582, "text": " Add Notes" } ]
Forward List and List of Unordered Maps in C++ with Examples - GeeksforGeeks
23 Nov, 2021 Forward List Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc. Functions used with forward list: push_front(x): Adds a new element ‘x’ at the beginning of the forward list. pop_front(): This function is used to delete the first element of the forward list. List Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list. Functions used with the list: front(): Returns the value of the first element in the list. back(): Returns the value of the last element in the list. push_front(x): Adds a new element ‘x’ at the beginning of the list. push_back(x): Adds a new element ‘x’ at the end of the list. Unordered_Map An Unordered map is an associated container that stores elements formed by the combination of key-value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined. Internally, an unordered map is implemented using Hash Table. Functions used with unordered map: at(): This function in C++ unordered_map returns the reference to the value with the element as key k. begin(): Returns an iterator pointing to the first element in the container in the unordered_map container end(): Returns an iterator pointing to the position past the last element in the container in the unordered_map container size(): Returns the number of elements present inside the unordered map. This article focuses on how we can use a forward list and a list of unordered maps in C++. vector of lists and forward lists can be quite useful while designing complex data structures. Forward List of Unordered Maps Below is the implementation using a forward list of unordered maps: Example 1: C++ // C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<unordered_map<int, int> >& forwardList1){ cout << "Forward List : \n"; for (auto currentUnorderedMap : forwardList1) { // Each element of the forward_list // is a unordered map cout << "Unordered Map : "; cout << "[ "; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << "First : " << it->first << " , " << "Second : " << it->second << " "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a forward list of // unordered maps forward_list<unordered_map<int, int> > forwardList1; // Declaring a unordered map unordered_map<int, int> unorderedMap1; // Hashing values unorderedMap1[2] = 4; unorderedMap1[4] = 3; unorderedMap1[6] = 9; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, int> unorderedMap2; // Hashing values unorderedMap2[31] = 8; unorderedMap2[11] = 3; unorderedMap2[23] = 7; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, int> unorderedMap3; // Hashing values unorderedMap3[7] = 3; unorderedMap3[18] = 1; unorderedMap3[9] = 6; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, int> unorderedMap4; // Hashing values unorderedMap4[32] = 9; unorderedMap4[15] = 3; unorderedMap4[97] = 5; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap4); print(forwardList1); return 0;} Output: Forward List : Unordered Map : [ First : 97 , Second : 5 First : 32 , Second : 9 First : 15 , Second : 3 ]Unordered Map : [ First : 9 , Second : 6 First : 7 , Second : 3 First : 18 , Second : 1 ]Unordered Map : [ First : 23 , Second : 7 First : 31 , Second : 8 First : 11 , Second : 3 ]Unordered Map : [ First : 6 , Second : 9 First : 2 , Second : 4 First : 4 , Second : 3 ] Example 2: C++ // C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<unordered_map<int, string> >& forwardList1){ cout << "Forward List : \n"; for (auto currentUnorderedMap : forwardList1) { // Each element of the forward list is // a unordered map cout << "Unordered Map : "; cout << "[ "; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << "First : " << it->first << " , " << "Second : " << it->second << " "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a forward_list of // unordered maps forward_list<unordered_map<int, string> > forwardList1; // Declaring a unordered map unordered_map<int, string> unorderedMap1; // Hashing values unorderedMap1[2] = "Geeks"; unorderedMap1[4] = "for"; unorderedMap1[6] = "Geeks"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, string> unorderedMap2; // Hashing values unorderedMap2[3] = "Python"; unorderedMap2[11] = "Java"; unorderedMap2[23] = "C++"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, string> unorderedMap3; // Hashing values unorderedMap3[7] = "C"; unorderedMap3[18] = "PHP"; unorderedMap3[9] = "Swift"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, string> unorderedMap4; // Hashing values unorderedMap4[121] = "Hello"; unorderedMap4[97] = "Coding"; unorderedMap4[197] = "World"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap4); print(forwardList1); return 0;} Output: Forward List : Unordered Map : [ First : 197 , Second : World First : 121 , Second : Hello First : 97 , Second : Coding ]Unordered Map : [ First : 9 , Second : Swift First : 7 , Second : C First : 18 , Second : PHP ]Unordered Map : [ First : 23 , Second : C++ First : 3 , Second : Python First : 11 , Second : Java ]Unordered Map : [ First : 6 , Second : Geeks First : 2 , Second : Geeks First : 4 , Second : for ] List of Unordered Maps Below is the implementation using a list of unordered maps: C++ // C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Function to print list elementsvoid print(list<unordered_map<int, int> >& List){ cout << "List : \n"; for (auto currentUnorderedMap : List) { // Each element of the list is // a unordered map cout << "Unordered Map : "; cout << "[ "; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << "First : " << it->first << " , " << "Second : " << it->second << " "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a list of unordered maps list<unordered_map<int, int> > List; // Declaring a unordered map unordered_map<int, int> unorderedMap1; // Hashing values unorderedMap1[2] = 4; unorderedMap1[4] = 3; unorderedMap1[6] = 9; // Push back the unordered map // in the list List.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, int> unorderedMap2; // Hashing values unorderedMap2[31] = 8; unorderedMap2[11] = 3; unorderedMap2[23] = 7; // Push back the unordered map // in the list List.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, int> unorderedMap3; // Hashing values unorderedMap3[7] = 3; unorderedMap3[18] = 1; unorderedMap3[9] = 6; // Push back the unordered map // in the list List.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, int> unorderedMap4; // Hashing values unorderedMap4[32] = 9; unorderedMap4[15] = 3; unorderedMap4[97] = 5; // Push back the unordered map // in the list List.push_front(unorderedMap4); print(List); return 0;} Output: List : Unordered Map : [ First : 97 , Second : 5 First : 32 , Second : 9 First : 15 , Second : 3 ]Unordered Map : [ First : 9 , Second : 6 First : 7 , Second : 3 First : 18 , Second : 1 ]Unordered Map : [ First : 23 , Second : 7 First : 31 , Second : 8 First : 11 , Second : 3 ]Unordered Map : [ First : 6 , Second : 9 First : 2 , Second : 4 First : 4 , Second : 3 ] Example 2: C++ // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print list elementsvoid print(list<unordered_map<int, string> >& List){ cout << "List : \n"; for (auto currentUnorderedMap : List) { // Each element of the list is // a unordered map cout << "Unordered Map : "; cout << "[ "; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << "First : " << it->first << " , " << "Second : " << it->second << " "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a list of unordered maps list<unordered_map<int, string> > List; // Declaring a unordered map unordered_map<int, string> unorderedMap1; // Hashing values unorderedMap1[2] = "Geeks"; unorderedMap1[4] = "for"; unorderedMap1[6] = "Geeks"; // Push back the unordered map in // the forward list List.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, string> unorderedMap2; // Hashing values unorderedMap2[3] = "Python"; unorderedMap2[11] = "Java"; unorderedMap2[23] = "C++"; // Push back the unordered map in // the forward list List.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, string> unorderedMap3; // Hashing values unorderedMap3[7] = "C"; unorderedMap3[18] = "PHP"; unorderedMap3[9] = "Swift"; // Push back the unordered map in // the forward list List.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, string> unorderedMap4; // Hashing values unorderedMap4[121] = "Hello"; unorderedMap4[97] = "Coding"; unorderedMap4[197] = "World"; // Push back the unordered map in // the forward list List.push_front(unorderedMap4); print(List); return 0;} Output: List : Unordered Map : [ First : 197 , Second : World First : 121 , Second : Hello First : 97 , Second : Coding ]Unordered Map : [ First : 9 , Second : Swift First : 7 , Second : C First : 18 , Second : PHP ]Unordered Map : [ First : 23 , Second : C++ First : 3 , Second : Python First : 11 , Second : Java ]Unordered Map : [ First : 6 , Second : Geeks First : 2 , Second : Geeks First : 4 , Second : for ] CPP-forward-list cpp-list cpp-unordered_map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Convert string to char array in C++ Destructors in C++ new and delete operators in C++ for dynamic memory Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23707, "s": 23679, "text": "\n23 Nov, 2021" }, { "code": null, "e": 23720, "s": 23707, "text": "Forward List" }, { "code": null, "e": 24596, "s": 23720, "text": "Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc." }, { "code": null, "e": 24630, "s": 24596, "text": "Functions used with forward list:" }, { "code": null, "e": 24706, "s": 24630, "text": "push_front(x): Adds a new element ‘x’ at the beginning of the forward list." }, { "code": null, "e": 24790, "s": 24706, "text": "pop_front(): This function is used to delete the first element of the forward list." }, { "code": null, "e": 24795, "s": 24790, "text": "List" }, { "code": null, "e": 25120, "s": 24795, "text": "Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list." }, { "code": null, "e": 25150, "s": 25120, "text": "Functions used with the list:" }, { "code": null, "e": 25211, "s": 25150, "text": "front(): Returns the value of the first element in the list." }, { "code": null, "e": 25270, "s": 25211, "text": "back(): Returns the value of the last element in the list." }, { "code": null, "e": 25338, "s": 25270, "text": "push_front(x): Adds a new element ‘x’ at the beginning of the list." }, { "code": null, "e": 25399, "s": 25338, "text": "push_back(x): Adds a new element ‘x’ at the end of the list." }, { "code": null, "e": 25413, "s": 25399, "text": "Unordered_Map" }, { "code": null, "e": 25782, "s": 25413, "text": "An Unordered map is an associated container that stores elements formed by the combination of key-value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined. Internally, an unordered map is implemented using Hash Table." }, { "code": null, "e": 25817, "s": 25782, "text": "Functions used with unordered map:" }, { "code": null, "e": 25920, "s": 25817, "text": "at(): This function in C++ unordered_map returns the reference to the value with the element as key k." }, { "code": null, "e": 26027, "s": 25920, "text": "begin(): Returns an iterator pointing to the first element in the container in the unordered_map container" }, { "code": null, "e": 26149, "s": 26027, "text": "end(): Returns an iterator pointing to the position past the last element in the container in the unordered_map container" }, { "code": null, "e": 26222, "s": 26149, "text": "size(): Returns the number of elements present inside the unordered map." }, { "code": null, "e": 26409, "s": 26222, "text": "This article focuses on how we can use a forward list and a list of unordered maps in C++. vector of lists and forward lists can be quite useful while designing complex data structures. " }, { "code": null, "e": 26440, "s": 26409, "text": "Forward List of Unordered Maps" }, { "code": null, "e": 26508, "s": 26440, "text": "Below is the implementation using a forward list of unordered maps:" }, { "code": null, "e": 26519, "s": 26508, "text": "Example 1:" }, { "code": null, "e": 26523, "s": 26519, "text": "C++" }, { "code": "// C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<unordered_map<int, int> >& forwardList1){ cout << \"Forward List : \\n\"; for (auto currentUnorderedMap : forwardList1) { // Each element of the forward_list // is a unordered map cout << \"Unordered Map : \"; cout << \"[ \"; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << \"First : \" << it->first << \" , \" << \"Second : \" << it->second << \" \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a forward list of // unordered maps forward_list<unordered_map<int, int> > forwardList1; // Declaring a unordered map unordered_map<int, int> unorderedMap1; // Hashing values unorderedMap1[2] = 4; unorderedMap1[4] = 3; unorderedMap1[6] = 9; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, int> unorderedMap2; // Hashing values unorderedMap2[31] = 8; unorderedMap2[11] = 3; unorderedMap2[23] = 7; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, int> unorderedMap3; // Hashing values unorderedMap3[7] = 3; unorderedMap3[18] = 1; unorderedMap3[9] = 6; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, int> unorderedMap4; // Hashing values unorderedMap4[32] = 9; unorderedMap4[15] = 3; unorderedMap4[97] = 5; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap4); print(forwardList1); return 0;}", "e": 28454, "s": 26523, "text": null }, { "code": null, "e": 28462, "s": 28454, "text": "Output:" }, { "code": null, "e": 28870, "s": 28462, "text": "Forward List : Unordered Map : [ First : 97 , Second : 5 First : 32 , Second : 9 First : 15 , Second : 3 ]Unordered Map : [ First : 9 , Second : 6 First : 7 , Second : 3 First : 18 , Second : 1 ]Unordered Map : [ First : 23 , Second : 7 First : 31 , Second : 8 First : 11 , Second : 3 ]Unordered Map : [ First : 6 , Second : 9 First : 2 , Second : 4 First : 4 , Second : 3 ]" }, { "code": null, "e": 28881, "s": 28870, "text": "Example 2:" }, { "code": null, "e": 28885, "s": 28881, "text": "C++" }, { "code": "// C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<unordered_map<int, string> >& forwardList1){ cout << \"Forward List : \\n\"; for (auto currentUnorderedMap : forwardList1) { // Each element of the forward list is // a unordered map cout << \"Unordered Map : \"; cout << \"[ \"; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << \"First : \" << it->first << \" , \" << \"Second : \" << it->second << \" \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a forward_list of // unordered maps forward_list<unordered_map<int, string> > forwardList1; // Declaring a unordered map unordered_map<int, string> unorderedMap1; // Hashing values unorderedMap1[2] = \"Geeks\"; unorderedMap1[4] = \"for\"; unorderedMap1[6] = \"Geeks\"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, string> unorderedMap2; // Hashing values unorderedMap2[3] = \"Python\"; unorderedMap2[11] = \"Java\"; unorderedMap2[23] = \"C++\"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, string> unorderedMap3; // Hashing values unorderedMap3[7] = \"C\"; unorderedMap3[18] = \"PHP\"; unorderedMap3[9] = \"Swift\"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, string> unorderedMap4; // Hashing values unorderedMap4[121] = \"Hello\"; unorderedMap4[97] = \"Coding\"; unorderedMap4[197] = \"World\"; // Push back the unordered map in // the forward list forwardList1.push_front(unorderedMap4); print(forwardList1); return 0;}", "e": 30897, "s": 28885, "text": null }, { "code": null, "e": 30905, "s": 30897, "text": "Output:" }, { "code": null, "e": 31353, "s": 30905, "text": "Forward List : Unordered Map : [ First : 197 , Second : World First : 121 , Second : Hello First : 97 , Second : Coding ]Unordered Map : [ First : 9 , Second : Swift First : 7 , Second : C First : 18 , Second : PHP ]Unordered Map : [ First : 23 , Second : C++ First : 3 , Second : Python First : 11 , Second : Java ]Unordered Map : [ First : 6 , Second : Geeks First : 2 , Second : Geeks First : 4 , Second : for ]" }, { "code": null, "e": 31376, "s": 31353, "text": "List of Unordered Maps" }, { "code": null, "e": 31436, "s": 31376, "text": "Below is the implementation using a list of unordered maps:" }, { "code": null, "e": 31440, "s": 31436, "text": "C++" }, { "code": "// C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Function to print list elementsvoid print(list<unordered_map<int, int> >& List){ cout << \"List : \\n\"; for (auto currentUnorderedMap : List) { // Each element of the list is // a unordered map cout << \"Unordered Map : \"; cout << \"[ \"; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << \"First : \" << it->first << \" , \" << \"Second : \" << it->second << \" \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a list of unordered maps list<unordered_map<int, int> > List; // Declaring a unordered map unordered_map<int, int> unorderedMap1; // Hashing values unorderedMap1[2] = 4; unorderedMap1[4] = 3; unorderedMap1[6] = 9; // Push back the unordered map // in the list List.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, int> unorderedMap2; // Hashing values unorderedMap2[31] = 8; unorderedMap2[11] = 3; unorderedMap2[23] = 7; // Push back the unordered map // in the list List.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, int> unorderedMap3; // Hashing values unorderedMap3[7] = 3; unorderedMap3[18] = 1; unorderedMap3[9] = 6; // Push back the unordered map // in the list List.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, int> unorderedMap4; // Hashing values unorderedMap4[32] = 9; unorderedMap4[15] = 3; unorderedMap4[97] = 5; // Push back the unordered map // in the list List.push_front(unorderedMap4); print(List); return 0;}", "e": 33211, "s": 31440, "text": null }, { "code": null, "e": 33219, "s": 33211, "text": "Output:" }, { "code": null, "e": 33619, "s": 33219, "text": "List : Unordered Map : [ First : 97 , Second : 5 First : 32 , Second : 9 First : 15 , Second : 3 ]Unordered Map : [ First : 9 , Second : 6 First : 7 , Second : 3 First : 18 , Second : 1 ]Unordered Map : [ First : 23 , Second : 7 First : 31 , Second : 8 First : 11 , Second : 3 ]Unordered Map : [ First : 6 , Second : 9 First : 2 , Second : 4 First : 4 , Second : 3 ]" }, { "code": null, "e": 33630, "s": 33619, "text": "Example 2:" }, { "code": null, "e": 33634, "s": 33630, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print list elementsvoid print(list<unordered_map<int, string> >& List){ cout << \"List : \\n\"; for (auto currentUnorderedMap : List) { // Each element of the list is // a unordered map cout << \"Unordered Map : \"; cout << \"[ \"; // Print unordered map elements for (auto it = currentUnorderedMap.begin(); it != currentUnorderedMap.end(); it++) { cout << \"First : \" << it->first << \" , \" << \"Second : \" << it->second << \" \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a list of unordered maps list<unordered_map<int, string> > List; // Declaring a unordered map unordered_map<int, string> unorderedMap1; // Hashing values unorderedMap1[2] = \"Geeks\"; unorderedMap1[4] = \"for\"; unorderedMap1[6] = \"Geeks\"; // Push back the unordered map in // the forward list List.push_front(unorderedMap1); // Declaring another unordered map unordered_map<int, string> unorderedMap2; // Hashing values unorderedMap2[3] = \"Python\"; unorderedMap2[11] = \"Java\"; unorderedMap2[23] = \"C++\"; // Push back the unordered map in // the forward list List.push_front(unorderedMap2); // Declaring another unordered map unordered_map<int, string> unorderedMap3; // Hashing values unorderedMap3[7] = \"C\"; unorderedMap3[18] = \"PHP\"; unorderedMap3[9] = \"Swift\"; // Push back the unordered map in // the forward list List.push_front(unorderedMap3); // Declaring another unordered map unordered_map<int, string> unorderedMap4; // Hashing values unorderedMap4[121] = \"Hello\"; unorderedMap4[97] = \"Coding\"; unorderedMap4[197] = \"World\"; // Push back the unordered map in // the forward list List.push_front(unorderedMap4); print(List); return 0;}", "e": 35509, "s": 33634, "text": null }, { "code": null, "e": 35517, "s": 35509, "text": "Output:" }, { "code": null, "e": 35957, "s": 35517, "text": "List : Unordered Map : [ First : 197 , Second : World First : 121 , Second : Hello First : 97 , Second : Coding ]Unordered Map : [ First : 9 , Second : Swift First : 7 , Second : C First : 18 , Second : PHP ]Unordered Map : [ First : 23 , Second : C++ First : 3 , Second : Python First : 11 , Second : Java ]Unordered Map : [ First : 6 , Second : Geeks First : 2 , Second : Geeks First : 4 , Second : for ]" }, { "code": null, "e": 35974, "s": 35957, "text": "CPP-forward-list" }, { "code": null, "e": 35983, "s": 35974, "text": "cpp-list" }, { "code": null, "e": 36001, "s": 35983, "text": "cpp-unordered_map" }, { "code": null, "e": 36005, "s": 36001, "text": "STL" }, { "code": null, "e": 36009, "s": 36005, "text": "C++" }, { "code": null, "e": 36013, "s": 36009, "text": "STL" }, { "code": null, "e": 36017, "s": 36013, "text": "CPP" }, { "code": null, "e": 36115, "s": 36017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36124, "s": 36115, "text": "Comments" }, { "code": null, "e": 36137, "s": 36124, "text": "Old Comments" }, { "code": null, "e": 36165, "s": 36137, "text": "Operator Overloading in C++" }, { "code": null, "e": 36189, "s": 36165, "text": "Sorting a vector in C++" }, { "code": null, "e": 36222, "s": 36189, "text": "Friend class and function in C++" }, { "code": null, "e": 36242, "s": 36222, "text": "Polymorphism in C++" }, { "code": null, "e": 36286, "s": 36242, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 36322, "s": 36286, "text": "Convert string to char array in C++" }, { "code": null, "e": 36341, "s": 36322, "text": "Destructors in C++" }, { "code": null, "e": 36392, "s": 36341, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 36436, "s": 36392, "text": "Pair in C++ Standard Template Library (STL)" } ]
Explain about regular expressions in TOC?
A regular expression is basically a shorthand way of showing how a regular language is built from the base set of regular languages. The symbols are identical which are used to construct the languages, and any given expression that has a language closely associated with it. For each regular expression E, there is a regular language L(E). Example 1 If the regular expression is as follows − a + b · a* It can be written in fully parenthesized form as follows − (a + (b · (a*))) Regular expressions vs. Languages The symbols of the regular expressions are distinct from those of the languages. These symbols are given below − Operators in Regular expression − There are two binary operations on regular expressions (+ and ·) and one unary operator (*) These are closely associated with the union, product and closure operations on the corresponding languages. Example 1 The regular expression a + bc* is basically shorthand for the regular language {a} ∪ ({b} · ({c}*)). Example 2 Find the language of the given regular expression. It is explained below − a + bc*. L(a + bc*) = L(a) ∪ L(bc*) = L(a) ∪ (L(b) · L(c*)) = L(a) ∪ (L(b) · L(c)*) = {a} ∪ ({b} · {c}*) = {a} ∪ ({b} · {∧, c, c2, . . . , cn, . . . , }) = {a} ∪ {b, bc, bc2, . . . , bcn, . . . } = {a, b, bc, bc2, . . . , bcn, . . . }.
[ { "code": null, "e": 1195, "s": 1062, "text": "A regular expression is basically a shorthand way of showing how a regular language is built from the base set of regular languages." }, { "code": null, "e": 1337, "s": 1195, "text": "The symbols are identical which are used to construct the languages, and any given expression that has a language closely associated with it." }, { "code": null, "e": 1402, "s": 1337, "text": "For each regular expression E, there is a regular language L(E)." }, { "code": null, "e": 1412, "s": 1402, "text": "Example 1" }, { "code": null, "e": 1454, "s": 1412, "text": "If the regular expression is as follows −" }, { "code": null, "e": 1465, "s": 1454, "text": "a + b · a*" }, { "code": null, "e": 1524, "s": 1465, "text": "It can be written in fully parenthesized form as follows −" }, { "code": null, "e": 1541, "s": 1524, "text": "(a + (b · (a*)))" }, { "code": null, "e": 1575, "s": 1541, "text": "Regular expressions vs. Languages" }, { "code": null, "e": 1688, "s": 1575, "text": "The symbols of the regular expressions are distinct from those of the languages. These symbols are given below −" }, { "code": null, "e": 1722, "s": 1688, "text": "Operators in Regular expression −" }, { "code": null, "e": 1814, "s": 1722, "text": "There are two binary operations on regular expressions (+ and ·) and one unary operator (*)" }, { "code": null, "e": 1922, "s": 1814, "text": "These are closely associated with the union, product and closure operations on the corresponding languages." }, { "code": null, "e": 1932, "s": 1922, "text": "Example 1" }, { "code": null, "e": 2033, "s": 1932, "text": "The regular expression a + bc* is basically shorthand for the regular language {a} ∪ ({b} · ({c}*))." }, { "code": null, "e": 2043, "s": 2033, "text": "Example 2" }, { "code": null, "e": 2118, "s": 2043, "text": "Find the language of the given regular expression. It is explained below −" }, { "code": null, "e": 2444, "s": 2118, "text": "a + bc*.\nL(a + bc*) = L(a) ∪ L(bc*)\n = L(a) ∪ (L(b) · L(c*))\n = L(a) ∪ (L(b) · L(c)*)\n = {a} ∪ ({b} · {c}*)\n = {a} ∪ ({b} · {∧, c, c2, . . . , cn, . . . , })\n = {a} ∪ {b, bc, bc2, . . . , bcn, . . . }\n = {a, b, bc, bc2, . . . , bcn, . . . }." } ]
Zipping and Unzipping Iterables in Python | by Luay Matalka | Towards Data Science
Let’s say that we have two lists, one that includes first names, and the other includes last names. We would like to somehow combine the first names with the corresponding last names as tuples. In other words, we would like to combine elements from multiple iterables that have the same index together in a list of tuples: list_1 = [‘Jane’, ‘John’, ‘Jennifer’]list_2 = [‘Doe’, ‘Williams’, ‘Smith’]Desired Output:[('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')] We can accomplish this with the zip() function, which is a built-in python function. The zip() function is named due to its analogous mechanism as physical zippers. When you zip something, you bring both sides together. And that’s how the zip() function works! It brings elements of the same index from multiple iterable objects together as elements of the same tuples. zip(*iterables) The zip() function takes in iterables as arguments, such as lists, files, tuples, sets, etc. The zip() function will then create an iterator that aggregates elements from each of the iterables passed in. In other words, it will return an iterator of tuples, where the i-th tuple will contain the i-th element from each of the iterables passed in. This iterator will stop once the shortest input iterable has been exhausted. Well, based on the above goal, we have two lists (which are iterable objects), and we would like to combine the same indexed elements from each of these lists together. Thus, we can use the zip() function to accomplish this as follows: first_names = [‘Jane’, ‘John’, ‘Jennifer’]last_names = [‘Doe’, ‘Williams’, ‘Smith’]full_names = list(zip(first_names, last_names))print(full_names)# [('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')] Remember, the zip() function returns an iterator. Thus, we need to use the list() function that will use this returned iterator (or zip object) to create a list. In addition, as long as the iterables passed in are ordered (sequences), then the tuples will contain elements in the same left-to-right order of the arguments passed in the zip() function. towardsdatascience.com Let’s say we have another list, ages, that contains the age of the corresponding individual in the other two lists, first_names and last_names. We would like to also include the ages in in the tuple with the first and last name. Well, as mentioned above, the zip() function takes in any number of iterables. first_names = ['Jane', 'John', 'Jennifer']last_names = ['Doe', 'Williams', 'Smith']ages = [20, 40, 30]names_and_ages = list(zip(first_names, last_names, ages))print(names_and_ages)# [('Jane', 'Doe', 20), ('John', 'Williams', 40), ('Jennifer', 'Smith', 30)] Notice how the names_and_ages contains tuples with n elements (the same number of arguments, or iterable objects, we passed in to the zip() function). If we only pass in one iterable object to the zip() function, then we will get a list of 1-item tuples as follows: first_names = ['Jane', 'John', 'Jennifer']print(list(zip(first_names)))# [('Jane',), ('John',), ('Jennifer',)] What if we pass in lists (or other iterable objects) of unequal lengths? In other words, let’s say that our last_names list contains 1 more element than first_names. Well, as mentioned above, the iterator returned by the zip() function will stop once the shortest input iterable has been exhausted. In other words, our list of tuples will only contain the elements from the indexes that are present in all the iterables passed in to the zip() function. Thus, the remaining elements in the longer iterables will be ignored. first_names = [‘Jane’, ‘John’, ‘Jennifer’]last_names = [‘Doe’, ‘Williams’, ‘Smith’, 'Jones']full_names = list(zip(first_names, last_names))print(full_names)# [('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')] If the elements in the longer iterables are needed, then we can use the itertools.zip_longest() (zip_longest() function located in the itertools module) function instead of zip(). It will continue until the longest iterable is exhausted, and will replace any missing values with the value passed in for the fillvalue argument (default is None). We can use the zip() function to iterate in parallel over multiple iterables. Since the zip() function returns an iterator, we can use this zip object (the iterator it returns) in a for loop. And since with each iteration of this iterator a tuple is returned, we can unpack the elements of this tuple within the for loop: first_names = ['Jane', 'John', 'Jennifer']last_names = ['Doe', 'Williams', 'Smith']for first, last in zip(first_names, last_names): print(first, last)# Output:Jane DoeJohn WilliamsJennifer Smith Or we can have three iterables: first_names = [‘Jane’, ‘John’, ‘Jennifer’]last_names = [‘Doe’, ‘Williams’, ‘Smith’]ages = [20, 40, 30]for first, last, age in zip(first_names, last_names, ages): print(f’{first} {last} is {age} years old’)# Output: Jane Doe is 20 years oldJohn Williams is 40 years oldJennifer Smith is 30 years old Another example of parallel iteration: We have two lists: a list of revenues and a list of costs. We would like to make a new list, profits, that is the difference between the revenues and costs. We can accomplish this using parallel iteration: revenue = [30000, 50000, 70000, 90000]cost = [10000, 15000, 20000, 30000]profit = []total_profit = 0for revenue, cost in zip(revenue, cost): profit.append(revenue — cost) total_profit += revenue — costprint(profit)# [20000, 35000, 50000, 60000]print(total_profit)# 165000 towardsdatascience.com Let’s say that we have the following list of tuples: first_and_last_names = [('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')] And we want to separate the elements in these tuples into two separate lists. Well, since that is the opposite of zipping (bringing things together), it would be unzipping (taking things apart). To unzip in python, we can use the unpacking operator * with the zip() function as follows: first_names, last_names = zip(*first_and_last_names)first_names = list(first_names)last_names = list(last_names)print(first_names)# ['Jane', 'John', 'Jennifer']print(last_names)# ['Doe', 'Williams', 'Smith'] The unpacking operator * will unpack the first_and_last_names list of tuples into its tuples. These tuples will then be passed to the zip() function, which will take these separate iterable objects (the tuples), and combines their same-indexed elements together into tuples, making two separate tuples. Lastly, through tuple unpacking, these separated tuples will be assigned to the first_names and last_names variables. We then use the list() function to convert these tuples into lists. For more on unpacking operators (* and **), iterables, iterators, and iteration, check out the following two blogs: towardsdatascience.com towardsdatascience.com In this tutorial, we looked at how the zip() function works in python. We learned how the zip() function operates in different scenarios, such as with one iterable, or with iterables that have unequal lengths. We then saw how we can use the zip() function to iterate over multiple iterable objects in parallel. And lastly, we learned how to use the unpacking operator * to unzip objects in python.
[ { "code": null, "e": 495, "s": 172, "text": "Let’s say that we have two lists, one that includes first names, and the other includes last names. We would like to somehow combine the first names with the corresponding last names as tuples. In other words, we would like to combine elements from multiple iterables that have the same index together in a list of tuples:" }, { "code": null, "e": 647, "s": 495, "text": "list_1 = [‘Jane’, ‘John’, ‘Jennifer’]list_2 = [‘Doe’, ‘Williams’, ‘Smith’]Desired Output:[('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')]" }, { "code": null, "e": 1017, "s": 647, "text": "We can accomplish this with the zip() function, which is a built-in python function. The zip() function is named due to its analogous mechanism as physical zippers. When you zip something, you bring both sides together. And that’s how the zip() function works! It brings elements of the same index from multiple iterable objects together as elements of the same tuples." }, { "code": null, "e": 1033, "s": 1017, "text": "zip(*iterables)" }, { "code": null, "e": 1457, "s": 1033, "text": "The zip() function takes in iterables as arguments, such as lists, files, tuples, sets, etc. The zip() function will then create an iterator that aggregates elements from each of the iterables passed in. In other words, it will return an iterator of tuples, where the i-th tuple will contain the i-th element from each of the iterables passed in. This iterator will stop once the shortest input iterable has been exhausted." }, { "code": null, "e": 1693, "s": 1457, "text": "Well, based on the above goal, we have two lists (which are iterable objects), and we would like to combine the same indexed elements from each of these lists together. Thus, we can use the zip() function to accomplish this as follows:" }, { "code": null, "e": 1905, "s": 1693, "text": "first_names = [‘Jane’, ‘John’, ‘Jennifer’]last_names = [‘Doe’, ‘Williams’, ‘Smith’]full_names = list(zip(first_names, last_names))print(full_names)# [('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')]" }, { "code": null, "e": 2257, "s": 1905, "text": "Remember, the zip() function returns an iterator. Thus, we need to use the list() function that will use this returned iterator (or zip object) to create a list. In addition, as long as the iterables passed in are ordered (sequences), then the tuples will contain elements in the same left-to-right order of the arguments passed in the zip() function." }, { "code": null, "e": 2280, "s": 2257, "text": "towardsdatascience.com" }, { "code": null, "e": 2588, "s": 2280, "text": "Let’s say we have another list, ages, that contains the age of the corresponding individual in the other two lists, first_names and last_names. We would like to also include the ages in in the tuple with the first and last name. Well, as mentioned above, the zip() function takes in any number of iterables." }, { "code": null, "e": 2845, "s": 2588, "text": "first_names = ['Jane', 'John', 'Jennifer']last_names = ['Doe', 'Williams', 'Smith']ages = [20, 40, 30]names_and_ages = list(zip(first_names, last_names, ages))print(names_and_ages)# [('Jane', 'Doe', 20), ('John', 'Williams', 40), ('Jennifer', 'Smith', 30)]" }, { "code": null, "e": 2996, "s": 2845, "text": "Notice how the names_and_ages contains tuples with n elements (the same number of arguments, or iterable objects, we passed in to the zip() function)." }, { "code": null, "e": 3111, "s": 2996, "text": "If we only pass in one iterable object to the zip() function, then we will get a list of 1-item tuples as follows:" }, { "code": null, "e": 3222, "s": 3111, "text": "first_names = ['Jane', 'John', 'Jennifer']print(list(zip(first_names)))# [('Jane',), ('John',), ('Jennifer',)]" }, { "code": null, "e": 3745, "s": 3222, "text": "What if we pass in lists (or other iterable objects) of unequal lengths? In other words, let’s say that our last_names list contains 1 more element than first_names. Well, as mentioned above, the iterator returned by the zip() function will stop once the shortest input iterable has been exhausted. In other words, our list of tuples will only contain the elements from the indexes that are present in all the iterables passed in to the zip() function. Thus, the remaining elements in the longer iterables will be ignored." }, { "code": null, "e": 3966, "s": 3745, "text": "first_names = [‘Jane’, ‘John’, ‘Jennifer’]last_names = [‘Doe’, ‘Williams’, ‘Smith’, 'Jones']full_names = list(zip(first_names, last_names))print(full_names)# [('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')]" }, { "code": null, "e": 4311, "s": 3966, "text": "If the elements in the longer iterables are needed, then we can use the itertools.zip_longest() (zip_longest() function located in the itertools module) function instead of zip(). It will continue until the longest iterable is exhausted, and will replace any missing values with the value passed in for the fillvalue argument (default is None)." }, { "code": null, "e": 4633, "s": 4311, "text": "We can use the zip() function to iterate in parallel over multiple iterables. Since the zip() function returns an iterator, we can use this zip object (the iterator it returns) in a for loop. And since with each iteration of this iterator a tuple is returned, we can unpack the elements of this tuple within the for loop:" }, { "code": null, "e": 4831, "s": 4633, "text": "first_names = ['Jane', 'John', 'Jennifer']last_names = ['Doe', 'Williams', 'Smith']for first, last in zip(first_names, last_names): print(first, last)# Output:Jane DoeJohn WilliamsJennifer Smith" }, { "code": null, "e": 4863, "s": 4831, "text": "Or we can have three iterables:" }, { "code": null, "e": 5165, "s": 4863, "text": "first_names = [‘Jane’, ‘John’, ‘Jennifer’]last_names = [‘Doe’, ‘Williams’, ‘Smith’]ages = [20, 40, 30]for first, last, age in zip(first_names, last_names, ages): print(f’{first} {last} is {age} years old’)# Output: Jane Doe is 20 years oldJohn Williams is 40 years oldJennifer Smith is 30 years old" }, { "code": null, "e": 5204, "s": 5165, "text": "Another example of parallel iteration:" }, { "code": null, "e": 5410, "s": 5204, "text": "We have two lists: a list of revenues and a list of costs. We would like to make a new list, profits, that is the difference between the revenues and costs. We can accomplish this using parallel iteration:" }, { "code": null, "e": 5688, "s": 5410, "text": "revenue = [30000, 50000, 70000, 90000]cost = [10000, 15000, 20000, 30000]profit = []total_profit = 0for revenue, cost in zip(revenue, cost): profit.append(revenue — cost) total_profit += revenue — costprint(profit)# [20000, 35000, 50000, 60000]print(total_profit)# 165000" }, { "code": null, "e": 5711, "s": 5688, "text": "towardsdatascience.com" }, { "code": null, "e": 5764, "s": 5711, "text": "Let’s say that we have the following list of tuples:" }, { "code": null, "e": 5850, "s": 5764, "text": "first_and_last_names = [('Jane', 'Doe'), ('John', 'Williams'), ('Jennifer', 'Smith')]" }, { "code": null, "e": 6137, "s": 5850, "text": "And we want to separate the elements in these tuples into two separate lists. Well, since that is the opposite of zipping (bringing things together), it would be unzipping (taking things apart). To unzip in python, we can use the unpacking operator * with the zip() function as follows:" }, { "code": null, "e": 6345, "s": 6137, "text": "first_names, last_names = zip(*first_and_last_names)first_names = list(first_names)last_names = list(last_names)print(first_names)# ['Jane', 'John', 'Jennifer']print(last_names)# ['Doe', 'Williams', 'Smith']" }, { "code": null, "e": 6834, "s": 6345, "text": "The unpacking operator * will unpack the first_and_last_names list of tuples into its tuples. These tuples will then be passed to the zip() function, which will take these separate iterable objects (the tuples), and combines their same-indexed elements together into tuples, making two separate tuples. Lastly, through tuple unpacking, these separated tuples will be assigned to the first_names and last_names variables. We then use the list() function to convert these tuples into lists." }, { "code": null, "e": 6950, "s": 6834, "text": "For more on unpacking operators (* and **), iterables, iterators, and iteration, check out the following two blogs:" }, { "code": null, "e": 6973, "s": 6950, "text": "towardsdatascience.com" }, { "code": null, "e": 6996, "s": 6973, "text": "towardsdatascience.com" } ]
Longest substring of vowels
13 Mar, 2022 Given a string s of lowercase letters, we need to find the longest substring length that contains (a, e, i, o, u) only. Examples : Input: s = "geeksforgeeks" Output: 2 Longest substring is "ee" Input: s = "theeare" Output: 3 The idea is to traverse the string and keep track of the current number of vowels in the string. If we see a character that is not a vowel, we reset count to 0. But before resetting we update the max count value which is going to be our result. C++ Java Python3 C# PHP Javascript // CPP program to find the// longest substring of vowels.#include <bits/stdc++.h>using namespace std; bool isVowel(char c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } int longestVowel(string s){ int count = 0, res = 0; for (int i = 0; i < s.length(); i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // check previous value // is greater then or not res = max(res, count); count = 0; } } return max(res, count);} // Driver codeint main(){ string s = "theeare"; cout << longestVowel(s) << endl; return 0;} // Java program to find the// longest substring of vowels.import java.util.*; class GFG{ static boolean isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } static int longestVowel(String str) { int count = 0, res = 0; char[] s = str.toCharArray(); for (int i = 0; i < s.length; i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // check previous value // is greater then or not res = Math.max(res, count); count = 0; } } return Math.max(res, count); } // Driver codepublic static void main (String[] args){ String s = "theeare"; System.out.println(longestVowel(s));}}// This code is contributed by Mr. Somesh Awasthi # Python3 program to find the# longest substring of vowels.def isVowel(c): return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u') def longestVowel(s): count, res = 0, 0 for i in range(len(s)): # Increment current count # if s[i] is vowel if (isVowel(s[i])): count += 1 else: # check previous value # is greater then or not res = max(res, count) count = 0 return max(res, count) # Driver codeif __name__ == "__main__": s = "theeare" print (longestVowel(s)) # This code is contributed by Chitranayal // C# program to find the// longest substring of vowels.using System; class GFG{ static bool isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } static int longestVowel(String str) { int count = 0, res = 0; char []s = str.ToCharArray(); for (int i = 0; i < s.Length; i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // check previous value // is greater then or not res = Math.Max(res, count); count = 0; } } return Math.Max(res, count); } // Driver codepublic static void Main () { String s = "theeare"; Console.Write(longestVowel(s)); }} // This code is contributed by nitin mittal <?php// PHP program to find the// longest substring of vowels.function isVowel($c){ return ($c == 'a' || $c == 'e' || $c == 'i' || $c == 'o' || $c == 'u');} function longestVowel($s){ $count = 0; $res = 0; for ($i = 0; $i < strlen($s); $i++) { // Increment current count // if s[i] is vowel if (isVowel($s[$i])) $count++; else { // check previous value // is greater then or not $res = max($res, $count); $count = 0; } } return max($res, $count);} // Driver code$s = "theeare";echo longestVowel($s) ; // This code is contributed// by nitin mittal.?> <script> // Javascript program to find the// longest substring of vowels.function isVowel(c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');} function longestVowel(str){ let count = 0, res = 0; let s = str.split(""); for(let i = 0; i < s.length; i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // Check previous value // is greater then or not res = Math.max(res, count); count = 0; } } return Math.max(res, count);} // Driver codelet s = "theeare";document.write(longestVowel(s)); // This code is contributed by avanitrachhadiya2155 </script> 3 Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Ajay Puri. 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. nitin mittal ukasp prashilgupta avanitrachhadiya2155 rishavnitro vowel-consonant Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Mar, 2022" }, { "code": null, "e": 173, "s": 52, "text": "Given a string s of lowercase letters, we need to find the longest substring length that contains (a, e, i, o, u) only. " }, { "code": null, "e": 185, "s": 173, "text": "Examples : " }, { "code": null, "e": 280, "s": 185, "text": "Input: s = \"geeksforgeeks\"\nOutput: 2\nLongest substring is \"ee\"\n\nInput: s = \"theeare\"\nOutput: 3" }, { "code": null, "e": 526, "s": 280, "text": "The idea is to traverse the string and keep track of the current number of vowels in the string. If we see a character that is not a vowel, we reset count to 0. But before resetting we update the max count value which is going to be our result. " }, { "code": null, "e": 530, "s": 526, "text": "C++" }, { "code": null, "e": 535, "s": 530, "text": "Java" }, { "code": null, "e": 543, "s": 535, "text": "Python3" }, { "code": null, "e": 546, "s": 543, "text": "C#" }, { "code": null, "e": 550, "s": 546, "text": "PHP" }, { "code": null, "e": 561, "s": 550, "text": "Javascript" }, { "code": "// CPP program to find the// longest substring of vowels.#include <bits/stdc++.h>using namespace std; bool isVowel(char c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } int longestVowel(string s){ int count = 0, res = 0; for (int i = 0; i < s.length(); i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // check previous value // is greater then or not res = max(res, count); count = 0; } } return max(res, count);} // Driver codeint main(){ string s = \"theeare\"; cout << longestVowel(s) << endl; return 0;}", "e": 1282, "s": 561, "text": null }, { "code": "// Java program to find the// longest substring of vowels.import java.util.*; class GFG{ static boolean isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } static int longestVowel(String str) { int count = 0, res = 0; char[] s = str.toCharArray(); for (int i = 0; i < s.length; i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // check previous value // is greater then or not res = Math.max(res, count); count = 0; } } return Math.max(res, count); } // Driver codepublic static void main (String[] args){ String s = \"theeare\"; System.out.println(longestVowel(s));}}// This code is contributed by Mr. Somesh Awasthi", "e": 2222, "s": 1282, "text": null }, { "code": "# Python3 program to find the# longest substring of vowels.def isVowel(c): return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u') def longestVowel(s): count, res = 0, 0 for i in range(len(s)): # Increment current count # if s[i] is vowel if (isVowel(s[i])): count += 1 else: # check previous value # is greater then or not res = max(res, count) count = 0 return max(res, count) # Driver codeif __name__ == \"__main__\": s = \"theeare\" print (longestVowel(s)) # This code is contributed by Chitranayal", "e": 2884, "s": 2222, "text": null }, { "code": "// C# program to find the// longest substring of vowels.using System; class GFG{ static bool isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } static int longestVowel(String str) { int count = 0, res = 0; char []s = str.ToCharArray(); for (int i = 0; i < s.Length; i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // check previous value // is greater then or not res = Math.Max(res, count); count = 0; } } return Math.Max(res, count); } // Driver codepublic static void Main () { String s = \"theeare\"; Console.Write(longestVowel(s)); }} // This code is contributed by nitin mittal", "e": 3806, "s": 2884, "text": null }, { "code": "<?php// PHP program to find the// longest substring of vowels.function isVowel($c){ return ($c == 'a' || $c == 'e' || $c == 'i' || $c == 'o' || $c == 'u');} function longestVowel($s){ $count = 0; $res = 0; for ($i = 0; $i < strlen($s); $i++) { // Increment current count // if s[i] is vowel if (isVowel($s[$i])) $count++; else { // check previous value // is greater then or not $res = max($res, $count); $count = 0; } } return max($res, $count);} // Driver code$s = \"theeare\";echo longestVowel($s) ; // This code is contributed// by nitin mittal.?>", "e": 4497, "s": 3806, "text": null }, { "code": "<script> // Javascript program to find the// longest substring of vowels.function isVowel(c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');} function longestVowel(str){ let count = 0, res = 0; let s = str.split(\"\"); for(let i = 0; i < s.length; i++) { // Increment current count // if s[i] is vowel if (isVowel(s[i])) count++; else { // Check previous value // is greater then or not res = Math.max(res, count); count = 0; } } return Math.max(res, count);} // Driver codelet s = \"theeare\";document.write(longestVowel(s)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 5278, "s": 4497, "text": null }, { "code": null, "e": 5280, "s": 5278, "text": "3" }, { "code": null, "e": 5302, "s": 5280, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5324, "s": 5302, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5741, "s": 5324, "text": "This article is contributed by Ajay Puri. 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": 5754, "s": 5741, "text": "nitin mittal" }, { "code": null, "e": 5760, "s": 5754, "text": "ukasp" }, { "code": null, "e": 5773, "s": 5760, "text": "prashilgupta" }, { "code": null, "e": 5794, "s": 5773, "text": "avanitrachhadiya2155" }, { "code": null, "e": 5806, "s": 5794, "text": "rishavnitro" }, { "code": null, "e": 5822, "s": 5806, "text": "vowel-consonant" }, { "code": null, "e": 5830, "s": 5822, "text": "Strings" }, { "code": null, "e": 5838, "s": 5830, "text": "Strings" } ]
Python | Pandas Period.freq
06 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 Period.freq attribute returns the frequency applied on the given Period object. Syntax : Period.freq Parameters : None Return : frequency Example #1: Use Period.freq attribute to find the time series frequency applied on the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='D', year = 2001, month = 2, day = 21) # Print the Period objectprint(prd) Output : Now we will use the Period.freq attribute to find the frequency applied on prd object. # return the frequencyprd.freq Output : As we can see in the output, the Period.freq attribute has returned ‘Day’ indicating that the time series frequency applied on the given object was day. Example #2: Use Period.freq attribute to find the time series frequency applied on the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='Q', year = 2006, quarter = 1) # Print the objectprint(prd) Output : Now we will use the Period.freq attribute to find the frequency applied on prd object. # return the frequencyprd.freq Output : As we can see in the output, the Period.freq attribute has returned ‘QuarterEnd’ indicating that the time series frequency applied on the given object was ‘Quarter’. Pandas scalar-period Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 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": 329, "s": 242, "text": "Pandas Period.freq attribute returns the frequency applied on the given Period object." }, { "code": null, "e": 350, "s": 329, "text": "Syntax : Period.freq" }, { "code": null, "e": 368, "s": 350, "text": "Parameters : None" }, { "code": null, "e": 387, "s": 368, "text": "Return : frequency" }, { "code": null, "e": 495, "s": 387, "text": "Example #1: Use Period.freq attribute to find the time series frequency applied on the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='D', year = 2001, month = 2, day = 21) # Print the Period objectprint(prd)", "e": 664, "s": 495, "text": null }, { "code": null, "e": 673, "s": 664, "text": "Output :" }, { "code": null, "e": 760, "s": 673, "text": "Now we will use the Period.freq attribute to find the frequency applied on prd object." }, { "code": "# return the frequencyprd.freq", "e": 791, "s": 760, "text": null }, { "code": null, "e": 800, "s": 791, "text": "Output :" }, { "code": null, "e": 953, "s": 800, "text": "As we can see in the output, the Period.freq attribute has returned ‘Day’ indicating that the time series frequency applied on the given object was day." }, { "code": null, "e": 1061, "s": 953, "text": "Example #2: Use Period.freq attribute to find the time series frequency applied on the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='Q', year = 2006, quarter = 1) # Print the objectprint(prd)", "e": 1215, "s": 1061, "text": null }, { "code": null, "e": 1224, "s": 1215, "text": "Output :" }, { "code": null, "e": 1311, "s": 1224, "text": "Now we will use the Period.freq attribute to find the frequency applied on prd object." }, { "code": "# return the frequencyprd.freq", "e": 1342, "s": 1311, "text": null }, { "code": null, "e": 1351, "s": 1342, "text": "Output :" }, { "code": null, "e": 1517, "s": 1351, "text": "As we can see in the output, the Period.freq attribute has returned ‘QuarterEnd’ indicating that the time series frequency applied on the given object was ‘Quarter’." }, { "code": null, "e": 1538, "s": 1517, "text": "Pandas scalar-period" }, { "code": null, "e": 1552, "s": 1538, "text": "Python-pandas" }, { "code": null, "e": 1559, "s": 1552, "text": "Python" } ]
Field setInt() method in Java with Examples
02 Jun, 2022 setInt() method of java.lang.reflect.Field used to set the value of a field as an int on the specified object. When you need to set the value of a field of an object as int then you can use this method to set value over an Object. Syntax: public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException Parameters: This method accepts two parameters: obj: which is the object whose field should be modified and i: which is the new value for the field of obj being modified. Return: This method returns nothing. Exception: This method throws the following Exception: IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final. IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails. NullPointerException: if the specified object is null and the field is an instance field. ExceptionInInitializerError: if the initialization provoked by this method fails. Below programs illustrate setInt() method: Program 1: Java // Java program to illustrate setInt() methodimport java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object Employee emp = new Employee(); // print value of salary System.out.println( "Value of salary before " + "applying setInt is " + emp.salary); // Get the field object Field field = Employee.class.getField("salary"); // Apply setInt Method field.setInt(emp, 2243599); // print value of salary System.out.println( "Value of salary after " + "applying setInt is " + emp.salary); // print value of uniqueNo System.out.println( "Value of uniqueNo before " + "applying setInt is " + emp.uniqueNo); // Get the field object field = Employee.class.getField("uniqueNo"); // Apply setInt Method field.setInt(emp, 123434); // print value of uniqueNo System.out.println( "Value of uniqueNo after " + "applying setInt is " + emp.uniqueNo); }} // sample classclass Employee { // static int values public static int uniqueNo = 234289; public static int salary = 1125213;} Value of salary before applying setInt is 1125213 Value of salary after applying setInt is 2243599 Value of uniqueNo before applying setInt is 234289 Value of uniqueNo after applying setInt is 123434 Program 2: Java // Java program to illustrate setInt() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create Numbers object Numbers no = new Numbers(); // Get the value field object Field field = Numbers.class .getField("value"); // Apply setInt Method field.setInt(no, 53266); // print value of isActive System.out.println( "Value after " + "applying setInt is " + Numbers.value); }} // sample Numbers classclass Numbers { // static int value public static int value = 13685;} Value after applying setInt is 53266 Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setInt-java.lang.Object-int- sagartomar9927 Java-Field Java-Functions java-lang-reflect-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2022" }, { "code": null, "e": 267, "s": 28, "text": "setInt() method of java.lang.reflect.Field used to set the value of a field as an int on the specified object. When you need to set the value of a field of an object as int then you can use this method to set value over an Object. Syntax:" }, { "code": null, "e": 392, "s": 267, "text": "public void setInt(Object obj, int i)\n throws IllegalArgumentException,\n IllegalAccessException" }, { "code": null, "e": 441, "s": 392, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 501, "s": 441, "text": "obj: which is the object whose field should be modified and" }, { "code": null, "e": 564, "s": 501, "text": "i: which is the new value for the field of obj being modified." }, { "code": null, "e": 656, "s": 564, "text": "Return: This method returns nothing. Exception: This method throws the following Exception:" }, { "code": null, "e": 801, "s": 656, "text": "IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final." }, { "code": null, "e": 1005, "s": 801, "text": "IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails." }, { "code": null, "e": 1095, "s": 1005, "text": "NullPointerException: if the specified object is null and the field is an instance field." }, { "code": null, "e": 1177, "s": 1095, "text": "ExceptionInInitializerError: if the initialization provoked by this method fails." }, { "code": null, "e": 1232, "s": 1177, "text": "Below programs illustrate setInt() method: Program 1: " }, { "code": null, "e": 1237, "s": 1232, "text": "Java" }, { "code": "// Java program to illustrate setInt() methodimport java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object Employee emp = new Employee(); // print value of salary System.out.println( \"Value of salary before \" + \"applying setInt is \" + emp.salary); // Get the field object Field field = Employee.class.getField(\"salary\"); // Apply setInt Method field.setInt(emp, 2243599); // print value of salary System.out.println( \"Value of salary after \" + \"applying setInt is \" + emp.salary); // print value of uniqueNo System.out.println( \"Value of uniqueNo before \" + \"applying setInt is \" + emp.uniqueNo); // Get the field object field = Employee.class.getField(\"uniqueNo\"); // Apply setInt Method field.setInt(emp, 123434); // print value of uniqueNo System.out.println( \"Value of uniqueNo after \" + \"applying setInt is \" + emp.uniqueNo); }} // sample classclass Employee { // static int values public static int uniqueNo = 234289; public static int salary = 1125213;}", "e": 2562, "s": 1237, "text": null }, { "code": null, "e": 2762, "s": 2562, "text": "Value of salary before applying setInt is 1125213\nValue of salary after applying setInt is 2243599\nValue of uniqueNo before applying setInt is 234289\nValue of uniqueNo after applying setInt is 123434" }, { "code": null, "e": 2774, "s": 2762, "text": "Program 2: " }, { "code": null, "e": 2779, "s": 2774, "text": "Java" }, { "code": "// Java program to illustrate setInt() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create Numbers object Numbers no = new Numbers(); // Get the value field object Field field = Numbers.class .getField(\"value\"); // Apply setInt Method field.setInt(no, 53266); // print value of isActive System.out.println( \"Value after \" + \"applying setInt is \" + Numbers.value); }} // sample Numbers classclass Numbers { // static int value public static int value = 13685;}", "e": 3455, "s": 2779, "text": null }, { "code": null, "e": 3492, "s": 3455, "text": "Value after applying setInt is 53266" }, { "code": null, "e": 3603, "s": 3492, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setInt-java.lang.Object-int-" }, { "code": null, "e": 3618, "s": 3603, "text": "sagartomar9927" }, { "code": null, "e": 3629, "s": 3618, "text": "Java-Field" }, { "code": null, "e": 3644, "s": 3629, "text": "Java-Functions" }, { "code": null, "e": 3670, "s": 3644, "text": "java-lang-reflect-package" }, { "code": null, "e": 3675, "s": 3670, "text": "Java" }, { "code": null, "e": 3680, "s": 3675, "text": "Java" }, { "code": null, "e": 3778, "s": 3680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3793, "s": 3778, "text": "Stream In Java" }, { "code": null, "e": 3814, "s": 3793, "text": "Introduction to Java" }, { "code": null, "e": 3835, "s": 3814, "text": "Constructors in Java" }, { "code": null, "e": 3854, "s": 3835, "text": "Exceptions in Java" }, { "code": null, "e": 3871, "s": 3854, "text": "Generics in Java" }, { "code": null, "e": 3901, "s": 3871, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3927, "s": 3901, "text": "Java Programming Examples" }, { "code": null, "e": 3943, "s": 3927, "text": "Strings in Java" }, { "code": null, "e": 3980, "s": 3943, "text": "Differences between JDK, JRE and JVM" } ]
Visualize correlation matrix using correlogram in R Programming
05 Sep, 2020 A graph of the correlation matrix is known as Correlogram. This is generally used to highlight the variables in a data set or data table that are correlated most. The correlation coefficients in the plot are colored based on the value. Based on the degree of association among the variables, we can reorder the correlation matrix accordingly. In R, we shall use the “corrplot” package to implement a correlogram. Hence, to install the package from the R Console we should execute the following command: install.packages("corrplot") Once we have installed the package properly, we shall load the package in our R script using the library() function as follows: library("corrplot") We shall now see how to implement the correlogram in R programming. We shall see the detailed explanation of the implementation with an example in a step by step manner. Example: Step 1: [Data for Correlation Analysis]: The first job is to select a proper dataset to implement the concept. For our example, we will be using the “mtcars” data set which is an inbuilt data set of R. We will see some of the data in this data set. R # Correlogram in R# including the required packageslibrary(corrplot) head(mtcars) Output: head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 Step 2: [Computing Correlation Matrix]: We will now compute a correlation matrix for which we want to plot the correlogram. We shall use the cor() function for computing a correlation matrix. R # Correlogram in R# required packageslibrary(corrplot) head(mtcars)#correlation matrixM<-cor(mtcars)head(round(M,2)) Output: head(round(M,2)) mpg cyl disp hp drat wt qsec vs am gear carb mpg 1.00 -0.85 -0.85 -0.78 0.68 -0.87 0.42 0.66 0.60 0.48 -0.55 cyl -0.85 1.00 0.90 0.83 -0.70 0.78 -0.59 -0.81 -0.52 -0.49 0.53 disp -0.85 0.90 1.00 0.79 -0.71 0.89 -0.43 -0.71 -0.59 -0.56 0.39 hp -0.78 0.83 0.79 1.00 -0.45 0.66 -0.71 -0.72 -0.24 -0.13 0.75 drat 0.68 -0.70 -0.71 -0.45 1.00 -0.71 0.09 0.44 0.71 0.70 -0.09 wt -0.87 0.78 0.89 0.66 -0.71 1.00 -0.17 -0.55 -0.69 -0.58 0.43 Step 3: [Visualizing using Method argument]: At first, we shall see how to visualize the correlogram in different shapes like circles, pie, ellipse, and so on. We shall use the corrplot() function and mention the shape in its method arguments. R # Correlogram in R# required packageslibrary(corrplot) head(mtcars)#correlation matrixM<-cor(mtcars)head(round(M,2)) #visualizing correlogram#as circlecorrplot(M, method="circle")# as piecorrplot(M, method="pie")# as colourcorrplot(M, method="color")# as numbercorrplot(M, method="number") Output: Step 4: [Visualizing using type argument]: We shall see how to visualize the correlogram in different types like upper and lower triangular matrices. We shall use the corrplot() function and mention the type argument. R # Correlogram in R# required packagelibrary(corrplot) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M,2)) # types# upper triangular matrixcorrplot(M, type="upper") # lower triangular matrixcorrplot(M, type="lower") Output: Step 5: [Reordering the correlogram]: We shall see how to reorder the correlogram. We shall use the corrplot() function and mention the order argument. We are going to use the “hclust” ordering for hierarchical clustering. R # Correlogram in R# required packageslibrary(corrplot) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M, 2)) # reordering# correlogram with hclust reorderingcorrplot(M, type = "upper", order = "hclust") # Using different color spectrumcol<- colorRampPalette(c("red", "white", "blue"))(20)corrplot(M, type="upper", order = "hclust", col = col) # Change background color to lightbluecorrplot(M, type="upper", order="hclust", col = c("black", "white"), bg = "lightblue") Output: Step 6: [Changing the color in correlogram]: We shall now see how to change the color in correlogram. For this purpose, we have installed the “RColorBrewer” package and added it to our R script to use its palette colors. R # Correlogram in R# required packagelibrary(corrplot)library(RColorBrewer) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M, 2)) # changing colour of the correlogramcorrplot(M, type="upper", order = "hclust", col=brewer.pal(n = 8, name = "RdBu"))corrplot(M, type="upper", order = "hclust", col=brewer.pal(n = 8, name = "RdYlBu"))corrplot(M, type="upper", order = "hclust", col=brewer.pal(n = 8, name = "PuOr")) Output: Step 7: [Changing the color and rotation of the text labels]: For this purpose, we shall include the tl.col and tl.str arguments in the corrplot() function. R # Correlogram in R# required packageslibrary(corrplot)library(RColorBrewer) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M, 2)) # changing the colour and # rotation of the text labelscorrplot(M, type = "upper", order = "hclust", tl.col = "black", tl.srt = 45) Output: Step 8: [Computing the p-value of correlations]: Before we can add significance test to the correlogram we shall compute the p-value of the correlations using a custom R function as follows: R # Correlogram in R# required packagelibrary(corrplot) head(mtcars)M<-cor(mtcars)head(round(M,2)) # mat : is a matrix of data# ... : further arguments to pass # to the native R cor.test functioncor.mtest <- function(mat, ...) { mat <- as.matrix(mat) n <- ncol(mat) p.mat<- matrix(NA, n, n) diag(p.mat) <- 0 for (i in 1:(n - 1)) { for (j in (i + 1):n) { tmp <- cor.test(mat[, i], mat[, j], ...) p.mat[i, j] <- p.mat[j, i] <- tmp$p.value } } colnames(p.mat) <- rownames(p.mat) <- colnames(mat) p.mat} # matrix of the p-value of the correlationp.mat <- cor.mtest(mtcars)head(p.mat[, 1:5]) Output: head(p.mat[, 1:5]) mpg cyl disp hp drat mpg 0.000000e+00 6.112687e-10 9.380327e-10 1.787835e-07 1.776240e-05 cyl 6.112687e-10 0.000000e+00 1.802838e-12 3.477861e-09 8.244636e-06 disp 9.380327e-10 1.802838e-12 0.000000e+00 7.142679e-08 5.282022e-06 hp 1.787835e-07 3.477861e-09 7.142679e-08 0.000000e+00 9.988772e-03 drat 1.776240e-05 8.244636e-06 5.282022e-06 9.988772e-03 0.000000e+00 wt 1.293959e-10 1.217567e-07 1.222320e-11 4.145827e-05 4.784260e-06 Step 9: [Add Significance Test]: We need to add the sig.level and insig argument in the corrplot() function. If the p-value is greater than 0.01 then it is an insignificant value for which the cells are either blank or crossed. R # Correlogram in R# required packagelibrary(corrplot) head(mtcars)M<-cor(mtcars)head(round(M, 2)) library(corrplot) # mat : is a matrix of data# ... : further arguments to pass # to the native R cor.test functioncor.mtest <- function(mat, ...){ mat <- as.matrix(mat) n <- ncol(mat) p.mat<- matrix(NA, n, n) diag(p.mat) <- 0 for (i in 1:(n - 1)) { for (j in (i + 1):n) { tmp <- cor.test(mat[, i], mat[, j], ...) p.mat[i, j] <- p.mat[j, i] <- tmp$p.value } } colnames(p.mat) <- rownames(p.mat) <- colnames(mat) p.mat} # matrix of the p-value of the correlationp.mat <- cor.mtest(mtcars)head(p.mat[, 1:5]) # Specialized the insignificant value# according to the significant levelcorrplot(M, type = "upper", order = "hclust", p.mat = p.mat, sig.level = 0.01) # Leave blank on no significant coefficientcorrplot(M, type = "upper", order = "hclust", p.mat = p.mat, sig.level = 0.01, insig = "blank") Output: Step 10: [Customizing the Correlogram]: We can customize our correlogram using the required arguments in corrplot() function and adjusting their values. R # Correlogram in R# required packagelibrary(corrplot)library(RColorBrewer) head(mtcars)M<-cor(mtcars)head(round(M,2)) # customize the correlogramlibrary(corrplot)col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA")) corrplot(M, method = "color", col = col(200), type = "upper", order = "hclust", addCoef.col = "black", # Add coefficient of correlation tl.col="black", tl.srt = 45, # Text label color and rotation # Combine with significance p.mat = p.mat, sig.level = 0.01, insig = "blank", # hide correlation coefficient # on the principal diagonal diag = FALSE ) Output: R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 371, "s": 28, "text": "A graph of the correlation matrix is known as Correlogram. This is generally used to highlight the variables in a data set or data table that are correlated most. The correlation coefficients in the plot are colored based on the value. Based on the degree of association among the variables, we can reorder the correlation matrix accordingly." }, { "code": null, "e": 531, "s": 371, "text": "In R, we shall use the “corrplot” package to implement a correlogram. Hence, to install the package from the R Console we should execute the following command:" }, { "code": null, "e": 561, "s": 531, "text": "install.packages(\"corrplot\")\n" }, { "code": null, "e": 691, "s": 561, "text": "Once we have installed the package properly, we shall load the package in our R script using the library() function as follows: " }, { "code": null, "e": 712, "s": 691, "text": "library(\"corrplot\")\n" }, { "code": null, "e": 882, "s": 712, "text": "We shall now see how to implement the correlogram in R programming. We shall see the detailed explanation of the implementation with an example in a step by step manner." }, { "code": null, "e": 891, "s": 882, "text": "Example:" }, { "code": null, "e": 1140, "s": 891, "text": "Step 1: [Data for Correlation Analysis]: The first job is to select a proper dataset to implement the concept. For our example, we will be using the “mtcars” data set which is an inbuilt data set of R. We will see some of the data in this data set." }, { "code": null, "e": 1142, "s": 1140, "text": "R" }, { "code": "# Correlogram in R# including the required packageslibrary(corrplot) head(mtcars)", "e": 1225, "s": 1142, "text": null }, { "code": null, "e": 1233, "s": 1225, "text": "Output:" }, { "code": null, "e": 1730, "s": 1233, "text": "head(mtcars)\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1\n" }, { "code": null, "e": 1922, "s": 1730, "text": "Step 2: [Computing Correlation Matrix]: We will now compute a correlation matrix for which we want to plot the correlogram. We shall use the cor() function for computing a correlation matrix." }, { "code": null, "e": 1924, "s": 1922, "text": "R" }, { "code": "# Correlogram in R# required packageslibrary(corrplot) head(mtcars)#correlation matrixM<-cor(mtcars)head(round(M,2))", "e": 2042, "s": 1924, "text": null }, { "code": null, "e": 2050, "s": 2042, "text": "Output:" }, { "code": null, "e": 2565, "s": 2050, "text": "head(round(M,2))\n mpg cyl disp hp drat wt qsec vs am gear carb\nmpg 1.00 -0.85 -0.85 -0.78 0.68 -0.87 0.42 0.66 0.60 0.48 -0.55\ncyl -0.85 1.00 0.90 0.83 -0.70 0.78 -0.59 -0.81 -0.52 -0.49 0.53\ndisp -0.85 0.90 1.00 0.79 -0.71 0.89 -0.43 -0.71 -0.59 -0.56 0.39\nhp -0.78 0.83 0.79 1.00 -0.45 0.66 -0.71 -0.72 -0.24 -0.13 0.75\ndrat 0.68 -0.70 -0.71 -0.45 1.00 -0.71 0.09 0.44 0.71 0.70 -0.09\nwt -0.87 0.78 0.89 0.66 -0.71 1.00 -0.17 -0.55 -0.69 -0.58 0.43\n" }, { "code": null, "e": 2809, "s": 2565, "text": "Step 3: [Visualizing using Method argument]: At first, we shall see how to visualize the correlogram in different shapes like circles, pie, ellipse, and so on. We shall use the corrplot() function and mention the shape in its method arguments." }, { "code": null, "e": 2811, "s": 2809, "text": "R" }, { "code": "# Correlogram in R# required packageslibrary(corrplot) head(mtcars)#correlation matrixM<-cor(mtcars)head(round(M,2)) #visualizing correlogram#as circlecorrplot(M, method=\"circle\")# as piecorrplot(M, method=\"pie\")# as colourcorrplot(M, method=\"color\")# as numbercorrplot(M, method=\"number\")", "e": 3103, "s": 2811, "text": null }, { "code": null, "e": 3111, "s": 3103, "text": "Output:" }, { "code": null, "e": 3329, "s": 3111, "text": "Step 4: [Visualizing using type argument]: We shall see how to visualize the correlogram in different types like upper and lower triangular matrices. We shall use the corrplot() function and mention the type argument." }, { "code": null, "e": 3331, "s": 3329, "text": "R" }, { "code": "# Correlogram in R# required packagelibrary(corrplot) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M,2)) # types# upper triangular matrixcorrplot(M, type=\"upper\") # lower triangular matrixcorrplot(M, type=\"lower\")", "e": 3562, "s": 3331, "text": null }, { "code": null, "e": 3570, "s": 3562, "text": "Output:" }, { "code": null, "e": 3793, "s": 3570, "text": "Step 5: [Reordering the correlogram]: We shall see how to reorder the correlogram. We shall use the corrplot() function and mention the order argument. We are going to use the “hclust” ordering for hierarchical clustering." }, { "code": null, "e": 3795, "s": 3793, "text": "R" }, { "code": "# Correlogram in R# required packageslibrary(corrplot) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M, 2)) # reordering# correlogram with hclust reorderingcorrplot(M, type = \"upper\", order = \"hclust\") # Using different color spectrumcol<- colorRampPalette(c(\"red\", \"white\", \"blue\"))(20)corrplot(M, type=\"upper\", order = \"hclust\", col = col) # Change background color to lightbluecorrplot(M, type=\"upper\", order=\"hclust\", col = c(\"black\", \"white\"), bg = \"lightblue\")", "e": 4297, "s": 3795, "text": null }, { "code": null, "e": 4305, "s": 4297, "text": "Output:" }, { "code": null, "e": 4526, "s": 4305, "text": "Step 6: [Changing the color in correlogram]: We shall now see how to change the color in correlogram. For this purpose, we have installed the “RColorBrewer” package and added it to our R script to use its palette colors." }, { "code": null, "e": 4528, "s": 4526, "text": "R" }, { "code": "# Correlogram in R# required packagelibrary(corrplot)library(RColorBrewer) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M, 2)) # changing colour of the correlogramcorrplot(M, type=\"upper\", order = \"hclust\", col=brewer.pal(n = 8, name = \"RdBu\"))corrplot(M, type=\"upper\", order = \"hclust\", col=brewer.pal(n = 8, name = \"RdYlBu\"))corrplot(M, type=\"upper\", order = \"hclust\", col=brewer.pal(n = 8, name = \"PuOr\"))", "e": 4978, "s": 4528, "text": null }, { "code": null, "e": 4986, "s": 4978, "text": "Output:" }, { "code": null, "e": 5143, "s": 4986, "text": "Step 7: [Changing the color and rotation of the text labels]: For this purpose, we shall include the tl.col and tl.str arguments in the corrplot() function." }, { "code": null, "e": 5145, "s": 5143, "text": "R" }, { "code": "# Correlogram in R# required packageslibrary(corrplot)library(RColorBrewer) head(mtcars) # correlation matrixM<-cor(mtcars)head(round(M, 2)) # changing the colour and # rotation of the text labelscorrplot(M, type = \"upper\", order = \"hclust\", tl.col = \"black\", tl.srt = 45)", "e": 5429, "s": 5145, "text": null }, { "code": null, "e": 5437, "s": 5429, "text": "Output:" }, { "code": null, "e": 5628, "s": 5437, "text": "Step 8: [Computing the p-value of correlations]: Before we can add significance test to the correlogram we shall compute the p-value of the correlations using a custom R function as follows:" }, { "code": null, "e": 5630, "s": 5628, "text": "R" }, { "code": "# Correlogram in R# required packagelibrary(corrplot) head(mtcars)M<-cor(mtcars)head(round(M,2)) # mat : is a matrix of data# ... : further arguments to pass # to the native R cor.test functioncor.mtest <- function(mat, ...) { mat <- as.matrix(mat) n <- ncol(mat) p.mat<- matrix(NA, n, n) diag(p.mat) <- 0 for (i in 1:(n - 1)) { for (j in (i + 1):n) { tmp <- cor.test(mat[, i], mat[, j], ...) p.mat[i, j] <- p.mat[j, i] <- tmp$p.value } } colnames(p.mat) <- rownames(p.mat) <- colnames(mat) p.mat} # matrix of the p-value of the correlationp.mat <- cor.mtest(mtcars)head(p.mat[, 1:5])", "e": 6247, "s": 5630, "text": null }, { "code": null, "e": 6255, "s": 6247, "text": "Output:" }, { "code": null, "e": 6765, "s": 6255, "text": "head(p.mat[, 1:5])\n mpg cyl disp hp drat\nmpg 0.000000e+00 6.112687e-10 9.380327e-10 1.787835e-07 1.776240e-05\ncyl 6.112687e-10 0.000000e+00 1.802838e-12 3.477861e-09 8.244636e-06\ndisp 9.380327e-10 1.802838e-12 0.000000e+00 7.142679e-08 5.282022e-06\nhp 1.787835e-07 3.477861e-09 7.142679e-08 0.000000e+00 9.988772e-03\ndrat 1.776240e-05 8.244636e-06 5.282022e-06 9.988772e-03 0.000000e+00\nwt 1.293959e-10 1.217567e-07 1.222320e-11 4.145827e-05 4.784260e-06\n" }, { "code": null, "e": 6993, "s": 6765, "text": "Step 9: [Add Significance Test]: We need to add the sig.level and insig argument in the corrplot() function. If the p-value is greater than 0.01 then it is an insignificant value for which the cells are either blank or crossed." }, { "code": null, "e": 6995, "s": 6993, "text": "R" }, { "code": "# Correlogram in R# required packagelibrary(corrplot) head(mtcars)M<-cor(mtcars)head(round(M, 2)) library(corrplot) # mat : is a matrix of data# ... : further arguments to pass # to the native R cor.test functioncor.mtest <- function(mat, ...){ mat <- as.matrix(mat) n <- ncol(mat) p.mat<- matrix(NA, n, n) diag(p.mat) <- 0 for (i in 1:(n - 1)) { for (j in (i + 1):n) { tmp <- cor.test(mat[, i], mat[, j], ...) p.mat[i, j] <- p.mat[j, i] <- tmp$p.value } } colnames(p.mat) <- rownames(p.mat) <- colnames(mat) p.mat} # matrix of the p-value of the correlationp.mat <- cor.mtest(mtcars)head(p.mat[, 1:5]) # Specialized the insignificant value# according to the significant levelcorrplot(M, type = \"upper\", order = \"hclust\", p.mat = p.mat, sig.level = 0.01) # Leave blank on no significant coefficientcorrplot(M, type = \"upper\", order = \"hclust\", p.mat = p.mat, sig.level = 0.01, insig = \"blank\")", "e": 7951, "s": 6995, "text": null }, { "code": null, "e": 7959, "s": 7951, "text": "Output:" }, { "code": null, "e": 8112, "s": 7959, "text": "Step 10: [Customizing the Correlogram]: We can customize our correlogram using the required arguments in corrplot() function and adjusting their values." }, { "code": null, "e": 8114, "s": 8112, "text": "R" }, { "code": "# Correlogram in R# required packagelibrary(corrplot)library(RColorBrewer) head(mtcars)M<-cor(mtcars)head(round(M,2)) # customize the correlogramlibrary(corrplot)col <- colorRampPalette(c(\"#BB4444\", \"#EE9988\", \"#FFFFFF\", \"#77AADD\", \"#4477AA\")) corrplot(M, method = \"color\", col = col(200), type = \"upper\", order = \"hclust\", addCoef.col = \"black\", # Add coefficient of correlation tl.col=\"black\", tl.srt = 45, # Text label color and rotation # Combine with significance p.mat = p.mat, sig.level = 0.01, insig = \"blank\", # hide correlation coefficient # on the principal diagonal diag = FALSE )", "e": 8851, "s": 8114, "text": null }, { "code": null, "e": 8859, "s": 8851, "text": "Output:" }, { "code": null, "e": 8872, "s": 8859, "text": "R-Statistics" }, { "code": null, "e": 8883, "s": 8872, "text": "R Language" }, { "code": null, "e": 8981, "s": 8883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9033, "s": 8981, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 9091, "s": 9033, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 9143, "s": 9091, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 9201, "s": 9143, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 9233, "s": 9201, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 9268, "s": 9233, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 9312, "s": 9268, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 9344, "s": 9312, "text": "Printing Output of an R Program" }, { "code": null, "e": 9382, "s": 9344, "text": "How to Change Axis Scales in R Plots?" } ]
Bucket Sort Visualization Using Javascript - GeeksforGeeks
19 Dec, 2021 GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Bucket Sort using JavaScript. We will see how the elements are stored into Buckets and then how Buckets get traversed to get the final sorted array. We will also visualize the time complexity of Bucket Sort. Refer: Bucket Sort Asynchronous Function in JavaScript Approach: First, we will generate a random array using Math.random() function. Different color is used to indicate which element is being traversed. Each traversed element is thrown into suitable Bucket. These buckets are sorted using Insertion Sort. Further, these buckets are traversed to get the final sorted array. Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process. New array can be generated by pressing the “Ctrl+R” key. The sorting is performed using BucketSort() function using Buckets. Example: Before Sorting After Sorting Below is the program to visualize the Bucket Sort algorithm. <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> </head> <body> <br /> <p class="header">Bucket Sort</p> <div id="array"></div> <br /> <br /> <div style="display: flex; justify-content: space-evenly"> <div class="bucket"> <div id="one" class="bucket2"></div> <br /> <h3 style="text-align: center">[1-5]</h3> </div> <div class="bucket"> <div id="two" class="bucket2"></div> <br /> <h3 style="text-align: center">[6-10]</h3> </div> <div class="bucket"> <div id="three" class="bucket2"></div> <br /> <h3 style="text-align: center">[11-15]</h3> </div> <div class="bucket"> <div id="four" class="bucket2"></div> <br /> <h3 style="text-align: center">[16-20]</h3> </div> </div> <script src="script.js"></script> </body> </html> style.css: The following is the content for “style.css” used in the above file. style.css * { margin: 0px; padding: 0px; box-sizing: border-box; } .header { font-size: 20px; text-align: center; } #array { background-color: white; height: 265px; width: 598px; margin: auto; position: relative; margin-top: 64px; } .block { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease; } .block_id { position: absolute; color: black; margin-top: -20px; width: 100%; text-align: center; } .block_id2 { position: absolute; color: black; margin-top: 22px; width: 100%; text-align: center; } .block_id3 { position: absolute; color: black; margin-top: 1px; width: 100%; text-align: center; } .bucket { width: 256px; height: 260px; position: relative; } .bucket2 { margin: auto; width: 148px; height: 260px; } .firstbucket { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease; } .secondbucket { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease; } .thirdbucket { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease; } .fourthbucket { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease; } script.js: The following is the content for “script.js” file used in the above HTML code. var container = document.getElementById("array"); // Function to randomly shuffle the array function shuffle(arr) { for (var i = arr.length - 1; i > 0; i--) { // Generate random number var j = Math.floor(Math.random() * (i + 1)); var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } function generatearray() { // Creating an array var arr = []; // Filling array with values from 1 to 20 for (var i = 0; i < 20; i++) { arr.push(i + 1); } // Shuffling the array shuffle(arr); for (var i = 0; i < 20; i++) { var value = arr[i]; // Creating element div var array_ele = document.createElement("div"); // Adding class 'block' to div array_ele.classList.add("block"); // Adding style to div array_ele.style.height = `${value * 13}px`; array_ele.style.transform = `translate(${i * 30}px)`; // Creating label element for displaying // size of particular block var array_ele_label = document.createElement("label"); array_ele_label.classList.add("block_id"); array_ele_label.innerText = value; // Appending created elements to index.html array_ele.appendChild(array_ele_label); container.appendChild(array_ele); } } async function InsertionSort(clsnam, delay = 600) { let blocks = document.getElementsByClassName(clsnam); blocks[0].style.backgroundColor = "rgb(49, 226, 13)"; for (var i = 1; i < blocks.length; i += 1) { var j = i - 1; // To store the integer value of ith block to key var key = parseInt(blocks[i].childNodes[0].innerHTML); // To store the ith block height to height var height = blocks[i].style.height; // Provide darkblue color to the ith block blocks[i].style.backgroundColor = "darkblue"; // To pause the execution of code for 600 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, 600) ); // For placing selected element at its correct position while (j >= 0 && parseInt(blocks[j].childNodes[0].innerHTML) > key) { // Provide darkblue color to the jth block blocks[j].style.backgroundColor = "darkblue"; // For placing jth element over (j+1)th element blocks[j + 1].style.height = blocks[j].style.height; blocks[j + 1].childNodes[0].innerText = blocks[j].childNodes[0].innerText; j = j - 1; // To pause the execution of code for 600 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); // Provide lightgreen color to the sorted part for (var k = i; k >= 0; k--) { blocks[k].style.backgroundColor = " rgb(49, 226, 13)"; } } // Placing the selected element to its correct position blocks[j + 1].style.height = height; blocks[j + 1].childNodes[0].innerHTML = key; // To pause the execution of code for 600 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); // Provide light green color to the ith block blocks[i].style.backgroundColor = " rgb(49, 226, 13)"; } } // Asynchronous CountingSort function async function CountingSort(delay = 250) { var blocks = document.querySelectorAll(".block"); var block1 = 0, block2 = 0, block3 = 0, block4 = 0; // CountingSort Algorithm for (var i = 0; i < blocks.length; i += 1) { blocks[i].style.backgroundColor = "#FF4949"; var value = Number(blocks[i].childNodes[0].innerHTML); // Creating element div var array_ele = document.createElement("div"); // Adding style to div array_ele.style.height = `${value * 13}px`; // Creating label element for displaying // size of particular block var array_ele_label = document.createElement("label"); array_ele_label.classList.add("block_id"); array_ele_label.innerText = value; array_ele.appendChild(array_ele_label); // Adding block to first bucket if (value >= 1 && value <= 5) { array_ele.classList.add("firstbucket"); var container = document.getElementById("one"); array_ele.style.transform = `translate(${block1 * 30}px)`; container.appendChild(array_ele); block1++; } // Adding block to second bucket if (value >= 6 && value <= 10) { array_ele.classList.add("secondbucket"); var container = document.getElementById("two"); array_ele.style.transform = `translate(${block2 * 30}px)`; container.appendChild(array_ele); block2++; } // Adding block to third bucket if (value >= 11 && value <= 15) { array_ele.classList.add("thirdbucket"); var container = document.getElementById("three"); array_ele.style.transform = `translate(${block3 * 30}px)`; container.appendChild(array_ele); block3++; } // Adding block to fourth bucket if (value >= 16 && value <= 20) { array_ele.classList.add("fourthbucket"); var container = document.getElementById("four"); array_ele.style.transform = `translate(${block4 * 30}px)`; container.appendChild(array_ele); block4++; } // To wait for 250 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); blocks[i].style.backgroundColor = "#6b5b95"; } // Performing insertion sort on every bucket await InsertionSort("firstbucket"); await InsertionSort("secondbucket"); await InsertionSort("thirdbucket"); await InsertionSort("fourthbucket"); // Copying elements from buckets to main array for (var i = 0; i < 4; i++) { var bucket_idx = 0; var block_idx; if (i == 0) block_idx = document.getElementsByClassName("firstbucket"); if (i == 1) block_idx = document.getElementsByClassName("secondbucket"); if (i == 2) block_idx = document.getElementsByClassName("thirdbucket"); if (i == 3) block_idx = document.getElementsByClassName("fourthbucket"); for (var j = i * 5; j < 5 * (i + 1); j++, bucket_idx++) { block_idx[bucket_idx].style.backgroundColor = "red"; // To wait for 300 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, 300) ); blocks[j].style.height = block_idx[bucket_idx].style.height; blocks[j].childNodes[0].innerText = block_idx[bucket_idx].childNodes[0].innerText; blocks[j].style.backgroundColor = "green"; // To wait for 300 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, 300) ); block_idx[bucket_idx] .style.backgroundColor = "#6b5b95"; } } } // Calling generatearray function generatearray(); // Calling CountingSort function CountingSort(); Output: akshaysingh98088 CSS-Questions HTML-Questions JavaScript-Questions Technical Scripter 2020 CSS HTML JavaScript Sorting Technical Scripter Web Technologies Sorting HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 26831, "s": 26803, "text": "\n19 Dec, 2021" }, { "code": null, "e": 27153, "s": 26831, "text": "GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Bucket Sort using JavaScript. We will see how the elements are stored into Buckets and then how Buckets get traversed to get the final sorted array. We will also visualize the time complexity of Bucket Sort. " }, { "code": null, "e": 27160, "s": 27153, "text": "Refer:" }, { "code": null, "e": 27172, "s": 27160, "text": "Bucket Sort" }, { "code": null, "e": 27208, "s": 27172, "text": "Asynchronous Function in JavaScript" }, { "code": null, "e": 27218, "s": 27208, "text": "Approach:" }, { "code": null, "e": 27287, "s": 27218, "text": "First, we will generate a random array using Math.random() function." }, { "code": null, "e": 27357, "s": 27287, "text": "Different color is used to indicate which element is being traversed." }, { "code": null, "e": 27412, "s": 27357, "text": "Each traversed element is thrown into suitable Bucket." }, { "code": null, "e": 27459, "s": 27412, "text": "These buckets are sorted using Insertion Sort." }, { "code": null, "e": 27527, "s": 27459, "text": "Further, these buckets are traversed to get the final sorted array." }, { "code": null, "e": 27647, "s": 27527, "text": "Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process." }, { "code": null, "e": 27704, "s": 27647, "text": "New array can be generated by pressing the “Ctrl+R” key." }, { "code": null, "e": 27772, "s": 27704, "text": "The sorting is performed using BucketSort() function using Buckets." }, { "code": null, "e": 27781, "s": 27772, "text": "Example:" }, { "code": null, "e": 27796, "s": 27781, "text": "Before Sorting" }, { "code": null, "e": 27810, "s": 27796, "text": "After Sorting" }, { "code": null, "e": 27871, "s": 27810, "text": "Below is the program to visualize the Bucket Sort algorithm." }, { "code": null, "e": 28890, "s": 27871, "text": "\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <link rel=\"stylesheet\" href=\"style.css\" />\n</head>\n\n<body>\n <br />\n <p class=\"header\">Bucket Sort</p>\n\n <div id=\"array\"></div>\n <br />\n <br />\n\n <div style=\"display: flex; justify-content: space-evenly\">\n <div class=\"bucket\">\n <div id=\"one\" class=\"bucket2\"></div>\n <br />\n <h3 style=\"text-align: center\">[1-5]</h3>\n </div>\n\n <div class=\"bucket\">\n <div id=\"two\" class=\"bucket2\"></div>\n <br />\n <h3 style=\"text-align: center\">[6-10]</h3>\n </div>\n\n <div class=\"bucket\">\n <div id=\"three\" class=\"bucket2\"></div>\n <br />\n <h3 style=\"text-align: center\">[11-15]</h3>\n </div>\n \n <div class=\"bucket\">\n <div id=\"four\" class=\"bucket2\"></div>\n <br />\n <h3 style=\"text-align: center\">[16-20]</h3>\n </div>\n </div>\n\n <script src=\"script.js\"></script>\n</body>\n\n</html>\n" }, { "code": null, "e": 28970, "s": 28890, "text": "style.css: The following is the content for “style.css” used in the above file." }, { "code": null, "e": 28980, "s": 28970, "text": "style.css" }, { "code": null, "e": 30316, "s": 28980, "text": "* {\n margin: 0px;\n padding: 0px;\n box-sizing: border-box;\n}\n.header {\n font-size: 20px;\n text-align: center;\n}\n#array {\n background-color: white;\n height: 265px;\n width: 598px;\n margin: auto;\n position: relative;\n margin-top: 64px;\n}\n.block {\n width: 28px;\n background-color: #6b5b95;\n position: absolute;\n bottom: 0px;\n transition: 0.2s all ease;\n}\n.block_id {\n position: absolute;\n color: black;\n margin-top: -20px;\n width: 100%;\n text-align: center;\n}\n.block_id2 {\n position: absolute;\n color: black;\n margin-top: 22px;\n width: 100%;\n text-align: center;\n}\n.block_id3 {\n position: absolute;\n color: black;\n margin-top: 1px;\n width: 100%;\n text-align: center;\n}\n.bucket {\n width: 256px;\n height: 260px;\n position: relative;\n}\n.bucket2 {\n margin: auto;\n width: 148px;\n height: 260px;\n}\n.firstbucket {\n width: 28px;\n background-color: #6b5b95;\n position: absolute;\n bottom: 0px;\n transition: 0.2s all ease;\n}\n.secondbucket {\n width: 28px;\n background-color: #6b5b95;\n position: absolute;\n bottom: 0px;\n transition: 0.2s all ease;\n}\n.thirdbucket {\n width: 28px;\n background-color: #6b5b95;\n position: absolute;\n bottom: 0px;\n transition: 0.2s all ease;\n}\n.fourthbucket {\n width: 28px;\n background-color: #6b5b95;\n position: absolute;\n bottom: 0px;\n transition: 0.2s all ease;\n}\n\n" }, { "code": null, "e": 30406, "s": 30316, "text": "script.js: The following is the content for “script.js” file used in the above HTML code." }, { "code": null, "e": 37273, "s": 30406, "text": "\nvar container = document.getElementById(\"array\");\n\n// Function to randomly shuffle the array\nfunction shuffle(arr) {\n for (var i = arr.length - 1; i > 0; i--) {\n\n // Generate random number\n var j = Math.floor(Math.random() * (i + 1));\n var temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}\n\nfunction generatearray() {\n\n // Creating an array\n var arr = [];\n\n // Filling array with values from 1 to 20\n for (var i = 0; i < 20; i++) {\n arr.push(i + 1);\n }\n\n // Shuffling the array\n shuffle(arr);\n for (var i = 0; i < 20; i++) {\n var value = arr[i];\n\n // Creating element div\n var array_ele = document.createElement(\"div\");\n\n // Adding class 'block' to div\n array_ele.classList.add(\"block\");\n\n // Adding style to div\n array_ele.style.height = `${value * 13}px`;\n array_ele.style.transform = `translate(${i * 30}px)`;\n\n // Creating label element for displaying\n // size of particular block\n var array_ele_label = document.createElement(\"label\");\n array_ele_label.classList.add(\"block_id\");\n array_ele_label.innerText = value;\n\n // Appending created elements to index.html\n array_ele.appendChild(array_ele_label);\n container.appendChild(array_ele);\n }\n}\n\nasync function InsertionSort(clsnam, delay = 600) {\n let blocks = document.getElementsByClassName(clsnam);\n blocks[0].style.backgroundColor = \"rgb(49, 226, 13)\";\n\n for (var i = 1; i < blocks.length; i += 1) {\n var j = i - 1;\n\n // To store the integer value of ith block to key\n var key = parseInt(blocks[i].childNodes[0].innerHTML);\n\n // To store the ith block height to height\n var height = blocks[i].style.height;\n\n // Provide darkblue color to the ith block\n blocks[i].style.backgroundColor = \"darkblue\";\n\n // To pause the execution of code for 600 milliseconds\n await new Promise((resolve) =>\n setTimeout(() => {\n resolve();\n }, 600)\n );\n\n // For placing selected element at its correct position\n while (j >= 0 && parseInt(blocks[j].childNodes[0].innerHTML) > key) {\n\n // Provide darkblue color to the jth block\n blocks[j].style.backgroundColor = \"darkblue\";\n\n // For placing jth element over (j+1)th element\n blocks[j + 1].style.height = blocks[j].style.height;\n blocks[j + 1].childNodes[0].innerText = \n blocks[j].childNodes[0].innerText;\n j = j - 1;\n\n // To pause the execution of code for 600 milliseconds\n await new Promise((resolve) =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n\n // Provide lightgreen color to the sorted part\n for (var k = i; k >= 0; k--) {\n blocks[k].style.backgroundColor = \" rgb(49, 226, 13)\";\n }\n }\n\n // Placing the selected element to its correct position\n blocks[j + 1].style.height = height;\n blocks[j + 1].childNodes[0].innerHTML = key;\n\n // To pause the execution of code for 600 milliseconds\n await new Promise((resolve) =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n\n // Provide light green color to the ith block\n blocks[i].style.backgroundColor = \" rgb(49, 226, 13)\";\n }\n}\n\n// Asynchronous CountingSort function\nasync function CountingSort(delay = 250) {\n var blocks = document.querySelectorAll(\".block\");\n\n var block1 = 0,\n block2 = 0,\n block3 = 0,\n block4 = 0;\n\n // CountingSort Algorithm\n for (var i = 0; i < blocks.length; i += 1) {\n blocks[i].style.backgroundColor = \"#FF4949\";\n var value = \n Number(blocks[i].childNodes[0].innerHTML);\n\n // Creating element div\n var array_ele = document.createElement(\"div\");\n\n // Adding style to div\n array_ele.style.height = `${value * 13}px`;\n\n // Creating label element for displaying\n // size of particular block\n var array_ele_label = document.createElement(\"label\");\n array_ele_label.classList.add(\"block_id\");\n array_ele_label.innerText = value;\n\n array_ele.appendChild(array_ele_label);\n\n // Adding block to first bucket\n if (value >= 1 && value <= 5) {\n array_ele.classList.add(\"firstbucket\");\n var container = document.getElementById(\"one\");\n array_ele.style.transform = \n `translate(${block1 * 30}px)`;\n container.appendChild(array_ele);\n block1++;\n }\n\n // Adding block to second bucket\n if (value >= 6 && value <= 10) {\n array_ele.classList.add(\"secondbucket\");\n var container = document.getElementById(\"two\");\n array_ele.style.transform = \n `translate(${block2 * 30}px)`;\n container.appendChild(array_ele);\n block2++;\n }\n\n // Adding block to third bucket\n if (value >= 11 && value <= 15) {\n array_ele.classList.add(\"thirdbucket\");\n var container = document.getElementById(\"three\");\n array_ele.style.transform = `translate(${block3 * 30}px)`;\n container.appendChild(array_ele);\n block3++;\n }\n\n // Adding block to fourth bucket\n if (value >= 16 && value <= 20) {\n array_ele.classList.add(\"fourthbucket\");\n var container = document.getElementById(\"four\");\n array_ele.style.transform = \n `translate(${block4 * 30}px)`;\n container.appendChild(array_ele);\n block4++;\n }\n\n // To wait for 250 milliseconds\n await new Promise((resolve) =>\n setTimeout(() => {\n resolve();\n }, delay)\n );\n\n blocks[i].style.backgroundColor = \"#6b5b95\";\n }\n\n // Performing insertion sort on every bucket\n await InsertionSort(\"firstbucket\");\n await InsertionSort(\"secondbucket\");\n await InsertionSort(\"thirdbucket\");\n await InsertionSort(\"fourthbucket\");\n\n // Copying elements from buckets to main array\n for (var i = 0; i < 4; i++) {\n var bucket_idx = 0;\n var block_idx;\n if (i == 0) block_idx =\n document.getElementsByClassName(\"firstbucket\");\n if (i == 1) block_idx = \n document.getElementsByClassName(\"secondbucket\");\n if (i == 2) block_idx =\n document.getElementsByClassName(\"thirdbucket\");\n if (i == 3) block_idx = \n document.getElementsByClassName(\"fourthbucket\");\n for (var j = i * 5; j < 5 * (i + 1); j++, bucket_idx++) {\n block_idx[bucket_idx].style.backgroundColor = \"red\";\n\n // To wait for 300 milliseconds\n await new Promise((resolve) =>\n setTimeout(() => {\n resolve();\n }, 300)\n );\n\n blocks[j].style.height = \n block_idx[bucket_idx].style.height;\n blocks[j].childNodes[0].innerText =\n block_idx[bucket_idx].childNodes[0].innerText;\n blocks[j].style.backgroundColor = \"green\";\n\n // To wait for 300 milliseconds\n await new Promise((resolve) =>\n setTimeout(() => {\n resolve();\n }, 300)\n );\n\n block_idx[bucket_idx]\n .style.backgroundColor = \"#6b5b95\";\n }\n }\n}\n\n// Calling generatearray function\ngeneratearray();\n\n// Calling CountingSort function\nCountingSort();\n" }, { "code": null, "e": 37281, "s": 37273, "text": "Output:" }, { "code": null, "e": 37298, "s": 37281, "text": "akshaysingh98088" }, { "code": null, "e": 37312, "s": 37298, "text": "CSS-Questions" }, { "code": null, "e": 37327, "s": 37312, "text": "HTML-Questions" }, { "code": null, "e": 37348, "s": 37327, "text": "JavaScript-Questions" }, { "code": null, "e": 37372, "s": 37348, "text": "Technical Scripter 2020" }, { "code": null, "e": 37376, "s": 37372, "text": "CSS" }, { "code": null, "e": 37381, "s": 37376, "text": "HTML" }, { "code": null, "e": 37392, "s": 37381, "text": "JavaScript" }, { "code": null, "e": 37400, "s": 37392, "text": "Sorting" }, { "code": null, "e": 37419, "s": 37400, "text": "Technical Scripter" }, { "code": null, "e": 37436, "s": 37419, "text": "Web Technologies" }, { "code": null, "e": 37444, "s": 37436, "text": "Sorting" }, { "code": null, "e": 37449, "s": 37444, "text": "HTML" }, { "code": null, "e": 37547, "s": 37449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37586, "s": 37547, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 37623, "s": 37586, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 37652, "s": 37623, "text": "Form validation using jQuery" }, { "code": null, "e": 37687, "s": 37652, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 37729, "s": 37687, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 37789, "s": 37729, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 37842, "s": 37789, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 37903, "s": 37842, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 37927, "s": 37903, "text": "REST API (Introduction)" } ]
Make Your Pandas DataFrame Output Report-Ready | by Christopher Tao | Towards Data Science
As a Data Scientist or Analyst who use Python as the primary programming language, I believe you must have use Pandas a lot. It is very frequently for us to output out pandas data frame in the Jupyter notebooks. However, have you ever think that we can actually let the data frame visualise itself? In other words, for some simple visualisation purposes, we don’t need Matplotlib or other visualisation libraries. The Pandas data frame output can be visualised like an Excel spreadsheet with complicated styles and with very easy code definition. In this article, I’ll introduce the style package in the Pandas library which is known by relatively fewer people than its data processing methods. Also, there are some interesting libraries that support more IN-LINE visualisations of the Pandas data frame. In the last section, I’ll also introduce one of them — Sparklines. It is known that Pandas data frames can be output in iPython/Jupyter notebook that is automatically rendered in HTML with CSS styles. This is definitely an amazing feature because the presentation is very nice even if we just simply print it. But wait, it makes use “HTML + CSS”. Yes, Pandas also allows us to customise the CSS styles to make it even looks nicer. This is achieved by the “style” API. pandas.pydata.org We can simply call df.style to get the Styler object of a data frame, and then add the styles we want. Now, let’s see what we can do. Of course, we can always format the data itself such as df.round(2) to round all the numerical values with 2 decimals. However, there are some benefits to do that using Pandas styles. For example, we don’t actually change the value, but only the presentation, so that we didn’t lose the precision. Let’s create a random data frame first. import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randn(10, 2)*100) Then, lets output the data frame with specific formats. df.style.format("{:.2f}") BTW, if you’re not that familiar with Python Format Specification Mini-Language, which is the expression I used {:.2f}, you can check out the official documentation here (highly recommend). docs.python.org I know, formatting is not cool enough. With CSS we can easily do a lot of things, such as changing background colours and Text Colours. For example, for the same data frame above-shown, we want to highlight the positive numbers and native numbers separately. If you have some basic knowledge about CSS, or just simply Google it, you will know the below properties to set the background colour and text colour of HTML table cells. background-color: red; color: white Let’s write a function to colour the table cells. def highlight_number(row): return [ 'background-color: red; color: white' if cell <= 0 else 'background-color: green; color: white' for cell in row ] If the value of the cell is negative, we use red colour as the background, otherwise use green colour if it is positive. Since the colour might be kind of dark, we also want to change the text colour to white. Then, we can apply the function to the data frame. df.style.apply(highlight_number) Super cool! Now it is very obvious that we got negative and positive numbers, and they are distinguished very well. So far, we’re only adding one type of style each time. In fact, once we called df.style, it returns the Styler object of the data frame. The Styler object supports chaining the style functions. Let’s have a look at another example which is more complex. Let’s say, we want to add the following styles to the original data frame. Highlight the negative number in red and positive number in green.Format the number in currency.Add a caption to the table using set_caption().Make the cell padding larger so that it looks not that squeezed.Add white borders between the cells to improve the presentation. Highlight the negative number in red and positive number in green. Format the number in currency. Add a caption to the table using set_caption(). Make the cell padding larger so that it looks not that squeezed. Add white borders between the cells to improve the presentation. Yes, we can do all of these in one go, by using the chain expression. df.style \ .apply(highlight_number) \ .format('${0:,.2f}') \ .set_caption('A Sample Table') \ .set_properties(padding="20px", border='2px solid white') Feels like the table can be directly used in some business report :) Don’t know CSS, but still want to show off? Yes, Pandas style also provides some built-in functions, which are very cool but very easy to use. Let’s use the same data frame for the demonstration. # Make a nan value for demo purposesdf.at[1, 1] = None# Add stylesdf.style \ .highlight_null('lightgray') \ .highlight_max(color='lightgreen') \ .highlight_min(color='pink') See, it is very easy to highlight the NULL values, Min and Max values using whatever colours you prefer. I would recommend using light colours because the text colour always gonna be black. Pandas style also support using cmap to colour the cell background in gradient colours. This is very useful when we want to visualise the numeric data in scales. df = pd.DataFrame(np.random.randn(10, 2))df.style \ .background_gradient(cmap='Blues') So, the background colour is gradient depends on the values. Please be noted that “Blues” is one of the cmap that that Pandas supports. If you wonder what are others that are supported, the following documentation page from Matplotlib is a good reference. matplotlib.org This is another super cool feature that is built-in. It can generate bars as in the background of each cell to indicate their values. Let’s use the above data frame. df.style.bar() Of course, we’re not satisfied by the default style of the bar chart. Let’s improve the presentation. df.style \ .format('{:.2f}') \ .bar(align='mid', color=['#FCC0CB', '#90EE90']) \ .set_caption('A Sample Table with Bar Chart') \ .set_properties(padding="15px", border='2px solid white', width='300px') Can you believe this is still the “Pandas dataframe” that you use to be very familiar with? :) Let me simply explain the parameters in the bar() method. The color parameter supports either a single string or a tuple, when it is a tuple, the first colour will be used for colouring the negative values and the second colour is for the positive. Since we’re using two colours, we need to set the bar to be aligned in the middle of the cell. I could stop here, but I want to show off another library I found which is very interesting called Sparklines. I wouldn’t say it’s very nice looking, but the idea is really cool. You can install the library using pip. pip install sparklines Then, let’s import the library and create another sample data frame for demonstration purposes. from sparklines import sparklinesdf = pd.DataFrame({ 'a': np.random.normal(0, 1, 100), 'b': np.random.normal(1, 1, 100), 'c': np.random.normal(0, 3, 100)}) The feature of the library Sparklines is simple. it can generate bar charts using Unicode strings such as ▁, ▂, ▃, until █. To make sure the bars in correct orders and make sense as a histogram, we need to prepare the values using NumPy to generate the histogram values first. def sparkline_dist(data): hist = np.histogram(data, bins=10)[0] dist_strings = ''.join(sparklines(hist)) return dist_strings For each column, we can generate the histogram using sparkline. [sparkline_dist(df[col]) for col in df.columns] Finally, we can put the strings along with other statistics to make a better report. df_stats = df.agg(['mean', 'std']).transpose()df_stats['histogram'] = sl_listdf_stats.style \ .format('{:.2f}', subset=['mean', 'std']) \ .set_caption('A Sample Table with Sparklines Distributions') \ .set_properties(padding="15px", border='2px solid white') Done! In this article, I have demonstrated to you all the major methods in the Pandas style package. We can format the values, colour the backgrounds, improve the presentation with customised CSS properties. There are also many built-in functions that can be used out-of-box to create a “report-ready” data frame output. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 384, "s": 172, "text": "As a Data Scientist or Analyst who use Python as the primary programming language, I believe you must have use Pandas a lot. It is very frequently for us to output out pandas data frame in the Jupyter notebooks." }, { "code": null, "e": 719, "s": 384, "text": "However, have you ever think that we can actually let the data frame visualise itself? In other words, for some simple visualisation purposes, we don’t need Matplotlib or other visualisation libraries. The Pandas data frame output can be visualised like an Excel spreadsheet with complicated styles and with very easy code definition." }, { "code": null, "e": 1044, "s": 719, "text": "In this article, I’ll introduce the style package in the Pandas library which is known by relatively fewer people than its data processing methods. Also, there are some interesting libraries that support more IN-LINE visualisations of the Pandas data frame. In the last section, I’ll also introduce one of them — Sparklines." }, { "code": null, "e": 1287, "s": 1044, "text": "It is known that Pandas data frames can be output in iPython/Jupyter notebook that is automatically rendered in HTML with CSS styles. This is definitely an amazing feature because the presentation is very nice even if we just simply print it." }, { "code": null, "e": 1445, "s": 1287, "text": "But wait, it makes use “HTML + CSS”. Yes, Pandas also allows us to customise the CSS styles to make it even looks nicer. This is achieved by the “style” API." }, { "code": null, "e": 1463, "s": 1445, "text": "pandas.pydata.org" }, { "code": null, "e": 1597, "s": 1463, "text": "We can simply call df.style to get the Styler object of a data frame, and then add the styles we want. Now, let’s see what we can do." }, { "code": null, "e": 1895, "s": 1597, "text": "Of course, we can always format the data itself such as df.round(2) to round all the numerical values with 2 decimals. However, there are some benefits to do that using Pandas styles. For example, we don’t actually change the value, but only the presentation, so that we didn’t lose the precision." }, { "code": null, "e": 1935, "s": 1895, "text": "Let’s create a random data frame first." }, { "code": null, "e": 2018, "s": 1935, "text": "import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randn(10, 2)*100)" }, { "code": null, "e": 2074, "s": 2018, "text": "Then, lets output the data frame with specific formats." }, { "code": null, "e": 2100, "s": 2074, "text": "df.style.format(\"{:.2f}\")" }, { "code": null, "e": 2290, "s": 2100, "text": "BTW, if you’re not that familiar with Python Format Specification Mini-Language, which is the expression I used {:.2f}, you can check out the official documentation here (highly recommend)." }, { "code": null, "e": 2306, "s": 2290, "text": "docs.python.org" }, { "code": null, "e": 2442, "s": 2306, "text": "I know, formatting is not cool enough. With CSS we can easily do a lot of things, such as changing background colours and Text Colours." }, { "code": null, "e": 2736, "s": 2442, "text": "For example, for the same data frame above-shown, we want to highlight the positive numbers and native numbers separately. If you have some basic knowledge about CSS, or just simply Google it, you will know the below properties to set the background colour and text colour of HTML table cells." }, { "code": null, "e": 2772, "s": 2736, "text": "background-color: red; color: white" }, { "code": null, "e": 2822, "s": 2772, "text": "Let’s write a function to colour the table cells." }, { "code": null, "e": 3000, "s": 2822, "text": "def highlight_number(row): return [ 'background-color: red; color: white' if cell <= 0 else 'background-color: green; color: white' for cell in row ]" }, { "code": null, "e": 3210, "s": 3000, "text": "If the value of the cell is negative, we use red colour as the background, otherwise use green colour if it is positive. Since the colour might be kind of dark, we also want to change the text colour to white." }, { "code": null, "e": 3261, "s": 3210, "text": "Then, we can apply the function to the data frame." }, { "code": null, "e": 3294, "s": 3261, "text": "df.style.apply(highlight_number)" }, { "code": null, "e": 3410, "s": 3294, "text": "Super cool! Now it is very obvious that we got negative and positive numbers, and they are distinguished very well." }, { "code": null, "e": 3664, "s": 3410, "text": "So far, we’re only adding one type of style each time. In fact, once we called df.style, it returns the Styler object of the data frame. The Styler object supports chaining the style functions. Let’s have a look at another example which is more complex." }, { "code": null, "e": 3739, "s": 3664, "text": "Let’s say, we want to add the following styles to the original data frame." }, { "code": null, "e": 4011, "s": 3739, "text": "Highlight the negative number in red and positive number in green.Format the number in currency.Add a caption to the table using set_caption().Make the cell padding larger so that it looks not that squeezed.Add white borders between the cells to improve the presentation." }, { "code": null, "e": 4078, "s": 4011, "text": "Highlight the negative number in red and positive number in green." }, { "code": null, "e": 4109, "s": 4078, "text": "Format the number in currency." }, { "code": null, "e": 4157, "s": 4109, "text": "Add a caption to the table using set_caption()." }, { "code": null, "e": 4222, "s": 4157, "text": "Make the cell padding larger so that it looks not that squeezed." }, { "code": null, "e": 4287, "s": 4222, "text": "Add white borders between the cells to improve the presentation." }, { "code": null, "e": 4357, "s": 4287, "text": "Yes, we can do all of these in one go, by using the chain expression." }, { "code": null, "e": 4513, "s": 4357, "text": "df.style \\ .apply(highlight_number) \\ .format('${0:,.2f}') \\ .set_caption('A Sample Table') \\ .set_properties(padding=\"20px\", border='2px solid white')" }, { "code": null, "e": 4582, "s": 4513, "text": "Feels like the table can be directly used in some business report :)" }, { "code": null, "e": 4725, "s": 4582, "text": "Don’t know CSS, but still want to show off? Yes, Pandas style also provides some built-in functions, which are very cool but very easy to use." }, { "code": null, "e": 4778, "s": 4725, "text": "Let’s use the same data frame for the demonstration." }, { "code": null, "e": 4955, "s": 4778, "text": "# Make a nan value for demo purposesdf.at[1, 1] = None# Add stylesdf.style \\ .highlight_null('lightgray') \\ .highlight_max(color='lightgreen') \\ .highlight_min(color='pink')" }, { "code": null, "e": 5145, "s": 4955, "text": "See, it is very easy to highlight the NULL values, Min and Max values using whatever colours you prefer. I would recommend using light colours because the text colour always gonna be black." }, { "code": null, "e": 5307, "s": 5145, "text": "Pandas style also support using cmap to colour the cell background in gradient colours. This is very useful when we want to visualise the numeric data in scales." }, { "code": null, "e": 5395, "s": 5307, "text": "df = pd.DataFrame(np.random.randn(10, 2))df.style \\ .background_gradient(cmap='Blues')" }, { "code": null, "e": 5651, "s": 5395, "text": "So, the background colour is gradient depends on the values. Please be noted that “Blues” is one of the cmap that that Pandas supports. If you wonder what are others that are supported, the following documentation page from Matplotlib is a good reference." }, { "code": null, "e": 5666, "s": 5651, "text": "matplotlib.org" }, { "code": null, "e": 5832, "s": 5666, "text": "This is another super cool feature that is built-in. It can generate bars as in the background of each cell to indicate their values. Let’s use the above data frame." }, { "code": null, "e": 5847, "s": 5832, "text": "df.style.bar()" }, { "code": null, "e": 5949, "s": 5847, "text": "Of course, we’re not satisfied by the default style of the bar chart. Let’s improve the presentation." }, { "code": null, "e": 6155, "s": 5949, "text": "df.style \\ .format('{:.2f}') \\ .bar(align='mid', color=['#FCC0CB', '#90EE90']) \\ .set_caption('A Sample Table with Bar Chart') \\ .set_properties(padding=\"15px\", border='2px solid white', width='300px')" }, { "code": null, "e": 6250, "s": 6155, "text": "Can you believe this is still the “Pandas dataframe” that you use to be very familiar with? :)" }, { "code": null, "e": 6594, "s": 6250, "text": "Let me simply explain the parameters in the bar() method. The color parameter supports either a single string or a tuple, when it is a tuple, the first colour will be used for colouring the negative values and the second colour is for the positive. Since we’re using two colours, we need to set the bar to be aligned in the middle of the cell." }, { "code": null, "e": 6773, "s": 6594, "text": "I could stop here, but I want to show off another library I found which is very interesting called Sparklines. I wouldn’t say it’s very nice looking, but the idea is really cool." }, { "code": null, "e": 6812, "s": 6773, "text": "You can install the library using pip." }, { "code": null, "e": 6835, "s": 6812, "text": "pip install sparklines" }, { "code": null, "e": 6931, "s": 6835, "text": "Then, let’s import the library and create another sample data frame for demonstration purposes." }, { "code": null, "e": 7096, "s": 6931, "text": "from sparklines import sparklinesdf = pd.DataFrame({ 'a': np.random.normal(0, 1, 100), 'b': np.random.normal(1, 1, 100), 'c': np.random.normal(0, 3, 100)})" }, { "code": null, "e": 7373, "s": 7096, "text": "The feature of the library Sparklines is simple. it can generate bar charts using Unicode strings such as ▁, ▂, ▃, until █. To make sure the bars in correct orders and make sense as a histogram, we need to prepare the values using NumPy to generate the histogram values first." }, { "code": null, "e": 7507, "s": 7373, "text": "def sparkline_dist(data): hist = np.histogram(data, bins=10)[0] dist_strings = ''.join(sparklines(hist)) return dist_strings" }, { "code": null, "e": 7571, "s": 7507, "text": "For each column, we can generate the histogram using sparkline." }, { "code": null, "e": 7619, "s": 7571, "text": "[sparkline_dist(df[col]) for col in df.columns]" }, { "code": null, "e": 7704, "s": 7619, "text": "Finally, we can put the strings along with other statistics to make a better report." }, { "code": null, "e": 7966, "s": 7704, "text": "df_stats = df.agg(['mean', 'std']).transpose()df_stats['histogram'] = sl_listdf_stats.style \\ .format('{:.2f}', subset=['mean', 'std']) \\ .set_caption('A Sample Table with Sparklines Distributions') \\ .set_properties(padding=\"15px\", border='2px solid white')" }, { "code": null, "e": 7972, "s": 7966, "text": "Done!" }, { "code": null, "e": 8287, "s": 7972, "text": "In this article, I have demonstrated to you all the major methods in the Pandas style package. We can format the values, colour the backgrounds, improve the presentation with customised CSS properties. There are also many built-in functions that can be used out-of-box to create a “report-ready” data frame output." }, { "code": null, "e": 8298, "s": 8287, "text": "medium.com" } ]
Add QT GUI to Python for plotting graphics - GeeksforGeeks
19 Feb, 2020 Qt framework (with QT Creator IDE) can be used to create a fancy interfaces for Python GUI application. Plotting graphics on a GUI is possible with pyqtgraph library. Installing pyqtgraph –There are several ways of installing pyqtgraph depending on your needs. If you are using Anaconda you can install with: conda install -c anaconda pyqtgraph Or with pip command: pip install pyqtgraph Creation of plot widgets with QT Creator – Add the buttons, text areas and other stuffs as usually done with QT Creator. To create a plot area you need to follow the steps: Add widget to UI and give it a proper name like “widgetSignal”Promote the widget to pyqtgraph Add widget to UI and give it a proper name like “widgetSignal” Promote the widget to pyqtgraph Load UI to Python – In your python code call the UI you created with QT Creator.Create a sin wave for plottingDraw the graph on UI In your python code call the UI you created with QT Creator. Create a sin wave for plotting Draw the graph on UI from PyQt5 import QtWidgets, uicimport sysimport numpy as np class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # Load the UI Page self. ui = uic.loadUi('mainwindow.ui', self) # Create a sin wave x_time = np.arange(0, 100, 0.1); y_amplitude = np.sin(x_time) pltSignal = self.widgetSignal pltSignal.clear() pltSignal.setLabel('left', 'Signal Sin Wave', units ='(V)') pltSignal.setLabel('bottom', 'Time', units ='(sec)') pltSignal.plot(x_time, y_amplitude, clear = True) self.ui.show() def main(): app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main() Output: Python-gui Python-PyQt Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n19 Feb, 2020" }, { "code": null, "e": 25814, "s": 25647, "text": "Qt framework (with QT Creator IDE) can be used to create a fancy interfaces for Python GUI application. Plotting graphics on a GUI is possible with pyqtgraph library." }, { "code": null, "e": 25908, "s": 25814, "text": "Installing pyqtgraph –There are several ways of installing pyqtgraph depending on your needs." }, { "code": null, "e": 25956, "s": 25908, "text": "If you are using Anaconda you can install with:" }, { "code": null, "e": 25993, "s": 25956, "text": "conda install -c anaconda pyqtgraph\n" }, { "code": null, "e": 26014, "s": 25993, "text": "Or with pip command:" }, { "code": null, "e": 26037, "s": 26014, "text": "pip install pyqtgraph\n" }, { "code": null, "e": 26080, "s": 26037, "text": "Creation of plot widgets with QT Creator –" }, { "code": null, "e": 26210, "s": 26080, "text": "Add the buttons, text areas and other stuffs as usually done with QT Creator. To create a plot area you need to follow the steps:" }, { "code": null, "e": 26304, "s": 26210, "text": "Add widget to UI and give it a proper name like “widgetSignal”Promote the widget to pyqtgraph" }, { "code": null, "e": 26367, "s": 26304, "text": "Add widget to UI and give it a proper name like “widgetSignal”" }, { "code": null, "e": 26399, "s": 26367, "text": "Promote the widget to pyqtgraph" }, { "code": null, "e": 26419, "s": 26399, "text": "Load UI to Python –" }, { "code": null, "e": 26530, "s": 26419, "text": "In your python code call the UI you created with QT Creator.Create a sin wave for plottingDraw the graph on UI" }, { "code": null, "e": 26591, "s": 26530, "text": "In your python code call the UI you created with QT Creator." }, { "code": null, "e": 26622, "s": 26591, "text": "Create a sin wave for plotting" }, { "code": null, "e": 26643, "s": 26622, "text": "Draw the graph on UI" }, { "code": "from PyQt5 import QtWidgets, uicimport sysimport numpy as np class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # Load the UI Page self. ui = uic.loadUi('mainwindow.ui', self) # Create a sin wave x_time = np.arange(0, 100, 0.1); y_amplitude = np.sin(x_time) pltSignal = self.widgetSignal pltSignal.clear() pltSignal.setLabel('left', 'Signal Sin Wave', units ='(V)') pltSignal.setLabel('bottom', 'Time', units ='(sec)') pltSignal.plot(x_time, y_amplitude, clear = True) self.ui.show() def main(): app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main() ", "e": 27459, "s": 26643, "text": null }, { "code": null, "e": 27467, "s": 27459, "text": "Output:" }, { "code": null, "e": 27478, "s": 27467, "text": "Python-gui" }, { "code": null, "e": 27490, "s": 27478, "text": "Python-PyQt" }, { "code": null, "e": 27514, "s": 27490, "text": "Technical Scripter 2019" }, { "code": null, "e": 27521, "s": 27514, "text": "Python" }, { "code": null, "e": 27540, "s": 27521, "text": "Technical Scripter" }, { "code": null, "e": 27638, "s": 27540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27670, "s": 27638, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27712, "s": 27670, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27754, "s": 27712, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27810, "s": 27754, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27837, "s": 27810, "text": "Python Classes and Objects" }, { "code": null, "e": 27868, "s": 27837, "text": "Python | os.path.join() method" }, { "code": null, "e": 27897, "s": 27868, "text": "Create a directory in Python" }, { "code": null, "e": 27919, "s": 27897, "text": "Defaultdict in Python" }, { "code": null, "e": 27955, "s": 27919, "text": "Python | Pandas dataframe.groupby()" } ]
Modifying PDF file using Python - GeeksforGeeks
02 Jul, 2021 The following article depicts how a PDF can be modified using python’s pylovepdf module. The Portable Document Format(PDF) is a file format developed by Adobe in 1993 to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems. pylovepdf module can be downloaded using pip command: pip install pylovepdf The iLovePDF API i.e ‘pylovepdf’ module is organized around REST. Their API are predictable, resource-oriented URLs, and uses HTTP response codes to indicate API errors. They use built-in HTTP features, like HTTP authentication and HTTP verbs, which are understood by off-the-shelf HTTP clients. They support cross-origin resource sharing, allowing you to interact securely with their API from a client-side web application. With this API we can compress the PDF files, also can add watermark, convert them to images and even split them and vice -versa and lots of other stuff. In order to do so first we need a public-key to use this module, for that login on to https://developer.ilovepdf.com/ and after login the public key will be visible in the ‘My Projects’ section. Below is the screenshot of the public key Now since we have our public key, we can use this API for modifying any PDF file using the steps given below: 1. Creating a ILovePdf object using the public key 2. Uploading the PDF file 3. Processing the PDF file 4. Downloading the PDF file Implementation of this module is depicted properly using examples. Click here for the PDF used in the examples provided in this article: Example 1: Compressing the PDF file Python3 # importing the ilovepdf apifrom pylovepdf.ilovepdf import ILovePdf # public keypublic_key = 'paste_your_public_key_here' # creating a ILovePdf objectilovepdf = ILovePdf(public_key, verify_ssl=True) # assigning a new compress tasktask = ilovepdf.new_task('compress') # adding the pdf file to the tasktask.add_file('my_pdf.pdf') # setting the output folder directory# if no folder exist it will create onetask.set_output_folder('output_folder') # execute the tasktask.execute() # download the tasktask.download() # delete the tasktask.delete_current_task() Before processing: Output : After Processing: Example 2: Splitting the PDF Python # public keyfrom pylovepdf.ilovepdf import ILovePdfpublic_key = 'paste your code here' # importing the ilovepdf api # creating a ILovePdf objectilovepdf = ILovePdf(public_key, verify_ssl=True) # assigning a new split task tasktask = ilovepdf.new_task('split') # adding the pdf file to the tasktask.add_file('my_pdf.pdf') # setting the output folder directory# if no folder exist it will create onetask.set_output_folder('output_folder') # execute the tasktask.execute() # download the tasktask.download() # delete the tasktask.delete_current_task() Output : After processing: zip sweetyty python-utility Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25671, "s": 25643, "text": "\n02 Jul, 2021" }, { "code": null, "e": 25980, "s": 25671, "text": "The following article depicts how a PDF can be modified using python’s pylovepdf module. The Portable Document Format(PDF) is a file format developed by Adobe in 1993 to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems." }, { "code": null, "e": 26034, "s": 25980, "text": "pylovepdf module can be downloaded using pip command:" }, { "code": null, "e": 26056, "s": 26034, "text": "pip install pylovepdf" }, { "code": null, "e": 26634, "s": 26056, "text": "The iLovePDF API i.e ‘pylovepdf’ module is organized around REST. Their API are predictable, resource-oriented URLs, and uses HTTP response codes to indicate API errors. They use built-in HTTP features, like HTTP authentication and HTTP verbs, which are understood by off-the-shelf HTTP clients. They support cross-origin resource sharing, allowing you to interact securely with their API from a client-side web application. With this API we can compress the PDF files, also can add watermark, convert them to images and even split them and vice -versa and lots of other stuff." }, { "code": null, "e": 26871, "s": 26634, "text": "In order to do so first we need a public-key to use this module, for that login on to https://developer.ilovepdf.com/ and after login the public key will be visible in the ‘My Projects’ section. Below is the screenshot of the public key" }, { "code": null, "e": 26981, "s": 26871, "text": "Now since we have our public key, we can use this API for modifying any PDF file using the steps given below:" }, { "code": null, "e": 27032, "s": 26981, "text": "1. Creating a ILovePdf object using the public key" }, { "code": null, "e": 27058, "s": 27032, "text": "2. Uploading the PDF file" }, { "code": null, "e": 27085, "s": 27058, "text": "3. Processing the PDF file" }, { "code": null, "e": 27113, "s": 27085, "text": "4. Downloading the PDF file" }, { "code": null, "e": 27251, "s": 27113, "text": "Implementation of this module is depicted properly using examples. Click here for the PDF used in the examples provided in this article: " }, { "code": null, "e": 27287, "s": 27251, "text": "Example 1: Compressing the PDF file" }, { "code": null, "e": 27295, "s": 27287, "text": "Python3" }, { "code": "# importing the ilovepdf apifrom pylovepdf.ilovepdf import ILovePdf # public keypublic_key = 'paste_your_public_key_here' # creating a ILovePdf objectilovepdf = ILovePdf(public_key, verify_ssl=True) # assigning a new compress tasktask = ilovepdf.new_task('compress') # adding the pdf file to the tasktask.add_file('my_pdf.pdf') # setting the output folder directory# if no folder exist it will create onetask.set_output_folder('output_folder') # execute the tasktask.execute() # download the tasktask.download() # delete the tasktask.delete_current_task()", "e": 27851, "s": 27295, "text": null }, { "code": null, "e": 27870, "s": 27851, "text": "Before processing:" }, { "code": null, "e": 27879, "s": 27870, "text": "Output :" }, { "code": null, "e": 27899, "s": 27879, "text": " After Processing: " }, { "code": null, "e": 27928, "s": 27899, "text": "Example 2: Splitting the PDF" }, { "code": null, "e": 27935, "s": 27928, "text": "Python" }, { "code": "# public keyfrom pylovepdf.ilovepdf import ILovePdfpublic_key = 'paste your code here' # importing the ilovepdf api # creating a ILovePdf objectilovepdf = ILovePdf(public_key, verify_ssl=True) # assigning a new split task tasktask = ilovepdf.new_task('split') # adding the pdf file to the tasktask.add_file('my_pdf.pdf') # setting the output folder directory# if no folder exist it will create onetask.set_output_folder('output_folder') # execute the tasktask.execute() # download the tasktask.download() # delete the tasktask.delete_current_task()", "e": 28485, "s": 27935, "text": null }, { "code": null, "e": 28494, "s": 28485, "text": "Output :" }, { "code": null, "e": 28512, "s": 28494, "text": "After processing:" }, { "code": null, "e": 28516, "s": 28512, "text": "zip" }, { "code": null, "e": 28527, "s": 28518, "text": "sweetyty" }, { "code": null, "e": 28542, "s": 28527, "text": "python-utility" }, { "code": null, "e": 28566, "s": 28542, "text": "Technical Scripter 2020" }, { "code": null, "e": 28573, "s": 28566, "text": "Python" }, { "code": null, "e": 28592, "s": 28573, "text": "Technical Scripter" }, { "code": null, "e": 28690, "s": 28592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28722, "s": 28690, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28764, "s": 28722, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28806, "s": 28764, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28862, "s": 28806, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28889, "s": 28862, "text": "Python Classes and Objects" }, { "code": null, "e": 28920, "s": 28889, "text": "Python | os.path.join() method" }, { "code": null, "e": 28949, "s": 28920, "text": "Create a directory in Python" }, { "code": null, "e": 28971, "s": 28949, "text": "Defaultdict in Python" }, { "code": null, "e": 29007, "s": 28971, "text": "Python | Pandas dataframe.groupby()" } ]