title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
SHA-384 Hash In Java - GeeksforGeeks | 27 Sep, 2018
The SHA-2 family of cryptographic hash functions consists of six hash functions. These are:
SHA-224, with 224 bit hash valuesSHA-256, with 256 bit hash valuesSHA-384, with 384 bit hash valuesSHA-512, with 512 bit hash valuesSHA-512/224, with 512 bit hash valuesSHA-512/256, with 512 bit hash valuesAmong these, SHA-256 and SHA-512 are the most commonly accepted and used hash functions computed with 32-bit and 64-bit words, respectively. SHA-224 and SHA-384 are truncated versions of SHA-256 and SHA-512 respectively, computed with different initial values.To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographic hash function to find hash value of a text as follows:MD2MD5SHA-1SHA-224SHA-256SHA-384SHA-512These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest.Examples:Input : hello worldOutput :fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bdInput : GeeksForGeeksOutput :19cc78d220368a892cc9c54d2f43d5e1823534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688e7f09bb226Program: Below program shows the implementation of SHA-384 hash in Java.// Java program to calculate SHA-384 hash value import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { public static String encryptThisString(String input) { try { // getInstance() method is called with algorithm SHA-384 MessageDigest md = MessageDigest.getInstance("SHA-384"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = "0" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println("HashCode Generated by SHA-384 for: "); String s1 = "GeeksForGeeks"; System.out.println("\n" + s1 + " : " + encryptThisString(s1)); String s2 = "hello world"; System.out.println("\n" + s2 + " : " + encryptThisString(s2)); }}Output:HashCode Generated by SHA-384 for:
GeeksForGeeks : 19cc78d220368a892cc9c54d2f43d5e1823
534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688
e7f09bb226
hello world : fdbd8e75a67f29f701a4e040385e2e2398630
3ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c
088de1bd
Application:CryptographyData IntegrityMy Personal Notes
arrow_drop_upSave
SHA-224, with 224 bit hash values
SHA-256, with 256 bit hash values
SHA-384, with 384 bit hash values
SHA-512, with 512 bit hash values
SHA-512/224, with 512 bit hash values
SHA-512/256, with 512 bit hash valuesAmong these, SHA-256 and SHA-512 are the most commonly accepted and used hash functions computed with 32-bit and 64-bit words, respectively. SHA-224 and SHA-384 are truncated versions of SHA-256 and SHA-512 respectively, computed with different initial values.To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographic hash function to find hash value of a text as follows:MD2MD5SHA-1SHA-224SHA-256SHA-384SHA-512These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest.Examples:Input : hello worldOutput :fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bdInput : GeeksForGeeksOutput :19cc78d220368a892cc9c54d2f43d5e1823534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688e7f09bb226Program: Below program shows the implementation of SHA-384 hash in Java.// Java program to calculate SHA-384 hash value import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { public static String encryptThisString(String input) { try { // getInstance() method is called with algorithm SHA-384 MessageDigest md = MessageDigest.getInstance("SHA-384"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = "0" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println("HashCode Generated by SHA-384 for: "); String s1 = "GeeksForGeeks"; System.out.println("\n" + s1 + " : " + encryptThisString(s1)); String s2 = "hello world"; System.out.println("\n" + s2 + " : " + encryptThisString(s2)); }}Output:HashCode Generated by SHA-384 for:
GeeksForGeeks : 19cc78d220368a892cc9c54d2f43d5e1823
534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688
e7f09bb226
hello world : fdbd8e75a67f29f701a4e040385e2e2398630
3ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c
088de1bd
Application:CryptographyData IntegrityMy Personal Notes
arrow_drop_upSave
Among these, SHA-256 and SHA-512 are the most commonly accepted and used hash functions computed with 32-bit and 64-bit words, respectively. SHA-224 and SHA-384 are truncated versions of SHA-256 and SHA-512 respectively, computed with different initial values.
To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.
MessagDigest Class provides following cryptographic hash function to find hash value of a text as follows:
MD2
MD5
SHA-1
SHA-224
SHA-256
SHA-384
SHA-512
These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest.
Examples:
Input : hello worldOutput :fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd
Input : GeeksForGeeksOutput :19cc78d220368a892cc9c54d2f43d5e1823534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688e7f09bb226
Program: Below program shows the implementation of SHA-384 hash in Java.
// Java program to calculate SHA-384 hash value import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { public static String encryptThisString(String input) { try { // getInstance() method is called with algorithm SHA-384 MessageDigest md = MessageDigest.getInstance("SHA-384"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = "0" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println("HashCode Generated by SHA-384 for: "); String s1 = "GeeksForGeeks"; System.out.println("\n" + s1 + " : " + encryptThisString(s1)); String s2 = "hello world"; System.out.println("\n" + s2 + " : " + encryptThisString(s2)); }}
HashCode Generated by SHA-384 for:
GeeksForGeeks : 19cc78d220368a892cc9c54d2f43d5e1823
534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688
e7f09bb226
hello world : fdbd8e75a67f29f701a4e040385e2e2398630
3ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c
088de1bd
Application:
Cryptography
Data Integrity
Hash
Computer Networks
Java
Java Programs
Hash
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 25779,
"s": 25751,
"text": "\n27 Sep, 2018"
},
{
"code": null,
"e": 25871,
"s": 25779,
"text": "The SHA-2 family of cryptographic hash functions consists of six hash functions. These are:"
},
{
"code": null,
"e": 29268,
"s": 25871,
"text": "SHA-224, with 224 bit hash valuesSHA-256, with 256 bit hash valuesSHA-384, with 384 bit hash valuesSHA-512, with 512 bit hash valuesSHA-512/224, with 512 bit hash valuesSHA-512/256, with 512 bit hash valuesAmong these, SHA-256 and SHA-512 are the most commonly accepted and used hash functions computed with 32-bit and 64-bit words, respectively. SHA-224 and SHA-384 are truncated versions of SHA-256 and SHA-512 respectively, computed with different initial values.To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographic hash function to find hash value of a text as follows:MD2MD5SHA-1SHA-224SHA-256SHA-384SHA-512These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest.Examples:Input : hello worldOutput :fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bdInput : GeeksForGeeksOutput :19cc78d220368a892cc9c54d2f43d5e1823534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688e7f09bb226Program: Below program shows the implementation of SHA-384 hash in Java.// Java program to calculate SHA-384 hash value import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { public static String encryptThisString(String input) { try { // getInstance() method is called with algorithm SHA-384 MessageDigest md = MessageDigest.getInstance(\"SHA-384\"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = \"0\" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println(\"HashCode Generated by SHA-384 for: \"); String s1 = \"GeeksForGeeks\"; System.out.println(\"\\n\" + s1 + \" : \" + encryptThisString(s1)); String s2 = \"hello world\"; System.out.println(\"\\n\" + s2 + \" : \" + encryptThisString(s2)); }}Output:HashCode Generated by SHA-384 for: \n\nGeeksForGeeks : 19cc78d220368a892cc9c54d2f43d5e1823\n534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688\ne7f09bb226\n\nhello world : fdbd8e75a67f29f701a4e040385e2e2398630\n3ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c\n088de1bd\nApplication:CryptographyData IntegrityMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29302,
"s": 29268,
"text": "SHA-224, with 224 bit hash values"
},
{
"code": null,
"e": 29336,
"s": 29302,
"text": "SHA-256, with 256 bit hash values"
},
{
"code": null,
"e": 29370,
"s": 29336,
"text": "SHA-384, with 384 bit hash values"
},
{
"code": null,
"e": 29404,
"s": 29370,
"text": "SHA-512, with 512 bit hash values"
},
{
"code": null,
"e": 29442,
"s": 29404,
"text": "SHA-512/224, with 512 bit hash values"
},
{
"code": null,
"e": 32670,
"s": 29442,
"text": "SHA-512/256, with 512 bit hash valuesAmong these, SHA-256 and SHA-512 are the most commonly accepted and used hash functions computed with 32-bit and 64-bit words, respectively. SHA-224 and SHA-384 are truncated versions of SHA-256 and SHA-512 respectively, computed with different initial values.To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographic hash function to find hash value of a text as follows:MD2MD5SHA-1SHA-224SHA-256SHA-384SHA-512These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest.Examples:Input : hello worldOutput :fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bdInput : GeeksForGeeksOutput :19cc78d220368a892cc9c54d2f43d5e1823534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688e7f09bb226Program: Below program shows the implementation of SHA-384 hash in Java.// Java program to calculate SHA-384 hash value import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { public static String encryptThisString(String input) { try { // getInstance() method is called with algorithm SHA-384 MessageDigest md = MessageDigest.getInstance(\"SHA-384\"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = \"0\" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println(\"HashCode Generated by SHA-384 for: \"); String s1 = \"GeeksForGeeks\"; System.out.println(\"\\n\" + s1 + \" : \" + encryptThisString(s1)); String s2 = \"hello world\"; System.out.println(\"\\n\" + s2 + \" : \" + encryptThisString(s2)); }}Output:HashCode Generated by SHA-384 for: \n\nGeeksForGeeks : 19cc78d220368a892cc9c54d2f43d5e1823\n534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688\ne7f09bb226\n\nhello world : fdbd8e75a67f29f701a4e040385e2e2398630\n3ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c\n088de1bd\nApplication:CryptographyData IntegrityMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32931,
"s": 32670,
"text": "Among these, SHA-256 and SHA-512 are the most commonly accepted and used hash functions computed with 32-bit and 64-bit words, respectively. SHA-224 and SHA-384 are truncated versions of SHA-256 and SHA-512 respectively, computed with different initial values."
},
{
"code": null,
"e": 33043,
"s": 32931,
"text": "To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security."
},
{
"code": null,
"e": 33150,
"s": 33043,
"text": "MessagDigest Class provides following cryptographic hash function to find hash value of a text as follows:"
},
{
"code": null,
"e": 33154,
"s": 33150,
"text": "MD2"
},
{
"code": null,
"e": 33158,
"s": 33154,
"text": "MD5"
},
{
"code": null,
"e": 33164,
"s": 33158,
"text": "SHA-1"
},
{
"code": null,
"e": 33172,
"s": 33164,
"text": "SHA-224"
},
{
"code": null,
"e": 33180,
"s": 33172,
"text": "SHA-256"
},
{
"code": null,
"e": 33188,
"s": 33180,
"text": "SHA-384"
},
{
"code": null,
"e": 33196,
"s": 33188,
"text": "SHA-512"
},
{
"code": null,
"e": 33576,
"s": 33196,
"text": "These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest."
},
{
"code": null,
"e": 33586,
"s": 33576,
"text": "Examples:"
},
{
"code": null,
"e": 33710,
"s": 33586,
"text": "Input : hello worldOutput :fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd"
},
{
"code": null,
"e": 33836,
"s": 33710,
"text": "Input : GeeksForGeeksOutput :19cc78d220368a892cc9c54d2f43d5e1823534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688e7f09bb226"
},
{
"code": null,
"e": 33909,
"s": 33836,
"text": "Program: Below program shows the implementation of SHA-384 hash in Java."
},
{
"code": "// Java program to calculate SHA-384 hash value import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { public static String encryptThisString(String input) { try { // getInstance() method is called with algorithm SHA-384 MessageDigest md = MessageDigest.getInstance(\"SHA-384\"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = \"0\" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println(\"HashCode Generated by SHA-384 for: \"); String s1 = \"GeeksForGeeks\"; System.out.println(\"\\n\" + s1 + \" : \" + encryptThisString(s1)); String s2 = \"hello world\"; System.out.println(\"\\n\" + s2 + \" : \" + encryptThisString(s2)); }}",
"e": 35530,
"s": 33909,
"text": null
},
{
"code": null,
"e": 35797,
"s": 35530,
"text": "HashCode Generated by SHA-384 for: \n\nGeeksForGeeks : 19cc78d220368a892cc9c54d2f43d5e1823\n534f3e22b0d475de18e030e7c4b411704c79e9600bb93399688\ne7f09bb226\n\nhello world : fdbd8e75a67f29f701a4e040385e2e2398630\n3ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c\n088de1bd\n"
},
{
"code": null,
"e": 35810,
"s": 35797,
"text": "Application:"
},
{
"code": null,
"e": 35823,
"s": 35810,
"text": "Cryptography"
},
{
"code": null,
"e": 35838,
"s": 35823,
"text": "Data Integrity"
},
{
"code": null,
"e": 35843,
"s": 35838,
"text": "Hash"
},
{
"code": null,
"e": 35861,
"s": 35843,
"text": "Computer Networks"
},
{
"code": null,
"e": 35866,
"s": 35861,
"text": "Java"
},
{
"code": null,
"e": 35880,
"s": 35866,
"text": "Java Programs"
},
{
"code": null,
"e": 35885,
"s": 35880,
"text": "Hash"
},
{
"code": null,
"e": 35890,
"s": 35885,
"text": "Java"
},
{
"code": null,
"e": 35908,
"s": 35890,
"text": "Computer Networks"
},
{
"code": null,
"e": 36006,
"s": 35908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36041,
"s": 36006,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 36074,
"s": 36041,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 36112,
"s": 36074,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 36138,
"s": 36112,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 36165,
"s": 36138,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 36180,
"s": 36165,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36224,
"s": 36180,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36246,
"s": 36224,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36297,
"s": 36246,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
GATE | GATE-CS-2001 | Question 34 - GeeksforGeeks | 28 Jun, 2021
Which is the most appropriate match for the items in the first column with the items in the second column
X. Indirect Addressing I. Array implementation
Y. Indexed Addressing II. Writing re-locatable code
Z. Base Register Addressing III. Passing array as parameter
(A) (X, III) (Y, I) (Z, II)(B) (X, II) (Y, III) (Z, I)(C) (X, III) (Y, II) (Z, I)(D) (X, I) (Y, III) (Z, II)Answer: (A)Explanation: Indexed addressing is used for array implementation where each element has indexes.
Base register is used to relocatable code which starts from base address and then all local addresses are added to base address.
Indirect addressing is done when array is passed as parameter where only name is passed.
So (A) is correct option.Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25801,
"s": 25695,
"text": "Which is the most appropriate match for the items in the first column with the items in the second column"
},
{
"code": null,
"e": 25977,
"s": 25801,
"text": "X. Indirect Addressing I. Array implementation\nY. Indexed Addressing II. Writing re-locatable code\nZ. Base Register Addressing III. Passing array as parameter"
},
{
"code": null,
"e": 26193,
"s": 25977,
"text": "(A) (X, III) (Y, I) (Z, II)(B) (X, II) (Y, III) (Z, I)(C) (X, III) (Y, II) (Z, I)(D) (X, I) (Y, III) (Z, II)Answer: (A)Explanation: Indexed addressing is used for array implementation where each element has indexes."
},
{
"code": null,
"e": 26322,
"s": 26193,
"text": "Base register is used to relocatable code which starts from base address and then all local addresses are added to base address."
},
{
"code": null,
"e": 26411,
"s": 26322,
"text": "Indirect addressing is done when array is passed as parameter where only name is passed."
},
{
"code": null,
"e": 26458,
"s": 26411,
"text": "So (A) is correct option.Quiz of this Question"
},
{
"code": null,
"e": 26471,
"s": 26458,
"text": "GATE-CS-2001"
},
{
"code": null,
"e": 26489,
"s": 26471,
"text": "GATE-GATE-CS-2001"
},
{
"code": null,
"e": 26494,
"s": 26489,
"text": "GATE"
},
{
"code": null,
"e": 26592,
"s": 26494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26626,
"s": 26592,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26660,
"s": 26626,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26694,
"s": 26660,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26727,
"s": 26694,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26763,
"s": 26727,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26797,
"s": 26763,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26833,
"s": 26797,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26867,
"s": 26833,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26901,
"s": 26867,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
OpenCV | Hands on Image Contrast - GeeksforGeeks | 13 Apr, 2021
Contrast means to change the value of each and every image pixel. This change can be done by either multiplying or dividing the pixel values of the image, by any constant. This article gives an in-depth knowledge about how can an image contrast be changed using OpenCV.
Input :
Original Image
Output :
-> Original Image
-> Image with contrast increased by 4
-> Image with contrast increased by 2
-> Image with contrast decreased by .5
-> Image with contrast decreased by .25
Code : CPP code to increase or decrease the contrast of an image
CPP
// c++ code explaining how to// increase or decrease the// contrast of an image // loading library files#include <highlevelmonitorconfigurationapi.h>#include <opencv2\highgui\highgui.hpp>#include <opencv2\opencv.hpp> using namespace cv;using namespace std; int main(int argc, char** argv){ // Loading the Image File under testing Mat image = imread("C:\\Users\\dell\\Desktop\\abc.jpg"); // Check whether the image is present or not if (image.empty()) { cout << "Could not open or find the image" << endl; // waiting for any key to be pressed return -1; } // Declaring the Contrast instances // increasing the contrast level by 100% Mat imageContrastHigh2; image.convertTo(imageContrastHigh2, -1, 2, 0); // increasing the contrast level by 200% Mat imageContrastHigh4; image.convertTo(imageContrastHigh4, -1, 4, 0); // decreasing the contrast level by 50% Mat imageContrastLow0_5; image.convertTo(imageContrastLow0_5, -1, 0.5, 0); // decreasing the contrast level by 75% Mat imageContrastLow0_25; image.convertTo(imageContrastLow0_25, -1, 0.25, 0); // Declaring the windows // for images belonging to different contrast level String windowNameOriginalImage = "Original Image"; String windowNameContrastHigh2 = "Contrast Increased by 2"; String windowNameContrastHigh4 = "Contrast Increased by 4"; String windowNameContrastLow0_5 = "Contrast Decreased by 0.5"; String windowNameContrastLow0_25 = "Contrast Decreased by 0.25"; // Running the window instance // and opening it namedWindow(windowNameOriginalImage, WINDOW_NORMAL); namedWindow(windowNameContrastHigh2, WINDOW_NORMAL); namedWindow(windowNameContrastHigh4, WINDOW_NORMAL); namedWindow(windowNameContrastLow0_5, WINDOW_NORMAL); namedWindow(windowNameContrastLow0_25, WINDOW_NORMAL); // Loading images inside the above created Windows imshow(windowNameOriginalImage, image); imshow(windowNameContrastHigh2, imageContrastHigh2); imshow(windowNameContrastHigh4, imageContrastHigh4); imshow(windowNameContrastLow0_5, imageContrastLow0_5); imshow(windowNameContrastLow0_25, imageContrastLow0_25); // waiting for any key to be pressed waitKey(0); // closing all the windows instances // when any key is pressed. destroyAllWindows(); return 0;}
Input :
Output :Image with contrast increased by 4
Image with contrast increased by 2
Image with contrast decreased by .5
Image with contrast decreased by .25
CPP
// Declaring the Contrast instances // increasing the contrast level by 100%Mat imageContrastHigh2;image.convertTo(imageContrastHigh2, -1, 2, 0); // increasing the contrast level by 200%Mat imageContrastHigh4;image.convertTo(imageContrastHigh4, -1, 4, 0); // decreasing the contrast level by 50%Mat imageContrastLow0_5;image.convertTo(imageContrastLow0_5, -1, 0.5, 0); // decreasing the contrast level by 75%Mat imageContrastLow0_25;image.convertTo(imageContrastLow0_25, -1, 0.25, 0);
These code lines will change the image pixel values by a specified amount. The final changed image is then stored to the given output image. The contrast level will increase if the specified amount factor is greater than 1, otherwise will decrease if the specified amount factor is less than 1. MAT Function : The “MAT” function changes each image pixel value to the target data type and the values are changed as the degree of factor multiplied.
Parameters :
m : Output Image
rtype : Output Image type, Output Image type is same
as input if it is set to -ve value
alpha : Input image pixel are multiplied with this
number prior to its assignment to output image
beta : adding this value to each input image pixel
arorakashish0911
Image-Processing
OpenCV
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Object Oriented Programming in C++
Substring in C++
Copy Constructor in C++ | [
{
"code": null,
"e": 25627,
"s": 25599,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 25899,
"s": 25627,
"text": "Contrast means to change the value of each and every image pixel. This change can be done by either multiplying or dividing the pixel values of the image, by any constant. This article gives an in-depth knowledge about how can an image contrast be changed using OpenCV. "
},
{
"code": null,
"e": 26107,
"s": 25899,
"text": "Input : \nOriginal Image\n\nOutput : \n-> Original Image\n-> Image with contrast increased by 4\n-> Image with contrast increased by 2\n-> Image with contrast decreased by .5\n-> Image with contrast decreased by .25"
},
{
"code": null,
"e": 26174,
"s": 26107,
"text": "Code : CPP code to increase or decrease the contrast of an image "
},
{
"code": null,
"e": 26178,
"s": 26174,
"text": "CPP"
},
{
"code": "// c++ code explaining how to// increase or decrease the// contrast of an image // loading library files#include <highlevelmonitorconfigurationapi.h>#include <opencv2\\highgui\\highgui.hpp>#include <opencv2\\opencv.hpp> using namespace cv;using namespace std; int main(int argc, char** argv){ // Loading the Image File under testing Mat image = imread(\"C:\\\\Users\\\\dell\\\\Desktop\\\\abc.jpg\"); // Check whether the image is present or not if (image.empty()) { cout << \"Could not open or find the image\" << endl; // waiting for any key to be pressed return -1; } // Declaring the Contrast instances // increasing the contrast level by 100% Mat imageContrastHigh2; image.convertTo(imageContrastHigh2, -1, 2, 0); // increasing the contrast level by 200% Mat imageContrastHigh4; image.convertTo(imageContrastHigh4, -1, 4, 0); // decreasing the contrast level by 50% Mat imageContrastLow0_5; image.convertTo(imageContrastLow0_5, -1, 0.5, 0); // decreasing the contrast level by 75% Mat imageContrastLow0_25; image.convertTo(imageContrastLow0_25, -1, 0.25, 0); // Declaring the windows // for images belonging to different contrast level String windowNameOriginalImage = \"Original Image\"; String windowNameContrastHigh2 = \"Contrast Increased by 2\"; String windowNameContrastHigh4 = \"Contrast Increased by 4\"; String windowNameContrastLow0_5 = \"Contrast Decreased by 0.5\"; String windowNameContrastLow0_25 = \"Contrast Decreased by 0.25\"; // Running the window instance // and opening it namedWindow(windowNameOriginalImage, WINDOW_NORMAL); namedWindow(windowNameContrastHigh2, WINDOW_NORMAL); namedWindow(windowNameContrastHigh4, WINDOW_NORMAL); namedWindow(windowNameContrastLow0_5, WINDOW_NORMAL); namedWindow(windowNameContrastLow0_25, WINDOW_NORMAL); // Loading images inside the above created Windows imshow(windowNameOriginalImage, image); imshow(windowNameContrastHigh2, imageContrastHigh2); imshow(windowNameContrastHigh4, imageContrastHigh4); imshow(windowNameContrastLow0_5, imageContrastLow0_5); imshow(windowNameContrastLow0_25, imageContrastLow0_25); // waiting for any key to be pressed waitKey(0); // closing all the windows instances // when any key is pressed. destroyAllWindows(); return 0;}",
"e": 28541,
"s": 26178,
"text": null
},
{
"code": null,
"e": 28551,
"s": 28541,
"text": "Input : "
},
{
"code": null,
"e": 28596,
"s": 28551,
"text": "Output :Image with contrast increased by 4 "
},
{
"code": null,
"e": 28633,
"s": 28596,
"text": "Image with contrast increased by 2 "
},
{
"code": null,
"e": 28671,
"s": 28633,
"text": "Image with contrast decreased by .5 "
},
{
"code": null,
"e": 28710,
"s": 28671,
"text": "Image with contrast decreased by .25 "
},
{
"code": null,
"e": 28718,
"s": 28714,
"text": "CPP"
},
{
"code": "// Declaring the Contrast instances // increasing the contrast level by 100%Mat imageContrastHigh2;image.convertTo(imageContrastHigh2, -1, 2, 0); // increasing the contrast level by 200%Mat imageContrastHigh4;image.convertTo(imageContrastHigh4, -1, 4, 0); // decreasing the contrast level by 50%Mat imageContrastLow0_5;image.convertTo(imageContrastLow0_5, -1, 0.5, 0); // decreasing the contrast level by 75%Mat imageContrastLow0_25;image.convertTo(imageContrastLow0_25, -1, 0.25, 0);",
"e": 29203,
"s": 28718,
"text": null
},
{
"code": null,
"e": 29652,
"s": 29203,
"text": "These code lines will change the image pixel values by a specified amount. The final changed image is then stored to the given output image. The contrast level will increase if the specified amount factor is greater than 1, otherwise will decrease if the specified amount factor is less than 1. MAT Function : The “MAT” function changes each image pixel value to the target data type and the values are changed as the degree of factor multiplied. "
},
{
"code": null,
"e": 29948,
"s": 29652,
"text": "Parameters : \n\nm : Output Image \nrtype : Output Image type, Output Image type is same\n as input if it is set to -ve value\nalpha : Input image pixel are multiplied with this\n number prior to its assignment to output image\nbeta : adding this value to each input image pixel "
},
{
"code": null,
"e": 29967,
"s": 29950,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29984,
"s": 29967,
"text": "Image-Processing"
},
{
"code": null,
"e": 29991,
"s": 29984,
"text": "OpenCV"
},
{
"code": null,
"e": 29995,
"s": 29991,
"text": "C++"
},
{
"code": null,
"e": 29999,
"s": 29995,
"text": "CPP"
},
{
"code": null,
"e": 30097,
"s": 29999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30121,
"s": 30097,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 30145,
"s": 30121,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 30176,
"s": 30145,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 30196,
"s": 30176,
"text": "Constructors in C++"
},
{
"code": null,
"e": 30224,
"s": 30196,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30252,
"s": 30224,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30286,
"s": 30252,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 30321,
"s": 30286,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 30338,
"s": 30321,
"text": "Substring in C++"
}
] |
Count occurrences of a character in a repeated string - GeeksforGeeks | 23 Aug, 2021
Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.Examples:
Input : N = 10 str = "abcac"
Output : 4
Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first 10 letters 'a' occurs 4 times.
Input: N = 10, str = "aba"
Output : 7
Approach: 1. Find the occurrences of character ‘a’ in the given string. 2. Find the No. of repetitions which are required to find the ‘a’ occurrences. 3. Multiply the single string occurrences to the No. of repetitions. 4. If given n is not the multiple of given string size then we will find the ‘a’ occurrences in the remaining substring.Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the occurrences of// character x in the infinite repeated string// upto length n#include <bits/stdc++.h>using namespace std; // Function to count the character 'a'int countChar(string str, char x){ int count = 0, n = 10; for (int i = 0; i < str.size(); i++) if (str[i] == x) count++; // atleast k repetition are required int repetitions = n / str.size(); count = count * repetitions; // if n is not the multiple of the string size // check for the remaining repeating character. for (int i = 0; i < n % str.size(); i++) { if (str[i] == x) count++; } return count;} // Driver codeint main(){ string str = "abcac"; cout << countChar(str, 'a'); return 0;} // This code is contributed by Surendra_Gangwar
// Java program to find the occurrences// of character x in the infinite// repeated string upto length nimport java.util.*;import java.lang.*; class GFG{// Function to count the character 'a'static int countChar(String str, char x){ int count = 0; int n = 10; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == x) count++; // atleast k repetition are required int repetitions = n / str.length(); count = count * repetitions; // if n is not the multiple of the // string size check for the remaining // repeating character. for (int i = 0; i < n % str.length(); i++) { if (str.charAt(i) == x) count++; } return count;} // Driver codepublic static void main(String args[]){ String str = "abcac"; System.out.println(countChar(str, 'a'));}} // This code is contributed// by Akanksha Rai
# Python3 program to find the occurrences of# character x in the infinite repeated string# upto length n # Function to count the character 'a'def countChar(str, x): count = 0 for i in range(len(str)): if (str[i] == x) : count += 1 n = 10 # atleast k repetition are required repetitions = n // len(str) count = count * repetitions # if n is not the multiple of the # string size check for the remaining # repeating character. l = n % len(str) for i in range(l): if (str[i] == x): count += 1 return count # Driver codestr = "abcac"print(countChar(str, 'a')) # This code is contributed# by sahishelangia
// C# program to find the occurrences// of character x in the infinite// repeated string upto length nusing System; class GFG{// Function to count the character 'a'static int countChar(string str, char x){ int count = 0; int n = 10; for (int i = 0; i < str.Length; i++) if (str[i] == x) count++; // atleast k repetition are required int repetitions = n / str.Length; count = count * repetitions; // if n is not the multiple of the // string size check for the remaining // repeating character. for (int i = 0; i < n % str.Length; i++) { if (str[i] == x) count++; } return count;} // Driver codepublic static void Main(){ string str = "abcac"; Console.WriteLine(countChar(str, 'a'));}} // This code is contributed// by Akanksha Rai
<?php// PHP program to find the occurrences// of character x in the infinite// repeated string upto length n // Function to count the character 'a'function countChar($str, $x){ $count = 0; $n = 10; for ($i = 0; $i < strlen($str); $i++) if ($str[$i] == $x) $count++; // atleast k repetition are required $repetitions = (int)($n / strlen($str)); $count = $count * $repetitions; // if n is not the multiple of // the string size check for the // remaining repeating character. for ($i = 0; $i < $n % strlen($str); $i++) { if ($str[$i] == $x) $count++; } return $count;} // Driver code$str = "abcac";echo countChar($str, 'a'); // This code is contributed by Sachin?>
<script> // JavaScript program to find the occurrences // of character x in the infinite // repeated string upto length n // Function to count the character 'a' function countChar(str, x) { let count = 0; let n = 10; for (let i = 0; i < str.length; i++) if (str[i] == x) count++; // atleast k repetition are required let repetitions = n / str.length; count = count * repetitions; // if n is not the multiple of the // string size check for the remaining // repeating character. for (let i = 0; i < n % str.length; i++) { if (str[i] == x) count++; } return count; } let str = "abcac"; document.write(countChar(str, 'a')); </script>
Output:
4
Sach_Code
Akanksha_Rai
sahilshelangia
gp6
rameshtravel07
clintra
saurabh1990aror
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
sprintf() in C
Print all subsequences of a string
Convert character array to string in C++
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching | [
{
"code": null,
"e": 26099,
"s": 26071,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 26274,
"s": 26099,
"text": "Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.Examples: "
},
{
"code": null,
"e": 26484,
"s": 26274,
"text": "Input : N = 10 str = \"abcac\"\nOutput : 4\nExplanation: \"abcacabcac\" is the substring from the infinitely repeated string. In first 10 letters 'a' occurs 4 times.\n \nInput: N = 10, str = \"aba\"\nOutput : 7"
},
{
"code": null,
"e": 26874,
"s": 26486,
"text": "Approach: 1. Find the occurrences of character ‘a’ in the given string. 2. Find the No. of repetitions which are required to find the ‘a’ occurrences. 3. Multiply the single string occurrences to the No. of repetitions. 4. If given n is not the multiple of given string size then we will find the ‘a’ occurrences in the remaining substring.Below is the implementation of above approach: "
},
{
"code": null,
"e": 26878,
"s": 26874,
"text": "C++"
},
{
"code": null,
"e": 26883,
"s": 26878,
"text": "Java"
},
{
"code": null,
"e": 26891,
"s": 26883,
"text": "Python3"
},
{
"code": null,
"e": 26894,
"s": 26891,
"text": "C#"
},
{
"code": null,
"e": 26898,
"s": 26894,
"text": "PHP"
},
{
"code": null,
"e": 26909,
"s": 26898,
"text": "Javascript"
},
{
"code": "// CPP program to find the occurrences of// character x in the infinite repeated string// upto length n#include <bits/stdc++.h>using namespace std; // Function to count the character 'a'int countChar(string str, char x){ int count = 0, n = 10; for (int i = 0; i < str.size(); i++) if (str[i] == x) count++; // atleast k repetition are required int repetitions = n / str.size(); count = count * repetitions; // if n is not the multiple of the string size // check for the remaining repeating character. for (int i = 0; i < n % str.size(); i++) { if (str[i] == x) count++; } return count;} // Driver codeint main(){ string str = \"abcac\"; cout << countChar(str, 'a'); return 0;} // This code is contributed by Surendra_Gangwar",
"e": 27711,
"s": 26909,
"text": null
},
{
"code": "// Java program to find the occurrences// of character x in the infinite// repeated string upto length nimport java.util.*;import java.lang.*; class GFG{// Function to count the character 'a'static int countChar(String str, char x){ int count = 0; int n = 10; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == x) count++; // atleast k repetition are required int repetitions = n / str.length(); count = count * repetitions; // if n is not the multiple of the // string size check for the remaining // repeating character. for (int i = 0; i < n % str.length(); i++) { if (str.charAt(i) == x) count++; } return count;} // Driver codepublic static void main(String args[]){ String str = \"abcac\"; System.out.println(countChar(str, 'a'));}} // This code is contributed// by Akanksha Rai",
"e": 28598,
"s": 27711,
"text": null
},
{
"code": "# Python3 program to find the occurrences of# character x in the infinite repeated string# upto length n # Function to count the character 'a'def countChar(str, x): count = 0 for i in range(len(str)): if (str[i] == x) : count += 1 n = 10 # atleast k repetition are required repetitions = n // len(str) count = count * repetitions # if n is not the multiple of the # string size check for the remaining # repeating character. l = n % len(str) for i in range(l): if (str[i] == x): count += 1 return count # Driver codestr = \"abcac\"print(countChar(str, 'a')) # This code is contributed# by sahishelangia",
"e": 29277,
"s": 28598,
"text": null
},
{
"code": "// C# program to find the occurrences// of character x in the infinite// repeated string upto length nusing System; class GFG{// Function to count the character 'a'static int countChar(string str, char x){ int count = 0; int n = 10; for (int i = 0; i < str.Length; i++) if (str[i] == x) count++; // atleast k repetition are required int repetitions = n / str.Length; count = count * repetitions; // if n is not the multiple of the // string size check for the remaining // repeating character. for (int i = 0; i < n % str.Length; i++) { if (str[i] == x) count++; } return count;} // Driver codepublic static void Main(){ string str = \"abcac\"; Console.WriteLine(countChar(str, 'a'));}} // This code is contributed// by Akanksha Rai",
"e": 30104,
"s": 29277,
"text": null
},
{
"code": "<?php// PHP program to find the occurrences// of character x in the infinite// repeated string upto length n // Function to count the character 'a'function countChar($str, $x){ $count = 0; $n = 10; for ($i = 0; $i < strlen($str); $i++) if ($str[$i] == $x) $count++; // atleast k repetition are required $repetitions = (int)($n / strlen($str)); $count = $count * $repetitions; // if n is not the multiple of // the string size check for the // remaining repeating character. for ($i = 0; $i < $n % strlen($str); $i++) { if ($str[$i] == $x) $count++; } return $count;} // Driver code$str = \"abcac\";echo countChar($str, 'a'); // This code is contributed by Sachin?>",
"e": 30845,
"s": 30104,
"text": null
},
{
"code": "<script> // JavaScript program to find the occurrences // of character x in the infinite // repeated string upto length n // Function to count the character 'a' function countChar(str, x) { let count = 0; let n = 10; for (let i = 0; i < str.length; i++) if (str[i] == x) count++; // atleast k repetition are required let repetitions = n / str.length; count = count * repetitions; // if n is not the multiple of the // string size check for the remaining // repeating character. for (let i = 0; i < n % str.length; i++) { if (str[i] == x) count++; } return count; } let str = \"abcac\"; document.write(countChar(str, 'a')); </script>",
"e": 31664,
"s": 30845,
"text": null
},
{
"code": null,
"e": 31674,
"s": 31664,
"text": "Output: "
},
{
"code": null,
"e": 31676,
"s": 31674,
"text": "4"
},
{
"code": null,
"e": 31688,
"s": 31678,
"text": "Sach_Code"
},
{
"code": null,
"e": 31701,
"s": 31688,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31716,
"s": 31701,
"text": "sahilshelangia"
},
{
"code": null,
"e": 31720,
"s": 31716,
"text": "gp6"
},
{
"code": null,
"e": 31735,
"s": 31720,
"text": "rameshtravel07"
},
{
"code": null,
"e": 31743,
"s": 31735,
"text": "clintra"
},
{
"code": null,
"e": 31759,
"s": 31743,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 31767,
"s": 31759,
"text": "Strings"
},
{
"code": null,
"e": 31775,
"s": 31767,
"text": "Strings"
},
{
"code": null,
"e": 31873,
"s": 31775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31918,
"s": 31873,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31963,
"s": 31918,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 31980,
"s": 31963,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 32009,
"s": 31980,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 32024,
"s": 32009,
"text": "sprintf() in C"
},
{
"code": null,
"e": 32059,
"s": 32024,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 32100,
"s": 32059,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 32143,
"s": 32100,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 32204,
"s": 32143,
"text": "Program to count occurrence of a given character in a string"
}
] |
How to Build a Weather App in Android? - GeeksforGeeks | 14 Feb, 2022
In this project, we will be building a weather application. This application will show the temperature of a location. To fetch weather information we will need an API. An API(Application Programming Interface) is a function that allows applications to interact and share data using various components and microservices. For this project, we will be using WeatherBit API for fetching weather data. WeatherBit API provides a fast and elegant way to fetch weather data. Note that we are going to implement this project using the Kotlin language.
In this project, we will build an app that will find the device’s location coordinates(longitude and latitude). Then we will send this data to the API via an API key(which we will see later). The API will send us a JSON from which we will extract the required data that is the temperature and city of the location.
Step 1: Create a New Project
YouTubeGeeksforGeeks507K subscribersMaking Weather App in Android Studio | Android Projects | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:12:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=q7NF-2gtfEU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Go to the app > res > drawable file and paste this image to this file. Now right-click on the drawable folder > New > Drawable resource File and name the file as btn_bg6. Below is the code for the btn_bg6.xml file.
Reference Article: How to Add Image to Drawable Folder in Android Studio?
XML
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <gradient android:angle="0" android:startColor="#BBE1FD" android:endColor="#6CC7E3" android:type="linear"/> </shape> </item></selector>
Step 3: Get the API key
To get the API key simply sign-in on WeatherBit and subscribe for a free API of Current Weather Data API. After doing so you will receive an API key and you are good to go.
Step 4: Permission Check
For this app to work we need to ask for three permissions from the system –
Coarse Location – <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
Fine Location – <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/>
Internet – <uses-permission android:name=”android.permission.INTERNET”/>
We will add code for use permission in the AndroidManifest.xml file. See the below code
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 5: Building the Layout
We will add a Button and TextView in the one and only screen of the application. When the user will click the Button the temperature and city of that location will be shown in the TextView. See the code below:
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/weather_background" tools:context=".MainActivity"> <Button android:id="@+id/btVar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@drawable/btn_bg6" android:padding="10dp" android:text="Get Weather" android:textSize="20dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="40dp" android:layout_marginBottom="100dp" android:fontFamily="sans-serif-black" android:text="Get temperature here" android:textColor="#F6F8F5" android:textSize="25dp" android:textStyle="bold" /> </RelativeLayout>
Step 6: Getting Device’s Coordinates
In this step, we will get the last location of the device using Google Play Services –
Setup google play services by downloading its components in the SDK manager.
Add dependency in build.gradle for location – “implementation com.google.android.gms:play-services-location:17.1.0′′, the version might change later.
In the onCreate() method create an instance of the Fused Location Provider Client.
After this use lastlocation() method to call the last location. See the Kotlin code after Step 5.
Step 7: Parse JSON after getting it
To get JSON we need to use Volley Library to make an HTTP client request
Add ‘implementation com.android.volley:volley:1.1.1’ to the gradle app file.
Create the http for the JSON. For example – “https://api.weatherbit.io/v2.0/current?” + “lat=” + location?.latitude +”&lon=”+ location?.longitude + “&key=”+ api_id1. Here we have already generated API key as well as the location coordinates.
Make a request from this URL and get the data.
Step 8: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.annotation.SuppressLintimport android.location.Locationimport android.os.Bundleimport android.util.Logimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport com.android.volley.Requestimport com.android.volley.Responseimport com.android.volley.toolbox.StringRequestimport com.android.volley.toolbox.Volleyimport com.google.android.gms.location.FusedLocationProviderClientimport com.google.android.gms.location.LocationServicesimport kotlinx.android.synthetic.main.activity_main.*import org.json.JSONObject class MainActivity : AppCompatActivity() { // weather url to get JSON var weather_url1 = "" // api id for url var api_id1 = "030314b750cc43e7b39e503dfe37150c" private lateinit var textView: TextView private lateinit var fusedLocationClient: FusedLocationProviderClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // link the textView in which the // temperature will be displayed textView = findViewById(R.id.textView) // create an instance of the Fused // Location Provider Client fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) Log.e("lat", weather_url1) // on clicking this button function to // get the coordinates will be called btVar1.setOnClickListener { Log.e("lat", "onClick") // function to find the coordinates // of the last location obtainLocation() } } @SuppressLint("MissingPermission") private fun obtainLocation() { Log.e("lat", "function") // get the last location fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // get the latitude and longitude // and create the http URL weather_url1 = "https://api.weatherbit.io/v2.0/current?" + "lat=" + location?.latitude + "&lon=" + location?.longitude + "&key=" + api_id1 Log.e("lat", weather_url1.toString()) // this function will // fetch data from URL getTemp() } } fun getTemp() { // Instantiate the RequestQueue. val queue = Volley.newRequestQueue(this) val url: String = weather_url1 Log.e("lat", url) // Request a string response // from the provided URL. val stringReq = StringRequest(Request.Method.GET, url, Response.Listener<String> { response -> Log.e("lat", response.toString()) // get the JSON object val obj = JSONObject(response) // get the Array from obj of name - "data" val arr = obj.getJSONArray("data") Log.e("lat obj1", arr.toString()) // get the JSON object from the // array at index position 0 val obj2 = arr.getJSONObject(0) Log.e("lat obj2", obj2.toString()) // set the temperature and the city // name using getString() function textView.text = obj2.getString("temp") + " deg Celsius in " + obj2.getString("city_name") }, // In case of any error Response.ErrorListener { textView!!.text = "That didn't work!" }) queue.add(stringReq) }}
Note: Before running the application make sure the location in the device is turned on and the application has access to that.
GitHub link: https://github.com/njdunk07/NJ-Weather-GFG
arorakashish0911
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
CardView in Android With Example
Broadcast Receiver in Android With Example
Android UI Layouts
Kotlin Array
Android RecyclerView in Kotlin
Content Providers in Android with Example | [
{
"code": null,
"e": 26121,
"s": 26093,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 26665,
"s": 26121,
"text": "In this project, we will be building a weather application. This application will show the temperature of a location. To fetch weather information we will need an API. An API(Application Programming Interface) is a function that allows applications to interact and share data using various components and microservices. For this project, we will be using WeatherBit API for fetching weather data. WeatherBit API provides a fast and elegant way to fetch weather data. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 26980,
"s": 26665,
"text": "In this project, we will build an app that will find the device’s location coordinates(longitude and latitude). Then we will send this data to the API via an API key(which we will see later). The API will send us a JSON from which we will extract the required data that is the temperature and city of the location."
},
{
"code": null,
"e": 27009,
"s": 26980,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27866,
"s": 27009,
"text": "YouTubeGeeksforGeeks507K subscribersMaking Weather App in Android Studio | Android Projects | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:12:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=q7NF-2gtfEU\" 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": 28030,
"s": 27866,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 28108,
"s": 28030,
"text": "Step 2: Before going to the coding section first you have to do some pre-task"
},
{
"code": null,
"e": 28323,
"s": 28108,
"text": "Go to the app > res > drawable file and paste this image to this file. Now right-click on the drawable folder > New > Drawable resource File and name the file as btn_bg6. Below is the code for the btn_bg6.xml file."
},
{
"code": null,
"e": 28397,
"s": 28323,
"text": "Reference Article: How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 28401,
"s": 28397,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item> <shape> <gradient android:angle=\"0\" android:startColor=\"#BBE1FD\" android:endColor=\"#6CC7E3\" android:type=\"linear\"/> </shape> </item></selector>",
"e": 28751,
"s": 28401,
"text": null
},
{
"code": null,
"e": 28780,
"s": 28755,
"text": "Step 3: Get the API key "
},
{
"code": null,
"e": 28955,
"s": 28782,
"text": "To get the API key simply sign-in on WeatherBit and subscribe for a free API of Current Weather Data API. After doing so you will receive an API key and you are good to go."
},
{
"code": null,
"e": 28982,
"s": 28957,
"text": "Step 4: Permission Check"
},
{
"code": null,
"e": 29061,
"s": 28984,
"text": "For this app to work we need to ask for three permissions from the system – "
},
{
"code": null,
"e": 29157,
"s": 29063,
"text": "Coarse Location – <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>"
},
{
"code": null,
"e": 29247,
"s": 29157,
"text": "Fine Location – <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/>"
},
{
"code": null,
"e": 29320,
"s": 29247,
"text": "Internet – <uses-permission android:name=”android.permission.INTERNET”/>"
},
{
"code": null,
"e": 29410,
"s": 29322,
"text": "We will add code for use permission in the AndroidManifest.xml file. See the below code"
},
{
"code": null,
"e": 29416,
"s": 29412,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/> <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/> <uses-permission android:name=\"android.permission.INTERNET\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 30300,
"s": 29416,
"text": null
},
{
"code": null,
"e": 30332,
"s": 30304,
"text": "Step 5: Building the Layout"
},
{
"code": null,
"e": 30545,
"s": 30334,
"text": "We will add a Button and TextView in the one and only screen of the application. When the user will click the Button the temperature and city of that location will be shown in the TextView. See the code below: "
},
{
"code": null,
"e": 30551,
"s": 30547,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@drawable/weather_background\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btVar1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:background=\"@drawable/btn_bg6\" android:padding=\"10dp\" android:text=\"Get Weather\" android:textSize=\"20dp\" /> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"40dp\" android:layout_marginBottom=\"100dp\" android:fontFamily=\"sans-serif-black\" android:text=\"Get temperature here\" android:textColor=\"#F6F8F5\" android:textSize=\"25dp\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 31623,
"s": 30551,
"text": null
},
{
"code": null,
"e": 31664,
"s": 31627,
"text": "Step 6: Getting Device’s Coordinates"
},
{
"code": null,
"e": 31754,
"s": 31666,
"text": "In this step, we will get the last location of the device using Google Play Services – "
},
{
"code": null,
"e": 31833,
"s": 31756,
"text": "Setup google play services by downloading its components in the SDK manager."
},
{
"code": null,
"e": 31983,
"s": 31833,
"text": "Add dependency in build.gradle for location – “implementation com.google.android.gms:play-services-location:17.1.0′′, the version might change later."
},
{
"code": null,
"e": 32066,
"s": 31983,
"text": "In the onCreate() method create an instance of the Fused Location Provider Client."
},
{
"code": null,
"e": 32164,
"s": 32066,
"text": "After this use lastlocation() method to call the last location. See the Kotlin code after Step 5."
},
{
"code": null,
"e": 32202,
"s": 32166,
"text": "Step 7: Parse JSON after getting it"
},
{
"code": null,
"e": 32277,
"s": 32204,
"text": "To get JSON we need to use Volley Library to make an HTTP client request"
},
{
"code": null,
"e": 32356,
"s": 32279,
"text": "Add ‘implementation com.android.volley:volley:1.1.1’ to the gradle app file."
},
{
"code": null,
"e": 32598,
"s": 32356,
"text": "Create the http for the JSON. For example – “https://api.weatherbit.io/v2.0/current?” + “lat=” + location?.latitude +”&lon=”+ location?.longitude + “&key=”+ api_id1. Here we have already generated API key as well as the location coordinates."
},
{
"code": null,
"e": 32645,
"s": 32598,
"text": "Make a request from this URL and get the data."
},
{
"code": null,
"e": 32693,
"s": 32647,
"text": "Step 8: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 32881,
"s": 32695,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32890,
"s": 32883,
"text": "Kotlin"
},
{
"code": "import android.annotation.SuppressLintimport android.location.Locationimport android.os.Bundleimport android.util.Logimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport com.android.volley.Requestimport com.android.volley.Responseimport com.android.volley.toolbox.StringRequestimport com.android.volley.toolbox.Volleyimport com.google.android.gms.location.FusedLocationProviderClientimport com.google.android.gms.location.LocationServicesimport kotlinx.android.synthetic.main.activity_main.*import org.json.JSONObject class MainActivity : AppCompatActivity() { // weather url to get JSON var weather_url1 = \"\" // api id for url var api_id1 = \"030314b750cc43e7b39e503dfe37150c\" private lateinit var textView: TextView private lateinit var fusedLocationClient: FusedLocationProviderClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // link the textView in which the // temperature will be displayed textView = findViewById(R.id.textView) // create an instance of the Fused // Location Provider Client fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) Log.e(\"lat\", weather_url1) // on clicking this button function to // get the coordinates will be called btVar1.setOnClickListener { Log.e(\"lat\", \"onClick\") // function to find the coordinates // of the last location obtainLocation() } } @SuppressLint(\"MissingPermission\") private fun obtainLocation() { Log.e(\"lat\", \"function\") // get the last location fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // get the latitude and longitude // and create the http URL weather_url1 = \"https://api.weatherbit.io/v2.0/current?\" + \"lat=\" + location?.latitude + \"&lon=\" + location?.longitude + \"&key=\" + api_id1 Log.e(\"lat\", weather_url1.toString()) // this function will // fetch data from URL getTemp() } } fun getTemp() { // Instantiate the RequestQueue. val queue = Volley.newRequestQueue(this) val url: String = weather_url1 Log.e(\"lat\", url) // Request a string response // from the provided URL. val stringReq = StringRequest(Request.Method.GET, url, Response.Listener<String> { response -> Log.e(\"lat\", response.toString()) // get the JSON object val obj = JSONObject(response) // get the Array from obj of name - \"data\" val arr = obj.getJSONArray(\"data\") Log.e(\"lat obj1\", arr.toString()) // get the JSON object from the // array at index position 0 val obj2 = arr.getJSONObject(0) Log.e(\"lat obj2\", obj2.toString()) // set the temperature and the city // name using getString() function textView.text = obj2.getString(\"temp\") + \" deg Celsius in \" + obj2.getString(\"city_name\") }, // In case of any error Response.ErrorListener { textView!!.text = \"That didn't work!\" }) queue.add(stringReq) }}",
"e": 36439,
"s": 32890,
"text": null
},
{
"code": null,
"e": 36569,
"s": 36442,
"text": "Note: Before running the application make sure the location in the device is turned on and the application has access to that."
},
{
"code": null,
"e": 36627,
"s": 36571,
"text": "GitHub link: https://github.com/njdunk07/NJ-Weather-GFG"
},
{
"code": null,
"e": 36646,
"s": 36629,
"text": "arorakashish0911"
},
{
"code": null,
"e": 36654,
"s": 36646,
"text": "android"
},
{
"code": null,
"e": 36662,
"s": 36654,
"text": "Android"
},
{
"code": null,
"e": 36669,
"s": 36662,
"text": "Kotlin"
},
{
"code": null,
"e": 36677,
"s": 36669,
"text": "Android"
},
{
"code": null,
"e": 36775,
"s": 36677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36833,
"s": 36775,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 36871,
"s": 36833,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 36914,
"s": 36871,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 36945,
"s": 36914,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 36978,
"s": 36945,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 37021,
"s": 36978,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 37040,
"s": 37021,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 37053,
"s": 37040,
"text": "Kotlin Array"
},
{
"code": null,
"e": 37084,
"s": 37053,
"text": "Android RecyclerView in Kotlin"
}
] |
Node.js server.listen() Method | 15 Sep, 2020
The server.listen() is an inbuilt application programming interface of class Socket within tls module which is used to start the server to listen the encrypted connection.
Syntax:
const server.listen([port[, host[, backlog]]][, callback])
Parameters: This method takes the following argument as parameter:
port: It is the port number.
port: It is the port number.
host: It’s the unspecified IPv4 address.
host: It’s the unspecified IPv4 address.
Return Value: This method has nothing to return but a callback function.
How to generate private key and public certificate?
Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg
JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5
HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB
AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu
o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT
Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu
0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ
fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ
sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC
TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy
GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5
JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m
nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC
-----END RSA PRIVATE KEY-----Save file as private-key.pemPublic certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----
MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV
BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG
9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw
OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw
DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM
Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB
nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm
Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi
QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC
kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX
bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG
BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC
hWF6W2H9+MAlU7yvtmCQQuZmfQ==
-----END CERTIFICATE-----Save file as public-cert.pem
Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg
JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5
HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB
AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu
o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT
Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu
0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ
fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ
sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC
TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy
GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5
JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m
nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC
-----END RSA PRIVATE KEY-----Save file as private-key.pem
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg
JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5
HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB
AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu
o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT
Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu
0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ
fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ
sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC
TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy
GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5
JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m
nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC
-----END RSA PRIVATE KEY-----
Save file as private-key.pem
Public certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----
MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV
BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG
9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw
OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw
DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM
Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB
nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm
Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi
QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC
kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX
bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG
BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC
hWF6W2H9+MAlU7yvtmCQQuZmfQ==
-----END CERTIFICATE-----Save file as public-cert.pem
-----BEGIN CERTIFICATE-----
MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV
BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG
9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw
OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw
DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM
Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB
nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm
Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi
QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC
kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX
bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG
BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC
hWF6W2H9+MAlU7yvtmCQQuZmfQ==
-----END CERTIFICATE-----
Save file as public-cert.pem
Example 1: Filename: index.js
// Node.js program to demonstrate the// server.listen() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1'; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on('data', function(data) { console.log('\nReceived: %s ', data.toString().replace(/(\n)/gm, "")); }); // Stopping the server // by using the close() method server.close();}); // Getting session key // by using getTicketKeys() methodconst value1 = server.getTicketKeys();console.log(value1) // Close eventserver.on('close', () => { console.log("Server closed successfully");}) // Start listening on a specific port and address// by using listen() methodserver.listen(PORT, HOST, function() { console.log("I'm listening at %s, on port %s", HOST, PORT);}); // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { // Getting the bound address // by using address method const value = client.address(); client.write("Bound address : " + value) client.end();});
Output:
<Buffer 72 59 e4 89 85 0f ae fb eb e6 cb 3a 1a bf 92 19 2f ab 97 be 5d 10 19 50 cc 0f 98 d3 27 fe 9c 68 2a 31 f3 e8 17 b7 77 38 88 f0 28 64 90 1c 36 40>I’m listening at 127.0.0.1, on port 1337
Received: Bound address : [object Object]Server closed successfully
Example 2: Filename: index.js
// Node.js program to demonstrate the// server.listen() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1',value = null; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on('data', function(data) { console.log('\nReceived: %s ', data.toString()); }); // Stopping the server // by using the close() method server.close();}); // Getting session key // by using getTicketKeys() methodvalue = server.getTicketKeys(); // Start listening on a specific port and address// by using listen() methodserver.listen(PORT, HOST, function() { console.log("I'm listening at %s, on port %s", HOST, PORT);}); // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { client.write("Session key : " + value[0]) client.end();});
Run the index.js file using the following command:
node index.js
Output:
I'm listening at 127.0.0.1, on port 1337
Received: Session key : 106
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/tls.html#tls_server_listen
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "The server.listen() is an inbuilt application programming interface of class Socket within tls module which is used to start the server to listen the encrypted connection."
},
{
"code": null,
"e": 208,
"s": 200,
"text": "Syntax:"
},
{
"code": null,
"e": 268,
"s": 208,
"text": "const server.listen([port[, host[, backlog]]][, callback])\n"
},
{
"code": null,
"e": 335,
"s": 268,
"text": "Parameters: This method takes the following argument as parameter:"
},
{
"code": null,
"e": 364,
"s": 335,
"text": "port: It is the port number."
},
{
"code": null,
"e": 393,
"s": 364,
"text": "port: It is the port number."
},
{
"code": null,
"e": 434,
"s": 393,
"text": "host: It’s the unspecified IPv4 address."
},
{
"code": null,
"e": 475,
"s": 434,
"text": "host: It’s the unspecified IPv4 address."
},
{
"code": null,
"e": 548,
"s": 475,
"text": "Return Value: This method has nothing to return but a callback function."
},
{
"code": null,
"e": 600,
"s": 548,
"text": "How to generate private key and public certificate?"
},
{
"code": null,
"e": 2595,
"s": 600,
"text": "Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----Save file as private-key.pemPublic certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----Save file as public-cert.pem"
},
{
"code": null,
"e": 3569,
"s": 2595,
"text": "Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----Save file as private-key.pem"
},
{
"code": null,
"e": 4456,
"s": 3569,
"text": "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----"
},
{
"code": null,
"e": 4485,
"s": 4456,
"text": "Save file as private-key.pem"
},
{
"code": null,
"e": 5507,
"s": 4485,
"text": "Public certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----Save file as public-cert.pem"
},
{
"code": null,
"e": 6435,
"s": 5507,
"text": "-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----"
},
{
"code": null,
"e": 6464,
"s": 6435,
"text": "Save file as public-cert.pem"
},
{
"code": null,
"e": 6494,
"s": 6464,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the// server.listen() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1'; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on('data', function(data) { console.log('\\nReceived: %s ', data.toString().replace(/(\\n)/gm, \"\")); }); // Stopping the server // by using the close() method server.close();}); // Getting session key // by using getTicketKeys() methodconst value1 = server.getTicketKeys();console.log(value1) // Close eventserver.on('close', () => { console.log(\"Server closed successfully\");}) // Start listening on a specific port and address// by using listen() methodserver.listen(PORT, HOST, function() { console.log(\"I'm listening at %s, on port %s\", HOST, PORT);}); // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { // Getting the bound address // by using address method const value = client.address(); client.write(\"Bound address : \" + value) client.end();});",
"e": 7824,
"s": 6494,
"text": null
},
{
"code": null,
"e": 7832,
"s": 7824,
"text": "Output:"
},
{
"code": null,
"e": 8025,
"s": 7832,
"text": "<Buffer 72 59 e4 89 85 0f ae fb eb e6 cb 3a 1a bf 92 19 2f ab 97 be 5d 10 19 50 cc 0f 98 d3 27 fe 9c 68 2a 31 f3 e8 17 b7 77 38 88 f0 28 64 90 1c 36 40>I’m listening at 127.0.0.1, on port 1337"
},
{
"code": null,
"e": 8093,
"s": 8025,
"text": "Received: Bound address : [object Object]Server closed successfully"
},
{
"code": null,
"e": 8123,
"s": 8093,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the// server.listen() method var tls = require('tls'), fs = require('fs'), // Port and host address for server PORT = 1337,HOST = '127.0.0.1',value = null; // Private key and public certificate for accessvar options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false}; // Creating and initializing servervar server = tls.createServer(options, function(socket) { // Print the data that we received socket.on('data', function(data) { console.log('\\nReceived: %s ', data.toString()); }); // Stopping the server // by using the close() method server.close();}); // Getting session key // by using getTicketKeys() methodvalue = server.getTicketKeys(); // Start listening on a specific port and address// by using listen() methodserver.listen(PORT, HOST, function() { console.log(\"I'm listening at %s, on port %s\", HOST, PORT);}); // Creating and initializing clientvar client = tls.connect(PORT, HOST, options, function() { client.write(\"Session key : \" + value[0]) client.end();});",
"e": 9233,
"s": 8123,
"text": null
},
{
"code": null,
"e": 9284,
"s": 9233,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 9299,
"s": 9284,
"text": "node index.js\n"
},
{
"code": null,
"e": 9307,
"s": 9299,
"text": "Output:"
},
{
"code": null,
"e": 9378,
"s": 9307,
"text": "I'm listening at 127.0.0.1, on port 1337\n\nReceived: Session key : 106\n"
},
{
"code": null,
"e": 9462,
"s": 9378,
"text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/tls.html#tls_server_listen"
},
{
"code": null,
"e": 9478,
"s": 9462,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 9486,
"s": 9478,
"text": "Node.js"
},
{
"code": null,
"e": 9503,
"s": 9486,
"text": "Web Technologies"
}
] |
C# | Method Overriding | 23 Mar, 2022
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding.
In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the ways by which C# achieve Run Time Polymorphism(Dynamic Polymorphism).
The method that is overridden by an override declaration is called the overridden base method. An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override.
Example:
class base_class
{
public void gfg();
}
class derived_class : base_class
{
public void gfg();
}
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();
d.gfg();
}
}
Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.
In C# we can use 3 types of keywords for Method Overriding:
virtual keyword: This modifier or keyword use within base class method. It is used to modify a method in base class for overridden that particular method in the derived class.
override: This modifier or keyword use with derived class method. It is used to modify a virtual or abstract method into derived class which presents in base class.
class base_class
{
public virtual void gfg();
}
class derived_class : base_class
{
public override void gfg();
}
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();
d.gfg();
base_class b = new derived_class();
b.gfg();
}
}
Here first, d refers to the object of the class derived_class and it invokes gfg() of the class derived_class then, b refers to the reference of the class base and it hold the object of class derived and it invokes gfg() of the class derived. Here gfg() method takes permission from base class to overriding the method in derived class.
Example 1: Method Overriding without using virtual and override modifiers
C#
// C# program to demonstrate the method overriding// without using 'virtual' and 'override' modifiersusing System; // base class name 'baseClass'class baseClass { public void show() { Console.WriteLine("Base class"); }} // derived class name 'derived'// 'baseClass' inherit hereclass derived : baseClass{ // overriding new public void show() { Console.WriteLine("Derived class"); }} class GFG { // Main Method public static void Main() { // 'obj' is the object of // class 'baseClass' baseClass obj = new baseClass(); // invokes the method 'show()' // of class 'baseClass' obj.show(); obj = new derived(); // it also invokes the method // 'show()' of class 'baseClass' obj.show(); }}
Base class
Base class
Explanation: In this program, the object obj invokes class baseClass two times and call the method show() of class baseClass. To avoid this problem we use virtual and override keyword.
Example 2: Method overriding using virtual and override modifiers.
C#
// C# program to illustrate the use of//'virtual' and 'override' modifiersusing System; class baseClass { // show() is 'virtual' here public virtual void show() { Console.WriteLine("Base class"); }} // class 'baseClass' inherit// class 'derived'class derived : baseClass{ //'show()' is 'override' here public override void show() { Console.WriteLine("Derived class"); }} class GFG { // Main Method public static void Main() { baseClass obj; // 'obj' is the object // of class 'baseClass' obj = new baseClass(); // it invokes 'show()' // of class 'baseClass' obj.show(); // the same object 'obj' is now // the object of class 'derived' obj = new derived(); // it invokes 'show()' of class 'derived' // 'show()' of class 'derived' is overridden // for 'override' modifier obj.show(); }}
Base class
Derived class
base Keyword: This is used to access members of the base class from derived class. It basically used to access constructors and methods or functions of the base class. The base keyword cannot use within a static method. Base keyword specifies which constructor of the base class should be invoked while creating the instances of the derived class.
Use of Base keyword:
Call methods or functions of base class from derived class.
Call constructor internally of base class at the time of inheritance.
Example 1:
C#
// C# program to show the use of 'base'// keyword in method overridingusing System; // base classpublic class web { string name = "GeeksForGeeks"; // 'showdata()' is member method, // declare as virtual public virtual void showdata() { Console.WriteLine("Website Name: " + name); }} // derived class// class 'web' is inherits// class 'stream'class stream : web { string s = "Computer Science"; //'showdata()' is overridden // in derived class public override void showdata() { // Calling 'showdata()' of base // class using 'base' keyword base.showdata(); Console.WriteLine("About: " + s); }} class GFG { // Main Method static void Main() { // 'E' is object of class stream // also works as object of // class 'web' stream E = new stream(); // it first invokes 'showdata()' // of class 'web' then it invokes // 'showdata()' of class 'stream' E.showdata(); }}
Website Name: GeeksForGeeks
About: Computer Science
Example 2: How base keyword specifies the calling of base-class constructor from derived class when derived class instances are created.
C#
// C# program to show how base keyword// specifies the calling of base-class// constructor from the derived class// when derived class instances are createdusing System; // base classpublic class clssA { int n1, n2; // default constructor public clssA() { Console.WriteLine("Default Constructor Invoked"); } // parameterized constructor public clssA(int i, int j) { // construct values n1 = i; n2 = j; Console.WriteLine("Parameterized Constructor Invoked"); Console.WriteLine("Invoked Values are: " + n1 + " and " + n2); }} // derived classpublic class DerivedClass : clssA{ // This constructor will instantiate // 'clssA()' [no argument constructor] // using 'base' keyword public DerivedClass() : base() { } // This constructor will instantiate // 'clssA(int i, int j)' [parameterized // constructor] using 'base' keyword public DerivedClass(int i, int j) : base(i, j) { } // Main Methodstatic void Main(){ // invoke no argument constructor DerivedClass d1 = new DerivedClass(); Console.WriteLine(); // invoke parameterized constructor DerivedClass d2 = new DerivedClass(10, 20); }}
Output:
Default Constructor Invoked
Parameterized Constructor Invoked
Invoked Values are: 10 and 20
Example 3: It shows how base keyword specifies the base-class constructor called from derived class and also calling of a method using the base keyword from the derived class.
C#
// C# program to show how 'base' keyword specifies// the base-class constructor that called from// derived class and also calling a method 'swap'// from derived class using base keywordusing System; // base classpublic class clssA { public int n1, n2; // default constructor public clssA() { Console.WriteLine("In clssA 'no argument constructor' invoked"); } // parameterized constructor public clssA(int i, int j) { // construct values n1 = i; n2 = j; Console.WriteLine("in clssA 'parameterized constructor' invoked"); Console.WriteLine("the invoked values are " + n1 + " and " + n2); Console.WriteLine(); } public virtual void swap() { Console.WriteLine("swap function of base class(clssA) invoked"); Console.WriteLine("Before swap num1 = {0} and num2 = {1}", n1, n2); // swapping int t = n1; n1 = n2; n2 = t; Console.WriteLine("After swap num1 = {0} and num2 = {1}", n1, n2); }} // derived classpublic class DerivedClass : clssA { // This constructor will instantiate // 'clssA' [no argument constructor] // using 'base' keyword public DerivedClass() : base() { } // This constructor will instantiate // 'clssA' [parameterized constructor] // using 'base' keyword public DerivedClass(int i, int j) : base(i, j) { } public override void swap() { // it access the swap function of // 'clssA' using 'base' keyword base.swap(); Console.WriteLine(); Console.WriteLine("Swap function of derived class invoked"); Console.WriteLine("Before swap num1 = {0} and num2 = {1}", n1, n2); // swapping int t = n1; n1 = n2; n2 = t; Console.WriteLine("After swap num1 = {0} and num2 = {1}", n1, n2); } // Main Methodstatic void Main(){ // invoke no argument constructor DerivedClass d1 = new DerivedClass(); Console.WriteLine(); // invoke parameterized constructor DerivedClass d2 = new DerivedClass(10, 20); // calling swap function d2.swap(); }}
Output:
In clssA 'no argument constructor' invoked
in clssA 'parameterized constructor' invoked
the invoked values are 10 and 20
swap function of base class(clssA) invoked
Before swap num1 = 10 and num2 = 20
After swap num1 = 20 and num2 = 10
Swap function of derived class invoked
Before swap num1 = 20 and num2 = 10
After swap num1 = 10 and num2 = 20
Note:
Method overriding is possible only in derived classes. Because a method is overridden in the derived class from the base class.
A non-virtual or a static method can’t be overridden.
Both the override method and the virtual method must have the same access level modifier.
subhasis mohanty
shubham_singh
pinkyratnani
kalrap615
flintjsf
simmytarika5
CSharp-Inheritance
CSharp-method
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C# | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 370,
"s": 52,
"text": "Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. "
},
{
"code": null,
"e": 897,
"s": 370,
"text": "In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the ways by which C# achieve Run Time Polymorphism(Dynamic Polymorphism)."
},
{
"code": null,
"e": 1151,
"s": 897,
"text": "The method that is overridden by an override declaration is called the overridden base method. An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override."
},
{
"code": null,
"e": 1160,
"s": 1151,
"text": "Example:"
},
{
"code": null,
"e": 1370,
"s": 1160,
"text": "class base_class\n{\n public void gfg();\n}\n\nclass derived_class : base_class\n{\n public void gfg();\n}\n\nclass Main_Method\n{\n static void Main()\n {\n derived_class d = new derived_class();\n d.gfg();\n }\n}"
},
{
"code": null,
"e": 1511,
"s": 1370,
"text": "Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden. "
},
{
"code": null,
"e": 1571,
"s": 1511,
"text": "In C# we can use 3 types of keywords for Method Overriding:"
},
{
"code": null,
"e": 1747,
"s": 1571,
"text": "virtual keyword: This modifier or keyword use within base class method. It is used to modify a method in base class for overridden that particular method in the derived class."
},
{
"code": null,
"e": 1912,
"s": 1747,
"text": "override: This modifier or keyword use with derived class method. It is used to modify a virtual or abstract method into derived class which presents in base class."
},
{
"code": null,
"e": 2202,
"s": 1912,
"text": "class base_class\n{\n public virtual void gfg();\n}\n\nclass derived_class : base_class\n{\n public override void gfg();\n}\nclass Main_Method\n{\n static void Main()\n {\n derived_class d = new derived_class();\n d.gfg();\n \n base_class b = new derived_class();\n b.gfg();\n }\n}"
},
{
"code": null,
"e": 2539,
"s": 2202,
"text": "Here first, d refers to the object of the class derived_class and it invokes gfg() of the class derived_class then, b refers to the reference of the class base and it hold the object of class derived and it invokes gfg() of the class derived. Here gfg() method takes permission from base class to overriding the method in derived class."
},
{
"code": null,
"e": 2613,
"s": 2539,
"text": "Example 1: Method Overriding without using virtual and override modifiers"
},
{
"code": null,
"e": 2616,
"s": 2613,
"text": "C#"
},
{
"code": "// C# program to demonstrate the method overriding// without using 'virtual' and 'override' modifiersusing System; // base class name 'baseClass'class baseClass { public void show() { Console.WriteLine(\"Base class\"); }} // derived class name 'derived'// 'baseClass' inherit hereclass derived : baseClass{ // overriding new public void show() { Console.WriteLine(\"Derived class\"); }} class GFG { // Main Method public static void Main() { // 'obj' is the object of // class 'baseClass' baseClass obj = new baseClass(); // invokes the method 'show()' // of class 'baseClass' obj.show(); obj = new derived(); // it also invokes the method // 'show()' of class 'baseClass' obj.show(); }}",
"e": 3480,
"s": 2616,
"text": null
},
{
"code": null,
"e": 3502,
"s": 3480,
"text": "Base class\nBase class"
},
{
"code": null,
"e": 3689,
"s": 3504,
"text": "Explanation: In this program, the object obj invokes class baseClass two times and call the method show() of class baseClass. To avoid this problem we use virtual and override keyword."
},
{
"code": null,
"e": 3756,
"s": 3689,
"text": "Example 2: Method overriding using virtual and override modifiers."
},
{
"code": null,
"e": 3759,
"s": 3756,
"text": "C#"
},
{
"code": "// C# program to illustrate the use of//'virtual' and 'override' modifiersusing System; class baseClass { // show() is 'virtual' here public virtual void show() { Console.WriteLine(\"Base class\"); }} // class 'baseClass' inherit// class 'derived'class derived : baseClass{ //'show()' is 'override' here public override void show() { Console.WriteLine(\"Derived class\"); }} class GFG { // Main Method public static void Main() { baseClass obj; // 'obj' is the object // of class 'baseClass' obj = new baseClass(); // it invokes 'show()' // of class 'baseClass' obj.show(); // the same object 'obj' is now // the object of class 'derived' obj = new derived(); // it invokes 'show()' of class 'derived' // 'show()' of class 'derived' is overridden // for 'override' modifier obj.show(); }}",
"e": 4751,
"s": 3759,
"text": null
},
{
"code": null,
"e": 4776,
"s": 4751,
"text": "Base class\nDerived class"
},
{
"code": null,
"e": 5126,
"s": 4778,
"text": "base Keyword: This is used to access members of the base class from derived class. It basically used to access constructors and methods or functions of the base class. The base keyword cannot use within a static method. Base keyword specifies which constructor of the base class should be invoked while creating the instances of the derived class."
},
{
"code": null,
"e": 5148,
"s": 5126,
"text": "Use of Base keyword: "
},
{
"code": null,
"e": 5208,
"s": 5148,
"text": "Call methods or functions of base class from derived class."
},
{
"code": null,
"e": 5278,
"s": 5208,
"text": "Call constructor internally of base class at the time of inheritance."
},
{
"code": null,
"e": 5289,
"s": 5278,
"text": "Example 1:"
},
{
"code": null,
"e": 5292,
"s": 5289,
"text": "C#"
},
{
"code": "// C# program to show the use of 'base'// keyword in method overridingusing System; // base classpublic class web { string name = \"GeeksForGeeks\"; // 'showdata()' is member method, // declare as virtual public virtual void showdata() { Console.WriteLine(\"Website Name: \" + name); }} // derived class// class 'web' is inherits// class 'stream'class stream : web { string s = \"Computer Science\"; //'showdata()' is overridden // in derived class public override void showdata() { // Calling 'showdata()' of base // class using 'base' keyword base.showdata(); Console.WriteLine(\"About: \" + s); }} class GFG { // Main Method static void Main() { // 'E' is object of class stream // also works as object of // class 'web' stream E = new stream(); // it first invokes 'showdata()' // of class 'web' then it invokes // 'showdata()' of class 'stream' E.showdata(); }}",
"e": 6375,
"s": 5292,
"text": null
},
{
"code": null,
"e": 6427,
"s": 6375,
"text": "Website Name: GeeksForGeeks\nAbout: Computer Science"
},
{
"code": null,
"e": 6566,
"s": 6429,
"text": "Example 2: How base keyword specifies the calling of base-class constructor from derived class when derived class instances are created."
},
{
"code": null,
"e": 6569,
"s": 6566,
"text": "C#"
},
{
"code": "// C# program to show how base keyword// specifies the calling of base-class// constructor from the derived class// when derived class instances are createdusing System; // base classpublic class clssA { int n1, n2; // default constructor public clssA() { Console.WriteLine(\"Default Constructor Invoked\"); } // parameterized constructor public clssA(int i, int j) { // construct values n1 = i; n2 = j; Console.WriteLine(\"Parameterized Constructor Invoked\"); Console.WriteLine(\"Invoked Values are: \" + n1 + \" and \" + n2); }} // derived classpublic class DerivedClass : clssA{ // This constructor will instantiate // 'clssA()' [no argument constructor] // using 'base' keyword public DerivedClass() : base() { } // This constructor will instantiate // 'clssA(int i, int j)' [parameterized // constructor] using 'base' keyword public DerivedClass(int i, int j) : base(i, j) { } // Main Methodstatic void Main(){ // invoke no argument constructor DerivedClass d1 = new DerivedClass(); Console.WriteLine(); // invoke parameterized constructor DerivedClass d2 = new DerivedClass(10, 20); }}",
"e": 7800,
"s": 6569,
"text": null
},
{
"code": null,
"e": 7810,
"s": 7800,
"text": "Output: "
},
{
"code": null,
"e": 7903,
"s": 7810,
"text": "Default Constructor Invoked\n\nParameterized Constructor Invoked\nInvoked Values are: 10 and 20"
},
{
"code": null,
"e": 8079,
"s": 7903,
"text": "Example 3: It shows how base keyword specifies the base-class constructor called from derived class and also calling of a method using the base keyword from the derived class."
},
{
"code": null,
"e": 8082,
"s": 8079,
"text": "C#"
},
{
"code": "// C# program to show how 'base' keyword specifies// the base-class constructor that called from// derived class and also calling a method 'swap'// from derived class using base keywordusing System; // base classpublic class clssA { public int n1, n2; // default constructor public clssA() { Console.WriteLine(\"In clssA 'no argument constructor' invoked\"); } // parameterized constructor public clssA(int i, int j) { // construct values n1 = i; n2 = j; Console.WriteLine(\"in clssA 'parameterized constructor' invoked\"); Console.WriteLine(\"the invoked values are \" + n1 + \" and \" + n2); Console.WriteLine(); } public virtual void swap() { Console.WriteLine(\"swap function of base class(clssA) invoked\"); Console.WriteLine(\"Before swap num1 = {0} and num2 = {1}\", n1, n2); // swapping int t = n1; n1 = n2; n2 = t; Console.WriteLine(\"After swap num1 = {0} and num2 = {1}\", n1, n2); }} // derived classpublic class DerivedClass : clssA { // This constructor will instantiate // 'clssA' [no argument constructor] // using 'base' keyword public DerivedClass() : base() { } // This constructor will instantiate // 'clssA' [parameterized constructor] // using 'base' keyword public DerivedClass(int i, int j) : base(i, j) { } public override void swap() { // it access the swap function of // 'clssA' using 'base' keyword base.swap(); Console.WriteLine(); Console.WriteLine(\"Swap function of derived class invoked\"); Console.WriteLine(\"Before swap num1 = {0} and num2 = {1}\", n1, n2); // swapping int t = n1; n1 = n2; n2 = t; Console.WriteLine(\"After swap num1 = {0} and num2 = {1}\", n1, n2); } // Main Methodstatic void Main(){ // invoke no argument constructor DerivedClass d1 = new DerivedClass(); Console.WriteLine(); // invoke parameterized constructor DerivedClass d2 = new DerivedClass(10, 20); // calling swap function d2.swap(); }}",
"e": 10245,
"s": 8082,
"text": null
},
{
"code": null,
"e": 10254,
"s": 10245,
"text": "Output: "
},
{
"code": null,
"e": 10602,
"s": 10254,
"text": "In clssA 'no argument constructor' invoked\n\nin clssA 'parameterized constructor' invoked\nthe invoked values are 10 and 20\n\nswap function of base class(clssA) invoked\nBefore swap num1 = 10 and num2 = 20\nAfter swap num1 = 20 and num2 = 10\n\nSwap function of derived class invoked\nBefore swap num1 = 20 and num2 = 10\nAfter swap num1 = 10 and num2 = 20"
},
{
"code": null,
"e": 10608,
"s": 10602,
"text": "Note:"
},
{
"code": null,
"e": 10736,
"s": 10608,
"text": "Method overriding is possible only in derived classes. Because a method is overridden in the derived class from the base class."
},
{
"code": null,
"e": 10790,
"s": 10736,
"text": "A non-virtual or a static method can’t be overridden."
},
{
"code": null,
"e": 10880,
"s": 10790,
"text": "Both the override method and the virtual method must have the same access level modifier."
},
{
"code": null,
"e": 10899,
"s": 10882,
"text": "subhasis mohanty"
},
{
"code": null,
"e": 10913,
"s": 10899,
"text": "shubham_singh"
},
{
"code": null,
"e": 10926,
"s": 10913,
"text": "pinkyratnani"
},
{
"code": null,
"e": 10936,
"s": 10926,
"text": "kalrap615"
},
{
"code": null,
"e": 10945,
"s": 10936,
"text": "flintjsf"
},
{
"code": null,
"e": 10958,
"s": 10945,
"text": "simmytarika5"
},
{
"code": null,
"e": 10977,
"s": 10958,
"text": "CSharp-Inheritance"
},
{
"code": null,
"e": 10991,
"s": 10977,
"text": "CSharp-method"
},
{
"code": null,
"e": 11002,
"s": 10991,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 11005,
"s": 11002,
"text": "C#"
},
{
"code": null,
"e": 11103,
"s": 11005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11157,
"s": 11103,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 11219,
"s": 11157,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 11242,
"s": 11219,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 11270,
"s": 11242,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 11312,
"s": 11270,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 11327,
"s": 11312,
"text": "C# | Delegates"
},
{
"code": null,
"e": 11370,
"s": 11327,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 11419,
"s": 11370,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 11459,
"s": 11419,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
Python | Pandas Series.last_valid_index() | 11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.last_valid_index() function return index for the last non-NA/null value in the given series object.
Syntax: Series.last_valid_index()
Parameter : None
Returns : scalar
Example #1: Use Series.last_valid_index() function to return the last valid index of the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.last_valid_index() function to return the last valid index of the given series object.
# return the last valid indexresult = sr.last_valid_index() # Print the resultprint(result)
Output :
As we can see in the output, the Series.last_valid_index() function has returned the last valid index in the given series object. Example #2: Use Series.last_valid_index() function to return the last valid index of the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, None, None]) # Print the seriesprint(sr)
Output :
Now we will use Series.last_valid_index() function to return the last valid index of the given series object.
# return the last valid indexresult = sr.last_valid_index() # Print the resultprint(result)
Output :As we can see in the output, the Series.last_valid_index() function has returned the last valid index in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 399,
"s": 285,
"text": "Pandas Series.last_valid_index() function return index for the last non-NA/null value in the given series object."
},
{
"code": null,
"e": 433,
"s": 399,
"text": "Syntax: Series.last_valid_index()"
},
{
"code": null,
"e": 450,
"s": 433,
"text": "Parameter : None"
},
{
"code": null,
"e": 467,
"s": 450,
"text": "Returns : scalar"
},
{
"code": null,
"e": 577,
"s": 467,
"text": "Example #1: Use Series.last_valid_index() function to return the last valid index of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 850,
"s": 577,
"text": null
},
{
"code": null,
"e": 859,
"s": 850,
"text": "Output :"
},
{
"code": null,
"e": 969,
"s": 859,
"text": "Now we will use Series.last_valid_index() function to return the last valid index of the given series object."
},
{
"code": "# return the last valid indexresult = sr.last_valid_index() # Print the resultprint(result)",
"e": 1062,
"s": 969,
"text": null
},
{
"code": null,
"e": 1071,
"s": 1062,
"text": "Output :"
},
{
"code": null,
"e": 1311,
"s": 1071,
"text": "As we can see in the output, the Series.last_valid_index() function has returned the last valid index in the given series object. Example #2: Use Series.last_valid_index() function to return the last valid index of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, None, None]) # Print the seriesprint(sr)",
"e": 1480,
"s": 1311,
"text": null
},
{
"code": null,
"e": 1489,
"s": 1480,
"text": "Output :"
},
{
"code": null,
"e": 1599,
"s": 1489,
"text": "Now we will use Series.last_valid_index() function to return the last valid index of the given series object."
},
{
"code": "# return the last valid indexresult = sr.last_valid_index() # Print the resultprint(result)",
"e": 1692,
"s": 1599,
"text": null
},
{
"code": null,
"e": 1830,
"s": 1692,
"text": "Output :As we can see in the output, the Series.last_valid_index() function has returned the last valid index in the given series object."
},
{
"code": null,
"e": 1851,
"s": 1830,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1880,
"s": 1851,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1894,
"s": 1880,
"text": "Python-pandas"
},
{
"code": null,
"e": 1901,
"s": 1894,
"text": "Python"
},
{
"code": null,
"e": 1999,
"s": 1901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2041,
"s": 1999,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2063,
"s": 2041,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2095,
"s": 2063,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2124,
"s": 2095,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2151,
"s": 2124,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2187,
"s": 2151,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2208,
"s": 2187,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2239,
"s": 2208,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2295,
"s": 2239,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Python | Sort given list of dictionaries by date | 11 May, 2020
Given a list of dictionary, the task is to sort the dictionary by date. Let’s see a few methods to solve the task.
Method #1: Using naive approach
# Python code to demonstrate# sort a list of dictionary# where value date is in string # Initialising list of dictionaryini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial listprint ("initial list : ", str(ini_list)) # code to sort list on dateini_list.sort(key = lambda x:x['d.o.b']) # printing final listprint ("result", str(ini_list))
initial list : [{‘name’: ‘akash’, ‘d.o.b’: ‘1997-03-02’}, {‘name’: ‘manjeet’, ‘d.o.b’: ‘1997-01-04’}, {‘name’: ‘nikhil’, ‘d.o.b’: ‘1997-09-13’}]
result [{‘name’: ‘manjeet’, ‘d.o.b’: ‘1997-01-04’}, {‘name’: ‘akash’, ‘d.o.b’: ‘1997-03-02’}, {‘name’: ‘nikhil’, ‘d.o.b’: ‘1997-09-13’}]
Method #2: Using datetime.strptime and lambda
# Python code to demonstrate# sort a list of dictionary# where value date is in a string from datetime import datetime # Initialising list of dictionaryini_list = [{'name':'akshat', 'd.o.b':'1997-09-01'}, {'name':'vashu', 'd.o.b':'1997-08-19'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial listprint ("initial list : ", str(ini_list)) # code to sort list on dateini_list.sort(key = lambda x: datetime.strptime(x['d.o.b'], '%Y-%m-%d')) # printing final listprint ("result", str(ini_list))
initial list : [{‘d.o.b’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘d.o.b’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]
result [{‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘d.o.b’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]
Method #3: Using operator.itemgetter
# Python code to demonstrate# sort a list of dictionary# where value date is in string import operator # Initialising list of dictionaryini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial listprint ("initial list : ", str(ini_list)) # code to sort list on dateini_list.sort(key = operator.itemgetter('d.o.b')) # printing final listprint ("result", str(ini_list))
initial list : [{‘d.o.b’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]
result [{‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]
Python dictionary-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "Given a list of dictionary, the task is to sort the dictionary by date. Let’s see a few methods to solve the task."
},
{
"code": null,
"e": 175,
"s": 143,
"text": "Method #1: Using naive approach"
},
{
"code": "# Python code to demonstrate# sort a list of dictionary# where value date is in string # Initialising list of dictionaryini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial listprint (\"initial list : \", str(ini_list)) # code to sort list on dateini_list.sort(key = lambda x:x['d.o.b']) # printing final listprint (\"result\", str(ini_list))",
"e": 658,
"s": 175,
"text": null
},
{
"code": null,
"e": 803,
"s": 658,
"text": "initial list : [{‘name’: ‘akash’, ‘d.o.b’: ‘1997-03-02’}, {‘name’: ‘manjeet’, ‘d.o.b’: ‘1997-01-04’}, {‘name’: ‘nikhil’, ‘d.o.b’: ‘1997-09-13’}]"
},
{
"code": null,
"e": 940,
"s": 803,
"text": "result [{‘name’: ‘manjeet’, ‘d.o.b’: ‘1997-01-04’}, {‘name’: ‘akash’, ‘d.o.b’: ‘1997-03-02’}, {‘name’: ‘nikhil’, ‘d.o.b’: ‘1997-09-13’}]"
},
{
"code": null,
"e": 986,
"s": 940,
"text": "Method #2: Using datetime.strptime and lambda"
},
{
"code": "# Python code to demonstrate# sort a list of dictionary# where value date is in a string from datetime import datetime # Initialising list of dictionaryini_list = [{'name':'akshat', 'd.o.b':'1997-09-01'}, {'name':'vashu', 'd.o.b':'1997-08-19'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial listprint (\"initial list : \", str(ini_list)) # code to sort list on dateini_list.sort(key = lambda x: datetime.strptime(x['d.o.b'], '%Y-%m-%d')) # printing final listprint (\"result\", str(ini_list))",
"e": 1585,
"s": 986,
"text": null
},
{
"code": null,
"e": 1773,
"s": 1585,
"text": "initial list : [{‘d.o.b’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘d.o.b’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]"
},
{
"code": null,
"e": 1953,
"s": 1773,
"text": "result [{‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘d.o.b’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]"
},
{
"code": null,
"e": 1991,
"s": 1953,
"text": " Method #3: Using operator.itemgetter"
},
{
"code": "# Python code to demonstrate# sort a list of dictionary# where value date is in string import operator # Initialising list of dictionaryini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial listprint (\"initial list : \", str(ini_list)) # code to sort list on dateini_list.sort(key = operator.itemgetter('d.o.b')) # printing final listprint (\"result\", str(ini_list))",
"e": 2499,
"s": 1991,
"text": null
},
{
"code": null,
"e": 2644,
"s": 2499,
"text": "initial list : [{‘d.o.b’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]"
},
{
"code": null,
"e": 2781,
"s": 2644,
"text": "result [{‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]"
},
{
"code": null,
"e": 2808,
"s": 2781,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2820,
"s": 2808,
"text": "Python-sort"
},
{
"code": null,
"e": 2827,
"s": 2820,
"text": "Python"
},
{
"code": null,
"e": 2843,
"s": 2827,
"text": "Python Programs"
},
{
"code": null,
"e": 2941,
"s": 2843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2959,
"s": 2941,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2981,
"s": 2959,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3023,
"s": 2981,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3058,
"s": 3023,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3090,
"s": 3058,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3133,
"s": 3090,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3155,
"s": 3133,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3194,
"s": 3155,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3232,
"s": 3194,
"text": "Python | Convert a list to dictionary"
}
] |
TCS Placement Paper | MCQ 8 | 21 May, 2019
This is a TCS model placement paper for aptitude preparation. This placement paper will cover aptitude questions that are asked in TCS recruitment drives and also strictly follows the pattern of questions asked in TCS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the TCS interview.
Identify the missing number in the series: 2, 5, __, 19, 37, 75?a) 16b) 12c) 10d) 9Answer: d) 9Solution:2 * 2 + 1 = 55 * 2 – 1 = 99 * 2 + 1 = 1919 * 2 – 1 = 37 and so onA rectangle is divided into four rectangles with area 70, 36, 20, and x. What is the value of ‘x’?a) 350/7b) 350/11c) 350/9d) 350/13
Video Player is loading.Play VideoPlayMuteCurrent Time 0:00/Duration 0:00Loaded: 0%0:00Stream Type LIVESeek to live, currently behind liveLIVERemaining Time -0:00 1xPlayback RateChaptersChaptersDescriptionsdescriptions off, selectedCaptionscaptions settings, opens captions settings dialogcaptions off, selectedEnglishAudio TrackPicture-in-PictureFullscreenThis is a modal window.The media could not be loaded, either because the server or network failed or because the format is not supported.Beginning of dialog window. Escape will cancel and close the window.TextColorWhiteBlackRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentBackgroundColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentTransparentWindowColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyTransparentSemi-TransparentOpaqueFont Size50%75%100%125%150%175%200%300%400%Text Edge StyleNoneRaisedDepressedUniformDropshadowFont FamilyProportional Sans-SerifMonospace Sans-SerifProportional SerifMonospace SerifCasualScriptSmall CapsReset restore all settings to the default valuesDoneClose Modal DialogEnd of dialog window.Answer: c) 350/9Solution:Since the areas of the rectangles are in proportion we can say,=> 70/x = 36/20=> x = 350/9If VXUPLVH is written as SURMISE, what is SHDVD written as?a) PEASAb) PBASAc) PEBSBd) None of the aboveAnswer: a) PEASASolution:It is a question of coding-decoding where,V is written as S (V – 3 = S)X is written as U (X – 3 = U)and so on.Similarly, SHDVD will be written as PEASAAman owes Bipul Rs 50. He agrees to pay Bipul over a number of the consecutive day starting on Monday, paying a single note of Rs 10 or Rs 20 on each day. In how many different ways can Aman repay Bipul. (Two ways are said to be different if at least one day, a note of a different denomination is given)a) 5b) 6c) 7d) 8Answer: d) 8Solution:Aman can pay Bipul in all 10 rupees note in 5 days = 5 * 10 = 50 rupees = 1 wayAman can pay Bipul in 3 ten rupee note and 1 twenty rupee note = 4!/(3! * 1!) = 4 waysAman can pay Bipul in 1 ten rupee note and 2 twenty rupee note = 3!/(1! * 2!) = 3 waysSo in all Aman can pay Bipul in 8 ways.Salim bought a certain number of oranges at a rate of 27 oranges for rupees 2 times M, where M is an integer. He divided these oranges into two equal halves, one part of which he sold at the rate of 13 oranges for Rs M and the other at the rate of 14 oranges for Rs M. He spent and received an integral no of rupees, but bought the least number of oranges. How many did he buy?a) 980b) 9828c) 1880d) 102660Answer: b) 9828Solution:Let Salim buy 2x number of oranges.So he buys 27 oranges at a price of 2M.He buys 1 orange at a price of 2M/27or, x oranges cost him Rs. 2Mx/27Now he sells x oranges at the rate of 13 oranges for Rs. MSo he sells 1 orange at Rs. M/13and x oranges at Rs Mx/13Same goes for 14 oranges which are Mx/14,According to the question, 2Mx/27, Mx/13, Mx/14 are integersSo, x oranges must be divisible by 27, 13 and 14The lcm of 27, 13 and 14 = 4914 or 2x = 9828In a football match, 16 teams participate and are divided into 4 groups. Every team from each group will play with each other once. The top 2 winning teams will move to the next round and so on the top two teams will play the final match. So how many minimum matches will be played in that tournament?a) 40b) 14c) 43d) 50Answer: c) 43Solution:Total matches to be played = 4C2 = 6 matches.So total number of matches played in the first round = 6 * 4 = 24 matchesNow top two teams from each group progress to the next round. These 8 teams are to be divided into 2 groups.Total matches played in the second round = 6 × 2 = 12 matchesNow 4 teams progress to the next round. Total matches played in the third round = 6 * 1 = 6matchesFrom this round, 2 teams progress to the next round. And final will be played between them.Total matches = 24 + 12 + 6 + 1 = 43There are 12 letters and exactly 12 envelopes. There is one letter to be inserted randomly into each envelope. What is the probability that exactly 1 letter is inserted in an improper envelope?a) 1b) 0c) 10!d) None of theseAnswer: b) 0Solution:This is a question of very common sense in which,12 letters are to be inserted in 12 envelopes, 1 in each, so if one letter is inserted into a wrong envelope there has to be another letter which is to be inserted into another wrong envelope. So the probability of this is 0.A hollow space on the earth surface is to be filled. The total cost of filling is Rs. 20000. The cost of filling per cubic-meter is Rs 225. How many times is a size of 3 cubic-meter soil required to fill the hollow space?a) 29.62b) 30.32c) 88.88d) 43.64Answer: a) 29.62Solution:The total cost of filling = 20, 000Cost of filling 1 cubic meter = Rs. 225So cubic meters to be filled = 20, 000/225 = 88.89 meter-cubeNow we need to find the three times of 88.89 to be filled = 88.89/3 = 29.63So the closest match is 29.62A 7-digit number is to be formed with all different digits. If the digits at the extreme right and extreme left are fixed to 5 and 6 respectively, find how many such numbers can be formed?a) 120b) 30240c) 6720d) None of theseAnswer: c) 6720Solution:If the digits at extreme left and right are fixed as 5 and 6, then the number of digits left = 8So the in-between 5 places can be filled in 8 * 7 * 6 * 5 * 4 ways= 6720 waysThere are five tires in a sedan (four road tires and one spare) which is to be used equally in a journey to travel 40, 000 km. The number of km of use of each tyre wasa) 32000b) 8000c) 4000d) 10000Answer: a) 32000Solution:The total km travelled by the sedan = 40, 000 kmSince every tire capacity’s = 40, 000/5 = 8000 km eachSo total distance covered by each tire = 8000*4 = 32000 km each will be travelled by each tire after being worn out after every 8000 km.My Personal Notes
arrow_drop_upSave
Identify the missing number in the series: 2, 5, __, 19, 37, 75?a) 16b) 12c) 10d) 9Answer: d) 9Solution:2 * 2 + 1 = 55 * 2 – 1 = 99 * 2 + 1 = 1919 * 2 – 1 = 37 and so on
Answer: d) 9
Solution:2 * 2 + 1 = 55 * 2 – 1 = 99 * 2 + 1 = 1919 * 2 – 1 = 37 and so on
A rectangle is divided into four rectangles with area 70, 36, 20, and x. What is the value of ‘x’?a) 350/7b) 350/11c) 350/9d) 350/13
Video Player is loading.Play VideoPlayMuteCurrent Time 0:00/Duration 0:00Loaded: 0%0:00Stream Type LIVESeek to live, currently behind liveLIVERemaining Time -0:00 1xPlayback RateChaptersChaptersDescriptionsdescriptions off, selectedCaptionscaptions settings, opens captions settings dialogcaptions off, selectedEnglishAudio TrackPicture-in-PictureFullscreenThis is a modal window.The media could not be loaded, either because the server or network failed or because the format is not supported.Beginning of dialog window. Escape will cancel and close the window.TextColorWhiteBlackRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentBackgroundColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentTransparentWindowColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyTransparentSemi-TransparentOpaqueFont Size50%75%100%125%150%175%200%300%400%Text Edge StyleNoneRaisedDepressedUniformDropshadowFont FamilyProportional Sans-SerifMonospace Sans-SerifProportional SerifMonospace SerifCasualScriptSmall CapsReset restore all settings to the default valuesDoneClose Modal DialogEnd of dialog window.Answer: c) 350/9Solution:Since the areas of the rectangles are in proportion we can say,=> 70/x = 36/20=> x = 350/9
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.
Answer: c) 350/9
Solution:Since the areas of the rectangles are in proportion we can say,=> 70/x = 36/20=> x = 350/9
If VXUPLVH is written as SURMISE, what is SHDVD written as?a) PEASAb) PBASAc) PEBSBd) None of the aboveAnswer: a) PEASASolution:It is a question of coding-decoding where,V is written as S (V – 3 = S)X is written as U (X – 3 = U)and so on.Similarly, SHDVD will be written as PEASA
Answer: a) PEASA
Solution:It is a question of coding-decoding where,V is written as S (V – 3 = S)X is written as U (X – 3 = U)and so on.Similarly, SHDVD will be written as PEASA
Aman owes Bipul Rs 50. He agrees to pay Bipul over a number of the consecutive day starting on Monday, paying a single note of Rs 10 or Rs 20 on each day. In how many different ways can Aman repay Bipul. (Two ways are said to be different if at least one day, a note of a different denomination is given)a) 5b) 6c) 7d) 8Answer: d) 8Solution:Aman can pay Bipul in all 10 rupees note in 5 days = 5 * 10 = 50 rupees = 1 wayAman can pay Bipul in 3 ten rupee note and 1 twenty rupee note = 4!/(3! * 1!) = 4 waysAman can pay Bipul in 1 ten rupee note and 2 twenty rupee note = 3!/(1! * 2!) = 3 waysSo in all Aman can pay Bipul in 8 ways.
Answer: d) 8
Solution:Aman can pay Bipul in all 10 rupees note in 5 days = 5 * 10 = 50 rupees = 1 wayAman can pay Bipul in 3 ten rupee note and 1 twenty rupee note = 4!/(3! * 1!) = 4 waysAman can pay Bipul in 1 ten rupee note and 2 twenty rupee note = 3!/(1! * 2!) = 3 waysSo in all Aman can pay Bipul in 8 ways.
Salim bought a certain number of oranges at a rate of 27 oranges for rupees 2 times M, where M is an integer. He divided these oranges into two equal halves, one part of which he sold at the rate of 13 oranges for Rs M and the other at the rate of 14 oranges for Rs M. He spent and received an integral no of rupees, but bought the least number of oranges. How many did he buy?a) 980b) 9828c) 1880d) 102660Answer: b) 9828Solution:Let Salim buy 2x number of oranges.So he buys 27 oranges at a price of 2M.He buys 1 orange at a price of 2M/27or, x oranges cost him Rs. 2Mx/27Now he sells x oranges at the rate of 13 oranges for Rs. MSo he sells 1 orange at Rs. M/13and x oranges at Rs Mx/13Same goes for 14 oranges which are Mx/14,According to the question, 2Mx/27, Mx/13, Mx/14 are integersSo, x oranges must be divisible by 27, 13 and 14The lcm of 27, 13 and 14 = 4914 or 2x = 9828
Answer: b) 9828
Solution:Let Salim buy 2x number of oranges.So he buys 27 oranges at a price of 2M.He buys 1 orange at a price of 2M/27or, x oranges cost him Rs. 2Mx/27Now he sells x oranges at the rate of 13 oranges for Rs. MSo he sells 1 orange at Rs. M/13and x oranges at Rs Mx/13Same goes for 14 oranges which are Mx/14,According to the question, 2Mx/27, Mx/13, Mx/14 are integersSo, x oranges must be divisible by 27, 13 and 14The lcm of 27, 13 and 14 = 4914 or 2x = 9828
In a football match, 16 teams participate and are divided into 4 groups. Every team from each group will play with each other once. The top 2 winning teams will move to the next round and so on the top two teams will play the final match. So how many minimum matches will be played in that tournament?a) 40b) 14c) 43d) 50Answer: c) 43Solution:Total matches to be played = 4C2 = 6 matches.So total number of matches played in the first round = 6 * 4 = 24 matchesNow top two teams from each group progress to the next round. These 8 teams are to be divided into 2 groups.Total matches played in the second round = 6 × 2 = 12 matchesNow 4 teams progress to the next round. Total matches played in the third round = 6 * 1 = 6matchesFrom this round, 2 teams progress to the next round. And final will be played between them.Total matches = 24 + 12 + 6 + 1 = 43
Answer: c) 43
Solution:Total matches to be played = 4C2 = 6 matches.So total number of matches played in the first round = 6 * 4 = 24 matchesNow top two teams from each group progress to the next round. These 8 teams are to be divided into 2 groups.Total matches played in the second round = 6 × 2 = 12 matchesNow 4 teams progress to the next round. Total matches played in the third round = 6 * 1 = 6matchesFrom this round, 2 teams progress to the next round. And final will be played between them.Total matches = 24 + 12 + 6 + 1 = 43
There are 12 letters and exactly 12 envelopes. There is one letter to be inserted randomly into each envelope. What is the probability that exactly 1 letter is inserted in an improper envelope?a) 1b) 0c) 10!d) None of theseAnswer: b) 0Solution:This is a question of very common sense in which,12 letters are to be inserted in 12 envelopes, 1 in each, so if one letter is inserted into a wrong envelope there has to be another letter which is to be inserted into another wrong envelope. So the probability of this is 0.
Answer: b) 0
Solution:This is a question of very common sense in which,12 letters are to be inserted in 12 envelopes, 1 in each, so if one letter is inserted into a wrong envelope there has to be another letter which is to be inserted into another wrong envelope. So the probability of this is 0.
A hollow space on the earth surface is to be filled. The total cost of filling is Rs. 20000. The cost of filling per cubic-meter is Rs 225. How many times is a size of 3 cubic-meter soil required to fill the hollow space?a) 29.62b) 30.32c) 88.88d) 43.64Answer: a) 29.62Solution:The total cost of filling = 20, 000Cost of filling 1 cubic meter = Rs. 225So cubic meters to be filled = 20, 000/225 = 88.89 meter-cubeNow we need to find the three times of 88.89 to be filled = 88.89/3 = 29.63So the closest match is 29.62
Answer: a) 29.62
Solution:The total cost of filling = 20, 000Cost of filling 1 cubic meter = Rs. 225So cubic meters to be filled = 20, 000/225 = 88.89 meter-cubeNow we need to find the three times of 88.89 to be filled = 88.89/3 = 29.63So the closest match is 29.62
A 7-digit number is to be formed with all different digits. If the digits at the extreme right and extreme left are fixed to 5 and 6 respectively, find how many such numbers can be formed?a) 120b) 30240c) 6720d) None of theseAnswer: c) 6720Solution:If the digits at extreme left and right are fixed as 5 and 6, then the number of digits left = 8So the in-between 5 places can be filled in 8 * 7 * 6 * 5 * 4 ways= 6720 ways
Answer: c) 6720
Solution:If the digits at extreme left and right are fixed as 5 and 6, then the number of digits left = 8So the in-between 5 places can be filled in 8 * 7 * 6 * 5 * 4 ways= 6720 ways
There are five tires in a sedan (four road tires and one spare) which is to be used equally in a journey to travel 40, 000 km. The number of km of use of each tyre wasa) 32000b) 8000c) 4000d) 10000Answer: a) 32000Solution:The total km travelled by the sedan = 40, 000 kmSince every tire capacity’s = 40, 000/5 = 8000 km eachSo total distance covered by each tire = 8000*4 = 32000 km each will be travelled by each tire after being worn out after every 8000 km.
Answer: a) 32000
Solution:The total km travelled by the sedan = 40, 000 kmSince every tire capacity’s = 40, 000/5 = 8000 km eachSo total distance covered by each tire = 8000*4 = 32000 km each will be travelled by each tire after being worn out after every 8000 km.
interview-preparation
placement preparation
TCS
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 20 Puzzles Commonly Asked During SDE Interviews
Programming Language For Placement - C++, Java or Python?
Cognizant Placement Paper | Aptitude Set 1
Permutation and Combination
Time Speed Distance
Interview Preparation
Progressions (AP, GP, HP)
Print the longest path from root to leaf in a Binary tree
Problem on Numbers
TCS Ninja Interview Experience and Interview Questions | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 403,
"s": 54,
"text": "This is a TCS model placement paper for aptitude preparation. This placement paper will cover aptitude questions that are asked in TCS recruitment drives and also strictly follows the pattern of questions asked in TCS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the TCS interview."
},
{
"code": null,
"e": 6551,
"s": 403,
"text": "Identify the missing number in the series: 2, 5, __, 19, 37, 75?a) 16b) 12c) 10d) 9Answer: d) 9Solution:2 * 2 + 1 = 55 * 2 – 1 = 99 * 2 + 1 = 1919 * 2 – 1 = 37 and so onA rectangle is divided into four rectangles with area 70, 36, 20, and x. What is the value of ‘x’?a) 350/7b) 350/11c) 350/9d) 350/13\nVideo Player is loading.Play VideoPlayMuteCurrent Time 0:00/Duration 0:00Loaded: 0%0:00Stream Type LIVESeek to live, currently behind liveLIVERemaining Time -0:00 1xPlayback RateChaptersChaptersDescriptionsdescriptions off, selectedCaptionscaptions settings, opens captions settings dialogcaptions off, selectedEnglishAudio TrackPicture-in-PictureFullscreenThis is a modal window.The media could not be loaded, either because the server or network failed or because the format is not supported.Beginning of dialog window. Escape will cancel and close the window.TextColorWhiteBlackRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentBackgroundColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentTransparentWindowColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyTransparentSemi-TransparentOpaqueFont Size50%75%100%125%150%175%200%300%400%Text Edge StyleNoneRaisedDepressedUniformDropshadowFont FamilyProportional Sans-SerifMonospace Sans-SerifProportional SerifMonospace SerifCasualScriptSmall CapsReset restore all settings to the default valuesDoneClose Modal DialogEnd of dialog window.Answer: c) 350/9Solution:Since the areas of the rectangles are in proportion we can say,=> 70/x = 36/20=> x = 350/9If VXUPLVH is written as SURMISE, what is SHDVD written as?a) PEASAb) PBASAc) PEBSBd) None of the aboveAnswer: a) PEASASolution:It is a question of coding-decoding where,V is written as S (V – 3 = S)X is written as U (X – 3 = U)and so on.Similarly, SHDVD will be written as PEASAAman owes Bipul Rs 50. He agrees to pay Bipul over a number of the consecutive day starting on Monday, paying a single note of Rs 10 or Rs 20 on each day. In how many different ways can Aman repay Bipul. (Two ways are said to be different if at least one day, a note of a different denomination is given)a) 5b) 6c) 7d) 8Answer: d) 8Solution:Aman can pay Bipul in all 10 rupees note in 5 days = 5 * 10 = 50 rupees = 1 wayAman can pay Bipul in 3 ten rupee note and 1 twenty rupee note = 4!/(3! * 1!) = 4 waysAman can pay Bipul in 1 ten rupee note and 2 twenty rupee note = 3!/(1! * 2!) = 3 waysSo in all Aman can pay Bipul in 8 ways.Salim bought a certain number of oranges at a rate of 27 oranges for rupees 2 times M, where M is an integer. He divided these oranges into two equal halves, one part of which he sold at the rate of 13 oranges for Rs M and the other at the rate of 14 oranges for Rs M. He spent and received an integral no of rupees, but bought the least number of oranges. How many did he buy?a) 980b) 9828c) 1880d) 102660Answer: b) 9828Solution:Let Salim buy 2x number of oranges.So he buys 27 oranges at a price of 2M.He buys 1 orange at a price of 2M/27or, x oranges cost him Rs. 2Mx/27Now he sells x oranges at the rate of 13 oranges for Rs. MSo he sells 1 orange at Rs. M/13and x oranges at Rs Mx/13Same goes for 14 oranges which are Mx/14,According to the question, 2Mx/27, Mx/13, Mx/14 are integersSo, x oranges must be divisible by 27, 13 and 14The lcm of 27, 13 and 14 = 4914 or 2x = 9828In a football match, 16 teams participate and are divided into 4 groups. Every team from each group will play with each other once. The top 2 winning teams will move to the next round and so on the top two teams will play the final match. So how many minimum matches will be played in that tournament?a) 40b) 14c) 43d) 50Answer: c) 43Solution:Total matches to be played = 4C2 = 6 matches.So total number of matches played in the first round = 6 * 4 = 24 matchesNow top two teams from each group progress to the next round. These 8 teams are to be divided into 2 groups.Total matches played in the second round = 6 × 2 = 12 matchesNow 4 teams progress to the next round. Total matches played in the third round = 6 * 1 = 6matchesFrom this round, 2 teams progress to the next round. And final will be played between them.Total matches = 24 + 12 + 6 + 1 = 43There are 12 letters and exactly 12 envelopes. There is one letter to be inserted randomly into each envelope. What is the probability that exactly 1 letter is inserted in an improper envelope?a) 1b) 0c) 10!d) None of theseAnswer: b) 0Solution:This is a question of very common sense in which,12 letters are to be inserted in 12 envelopes, 1 in each, so if one letter is inserted into a wrong envelope there has to be another letter which is to be inserted into another wrong envelope. So the probability of this is 0.A hollow space on the earth surface is to be filled. The total cost of filling is Rs. 20000. The cost of filling per cubic-meter is Rs 225. How many times is a size of 3 cubic-meter soil required to fill the hollow space?a) 29.62b) 30.32c) 88.88d) 43.64Answer: a) 29.62Solution:The total cost of filling = 20, 000Cost of filling 1 cubic meter = Rs. 225So cubic meters to be filled = 20, 000/225 = 88.89 meter-cubeNow we need to find the three times of 88.89 to be filled = 88.89/3 = 29.63So the closest match is 29.62A 7-digit number is to be formed with all different digits. If the digits at the extreme right and extreme left are fixed to 5 and 6 respectively, find how many such numbers can be formed?a) 120b) 30240c) 6720d) None of theseAnswer: c) 6720Solution:If the digits at extreme left and right are fixed as 5 and 6, then the number of digits left = 8So the in-between 5 places can be filled in 8 * 7 * 6 * 5 * 4 ways= 6720 waysThere are five tires in a sedan (four road tires and one spare) which is to be used equally in a journey to travel 40, 000 km. The number of km of use of each tyre wasa) 32000b) 8000c) 4000d) 10000Answer: a) 32000Solution:The total km travelled by the sedan = 40, 000 kmSince every tire capacity’s = 40, 000/5 = 8000 km eachSo total distance covered by each tire = 8000*4 = 32000 km each will be travelled by each tire after being worn out after every 8000 km.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 6721,
"s": 6551,
"text": "Identify the missing number in the series: 2, 5, __, 19, 37, 75?a) 16b) 12c) 10d) 9Answer: d) 9Solution:2 * 2 + 1 = 55 * 2 – 1 = 99 * 2 + 1 = 1919 * 2 – 1 = 37 and so on"
},
{
"code": null,
"e": 6734,
"s": 6721,
"text": "Answer: d) 9"
},
{
"code": null,
"e": 6809,
"s": 6734,
"text": "Solution:2 * 2 + 1 = 55 * 2 – 1 = 99 * 2 + 1 = 1919 * 2 – 1 = 37 and so on"
},
{
"code": null,
"e": 8190,
"s": 6809,
"text": "A rectangle is divided into four rectangles with area 70, 36, 20, and x. What is the value of ‘x’?a) 350/7b) 350/11c) 350/9d) 350/13\nVideo Player is loading.Play VideoPlayMuteCurrent Time 0:00/Duration 0:00Loaded: 0%0:00Stream Type LIVESeek to live, currently behind liveLIVERemaining Time -0:00 1xPlayback RateChaptersChaptersDescriptionsdescriptions off, selectedCaptionscaptions settings, opens captions settings dialogcaptions off, selectedEnglishAudio TrackPicture-in-PictureFullscreenThis is a modal window.The media could not be loaded, either because the server or network failed or because the format is not supported.Beginning of dialog window. Escape will cancel and close the window.TextColorWhiteBlackRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentBackgroundColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyOpaqueSemi-TransparentTransparentWindowColorBlackWhiteRedGreenBlueYellowMagentaCyanTransparencyTransparentSemi-TransparentOpaqueFont Size50%75%100%125%150%175%200%300%400%Text Edge StyleNoneRaisedDepressedUniformDropshadowFont FamilyProportional Sans-SerifMonospace Sans-SerifProportional SerifMonospace SerifCasualScriptSmall CapsReset restore all settings to the default valuesDoneClose Modal DialogEnd of dialog window.Answer: c) 350/9Solution:Since the areas of the rectangles are in proportion we can say,=> 70/x = 36/20=> x = 350/9"
},
{
"code": null,
"e": 8199,
"s": 8190,
"text": "Chapters"
},
{
"code": null,
"e": 8226,
"s": 8199,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 8276,
"s": 8226,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 8299,
"s": 8276,
"text": "captions off, selected"
},
{
"code": null,
"e": 8307,
"s": 8299,
"text": "English"
},
{
"code": null,
"e": 8331,
"s": 8307,
"text": "This is a modal window."
},
{
"code": null,
"e": 8400,
"s": 8331,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 8422,
"s": 8400,
"text": "End of dialog window."
},
{
"code": null,
"e": 8439,
"s": 8422,
"text": "Answer: c) 350/9"
},
{
"code": null,
"e": 8539,
"s": 8439,
"text": "Solution:Since the areas of the rectangles are in proportion we can say,=> 70/x = 36/20=> x = 350/9"
},
{
"code": null,
"e": 8819,
"s": 8539,
"text": "If VXUPLVH is written as SURMISE, what is SHDVD written as?a) PEASAb) PBASAc) PEBSBd) None of the aboveAnswer: a) PEASASolution:It is a question of coding-decoding where,V is written as S (V – 3 = S)X is written as U (X – 3 = U)and so on.Similarly, SHDVD will be written as PEASA"
},
{
"code": null,
"e": 8836,
"s": 8819,
"text": "Answer: a) PEASA"
},
{
"code": null,
"e": 8997,
"s": 8836,
"text": "Solution:It is a question of coding-decoding where,V is written as S (V – 3 = S)X is written as U (X – 3 = U)and so on.Similarly, SHDVD will be written as PEASA"
},
{
"code": null,
"e": 9629,
"s": 8997,
"text": "Aman owes Bipul Rs 50. He agrees to pay Bipul over a number of the consecutive day starting on Monday, paying a single note of Rs 10 or Rs 20 on each day. In how many different ways can Aman repay Bipul. (Two ways are said to be different if at least one day, a note of a different denomination is given)a) 5b) 6c) 7d) 8Answer: d) 8Solution:Aman can pay Bipul in all 10 rupees note in 5 days = 5 * 10 = 50 rupees = 1 wayAman can pay Bipul in 3 ten rupee note and 1 twenty rupee note = 4!/(3! * 1!) = 4 waysAman can pay Bipul in 1 ten rupee note and 2 twenty rupee note = 3!/(1! * 2!) = 3 waysSo in all Aman can pay Bipul in 8 ways."
},
{
"code": null,
"e": 9642,
"s": 9629,
"text": "Answer: d) 8"
},
{
"code": null,
"e": 9942,
"s": 9642,
"text": "Solution:Aman can pay Bipul in all 10 rupees note in 5 days = 5 * 10 = 50 rupees = 1 wayAman can pay Bipul in 3 ten rupee note and 1 twenty rupee note = 4!/(3! * 1!) = 4 waysAman can pay Bipul in 1 ten rupee note and 2 twenty rupee note = 3!/(1! * 2!) = 3 waysSo in all Aman can pay Bipul in 8 ways."
},
{
"code": null,
"e": 10824,
"s": 9942,
"text": "Salim bought a certain number of oranges at a rate of 27 oranges for rupees 2 times M, where M is an integer. He divided these oranges into two equal halves, one part of which he sold at the rate of 13 oranges for Rs M and the other at the rate of 14 oranges for Rs M. He spent and received an integral no of rupees, but bought the least number of oranges. How many did he buy?a) 980b) 9828c) 1880d) 102660Answer: b) 9828Solution:Let Salim buy 2x number of oranges.So he buys 27 oranges at a price of 2M.He buys 1 orange at a price of 2M/27or, x oranges cost him Rs. 2Mx/27Now he sells x oranges at the rate of 13 oranges for Rs. MSo he sells 1 orange at Rs. M/13and x oranges at Rs Mx/13Same goes for 14 oranges which are Mx/14,According to the question, 2Mx/27, Mx/13, Mx/14 are integersSo, x oranges must be divisible by 27, 13 and 14The lcm of 27, 13 and 14 = 4914 or 2x = 9828"
},
{
"code": null,
"e": 10840,
"s": 10824,
"text": "Answer: b) 9828"
},
{
"code": null,
"e": 11301,
"s": 10840,
"text": "Solution:Let Salim buy 2x number of oranges.So he buys 27 oranges at a price of 2M.He buys 1 orange at a price of 2M/27or, x oranges cost him Rs. 2Mx/27Now he sells x oranges at the rate of 13 oranges for Rs. MSo he sells 1 orange at Rs. M/13and x oranges at Rs Mx/13Same goes for 14 oranges which are Mx/14,According to the question, 2Mx/27, Mx/13, Mx/14 are integersSo, x oranges must be divisible by 27, 13 and 14The lcm of 27, 13 and 14 = 4914 or 2x = 9828"
},
{
"code": null,
"e": 12157,
"s": 11301,
"text": "In a football match, 16 teams participate and are divided into 4 groups. Every team from each group will play with each other once. The top 2 winning teams will move to the next round and so on the top two teams will play the final match. So how many minimum matches will be played in that tournament?a) 40b) 14c) 43d) 50Answer: c) 43Solution:Total matches to be played = 4C2 = 6 matches.So total number of matches played in the first round = 6 * 4 = 24 matchesNow top two teams from each group progress to the next round. These 8 teams are to be divided into 2 groups.Total matches played in the second round = 6 × 2 = 12 matchesNow 4 teams progress to the next round. Total matches played in the third round = 6 * 1 = 6matchesFrom this round, 2 teams progress to the next round. And final will be played between them.Total matches = 24 + 12 + 6 + 1 = 43"
},
{
"code": null,
"e": 12171,
"s": 12157,
"text": "Answer: c) 43"
},
{
"code": null,
"e": 12693,
"s": 12171,
"text": "Solution:Total matches to be played = 4C2 = 6 matches.So total number of matches played in the first round = 6 * 4 = 24 matchesNow top two teams from each group progress to the next round. These 8 teams are to be divided into 2 groups.Total matches played in the second round = 6 × 2 = 12 matchesNow 4 teams progress to the next round. Total matches played in the third round = 6 * 1 = 6matchesFrom this round, 2 teams progress to the next round. And final will be played between them.Total matches = 24 + 12 + 6 + 1 = 43"
},
{
"code": null,
"e": 13212,
"s": 12693,
"text": "There are 12 letters and exactly 12 envelopes. There is one letter to be inserted randomly into each envelope. What is the probability that exactly 1 letter is inserted in an improper envelope?a) 1b) 0c) 10!d) None of theseAnswer: b) 0Solution:This is a question of very common sense in which,12 letters are to be inserted in 12 envelopes, 1 in each, so if one letter is inserted into a wrong envelope there has to be another letter which is to be inserted into another wrong envelope. So the probability of this is 0."
},
{
"code": null,
"e": 13225,
"s": 13212,
"text": "Answer: b) 0"
},
{
"code": null,
"e": 13509,
"s": 13225,
"text": "Solution:This is a question of very common sense in which,12 letters are to be inserted in 12 envelopes, 1 in each, so if one letter is inserted into a wrong envelope there has to be another letter which is to be inserted into another wrong envelope. So the probability of this is 0."
},
{
"code": null,
"e": 14027,
"s": 13509,
"text": "A hollow space on the earth surface is to be filled. The total cost of filling is Rs. 20000. The cost of filling per cubic-meter is Rs 225. How many times is a size of 3 cubic-meter soil required to fill the hollow space?a) 29.62b) 30.32c) 88.88d) 43.64Answer: a) 29.62Solution:The total cost of filling = 20, 000Cost of filling 1 cubic meter = Rs. 225So cubic meters to be filled = 20, 000/225 = 88.89 meter-cubeNow we need to find the three times of 88.89 to be filled = 88.89/3 = 29.63So the closest match is 29.62"
},
{
"code": null,
"e": 14044,
"s": 14027,
"text": "Answer: a) 29.62"
},
{
"code": null,
"e": 14293,
"s": 14044,
"text": "Solution:The total cost of filling = 20, 000Cost of filling 1 cubic meter = Rs. 225So cubic meters to be filled = 20, 000/225 = 88.89 meter-cubeNow we need to find the three times of 88.89 to be filled = 88.89/3 = 29.63So the closest match is 29.62"
},
{
"code": null,
"e": 14716,
"s": 14293,
"text": "A 7-digit number is to be formed with all different digits. If the digits at the extreme right and extreme left are fixed to 5 and 6 respectively, find how many such numbers can be formed?a) 120b) 30240c) 6720d) None of theseAnswer: c) 6720Solution:If the digits at extreme left and right are fixed as 5 and 6, then the number of digits left = 8So the in-between 5 places can be filled in 8 * 7 * 6 * 5 * 4 ways= 6720 ways"
},
{
"code": null,
"e": 14732,
"s": 14716,
"text": "Answer: c) 6720"
},
{
"code": null,
"e": 14915,
"s": 14732,
"text": "Solution:If the digits at extreme left and right are fixed as 5 and 6, then the number of digits left = 8So the in-between 5 places can be filled in 8 * 7 * 6 * 5 * 4 ways= 6720 ways"
},
{
"code": null,
"e": 15376,
"s": 14915,
"text": "There are five tires in a sedan (four road tires and one spare) which is to be used equally in a journey to travel 40, 000 km. The number of km of use of each tyre wasa) 32000b) 8000c) 4000d) 10000Answer: a) 32000Solution:The total km travelled by the sedan = 40, 000 kmSince every tire capacity’s = 40, 000/5 = 8000 km eachSo total distance covered by each tire = 8000*4 = 32000 km each will be travelled by each tire after being worn out after every 8000 km."
},
{
"code": null,
"e": 15393,
"s": 15376,
"text": "Answer: a) 32000"
},
{
"code": null,
"e": 15641,
"s": 15393,
"text": "Solution:The total km travelled by the sedan = 40, 000 kmSince every tire capacity’s = 40, 000/5 = 8000 km eachSo total distance covered by each tire = 8000*4 = 32000 km each will be travelled by each tire after being worn out after every 8000 km."
},
{
"code": null,
"e": 15663,
"s": 15641,
"text": "interview-preparation"
},
{
"code": null,
"e": 15685,
"s": 15663,
"text": "placement preparation"
},
{
"code": null,
"e": 15689,
"s": 15685,
"text": "TCS"
},
{
"code": null,
"e": 15700,
"s": 15689,
"text": "Placements"
},
{
"code": null,
"e": 15704,
"s": 15700,
"text": "TCS"
},
{
"code": null,
"e": 15802,
"s": 15704,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15854,
"s": 15802,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 15912,
"s": 15854,
"text": "Programming Language For Placement - C++, Java or Python?"
},
{
"code": null,
"e": 15955,
"s": 15912,
"text": "Cognizant Placement Paper | Aptitude Set 1"
},
{
"code": null,
"e": 15983,
"s": 15955,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 16003,
"s": 15983,
"text": "Time Speed Distance"
},
{
"code": null,
"e": 16025,
"s": 16003,
"text": "Interview Preparation"
},
{
"code": null,
"e": 16051,
"s": 16025,
"text": "Progressions (AP, GP, HP)"
},
{
"code": null,
"e": 16109,
"s": 16051,
"text": "Print the longest path from root to leaf in a Binary tree"
},
{
"code": null,
"e": 16128,
"s": 16109,
"text": "Problem on Numbers"
}
] |
Python Program to Convert Matrix to String | 02 Feb, 2021
Given a matrix, our task is to write a Python program to convert to the matrix, with different delimiters for element and row separation.
Examples:
Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, ” “
Output : 1,3,gfg 2,is,4 best,9,5
Explanation : Element in list separated by “,”, and lists separated by ” “.
Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, “-“
Output : 1,3,gfg-2,is,4-best,9,5
Explanation : Element in list separated by “,”, and lists separated by “-“.
Method #1 : Using join() + list comprehension
In this, we perform task of iterating each element of each row using list comprehension. The inner and outer join for element and row with different delimiters using join().
Python3
# Python3 code to demonstrate working of# Convert Matrix to String# Using list comprehension + join() # initializing listtest_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]] # printing original listprint("The original list is : " + str(test_list)) # initializing delimsin_del, out_del = ",", " " # nested join using join()res = out_del.join([in_del.join([str(ele) for ele in sub]) for sub in test_list]) # printing resultprint("Conversion to String : " + str(res))
Output:
The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]
Conversion to String : 1,3,gfg 2,is,4 best,9,5
Method #2 : Using map() + join()
In this, task of inner joining of elements is extending to each character using map(). Rest all the functionalities are similar to upper method.
Python3
# Python3 code to demonstrate working of# Convert Matrix to String# Using map() + join() # initializing listtest_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]] # printing original listprint("The original list is : " + str(test_list)) # initializing delimsin_del, out_del = ",", " " # nested join using join()# map() for joining inner elementsres = out_del.join(in_del.join(map(str, sub)) for sub in test_list) # printing resultprint("Conversion to String : " + str(res))
Output:
The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]
Conversion to String : 1,3,gfg 2,is,4 best,9,5
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "Given a matrix, our task is to write a Python program to convert to the matrix, with different delimiters for element and row separation."
},
{
"code": null,
"e": 176,
"s": 166,
"text": "Examples:"
},
{
"code": null,
"e": 282,
"s": 176,
"text": "Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, ” “"
},
{
"code": null,
"e": 315,
"s": 282,
"text": "Output : 1,3,gfg 2,is,4 best,9,5"
},
{
"code": null,
"e": 391,
"s": 315,
"text": "Explanation : Element in list separated by “,”, and lists separated by ” “."
},
{
"code": null,
"e": 497,
"s": 391,
"text": "Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, “-“"
},
{
"code": null,
"e": 530,
"s": 497,
"text": "Output : 1,3,gfg-2,is,4-best,9,5"
},
{
"code": null,
"e": 606,
"s": 530,
"text": "Explanation : Element in list separated by “,”, and lists separated by “-“."
},
{
"code": null,
"e": 652,
"s": 606,
"text": "Method #1 : Using join() + list comprehension"
},
{
"code": null,
"e": 826,
"s": 652,
"text": "In this, we perform task of iterating each element of each row using list comprehension. The inner and outer join for element and row with different delimiters using join()."
},
{
"code": null,
"e": 834,
"s": 826,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert Matrix to String# Using list comprehension + join() # initializing listtest_list = [[1, 3, \"gfg\"], [2, \"is\", 4], [\"best\", 9, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing delimsin_del, out_del = \",\", \" \" # nested join using join()res = out_del.join([in_del.join([str(ele) for ele in sub]) for sub in test_list]) # printing resultprint(\"Conversion to String : \" + str(res))",
"e": 1309,
"s": 834,
"text": null
},
{
"code": null,
"e": 1317,
"s": 1309,
"text": "Output:"
},
{
"code": null,
"e": 1386,
"s": 1317,
"text": "The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]"
},
{
"code": null,
"e": 1433,
"s": 1386,
"text": "Conversion to String : 1,3,gfg 2,is,4 best,9,5"
},
{
"code": null,
"e": 1466,
"s": 1433,
"text": "Method #2 : Using map() + join()"
},
{
"code": null,
"e": 1611,
"s": 1466,
"text": "In this, task of inner joining of elements is extending to each character using map(). Rest all the functionalities are similar to upper method."
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Convert Matrix to String# Using map() + join() # initializing listtest_list = [[1, 3, \"gfg\"], [2, \"is\", 4], [\"best\", 9, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing delimsin_del, out_del = \",\", \" \" # nested join using join()# map() for joining inner elementsres = out_del.join(in_del.join(map(str, sub)) for sub in test_list) # printing resultprint(\"Conversion to String : \" + str(res))",
"e": 2101,
"s": 1619,
"text": null
},
{
"code": null,
"e": 2109,
"s": 2101,
"text": "Output:"
},
{
"code": null,
"e": 2178,
"s": 2109,
"text": "The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]"
},
{
"code": null,
"e": 2225,
"s": 2178,
"text": "Conversion to String : 1,3,gfg 2,is,4 best,9,5"
},
{
"code": null,
"e": 2246,
"s": 2225,
"text": "Python list-programs"
},
{
"code": null,
"e": 2269,
"s": 2246,
"text": "Python string-programs"
},
{
"code": null,
"e": 2276,
"s": 2269,
"text": "Python"
},
{
"code": null,
"e": 2292,
"s": 2276,
"text": "Python Programs"
}
] |
Nested try blocks in Exception Handling in Java | 23 Oct, 2018
In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try.In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block) handles the ArrayIndexOutOfBoundsException.
Example 1:
class NestedTry { // main method public static void main(String args[]) { // Main try block try { // initializing array int a[] = { 1, 2, 3, 4, 5 }; // trying to print element at index 5 System.out.println(a[5]); // try-block2 inside another try block try { // performing division by zero int x = a[2] / 0; } catch (ArithmeticException e2) { System.out.println("division by zero is not possible"); } } catch (ArrayIndexOutOfBoundsException e1) { System.out.println("ArrayIndexOutOfBoundsException"); System.out.println("Element at such index does not exists"); } } // end of main method}
ArrayIndexOutOfBoundsException
Element at such index does not exists
Whenever a try block does not have a catch block for a particular exception, then the catch blocks of parent try block are inspected for that exception, and if a match is found then that catch block is executed.
If none of the catch blocks handles the exception then the Java run-time system will handle the exception and a system generated message would be shown for the exception.
Example 2:
class Nesting { // main method public static void main(String args[]) { // main try-block try { // try-block2 try { // try-block3 try { int arr[] = { 1, 2, 3, 4 }; System.out.println(arr[10]); } // handles ArithmeticException if any catch (ArithmeticException e) { System.out.println("Arithmetic exception"); System.out.println(" try-block1"); } } // handles ArithmeticException if any catch (ArithmeticException e) { System.out.println("Arithmetic exception"); System.out.println(" try-block2"); } } // handles ArrayIndexOutOfBoundsException if any catch (ArrayIndexOutOfBoundsException e4) { System.out.print("ArrayIndexOutOfBoundsException"); System.out.println(" main try-block"); } catch (Exception e5) { System.out.print("Exception"); System.out.println(" handled in main try-block"); } }}
ArrayIndexOutOfBoundsException main try-block
Java-Exception Handling
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Oct, 2018"
},
{
"code": null,
"e": 442,
"s": 52,
"text": "In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try.In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block) handles the ArrayIndexOutOfBoundsException."
},
{
"code": null,
"e": 453,
"s": 442,
"text": "Example 1:"
},
{
"code": "class NestedTry { // main method public static void main(String args[]) { // Main try block try { // initializing array int a[] = { 1, 2, 3, 4, 5 }; // trying to print element at index 5 System.out.println(a[5]); // try-block2 inside another try block try { // performing division by zero int x = a[2] / 0; } catch (ArithmeticException e2) { System.out.println(\"division by zero is not possible\"); } } catch (ArrayIndexOutOfBoundsException e1) { System.out.println(\"ArrayIndexOutOfBoundsException\"); System.out.println(\"Element at such index does not exists\"); } } // end of main method}",
"e": 1267,
"s": 453,
"text": null
},
{
"code": null,
"e": 1337,
"s": 1267,
"text": "ArrayIndexOutOfBoundsException\nElement at such index does not exists\n"
},
{
"code": null,
"e": 1549,
"s": 1337,
"text": "Whenever a try block does not have a catch block for a particular exception, then the catch blocks of parent try block are inspected for that exception, and if a match is found then that catch block is executed."
},
{
"code": null,
"e": 1720,
"s": 1549,
"text": "If none of the catch blocks handles the exception then the Java run-time system will handle the exception and a system generated message would be shown for the exception."
},
{
"code": null,
"e": 1731,
"s": 1720,
"text": "Example 2:"
},
{
"code": "class Nesting { // main method public static void main(String args[]) { // main try-block try { // try-block2 try { // try-block3 try { int arr[] = { 1, 2, 3, 4 }; System.out.println(arr[10]); } // handles ArithmeticException if any catch (ArithmeticException e) { System.out.println(\"Arithmetic exception\"); System.out.println(\" try-block1\"); } } // handles ArithmeticException if any catch (ArithmeticException e) { System.out.println(\"Arithmetic exception\"); System.out.println(\" try-block2\"); } } // handles ArrayIndexOutOfBoundsException if any catch (ArrayIndexOutOfBoundsException e4) { System.out.print(\"ArrayIndexOutOfBoundsException\"); System.out.println(\" main try-block\"); } catch (Exception e5) { System.out.print(\"Exception\"); System.out.println(\" handled in main try-block\"); } }}",
"e": 2911,
"s": 1731,
"text": null
},
{
"code": null,
"e": 2958,
"s": 2911,
"text": "ArrayIndexOutOfBoundsException main try-block\n"
},
{
"code": null,
"e": 2982,
"s": 2958,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 2998,
"s": 2982,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 3003,
"s": 2998,
"text": "Java"
},
{
"code": null,
"e": 3008,
"s": 3003,
"text": "Java"
}
] |
Java Program for Phone Mnemonics | 03 Oct, 2018
In our daily lives, we have to remember a lot of phone numbers. Most people find it quite difficult to remember such huge 10-digit phone numbers. A simple solution is to relate that phone number to some known word.For example, we can relate the phone number 32627287 with DAMASCUS based on the characters in our dial pad. (We can replace a DIGIT with any one of the corresponding CHARACTER it represents on the dial pad. For example, we have ABC mentioned under 2 in our dial pad. So we can represent 2 with either A or B or C. Similarly we can replace 3 with D or E or F.
Write a program that will take in a phone number and print all possible such words which are in our dictionary.
Let us consider the sample input 23.Here,2 can be replaced using A or B or C.3 can be replaced using D or E or F.So one valid combination would be AD which corresponds to 623.Another can be CD and so on.We are generating all the possible permutations starting with {A or B or C} and then {D or E or F}.However, only those permutations will be printed which are in our dictionary. These selected words will represent our sample output.
However, DIGITS like 1 and 0 will be replaced by a null string as they don’t represent any character on the dial pad i.e 1 and 0 will represent “”.
Examples:
Input : 23
Output : [BE]
Input : 623
Output : [MAD, OCD]
Input : 726
Output : [PAN, PCM, PCO, RAM, SAM]
Input : 2
Output : [A, B, C]
Input : 123
Output : [BE]
.Naive ApproachThis program uses backtracking to generate all possible words .Click here to know more. The concept of backtracking has been explained there.
import java.util.*; public class PhoneMnemonics { static ArrayList<String> dictionary = new ArrayList<String>(); /* List all the phone mnemonics for the given digit sequence. * @param input a digit sequence, like "23432" */ public static ArrayList<String> listMnemonics(String input) { ArrayList<String> list = new ArrayList<String>(); String[] dic = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "MAD", "OCD", "PAN", "PCM", "PCO", "RAM", "SAM", "BE" }; for (String i : dic) dictionary.add(i); listMnemonics("", input, list); return list; } /* Helper recursive method to list phone mnemonics. This works by finding * all possibilities for the first digit, then recursing on the rest of the * string. For example, if prefix is "AB" and remaining is "2", then the * mnemonics "ABA", "ABB", and "ABC" would be printed. * * @param prefix : the part of the mnemonic that has already been built * @param remaining : the remaining digits to include in the mnemonic */ private static void listMnemonics(String prefix, String remaining, ArrayList<String> list) { // Base case: when there are no more characters to process, // just print out the mnemonic that we've already built. if (remaining.isEmpty()) { if (!list.contains(prefix) && dictionary.contains(prefix)) list.add(prefix); return; } // Recursive case. if (remaining.charAt(0) == '1' || remaining.charAt(0) == '0') { listMnemonics(prefix, remaining.substring(1), list); } String digits = digitLetters(remaining.charAt(0)); for (int i = 0; i < digits.length(); i++) { String newPrefix = prefix + digits.charAt(i); String newRemaining = remaining.substring(1); listMnemonics(newPrefix, newRemaining, list); } } /** * Get the letters appearing on a given key of a standard phone keypad. * @param ch the character representation of a digit on the phone keypad * (like '2') * @return a string containing the letters on the given key, or the empty * string if the key is not recognized */ private static String digitLetters(char ch) { switch (ch) { case '2': return "ABC"; case '3': return "DEF"; case '4': return "GHI"; case '5': return "JKL"; case '6': return "MNO"; case '7': return "PQRS"; case '8': return "TUV"; case '9': return "WXYZ"; } return ""; } public static void main(String[] args) { String str = "123"; ArrayList<String> list = listMnemonics(str); System.out.println(list); }}
[BE]
Note: This program will become more convenient for the users once we add a dictionary of words along with their frequency of use.Using a dictionary, the following output could have been optimized to print MAD, OCD, ... so on based on their frequency of use by the users. Check out this link: https://phonespell.org/.Related Article with C++ implementation : Print all possible words from phone digits
Reference :Thinking Recursively by Eric Roberts.
Backtracking
Java Programs
Misc
Misc
Misc
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Oct, 2018"
},
{
"code": null,
"e": 627,
"s": 54,
"text": "In our daily lives, we have to remember a lot of phone numbers. Most people find it quite difficult to remember such huge 10-digit phone numbers. A simple solution is to relate that phone number to some known word.For example, we can relate the phone number 32627287 with DAMASCUS based on the characters in our dial pad. (We can replace a DIGIT with any one of the corresponding CHARACTER it represents on the dial pad. For example, we have ABC mentioned under 2 in our dial pad. So we can represent 2 with either A or B or C. Similarly we can replace 3 with D or E or F."
},
{
"code": null,
"e": 739,
"s": 627,
"text": "Write a program that will take in a phone number and print all possible such words which are in our dictionary."
},
{
"code": null,
"e": 1174,
"s": 739,
"text": "Let us consider the sample input 23.Here,2 can be replaced using A or B or C.3 can be replaced using D or E or F.So one valid combination would be AD which corresponds to 623.Another can be CD and so on.We are generating all the possible permutations starting with {A or B or C} and then {D or E or F}.However, only those permutations will be printed which are in our dictionary. These selected words will represent our sample output."
},
{
"code": null,
"e": 1322,
"s": 1174,
"text": "However, DIGITS like 1 and 0 will be replaced by a null string as they don’t represent any character on the dial pad i.e 1 and 0 will represent “”."
},
{
"code": null,
"e": 1332,
"s": 1322,
"text": "Examples:"
},
{
"code": null,
"e": 1496,
"s": 1332,
"text": "Input : 23\nOutput : [BE]\n\nInput : 623\nOutput : [MAD, OCD]\n\nInput : 726\nOutput : [PAN, PCM, PCO, RAM, SAM]\n\nInput : 2\nOutput : [A, B, C]\n\nInput : 123\nOutput : [BE]\n"
},
{
"code": null,
"e": 1653,
"s": 1496,
"text": ".Naive ApproachThis program uses backtracking to generate all possible words .Click here to know more. The concept of backtracking has been explained there."
},
{
"code": "import java.util.*; public class PhoneMnemonics { static ArrayList<String> dictionary = new ArrayList<String>(); /* List all the phone mnemonics for the given digit sequence. * @param input a digit sequence, like \"23432\" */ public static ArrayList<String> listMnemonics(String input) { ArrayList<String> list = new ArrayList<String>(); String[] dic = { \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"MAD\", \"OCD\", \"PAN\", \"PCM\", \"PCO\", \"RAM\", \"SAM\", \"BE\" }; for (String i : dic) dictionary.add(i); listMnemonics(\"\", input, list); return list; } /* Helper recursive method to list phone mnemonics. This works by finding * all possibilities for the first digit, then recursing on the rest of the * string. For example, if prefix is \"AB\" and remaining is \"2\", then the * mnemonics \"ABA\", \"ABB\", and \"ABC\" would be printed. * * @param prefix : the part of the mnemonic that has already been built * @param remaining : the remaining digits to include in the mnemonic */ private static void listMnemonics(String prefix, String remaining, ArrayList<String> list) { // Base case: when there are no more characters to process, // just print out the mnemonic that we've already built. if (remaining.isEmpty()) { if (!list.contains(prefix) && dictionary.contains(prefix)) list.add(prefix); return; } // Recursive case. if (remaining.charAt(0) == '1' || remaining.charAt(0) == '0') { listMnemonics(prefix, remaining.substring(1), list); } String digits = digitLetters(remaining.charAt(0)); for (int i = 0; i < digits.length(); i++) { String newPrefix = prefix + digits.charAt(i); String newRemaining = remaining.substring(1); listMnemonics(newPrefix, newRemaining, list); } } /** * Get the letters appearing on a given key of a standard phone keypad. * @param ch the character representation of a digit on the phone keypad * (like '2') * @return a string containing the letters on the given key, or the empty * string if the key is not recognized */ private static String digitLetters(char ch) { switch (ch) { case '2': return \"ABC\"; case '3': return \"DEF\"; case '4': return \"GHI\"; case '5': return \"JKL\"; case '6': return \"MNO\"; case '7': return \"PQRS\"; case '8': return \"TUV\"; case '9': return \"WXYZ\"; } return \"\"; } public static void main(String[] args) { String str = \"123\"; ArrayList<String> list = listMnemonics(str); System.out.println(list); }}",
"e": 4739,
"s": 1653,
"text": null
},
{
"code": null,
"e": 4745,
"s": 4739,
"text": "[BE]\n"
},
{
"code": null,
"e": 5146,
"s": 4745,
"text": "Note: This program will become more convenient for the users once we add a dictionary of words along with their frequency of use.Using a dictionary, the following output could have been optimized to print MAD, OCD, ... so on based on their frequency of use by the users. Check out this link: https://phonespell.org/.Related Article with C++ implementation : Print all possible words from phone digits"
},
{
"code": null,
"e": 5195,
"s": 5146,
"text": "Reference :Thinking Recursively by Eric Roberts."
},
{
"code": null,
"e": 5208,
"s": 5195,
"text": "Backtracking"
},
{
"code": null,
"e": 5222,
"s": 5208,
"text": "Java Programs"
},
{
"code": null,
"e": 5227,
"s": 5222,
"text": "Misc"
},
{
"code": null,
"e": 5232,
"s": 5227,
"text": "Misc"
},
{
"code": null,
"e": 5237,
"s": 5232,
"text": "Misc"
},
{
"code": null,
"e": 5250,
"s": 5237,
"text": "Backtracking"
}
] |
Rendering a Triangle using OpenGL(using Shaders) | 02 Jul, 2021
In this article we’ll see how to render a triangle using OpenGL. A triangle is probably the simplest shapes you can draw in OpenGL after points and lines and any complicated geometry that you make will me made up of number of triangles joined together.We’ll be using the programmable pipeline, so we’ll be writing simple shader programs as well and compiling them and using them later for rendering. Now this will make our program a bit lengthy but the cool thing is we have do this only once and then reuse the code we’ve already written. This is actually true for most of the OpenGL code and hence we tend to write most of OpenGL codes in different functions and reuse them multiple times later.The libraries that we’ll be using for this is Glew and Glut and Ç++ as our programming language.Setting up the Environment
Download the latest glew and glut header, library and dll files.In Visual Studio create a Win 32 console application project.Go to your project properties.Import and include header and library for all configuration.Put the dll files where your source files are.
Download the latest glew and glut header, library and dll files.
In Visual Studio create a Win 32 console application project.
Go to your project properties.
Import and include header and library for all configuration.
Put the dll files where your source files are.
The complete Program(Explanation follows after the program)
CPP
// CPP program to render a triangle using Shaders#include <GL\freeglut.h>#include <GL\glew.h>#include <iostream>#include <string> std::string vertexShader = "#version 430\n" "in vec3 pos;" "void main() {" "gl_Position = vec4(pos, 1);" "}"; std::string fragmentShader = "#version 430\n" "void main() {" "gl_FragColor = vec4(1, 0, 0, 1);" "}"; // Compile and create shader object and returns its idGLuint compileShaders(std::string shader, GLenum type){ const char* shaderCode = shader.c_str(); GLuint shaderId = glCreateShader(type); if (shaderId == 0) { // Error: Cannot create shader object std::cout << "Error creating shaders"; return 0; } // Attach source code to this object glShaderSource(shaderId, 1, &shaderCode, NULL); glCompileShader(shaderId); // compile the shader object GLint compileStatus; // check for compilation status glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileStatus); if (!compileStatus) { // If compilation was not successful int length; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &length); char* cMessage = new char[length]; // Get additional information glGetShaderInfoLog(shaderId, length, &length, cMessage); std::cout << "Cannot Compile Shader: " << cMessage; delete[] cMessage; glDeleteShader(shaderId); return 0; } return shaderId;} // Creates a program containing vertex and fragment shader// links it and returns its IDGLuint linkProgram(GLuint vertexShaderId, GLuint fragmentShaderId){ GLuint programId = glCreateProgram(); // create a program if (programId == 0) { std::cout << "Error Creating Shader Program"; return 0; } // Attach both the shaders to it glAttachShader(programId, vertexShaderId); glAttachShader(programId, fragmentShaderId); // Create executable of this program glLinkProgram(programId); GLint linkStatus; // Get the link status for this program glGetProgramiv(programId, GL_LINK_STATUS, &linkStatus); if (!linkStatus) { // If the linking failed std::cout << "Error Linking program"; glDetachShader(programId, vertexShaderId); glDetachShader(programId, fragmentShaderId); glDeleteProgram(programId); return 0; } return programId;} // Load data in VBO and return the vbo's idGLuint loadDataInBuffers(){ GLfloat vertices[] = { // vertex coordinates -0.7, -0.7, 0, 0.7, -0.7, 0, 0, 0.7, 0 }; GLuint vboId; // allocate buffer space and pass data to it glGenBuffers(1, &vboId); glBindBuffer(GL_ARRAY_BUFFER, vboId); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // unbind the active buffer glBindBuffer(GL_ARRAY_BUFFER, 0); return vboId;} // Initialize and put everything togethervoid init(){ // clear the framebuffer each frame with black color glClearColor(0, 0, 0, 0); GLuint vboId = loadDataInBuffers(); GLuint vShaderId = compileShaders(vertexShader, GL_VERTEX_SHADER); GLuint fShaderId = compileShaders(fragmentShader, GL_FRAGMENT_SHADER); GLuint programId = linkProgram(vShaderId, fShaderId); // Get the 'pos' variable location inside this program GLuint posAttributePosition = glGetAttribLocation(programId, "pos"); GLuint vaoId; glGenVertexArrays(1, &vaoId); // Generate VAO // Bind it so that rest of vao operations affect this vao glBindVertexArray(vaoId); // buffer from which 'pos' will receive its data and the format of that data glBindBuffer(GL_ARRAY_BUFFER, vboId); glVertexAttribPointer(posAttributePosition, 3, GL_FLOAT, false, 0, 0); // Enable this attribute array linked to 'pos' glEnableVertexAttribArray(posAttributePosition); // Use this program for rendering. glUseProgram(programId);} // Function that does the drawing// glut calls this function whenever it needs to redrawvoid display(){ // clear the color buffer before each drawing glClear(GL_COLOR_BUFFER_BIT); // draw triangles starting from index 0 and // using 3 indices glDrawArrays(GL_TRIANGLES, 0, 3); // swap the buffers and hence show the buffers // content to the screen glutSwapBuffers();} // main function// sets up window to which we'll drawint main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(500, 500); glutInitWindowPosition(100, 50); glutCreateWindow("Triangle Using OpenGL"); glewInit(); init(); glutDisplayFunc(display); glutMainLoop(); return 0;}
Output Now when you run the program you should have a red triangle on the screen that should look something like the image below.
main() Function Main function sets up our window. We initialize glut, glew, specify windows size, its position on the screen, specify display mode(which just tells what color space will be used by the window and will it use single or double buffer), set windows title, set the callback method that glut will use to draw stuff on this window and finally make the window visible.loadDataInBuffers() Function A triangle is made up of three coordinate points. These points(stored as floating point array) needs to be sent to graphics processor memory. The way we refer to a location in system memory is relatively easy, just get a pointer to the memory location but using your GPU’s memory is not that straightforward. We do this by something known as buffer objects. Buffer objects are the way you upload your data to the V-RAM and refer to it later. There are usually three steps that you need to follow to get your data into the video memory.
Generate a unsigned integer identifier for your buffer object.Bind that buffer object to a target.Specify the size of the buffer and optionally load data into it.
Generate a unsigned integer identifier for your buffer object.
Bind that buffer object to a target.
Specify the size of the buffer and optionally load data into it.
Remember that OpenGL expects vertex coordinates in the range of [-1, 1]. Anything outside this range is clipped. However, we are free to choose our own coordinate system in-fact, it is a very common practice to define our own coordinate system and define our objects according to this coordinate system and later change it to the OpengGL coordinate system.But in this post we’ll travel down the easier road and specify our triangle’s coordinates in [-1, 1] range. FYI coordinates in these range are known as normalized device coordinate(NDC).Shaders Throughout the rendering pipeline the input data(here vertex coordinates) go through various stages. We control these stages using something called Shaders Shaders are programs that execute on GPU. Shaders in OpenGL are written in a special language commonly known as GLSL(OpenGL shading language) which you will come to notice is very similar to C and C++. Shaders give you direct control over the graphics pipeline. GLSL was formally included into the OpenGL 2.0 core in 2004 by the OpenGL ARB.The two shaders that you will need all the time are
Vertex Shader: These shaders are executed once for every vertex(in case of a triangle it will execute 3 times) that the GPU processes. So if your scene consist of one million vertices, the vertex shader will execute one million times once for each vertex. The main job of a vertex shader is to calculate the final positions of the vertices in the scene. It does so by writing a vector(this vector has 4 component) to a special output variable known as gl_Position(only available in vertex shader). The input to the vertex shader is specified using an in type qualifier and output with an out qualifier before the variable. The input and output variable must have global scope.Fragment Shader: After your geometry has passes through other intermediate stages if finally reaches to the rasterizer. Rasterizer divides your geometry into fragments. Then the fragment shader runs for each fragment in your geometry(or triangle). The job of the fragment shader is to determine the final color for each fragment. It writes the final color to a special output variable gl_FragColor(only available to fragment shader). The value passed to the gl_FragColor is a vector containing rgba values for that fragment.
Vertex Shader: These shaders are executed once for every vertex(in case of a triangle it will execute 3 times) that the GPU processes. So if your scene consist of one million vertices, the vertex shader will execute one million times once for each vertex. The main job of a vertex shader is to calculate the final positions of the vertices in the scene. It does so by writing a vector(this vector has 4 component) to a special output variable known as gl_Position(only available in vertex shader). The input to the vertex shader is specified using an in type qualifier and output with an out qualifier before the variable. The input and output variable must have global scope.
Fragment Shader: After your geometry has passes through other intermediate stages if finally reaches to the rasterizer. Rasterizer divides your geometry into fragments. Then the fragment shader runs for each fragment in your geometry(or triangle). The job of the fragment shader is to determine the final color for each fragment. It writes the final color to a special output variable gl_FragColor(only available to fragment shader). The value passed to the gl_FragColor is a vector containing rgba values for that fragment.
The shader code is stored as strings global variable. We’ll link this variable to the data in our openGL program later. The vertex position are passed to gl_Position without modification.Note: It is a common practice to put your shader codes in different files and later store that files contents in string variables.After you done writing your shader you need to create shader objects, attach their corresponding source code, compile them and check for errors if there are.compileShaders() FunctionThis function compiles the shader code, checks for error and creates shader object and returns its id. We’ll call this function once for vertex and fragment shaderlinkProgram() Function Shaders that you write for rendering needs to clubbed together into a shader program. This function clubs these shader objects into a shader program, links them(that sort of creates an executable file for that program) and check for errors that may occur in this process.init() FunctionIt uses all the above functions and puts everything together. We use what is known as VAO(Vertex Array Objects). VAO: A Vertex Array Object (VAO) is an OpenGL Object that stores all of the state needed to supply vertex data. It stores the format of the vertex data as well as the Buffer Objects providing the vertex data arrays. Note that VAOs do not copy, freeze or store the contents of the referenced buffers, if you change any of the data in the buffers referenced by an existing VAO, those changes will be seen by users of the VAO.A shader program assigns to each of the input variable of vertex shader(aka vertex attributes) and uniform variables(variables whose values do not change for the primitive we are rendering) a position that we need to know if we want to link them to their data source.display() Function Remember we haven’t yet told GPU to start rendering. display Function is what gives this command to the GPU. Glut calls this callback function whenever it needs to draw stuff to the screen.
nidhi_biet
Akanksha_Rai
sweetyty
arorakashish0911
surinderdawra388
computer-graphics
OpenGL
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
C++ Program to check if a given String is Palindrome or not
How to find the minimum and maximum element of a Vector using STL in C++?
C++ Program for QuickSort
C Program to Swap two Numbers
delete keyword in C++
cin in C++
Passing a function as a parameter in C++
Const keyword in C++
Enumerated Types or Enums in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 875,
"s": 52,
"text": "In this article we’ll see how to render a triangle using OpenGL. A triangle is probably the simplest shapes you can draw in OpenGL after points and lines and any complicated geometry that you make will me made up of number of triangles joined together.We’ll be using the programmable pipeline, so we’ll be writing simple shader programs as well and compiling them and using them later for rendering. Now this will make our program a bit lengthy but the cool thing is we have do this only once and then reuse the code we’ve already written. This is actually true for most of the OpenGL code and hence we tend to write most of OpenGL codes in different functions and reuse them multiple times later.The libraries that we’ll be using for this is Glew and Glut and Ç++ as our programming language.Setting up the Environment "
},
{
"code": null,
"e": 1137,
"s": 875,
"text": "Download the latest glew and glut header, library and dll files.In Visual Studio create a Win 32 console application project.Go to your project properties.Import and include header and library for all configuration.Put the dll files where your source files are."
},
{
"code": null,
"e": 1202,
"s": 1137,
"text": "Download the latest glew and glut header, library and dll files."
},
{
"code": null,
"e": 1264,
"s": 1202,
"text": "In Visual Studio create a Win 32 console application project."
},
{
"code": null,
"e": 1295,
"s": 1264,
"text": "Go to your project properties."
},
{
"code": null,
"e": 1356,
"s": 1295,
"text": "Import and include header and library for all configuration."
},
{
"code": null,
"e": 1403,
"s": 1356,
"text": "Put the dll files where your source files are."
},
{
"code": null,
"e": 1465,
"s": 1403,
"text": "The complete Program(Explanation follows after the program) "
},
{
"code": null,
"e": 1469,
"s": 1465,
"text": "CPP"
},
{
"code": "// CPP program to render a triangle using Shaders#include <GL\\freeglut.h>#include <GL\\glew.h>#include <iostream>#include <string> std::string vertexShader = \"#version 430\\n\" \"in vec3 pos;\" \"void main() {\" \"gl_Position = vec4(pos, 1);\" \"}\"; std::string fragmentShader = \"#version 430\\n\" \"void main() {\" \"gl_FragColor = vec4(1, 0, 0, 1);\" \"}\"; // Compile and create shader object and returns its idGLuint compileShaders(std::string shader, GLenum type){ const char* shaderCode = shader.c_str(); GLuint shaderId = glCreateShader(type); if (shaderId == 0) { // Error: Cannot create shader object std::cout << \"Error creating shaders\"; return 0; } // Attach source code to this object glShaderSource(shaderId, 1, &shaderCode, NULL); glCompileShader(shaderId); // compile the shader object GLint compileStatus; // check for compilation status glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileStatus); if (!compileStatus) { // If compilation was not successful int length; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &length); char* cMessage = new char[length]; // Get additional information glGetShaderInfoLog(shaderId, length, &length, cMessage); std::cout << \"Cannot Compile Shader: \" << cMessage; delete[] cMessage; glDeleteShader(shaderId); return 0; } return shaderId;} // Creates a program containing vertex and fragment shader// links it and returns its IDGLuint linkProgram(GLuint vertexShaderId, GLuint fragmentShaderId){ GLuint programId = glCreateProgram(); // create a program if (programId == 0) { std::cout << \"Error Creating Shader Program\"; return 0; } // Attach both the shaders to it glAttachShader(programId, vertexShaderId); glAttachShader(programId, fragmentShaderId); // Create executable of this program glLinkProgram(programId); GLint linkStatus; // Get the link status for this program glGetProgramiv(programId, GL_LINK_STATUS, &linkStatus); if (!linkStatus) { // If the linking failed std::cout << \"Error Linking program\"; glDetachShader(programId, vertexShaderId); glDetachShader(programId, fragmentShaderId); glDeleteProgram(programId); return 0; } return programId;} // Load data in VBO and return the vbo's idGLuint loadDataInBuffers(){ GLfloat vertices[] = { // vertex coordinates -0.7, -0.7, 0, 0.7, -0.7, 0, 0, 0.7, 0 }; GLuint vboId; // allocate buffer space and pass data to it glGenBuffers(1, &vboId); glBindBuffer(GL_ARRAY_BUFFER, vboId); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // unbind the active buffer glBindBuffer(GL_ARRAY_BUFFER, 0); return vboId;} // Initialize and put everything togethervoid init(){ // clear the framebuffer each frame with black color glClearColor(0, 0, 0, 0); GLuint vboId = loadDataInBuffers(); GLuint vShaderId = compileShaders(vertexShader, GL_VERTEX_SHADER); GLuint fShaderId = compileShaders(fragmentShader, GL_FRAGMENT_SHADER); GLuint programId = linkProgram(vShaderId, fShaderId); // Get the 'pos' variable location inside this program GLuint posAttributePosition = glGetAttribLocation(programId, \"pos\"); GLuint vaoId; glGenVertexArrays(1, &vaoId); // Generate VAO // Bind it so that rest of vao operations affect this vao glBindVertexArray(vaoId); // buffer from which 'pos' will receive its data and the format of that data glBindBuffer(GL_ARRAY_BUFFER, vboId); glVertexAttribPointer(posAttributePosition, 3, GL_FLOAT, false, 0, 0); // Enable this attribute array linked to 'pos' glEnableVertexAttribArray(posAttributePosition); // Use this program for rendering. glUseProgram(programId);} // Function that does the drawing// glut calls this function whenever it needs to redrawvoid display(){ // clear the color buffer before each drawing glClear(GL_COLOR_BUFFER_BIT); // draw triangles starting from index 0 and // using 3 indices glDrawArrays(GL_TRIANGLES, 0, 3); // swap the buffers and hence show the buffers // content to the screen glutSwapBuffers();} // main function// sets up window to which we'll drawint main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(500, 500); glutInitWindowPosition(100, 50); glutCreateWindow(\"Triangle Using OpenGL\"); glewInit(); init(); glutDisplayFunc(display); glutMainLoop(); return 0;}",
"e": 6312,
"s": 1469,
"text": null
},
{
"code": null,
"e": 6443,
"s": 6312,
"text": "Output Now when you run the program you should have a red triangle on the screen that should look something like the image below. "
},
{
"code": null,
"e": 7387,
"s": 6443,
"text": "main() Function Main function sets up our window. We initialize glut, glew, specify windows size, its position on the screen, specify display mode(which just tells what color space will be used by the window and will it use single or double buffer), set windows title, set the callback method that glut will use to draw stuff on this window and finally make the window visible.loadDataInBuffers() Function A triangle is made up of three coordinate points. These points(stored as floating point array) needs to be sent to graphics processor memory. The way we refer to a location in system memory is relatively easy, just get a pointer to the memory location but using your GPU’s memory is not that straightforward. We do this by something known as buffer objects. Buffer objects are the way you upload your data to the V-RAM and refer to it later. There are usually three steps that you need to follow to get your data into the video memory. "
},
{
"code": null,
"e": 7550,
"s": 7387,
"text": "Generate a unsigned integer identifier for your buffer object.Bind that buffer object to a target.Specify the size of the buffer and optionally load data into it."
},
{
"code": null,
"e": 7613,
"s": 7550,
"text": "Generate a unsigned integer identifier for your buffer object."
},
{
"code": null,
"e": 7650,
"s": 7613,
"text": "Bind that buffer object to a target."
},
{
"code": null,
"e": 7715,
"s": 7650,
"text": "Specify the size of the buffer and optionally load data into it."
},
{
"code": null,
"e": 8814,
"s": 7715,
"text": "Remember that OpenGL expects vertex coordinates in the range of [-1, 1]. Anything outside this range is clipped. However, we are free to choose our own coordinate system in-fact, it is a very common practice to define our own coordinate system and define our objects according to this coordinate system and later change it to the OpengGL coordinate system.But in this post we’ll travel down the easier road and specify our triangle’s coordinates in [-1, 1] range. FYI coordinates in these range are known as normalized device coordinate(NDC).Shaders Throughout the rendering pipeline the input data(here vertex coordinates) go through various stages. We control these stages using something called Shaders Shaders are programs that execute on GPU. Shaders in OpenGL are written in a special language commonly known as GLSL(OpenGL shading language) which you will come to notice is very similar to C and C++. Shaders give you direct control over the graphics pipeline. GLSL was formally included into the OpenGL 2.0 core in 2004 by the OpenGL ARB.The two shaders that you will need all the time are "
},
{
"code": null,
"e": 10015,
"s": 8814,
"text": "Vertex Shader: These shaders are executed once for every vertex(in case of a triangle it will execute 3 times) that the GPU processes. So if your scene consist of one million vertices, the vertex shader will execute one million times once for each vertex. The main job of a vertex shader is to calculate the final positions of the vertices in the scene. It does so by writing a vector(this vector has 4 component) to a special output variable known as gl_Position(only available in vertex shader). The input to the vertex shader is specified using an in type qualifier and output with an out qualifier before the variable. The input and output variable must have global scope.Fragment Shader: After your geometry has passes through other intermediate stages if finally reaches to the rasterizer. Rasterizer divides your geometry into fragments. Then the fragment shader runs for each fragment in your geometry(or triangle). The job of the fragment shader is to determine the final color for each fragment. It writes the final color to a special output variable gl_FragColor(only available to fragment shader). The value passed to the gl_FragColor is a vector containing rgba values for that fragment."
},
{
"code": null,
"e": 10692,
"s": 10015,
"text": "Vertex Shader: These shaders are executed once for every vertex(in case of a triangle it will execute 3 times) that the GPU processes. So if your scene consist of one million vertices, the vertex shader will execute one million times once for each vertex. The main job of a vertex shader is to calculate the final positions of the vertices in the scene. It does so by writing a vector(this vector has 4 component) to a special output variable known as gl_Position(only available in vertex shader). The input to the vertex shader is specified using an in type qualifier and output with an out qualifier before the variable. The input and output variable must have global scope."
},
{
"code": null,
"e": 11217,
"s": 10692,
"text": "Fragment Shader: After your geometry has passes through other intermediate stages if finally reaches to the rasterizer. Rasterizer divides your geometry into fragments. Then the fragment shader runs for each fragment in your geometry(or triangle). The job of the fragment shader is to determine the final color for each fragment. It writes the final color to a special output variable gl_FragColor(only available to fragment shader). The value passed to the gl_FragColor is a vector containing rgba values for that fragment."
},
{
"code": null,
"e": 13201,
"s": 11217,
"text": "The shader code is stored as strings global variable. We’ll link this variable to the data in our openGL program later. The vertex position are passed to gl_Position without modification.Note: It is a common practice to put your shader codes in different files and later store that files contents in string variables.After you done writing your shader you need to create shader objects, attach their corresponding source code, compile them and check for errors if there are.compileShaders() FunctionThis function compiles the shader code, checks for error and creates shader object and returns its id. We’ll call this function once for vertex and fragment shaderlinkProgram() Function Shaders that you write for rendering needs to clubbed together into a shader program. This function clubs these shader objects into a shader program, links them(that sort of creates an executable file for that program) and check for errors that may occur in this process.init() FunctionIt uses all the above functions and puts everything together. We use what is known as VAO(Vertex Array Objects). VAO: A Vertex Array Object (VAO) is an OpenGL Object that stores all of the state needed to supply vertex data. It stores the format of the vertex data as well as the Buffer Objects providing the vertex data arrays. Note that VAOs do not copy, freeze or store the contents of the referenced buffers, if you change any of the data in the buffers referenced by an existing VAO, those changes will be seen by users of the VAO.A shader program assigns to each of the input variable of vertex shader(aka vertex attributes) and uniform variables(variables whose values do not change for the primitive we are rendering) a position that we need to know if we want to link them to their data source.display() Function Remember we haven’t yet told GPU to start rendering. display Function is what gives this command to the GPU. Glut calls this callback function whenever it needs to draw stuff to the screen. "
},
{
"code": null,
"e": 13212,
"s": 13201,
"text": "nidhi_biet"
},
{
"code": null,
"e": 13225,
"s": 13212,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 13234,
"s": 13225,
"text": "sweetyty"
},
{
"code": null,
"e": 13251,
"s": 13234,
"text": "arorakashish0911"
},
{
"code": null,
"e": 13268,
"s": 13251,
"text": "surinderdawra388"
},
{
"code": null,
"e": 13286,
"s": 13268,
"text": "computer-graphics"
},
{
"code": null,
"e": 13293,
"s": 13286,
"text": "OpenGL"
},
{
"code": null,
"e": 13306,
"s": 13293,
"text": "C++ Programs"
},
{
"code": null,
"e": 13404,
"s": 13306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13438,
"s": 13404,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 13498,
"s": 13438,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 13572,
"s": 13498,
"text": "How to find the minimum and maximum element of a Vector using STL in C++?"
},
{
"code": null,
"e": 13598,
"s": 13572,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 13628,
"s": 13598,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 13650,
"s": 13628,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 13661,
"s": 13650,
"text": "cin in C++"
},
{
"code": null,
"e": 13702,
"s": 13661,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 13723,
"s": 13702,
"text": "Const keyword in C++"
}
] |
Taking input from the user in Tkinter | There might be times when we need to take the user input in our Tkinter application. We can get the user Input in a Single Line text input through the Entry widget using get() method. To display the Captured input, we can either print the message on the screen or display the input with the help of the Label widget.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win= Tk()
#Set the geometry of Tkinter frame
win.geometry("750x250")
def display_text():
global entry
string= entry.get()
label.configure(text=string)
#Initialize a Label to display the User Input
label=Label(win, text="", font=("Courier 22 bold"))
label.pack()
#Create an Entry widget to accept User Input
entry= Entry(win, width= 40)
entry.focus_set()
entry.pack()
#Create a Button to validate Entry Widget
ttk.Button(win, text= "Okay",width= 20, command= display_text).pack(pady=20)
win.mainloop()
Running the above code will display a window that will contain an entry widget that accepts the single line User Input.
Now, write some text in the given entry widget and press "Okay" to validate and display the entry widget on the screen. | [
{
"code": null,
"e": 1504,
"s": 1187,
"text": "There might be times when we need to take the user input in our Tkinter application. We can get the user Input in a Single Line text input through the Entry widget using get() method. To display the Captured input, we can either print the message on the screen or display the input with the help of the Label widget."
},
{
"code": null,
"e": 2135,
"s": 1504,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter frame\nwin= Tk()\n\n#Set the geometry of Tkinter frame\nwin.geometry(\"750x250\")\n\ndef display_text():\n global entry\n string= entry.get()\n label.configure(text=string)\n\n#Initialize a Label to display the User Input\nlabel=Label(win, text=\"\", font=(\"Courier 22 bold\"))\nlabel.pack()\n\n#Create an Entry widget to accept User Input\nentry= Entry(win, width= 40)\nentry.focus_set()\nentry.pack()\n\n#Create a Button to validate Entry Widget\nttk.Button(win, text= \"Okay\",width= 20, command= display_text).pack(pady=20)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2255,
"s": 2135,
"text": "Running the above code will display a window that will contain an entry widget that accepts the single line User Input."
},
{
"code": null,
"e": 2375,
"s": 2255,
"text": "Now, write some text in the given entry widget and press \"Okay\" to validate and display the entry widget on the screen."
}
] |
Vector vs ArrayList in Java | 21 Dec, 2021
ArrayList and Vectors both implement the List interface, and both use (dynamically resizable) arrays for their internal data structure, much like using an ordinary array.
Syntax:
ArrayList: ArrayList<T> al = new ArrayList<T>();
Vector: Vector<T> v = new Vector<T>();
Significant Differences between ArrayList and Vector:
Synchronization: Vector is synchronized, which means only one thread at a time can access the code, while ArrayList is not synchronized, which means multiple threads can work on ArrayList at the same time. For example, if one thread is performing an add operation, then there can be another thread performing a remove operation in a multithreading environment. If multiple threads access ArrayList concurrently, then we must synchronize the block of the code which modifies the list structurally or allow simple element modifications. Structural modification means the addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Performance: ArrayList is faster. Since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe), if one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.
Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage – but the way they resize is different. ArrayList increments 50% of the current array size if the number of elements exceeds its capacity, while vector increments 100% – essentially doubling the current array size.
Traversal: Vector can use both Enumeration and Iterator for traversing over vector elements, while ArrayList can only use Iterator for traversing.
Applications: Most of the time, programmers prefer ArrayList over Vector because ArrayList can be synchronized explicitly using Collections.synchronizedList.
Note: ArrayList is preferable when there is no specific requirement to use vector.
Java
// Java Program to illustrate use// of ArrayList and Vector in Java import java.io.*;import java.util.*; class GFG{ public static void main (String[] args) { // creating an ArrayList ArrayList<String> al = new ArrayList<String>(); // adding object to arraylist al.add("Practice.GeeksforGeeks.org"); al.add("quiz.GeeksforGeeks.org"); al.add("code.GeeksforGeeks.org"); al.add("contribute.GeeksforGeeks.org"); // traversing elements using Iterator' System.out.println("ArrayList elements are:"); Iterator it = al.iterator(); while (it.hasNext()) System.out.println(it.next()); // creating Vector Vector<String> v = new Vector<String>(); v.addElement("Practice"); v.addElement("quiz"); v.addElement("code"); // traversing elements using Enumeration System.out.println("\nVector elements are:"); Enumeration e = v.elements(); while (e.hasMoreElements()) System.out.println(e.nextElement()); }}
ArrayList elements are:
Practice.GeeksforGeeks.org
quiz.GeeksforGeeks.org
code.GeeksforGeeks.org
contribute.GeeksforGeeks.org
Vector elements are:
Practice
quiz
code
How to choose between ArrayList and Vector?
ArrayList is unsynchronized and not thread-safe, whereas Vectors are. Only one thread can call methods on a Vector, which is slightly overhead but helpful when safety is a concern. Therefore, in a single-threaded case, ArrayList is the obvious choice, but where multithreading is concerned, vectors are often preferable.
If we don’t know how much data we will have but know the rate at which it grows, Vector has an advantage since we can set the increment value in vectors.
ArrayList is newer and faster. If we don’t have any explicit requirements for using either of them, we use ArrayList over vector.
This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Koolstr
nishkarshgandhi
Java-ArrayList
Java-Collections
java-list
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 224,
"s": 52,
"text": "ArrayList and Vectors both implement the List interface, and both use (dynamically resizable) arrays for their internal data structure, much like using an ordinary array. "
},
{
"code": null,
"e": 232,
"s": 224,
"text": "Syntax:"
},
{
"code": null,
"e": 322,
"s": 232,
"text": "ArrayList: ArrayList<T> al = new ArrayList<T>();\n\nVector: Vector<T> v = new Vector<T>(); "
},
{
"code": null,
"e": 376,
"s": 322,
"text": "Significant Differences between ArrayList and Vector:"
},
{
"code": null,
"e": 1070,
"s": 376,
"text": "Synchronization: Vector is synchronized, which means only one thread at a time can access the code, while ArrayList is not synchronized, which means multiple threads can work on ArrayList at the same time. For example, if one thread is performing an add operation, then there can be another thread performing a remove operation in a multithreading environment. If multiple threads access ArrayList concurrently, then we must synchronize the block of the code which modifies the list structurally or allow simple element modifications. Structural modification means the addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification."
},
{
"code": null,
"e": 1384,
"s": 1070,
"text": "Performance: ArrayList is faster. Since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe), if one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released."
},
{
"code": null,
"e": 1701,
"s": 1384,
"text": "Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage – but the way they resize is different. ArrayList increments 50% of the current array size if the number of elements exceeds its capacity, while vector increments 100% – essentially doubling the current array size."
},
{
"code": null,
"e": 1848,
"s": 1701,
"text": "Traversal: Vector can use both Enumeration and Iterator for traversing over vector elements, while ArrayList can only use Iterator for traversing."
},
{
"code": null,
"e": 2006,
"s": 1848,
"text": "Applications: Most of the time, programmers prefer ArrayList over Vector because ArrayList can be synchronized explicitly using Collections.synchronizedList."
},
{
"code": null,
"e": 2089,
"s": 2006,
"text": "Note: ArrayList is preferable when there is no specific requirement to use vector."
},
{
"code": null,
"e": 2094,
"s": 2089,
"text": "Java"
},
{
"code": "// Java Program to illustrate use// of ArrayList and Vector in Java import java.io.*;import java.util.*; class GFG{ public static void main (String[] args) { // creating an ArrayList ArrayList<String> al = new ArrayList<String>(); // adding object to arraylist al.add(\"Practice.GeeksforGeeks.org\"); al.add(\"quiz.GeeksforGeeks.org\"); al.add(\"code.GeeksforGeeks.org\"); al.add(\"contribute.GeeksforGeeks.org\"); // traversing elements using Iterator' System.out.println(\"ArrayList elements are:\"); Iterator it = al.iterator(); while (it.hasNext()) System.out.println(it.next()); // creating Vector Vector<String> v = new Vector<String>(); v.addElement(\"Practice\"); v.addElement(\"quiz\"); v.addElement(\"code\"); // traversing elements using Enumeration System.out.println(\"\\nVector elements are:\"); Enumeration e = v.elements(); while (e.hasMoreElements()) System.out.println(e.nextElement()); }}",
"e": 3158,
"s": 2094,
"text": null
},
{
"code": null,
"e": 3325,
"s": 3158,
"text": "ArrayList elements are:\nPractice.GeeksforGeeks.org\nquiz.GeeksforGeeks.org\ncode.GeeksforGeeks.org\ncontribute.GeeksforGeeks.org\n\nVector elements are:\nPractice\nquiz\ncode"
},
{
"code": null,
"e": 3370,
"s": 3325,
"text": "How to choose between ArrayList and Vector? "
},
{
"code": null,
"e": 3691,
"s": 3370,
"text": "ArrayList is unsynchronized and not thread-safe, whereas Vectors are. Only one thread can call methods on a Vector, which is slightly overhead but helpful when safety is a concern. Therefore, in a single-threaded case, ArrayList is the obvious choice, but where multithreading is concerned, vectors are often preferable."
},
{
"code": null,
"e": 3845,
"s": 3691,
"text": "If we don’t know how much data we will have but know the rate at which it grows, Vector has an advantage since we can set the increment value in vectors."
},
{
"code": null,
"e": 3975,
"s": 3845,
"text": "ArrayList is newer and faster. If we don’t have any explicit requirements for using either of them, we use ArrayList over vector."
},
{
"code": null,
"e": 4398,
"s": 3975,
"text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4406,
"s": 4398,
"text": "Koolstr"
},
{
"code": null,
"e": 4422,
"s": 4406,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 4437,
"s": 4422,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 4454,
"s": 4437,
"text": "Java-Collections"
},
{
"code": null,
"e": 4464,
"s": 4454,
"text": "java-list"
},
{
"code": null,
"e": 4483,
"s": 4464,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 4488,
"s": 4483,
"text": "Java"
},
{
"code": null,
"e": 4493,
"s": 4488,
"text": "Java"
},
{
"code": null,
"e": 4510,
"s": 4493,
"text": "Java-Collections"
},
{
"code": null,
"e": 4608,
"s": 4510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4659,
"s": 4608,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4690,
"s": 4659,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4709,
"s": 4690,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4739,
"s": 4709,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4754,
"s": 4739,
"text": "Stream In Java"
},
{
"code": null,
"e": 4772,
"s": 4754,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4792,
"s": 4772,
"text": "Collections in Java"
},
{
"code": null,
"e": 4816,
"s": 4792,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 4848,
"s": 4816,
"text": "Multidimensional Arrays in Java"
}
] |
Python calendar module : itermonthdays() method | 13 May, 2021
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
itermonthdays() method returns an iterator of a specified month and a year. Days returned will simply be day numbers. itermonthdays() method is similar to itermonthdates().
Syntax: itermonthdays(year, month)
Parameter:
year: year of the calendar
month: month of the calendar
Returns: an iterator of the specified month.
Code #1:
Python3
# Python program to demonstrate working# of itermonthdays() method # importing calendar moduleimport calendar year = 2018month = 9 obj = calendar.Calendar() # iterating with itermonthdaysfor day in obj.itermonthdays(year, month): print(day)
Output:
0
0
0
0
0
1
2
3
4
5
6
.
.
29
30
Code #2:
Python3
# Python program to demonstrate working# of itermonthdays() method # importing calendar moduleimport calendar # use with firstweekday = 5obj = calendar.Calendar(firstweekday = 2) # iterating with itermonthdaysfor day in obj.itermonthdays(2018, 4): print(day)
Output:
0
0
0
0
1
2
3
4
5
.
.
28
29
30
0
anikakapoor
Python Calander-module
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. "
},
{
"code": null,
"e": 475,
"s": 301,
"text": "itermonthdays() method returns an iterator of a specified month and a year. Days returned will simply be day numbers. itermonthdays() method is similar to itermonthdates(). "
},
{
"code": null,
"e": 625,
"s": 475,
"text": "Syntax: itermonthdays(year, month)\n\nParameter: \nyear: year of the calendar\nmonth: month of the calendar\n\nReturns: an iterator of the specified month."
},
{
"code": null,
"e": 635,
"s": 625,
"text": "Code #1: "
},
{
"code": null,
"e": 643,
"s": 635,
"text": "Python3"
},
{
"code": "# Python program to demonstrate working# of itermonthdays() method # importing calendar moduleimport calendar year = 2018month = 9 obj = calendar.Calendar() # iterating with itermonthdaysfor day in obj.itermonthdays(year, month): print(day)",
"e": 888,
"s": 643,
"text": null
},
{
"code": null,
"e": 897,
"s": 888,
"text": "Output: "
},
{
"code": null,
"e": 929,
"s": 897,
"text": "0\n0\n0\n0\n0\n1\n2\n3\n4\n5\n6\n.\n.\n29\n30"
},
{
"code": null,
"e": 939,
"s": 929,
"text": "Code #2: "
},
{
"code": null,
"e": 947,
"s": 939,
"text": "Python3"
},
{
"code": "# Python program to demonstrate working# of itermonthdays() method # importing calendar moduleimport calendar # use with firstweekday = 5obj = calendar.Calendar(firstweekday = 2) # iterating with itermonthdaysfor day in obj.itermonthdays(2018, 4): print(day)",
"e": 1209,
"s": 947,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1209,
"text": "Output: "
},
{
"code": null,
"e": 1251,
"s": 1218,
"text": "0\n0\n0\n0\n1\n2\n3\n4\n5\n.\n.\n28\n29\n30\n0"
},
{
"code": null,
"e": 1265,
"s": 1253,
"text": "anikakapoor"
},
{
"code": null,
"e": 1288,
"s": 1265,
"text": "Python Calander-module"
},
{
"code": null,
"e": 1303,
"s": 1288,
"text": "python-modules"
},
{
"code": null,
"e": 1310,
"s": 1303,
"text": "Python"
},
{
"code": null,
"e": 1408,
"s": 1310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1453,
"s": 1408,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 1469,
"s": 1453,
"text": "Deque in Python"
},
{
"code": null,
"e": 1491,
"s": 1469,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1507,
"s": 1491,
"text": "Queue in Python"
},
{
"code": null,
"e": 1557,
"s": 1507,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 1599,
"s": 1557,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1626,
"s": 1599,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1649,
"s": 1626,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 1670,
"s": 1649,
"text": "Python OOPs Concepts"
}
] |
GATE | GATE-CS-2004 | Question 8 | 23 Dec, 2019
Which of the following grammar rules violate the requirements of an operator grammar ? P, Q, R are nonterminals, and r, s, t are terminals.
1. P → Q R
2. P → Q s R
3. P → ε
4. P → Q t R r
(A) 1 only(B) 1 and 3 only(C) 2 and 3 only(D) 3 and 4 onlyAnswer: (B)Explanation: See Question 4 of https://www.geeksforgeeks.org/compilers-set-1/.
Operator grammar should not have two or more variables in its production side by side, and should not have null productions.Quiz of this Question
madarsh986
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2016 (Set 1) | Question 45 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2019"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Which of the following grammar rules violate the requirements of an operator grammar ? P, Q, R are nonterminals, and r, s, t are terminals."
},
{
"code": null,
"e": 256,
"s": 168,
"text": "1. P → Q R \n2. P → Q s R\n3. P → ε \n4. P → Q t R r "
},
{
"code": null,
"e": 404,
"s": 256,
"text": "(A) 1 only(B) 1 and 3 only(C) 2 and 3 only(D) 3 and 4 onlyAnswer: (B)Explanation: See Question 4 of https://www.geeksforgeeks.org/compilers-set-1/."
},
{
"code": null,
"e": 550,
"s": 404,
"text": "Operator grammar should not have two or more variables in its production side by side, and should not have null productions.Quiz of this Question"
},
{
"code": null,
"e": 561,
"s": 550,
"text": "madarsh986"
},
{
"code": null,
"e": 574,
"s": 561,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 592,
"s": 574,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 597,
"s": 592,
"text": "GATE"
},
{
"code": null,
"e": 695,
"s": 597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 737,
"s": 695,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 799,
"s": 737,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 833,
"s": 799,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 867,
"s": 833,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 909,
"s": 867,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 951,
"s": 909,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 985,
"s": 951,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 1019,
"s": 985,
"text": "GATE | GATE CS 1996 | Question 38"
},
{
"code": null,
"e": 1053,
"s": 1019,
"text": "GATE | GATE-CS-2004 | Question 31"
}
] |
What is the meaning of let-* in Angular 2 Templates ? | 18 May, 2021
The let keyword in Angular declares a template input variable that is referenced within the template. In Angular, the micro syntax is used to configure a directive in a compact and friendly string. It is a capability given in angular to embed the variables in the template directly by translating that string into attributes on the <ng-template> tag.
Syntax:
let-variable_name = "Exported_var"
or
let-variable_name
Usage: Being a micro syntax, let is used to create temporary variable in angular which can be linked by the variable of the component class. So to bring the component variable information to the template, let is used it.
Example 1: With this example, there is a very simple implementation of the creation of an embedded variable using the ng-template tag. Here variables are formed, for which the value is assigned as This is ‘GeeksForGeeks’. The code below is to be written in the template file of the component, this is an angular 5 update.
Template File:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>let-* in Angular 2</title></head> <body> <ng-template [ngTemplateOutlet]= "TheGeekTemplate" [ngTemplateOutletContext]=" { GeeksForGeeks: 'This is GeeksForGeeks' }" #TheGeekTemplate let-GFG="GeeksForGeeks"> <div>{{GFG}}</div> </ng-template> </body> </html>
Output: In this example, the template reference is created by the #TheGeekTemplate, which is given in the next ng-template tag under the [ngTemplateOutletContext] property. The variable GFG is the variable defined by the let keyword which has a string acting as the export variable and to this variable a new value is assigned within the template by [ngTemplateOutletContext] property. For the variable Geek, the value is not provided so it takes the implicated value given to the $implicit i.e. default value.
This is GeeksForGeeks
Example 2: This example is a demo for using let in ngFor directive. Here a variable items will be linked to the component class and directly be used in the variable named elt, made by let-elt.
Template File:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>let-* in Angular 2</title></head> <body> <!--The item variable used as --> <ng-template ngFor let-elt [ngForOf]="array"> <div style="color:green;"> <h1>{{elt}} GeeksForGeeks</h1> </div> </ng-template></body> </html>
Component File:
Javascript
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { // The array variable in component file array=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
Output: Here the output will be GeeksForGeeks written 10 times along with the index, in the code the array variable is an array with elements in range 1 to 10. The elements are shown by the embedded variable item using let, along with GeeksForGeeks written on it.
let-* Vs let-*=”Var”: The let-*=”Var” will pick the value of the variable defined in the ngTemplateOutletContext property of the <ng-template> tag and “let-*” will pick up the default value defined in the same property given under the $implicit variable name.
Example 3: Here two variables are formed, for one the value is assigned and for the second variable, the values will be linked to an export variable. The code below is to be written in the template file of the component.
Template File:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>let-* in Angular 2</title></head> <body> <ng-template [ngTemplateOutlet]= "TheGeekTemplate" [ngTemplateOutletContext]="{ $implicit: 'Default Value', GeeksforGeeks: 'This is GeeksforGeeks' }" #TheGeekTemplate let-GFG="GeeksforGeeks" let-Geek> <div>{{GFG}}</div> <div>{{Geek}}</div> </ng-template></body> </html>
Output:
This is GeeksForGeeks
Default Value
bunnyram19
saurabh1990aror
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
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": "\n18 May, 2021"
},
{
"code": null,
"e": 380,
"s": 28,
"text": "The let keyword in Angular declares a template input variable that is referenced within the template. In Angular, the micro syntax is used to configure a directive in a compact and friendly string. It is a capability given in angular to embed the variables in the template directly by translating that string into attributes on the <ng-template> tag. "
},
{
"code": null,
"e": 389,
"s": 380,
"text": "Syntax: "
},
{
"code": null,
"e": 424,
"s": 389,
"text": "let-variable_name = \"Exported_var\""
},
{
"code": null,
"e": 429,
"s": 424,
"text": "or "
},
{
"code": null,
"e": 447,
"s": 429,
"text": "let-variable_name"
},
{
"code": null,
"e": 668,
"s": 447,
"text": "Usage: Being a micro syntax, let is used to create temporary variable in angular which can be linked by the variable of the component class. So to bring the component variable information to the template, let is used it."
},
{
"code": null,
"e": 990,
"s": 668,
"text": "Example 1: With this example, there is a very simple implementation of the creation of an embedded variable using the ng-template tag. Here variables are formed, for which the value is assigned as This is ‘GeeksForGeeks’. The code below is to be written in the template file of the component, this is an angular 5 update."
},
{
"code": null,
"e": 1005,
"s": 990,
"text": "Template File:"
},
{
"code": null,
"e": 1010,
"s": 1005,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>let-* in Angular 2</title></head> <body> <ng-template [ngTemplateOutlet]= \"TheGeekTemplate\" [ngTemplateOutletContext]=\" { GeeksForGeeks: 'This is GeeksForGeeks' }\" #TheGeekTemplate let-GFG=\"GeeksForGeeks\"> <div>{{GFG}}</div> </ng-template> </body> </html>",
"e": 1576,
"s": 1010,
"text": null
},
{
"code": null,
"e": 2088,
"s": 1576,
"text": "Output: In this example, the template reference is created by the #TheGeekTemplate, which is given in the next ng-template tag under the [ngTemplateOutletContext] property. The variable GFG is the variable defined by the let keyword which has a string acting as the export variable and to this variable a new value is assigned within the template by [ngTemplateOutletContext] property. For the variable Geek, the value is not provided so it takes the implicated value given to the $implicit i.e. default value. "
},
{
"code": null,
"e": 2110,
"s": 2088,
"text": "This is GeeksForGeeks"
},
{
"code": null,
"e": 2304,
"s": 2110,
"text": "Example 2: This example is a demo for using let in ngFor directive. Here a variable items will be linked to the component class and directly be used in the variable named elt, made by let-elt. "
},
{
"code": null,
"e": 2319,
"s": 2304,
"text": "Template File:"
},
{
"code": null,
"e": 2324,
"s": 2319,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>let-* in Angular 2</title></head> <body> <!--The item variable used as --> <ng-template ngFor let-elt [ngForOf]=\"array\"> <div style=\"color:green;\"> <h1>{{elt}} GeeksForGeeks</h1> </div> </ng-template></body> </html>",
"e": 2792,
"s": 2324,
"text": null
},
{
"code": null,
"e": 2808,
"s": 2792,
"text": "Component File:"
},
{
"code": null,
"e": 2819,
"s": 2808,
"text": "Javascript"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { // The array variable in component file array=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}",
"e": 3083,
"s": 2819,
"text": null
},
{
"code": null,
"e": 3348,
"s": 3083,
"text": "Output: Here the output will be GeeksForGeeks written 10 times along with the index, in the code the array variable is an array with elements in range 1 to 10. The elements are shown by the embedded variable item using let, along with GeeksForGeeks written on it. "
},
{
"code": null,
"e": 3608,
"s": 3348,
"text": "let-* Vs let-*=”Var”: The let-*=”Var” will pick the value of the variable defined in the ngTemplateOutletContext property of the <ng-template> tag and “let-*” will pick up the default value defined in the same property given under the $implicit variable name."
},
{
"code": null,
"e": 3831,
"s": 3608,
"text": "Example 3: Here two variables are formed, for one the value is assigned and for the second variable, the values will be linked to an export variable. The code below is to be written in the template file of the component. "
},
{
"code": null,
"e": 3846,
"s": 3831,
"text": "Template File:"
},
{
"code": null,
"e": 3851,
"s": 3846,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>let-* in Angular 2</title></head> <body> <ng-template [ngTemplateOutlet]= \"TheGeekTemplate\" [ngTemplateOutletContext]=\"{ $implicit: 'Default Value', GeeksforGeeks: 'This is GeeksforGeeks' }\" #TheGeekTemplate let-GFG=\"GeeksforGeeks\" let-Geek> <div>{{GFG}}</div> <div>{{Geek}}</div> </ng-template></body> </html>",
"e": 4486,
"s": 3851,
"text": null
},
{
"code": null,
"e": 4495,
"s": 4486,
"text": "Output: "
},
{
"code": null,
"e": 4531,
"s": 4495,
"text": "This is GeeksForGeeks\nDefault Value"
},
{
"code": null,
"e": 4544,
"s": 4533,
"text": "bunnyram19"
},
{
"code": null,
"e": 4560,
"s": 4544,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4575,
"s": 4560,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 4582,
"s": 4575,
"text": "Picked"
},
{
"code": null,
"e": 4592,
"s": 4582,
"text": "AngularJS"
},
{
"code": null,
"e": 4609,
"s": 4592,
"text": "Web Technologies"
},
{
"code": null,
"e": 4636,
"s": 4609,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4734,
"s": 4636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4758,
"s": 4734,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 4793,
"s": 4758,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 4817,
"s": 4793,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 4870,
"s": 4817,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 4919,
"s": 4870,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 4952,
"s": 4919,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5014,
"s": 4952,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5075,
"s": 5014,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5125,
"s": 5075,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Menu widget in Tkinter | 12 Apr, 2019
Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used package for GUI applications which comes with the Python itself.
Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows.
menu = Menu(master, **options)
Below is the implementation:
# importing only those functions # which are neededfrom tkinter import * from tkinter.ttk import * from time import strftime # creating tkinter windowroot = Tk()root.title('Menu Demonstration') # Creating Menubarmenubar = Menu(root) # Adding File Menu and commandsfile = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='File', menu = file)file.add_command(label ='New File', command = None)file.add_command(label ='Open...', command = None)file.add_command(label ='Save', command = None)file.add_separator()file.add_command(label ='Exit', command = root.destroy) # Adding Edit Menu and commandsedit = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='Edit', menu = edit)edit.add_command(label ='Cut', command = None)edit.add_command(label ='Copy', command = None)edit.add_command(label ='Paste', command = None)edit.add_command(label ='Select All', command = None)edit.add_separator()edit.add_command(label ='Find...', command = None)edit.add_command(label ='Find again', command = None) # Adding Help Menuhelp_ = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='Help', menu = help_)help_.add_command(label ='Tk Help', command = None)help_.add_command(label ='Demo', command = None)help_.add_separator()help_.add_command(label ='About Tk', command = None) # display Menuroot.config(menu = menubar)mainloop()
Output:
Note: In above application, commands are set to None but one may add different commands to different labels to perform the required task.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 223,
"s": 53,
"text": "Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used package for GUI applications which comes with the Python itself."
},
{
"code": null,
"e": 513,
"s": 223,
"text": "Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows."
},
{
"code": null,
"e": 544,
"s": 513,
"text": "menu = Menu(master, **options)"
},
{
"code": null,
"e": 574,
"s": 544,
"text": " Below is the implementation:"
},
{
"code": "# importing only those functions # which are neededfrom tkinter import * from tkinter.ttk import * from time import strftime # creating tkinter windowroot = Tk()root.title('Menu Demonstration') # Creating Menubarmenubar = Menu(root) # Adding File Menu and commandsfile = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='File', menu = file)file.add_command(label ='New File', command = None)file.add_command(label ='Open...', command = None)file.add_command(label ='Save', command = None)file.add_separator()file.add_command(label ='Exit', command = root.destroy) # Adding Edit Menu and commandsedit = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='Edit', menu = edit)edit.add_command(label ='Cut', command = None)edit.add_command(label ='Copy', command = None)edit.add_command(label ='Paste', command = None)edit.add_command(label ='Select All', command = None)edit.add_separator()edit.add_command(label ='Find...', command = None)edit.add_command(label ='Find again', command = None) # Adding Help Menuhelp_ = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='Help', menu = help_)help_.add_command(label ='Tk Help', command = None)help_.add_command(label ='Demo', command = None)help_.add_separator()help_.add_command(label ='About Tk', command = None) # display Menuroot.config(menu = menubar)mainloop()",
"e": 1903,
"s": 574,
"text": null
},
{
"code": null,
"e": 1911,
"s": 1903,
"text": "Output:"
},
{
"code": null,
"e": 2049,
"s": 1911,
"text": "Note: In above application, commands are set to None but one may add different commands to different labels to perform the required task."
},
{
"code": null,
"e": 2060,
"s": 2049,
"text": "Python-gui"
},
{
"code": null,
"e": 2075,
"s": 2060,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2082,
"s": 2075,
"text": "Python"
},
{
"code": null,
"e": 2180,
"s": 2082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2208,
"s": 2180,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2258,
"s": 2208,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2280,
"s": 2258,
"text": "Python map() function"
},
{
"code": null,
"e": 2324,
"s": 2280,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2366,
"s": 2324,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2388,
"s": 2366,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2423,
"s": 2388,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2449,
"s": 2423,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2481,
"s": 2449,
"text": "How to Install PIP on Windows ?"
}
] |
How to send a variable from Activity to Fragment in Android using Kotlin? | This example demonstrates how to send a variable from Activity to Fragment in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="2dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"
android:hint="ENTER YOUR MESSAGE" />
<Button
android:id="@+id/btnSendData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send data" />
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val fragmentManager: FragmentManager = supportFragmentManager
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
val myFragment = MyFragment()
button = findViewById(R.id.btnSendData)
editText = findViewById(R.id.editText)
button.setOnClickListener {
val bundle = Bundle()
bundle.putString("message", editText.text.toString())
myFragment.arguments = bundle
fragmentTransaction.add(R.id.frameLayout, myFragment).commit()
}
}
}
Step 4 − Create a new Blank Fragment and add the following codes
MyFragment.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
class MyFragment : Fragment() {
private lateinit var textView:TextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_my, container, false)
textView = view.findViewById<View>(R.id.textView) as TextView
val bundle = arguments
val message = bundle!!.getString("message")
textView.text = message
return view
}
}
fragment_my.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="4dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@android:color/holo_orange_dark"
android:textSize="36sp"
android:textStyle="bold" />
</LinearLayout>
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. | [
{
"code": null,
"e": 1287,
"s": 1187,
"text": "This example demonstrates how to send a variable from Activity to Fragment in Android using Kotlin."
},
{
"code": null,
"e": 1416,
"s": 1287,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1481,
"s": 1416,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2393,
"s": 1481,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"2dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20sp\"\n android:hint=\"ENTER YOUR MESSAGE\" />\n <Button\n android:id=\"@+id/btnSendData\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Send data\" />\n <FrameLayout\n android:id=\"@+id/frameLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n </FrameLayout>\n</LinearLayout>"
},
{
"code": null,
"e": 2448,
"s": 2393,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3489,
"s": 2448,
"text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.EditText\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.fragment.app.FragmentManager\nimport androidx.fragment.app.FragmentTransaction\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val fragmentManager: FragmentManager = supportFragmentManager\n val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()\n val myFragment = MyFragment()\n button = findViewById(R.id.btnSendData)\n editText = findViewById(R.id.editText)\n button.setOnClickListener {\n val bundle = Bundle()\n bundle.putString(\"message\", editText.text.toString())\n myFragment.arguments = bundle\n fragmentTransaction.add(R.id.frameLayout, myFragment).commit()\n }\n }\n}"
},
{
"code": null,
"e": 3554,
"s": 3489,
"text": "Step 4 − Create a new Blank Fragment and add the following codes"
},
{
"code": null,
"e": 3568,
"s": 3554,
"text": "MyFragment.kt"
},
{
"code": null,
"e": 4241,
"s": 3568,
"text": "import android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.TextView\nimport androidx.fragment.app.Fragment\nclass MyFragment : Fragment() {\n private lateinit var textView:TextView\n override fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n val view: View = inflater.inflate(R.layout.fragment_my, container, false)\n textView = view.findViewById<View>(R.id.textView) as TextView\n val bundle = arguments\n val message = bundle!!.getString(\"message\")\n textView.text = message\n return view\n }\n}"
},
{
"code": null,
"e": 4257,
"s": 4241,
"text": "fragment_my.xml"
},
{
"code": null,
"e": 4771,
"s": 4257,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:padding=\"4dp\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:textColor=\"@android:color/holo_orange_dark\"\n android:textSize=\"36sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 4826,
"s": 4771,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5500,
"s": 4826,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5849,
"s": 5500,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
How to align image vertically in a division that spans vertically on the whole webpage using CSS ? | 22 Aug, 2021
In this article, we will discuss the vertical alignment of images in a single division that spans vertically on the whole webpage. Vertical alignment of images refers to placing the images in a column. We often need to align the image vertically in order to display it properly on the mobile version or sometimes, we don’t want to insert a horizontal scroll bar. We will use the CSS flex property for this purpose.
Approach:
Create a div tag to place the images.
In the <img> tag, provide the path of the images using the src attribute and an alternative text using the alt attribute.
Add CSS properties to display the images in a vertical alignment.
Example 1: In this example, we have used the text that illustrates the vertical alignment of the image along with the text. For this, we have used the vertical-align CSS property to align it vertically.
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Vertical images layout</title> <style> body { background: rgb(225, 227, 222); } .container { border: 1px solid black; height: 205px; width: 590px; padding: 5px; margin-top: 180px; margin-left: 350px; border-radius: 5px; } .container img { width: 200px; height: 200px; padding: 3px; border-radius: 7px; } span { padding: 1px; font-size: 60px; color: green; vertical-align: 128%; } </style> </head> <body> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="image-2"/> <span>GeeksforGeeks</span> </div> </body></html>
Output: From the output, we can see that the image that is vertical-align with the text.
In order to align the series of images vertically, we will use CSS display property combined with align-items & flex-direction property. We need to create a parent element. After declaring the parent element as flexbox using display: flex;, we can align the items to the center using align-items: center; along with setting the direction of the column as vertical using flex-direction: column;.
Syntax:
.class_name {
display: flex;
flex-direction: column;
align-items: center;
}
We will declare the CSS properties in the style tag to change the layout.
display: flex – The flex property in CSS is used to set the length of flexible items and expands or shrink the items to fill extra space or to prevent overflow respectively.flex-direction: column – This property is used to align the items of the class on which it is applied in a vertical way.align-items: center – This property is used to display the items in the center of the screen.
display: flex – The flex property in CSS is used to set the length of flexible items and expands or shrink the items to fill extra space or to prevent overflow respectively.
flex-direction: column – This property is used to align the items of the class on which it is applied in a vertical way.
align-items: center – This property is used to display the items in the center of the screen.
Example 2: In this example, we will display the images vertically using the above approach.
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Vertical images layout</title> <style> body { background: rgb(225, 227, 222); } .container { display: flex; flex-direction: column; align-items: center; } .container img { width: 200px; height: 200px; padding: 3px; margin-left: 3px; } </style> </head> <body> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png" alt="image-1"/> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="image-2"/> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png" alt="image-3"/> </div> </body></html>
Output: Here, we can see that all 3 images are aligned vertically.
Note: If we do need not define the size of the images explicitly, images will cover the whole webpage. The size of the images may vary as per the requirement.
Supported Browsers:
Google Chrome 29.0
Firefox 28.0
Microsoft Edge 11.0
Safari 9.0
Opera 17.0
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Aug, 2021"
},
{
"code": null,
"e": 469,
"s": 54,
"text": "In this article, we will discuss the vertical alignment of images in a single division that spans vertically on the whole webpage. Vertical alignment of images refers to placing the images in a column. We often need to align the image vertically in order to display it properly on the mobile version or sometimes, we don’t want to insert a horizontal scroll bar. We will use the CSS flex property for this purpose."
},
{
"code": null,
"e": 479,
"s": 469,
"text": "Approach:"
},
{
"code": null,
"e": 517,
"s": 479,
"text": "Create a div tag to place the images."
},
{
"code": null,
"e": 639,
"s": 517,
"text": "In the <img> tag, provide the path of the images using the src attribute and an alternative text using the alt attribute."
},
{
"code": null,
"e": 705,
"s": 639,
"text": "Add CSS properties to display the images in a vertical alignment."
},
{
"code": null,
"e": 908,
"s": 705,
"text": "Example 1: In this example, we have used the text that illustrates the vertical alignment of the image along with the text. For this, we have used the vertical-align CSS property to align it vertically."
},
{
"code": null,
"e": 913,
"s": 908,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Vertical images layout</title> <style> body { background: rgb(225, 227, 222); } .container { border: 1px solid black; height: 205px; width: 590px; padding: 5px; margin-top: 180px; margin-left: 350px; border-radius: 5px; } .container img { width: 200px; height: 200px; padding: 3px; border-radius: 7px; } span { padding: 1px; font-size: 60px; color: green; vertical-align: 128%; } </style> </head> <body> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"image-2\"/> <span>GeeksforGeeks</span> </div> </body></html>",
"e": 1737,
"s": 913,
"text": null
},
{
"code": null,
"e": 1826,
"s": 1737,
"text": "Output: From the output, we can see that the image that is vertical-align with the text."
},
{
"code": null,
"e": 2221,
"s": 1826,
"text": "In order to align the series of images vertically, we will use CSS display property combined with align-items & flex-direction property. We need to create a parent element. After declaring the parent element as flexbox using display: flex;, we can align the items to the center using align-items: center; along with setting the direction of the column as vertical using flex-direction: column;."
},
{
"code": null,
"e": 2229,
"s": 2221,
"text": "Syntax:"
},
{
"code": null,
"e": 2317,
"s": 2229,
"text": ".class_name {\n display: flex;\n flex-direction: column;\n align-items: center;\n}"
},
{
"code": null,
"e": 2391,
"s": 2317,
"text": "We will declare the CSS properties in the style tag to change the layout."
},
{
"code": null,
"e": 2778,
"s": 2391,
"text": "display: flex – The flex property in CSS is used to set the length of flexible items and expands or shrink the items to fill extra space or to prevent overflow respectively.flex-direction: column – This property is used to align the items of the class on which it is applied in a vertical way.align-items: center – This property is used to display the items in the center of the screen."
},
{
"code": null,
"e": 2952,
"s": 2778,
"text": "display: flex – The flex property in CSS is used to set the length of flexible items and expands or shrink the items to fill extra space or to prevent overflow respectively."
},
{
"code": null,
"e": 3073,
"s": 2952,
"text": "flex-direction: column – This property is used to align the items of the class on which it is applied in a vertical way."
},
{
"code": null,
"e": 3167,
"s": 3073,
"text": "align-items: center – This property is used to display the items in the center of the screen."
},
{
"code": null,
"e": 3259,
"s": 3167,
"text": "Example 2: In this example, we will display the images vertically using the above approach."
},
{
"code": null,
"e": 3264,
"s": 3259,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Vertical images layout</title> <style> body { background: rgb(225, 227, 222); } .container { display: flex; flex-direction: column; align-items: center; } .container img { width: 200px; height: 200px; padding: 3px; margin-left: 3px; } </style> </head> <body> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png\" alt=\"image-1\"/> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"image-2\"/> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png\" alt=\"image-3\"/> </div> </body></html>",
"e": 4075,
"s": 3264,
"text": null
},
{
"code": null,
"e": 4142,
"s": 4075,
"text": "Output: Here, we can see that all 3 images are aligned vertically."
},
{
"code": null,
"e": 4302,
"s": 4142,
"text": "Note: If we do need not define the size of the images explicitly, images will cover the whole webpage. The size of the images may vary as per the requirement. "
},
{
"code": null,
"e": 4322,
"s": 4302,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 4341,
"s": 4322,
"text": "Google Chrome 29.0"
},
{
"code": null,
"e": 4354,
"s": 4341,
"text": "Firefox 28.0"
},
{
"code": null,
"e": 4374,
"s": 4354,
"text": "Microsoft Edge 11.0"
},
{
"code": null,
"e": 4385,
"s": 4374,
"text": "Safari 9.0"
},
{
"code": null,
"e": 4396,
"s": 4385,
"text": "Opera 17.0"
},
{
"code": null,
"e": 4411,
"s": 4396,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4425,
"s": 4411,
"text": "CSS-Questions"
},
{
"code": null,
"e": 4440,
"s": 4425,
"text": "HTML-Questions"
},
{
"code": null,
"e": 4447,
"s": 4440,
"text": "Picked"
},
{
"code": null,
"e": 4451,
"s": 4447,
"text": "CSS"
},
{
"code": null,
"e": 4456,
"s": 4451,
"text": "HTML"
},
{
"code": null,
"e": 4473,
"s": 4456,
"text": "Web Technologies"
},
{
"code": null,
"e": 4478,
"s": 4473,
"text": "HTML"
},
{
"code": null,
"e": 4576,
"s": 4478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4615,
"s": 4576,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4654,
"s": 4615,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4693,
"s": 4654,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4722,
"s": 4693,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4759,
"s": 4722,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 4783,
"s": 4759,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4836,
"s": 4783,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4896,
"s": 4836,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4957,
"s": 4896,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to get the longest string in an array using JavaScript ? | 31 Dec, 2019
The task is to get the longest string from the array. Here a few of the most used techniques discussed with the help of JavaScript. In this article, we will use two JavaScript methods sort() method and the reduce() method to find out the longest string the array. Both the approach are described below with the example.
Approach 1: In this approach we will use .sort() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. If the answer is positive then ‘b’ is greater else ‘a’ is greater. This method arranges the elements in the decreasing order of their length and we can access the first element by [0].
Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ] </b> </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ]; // It compares the length of an element with // every other element and after sorting // them in decreasing order it returns the // first element. function gfg_Run() { el_down.innerHTML = "'" + arr.sort(function(a, b) { return b.length - a.length; })[0] + "' is the longest string" + " in the array."; } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ] </b> </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ]; // It compares the length of an element with // every other element and after sorting // them in decreasing order it returns the // first element. function gfg_Run() { el_down.innerHTML = "'" + arr.sort(function(a, b) { return b.length - a.length; })[0] + "' is the longest string" + " in the array."; } </script></body> </html>
Output:
Approach 2: In this approach we will use .reduce() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. It returns the elements which has its length greater than every element.
Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ] </b> </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ]; // It compares the length of a element with // every other element and return it if its // greater than every other element. function gfg_Run() { el_down.innerHTML = "'" + arr.reduce(function (a, b) { return a.length > b.length ? a : b; }) + "' is the longest string" + " in the array."; } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ] </b> </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [ "A_Copmuter_Science_Portal", "GeeksforGeeks", "GFG", "geeks" ]; // It compares the length of a element with // every other element and return it if its // greater than every other element. function gfg_Run() { el_down.innerHTML = "'" + arr.reduce(function (a, b) { return a.length > b.length ? a : b; }) + "' is the longest string" + " in the array."; } </script></body> </html>
Output:
JavaScript-Misc
javascript-string
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "The task is to get the longest string from the array. Here a few of the most used techniques discussed with the help of JavaScript. In this article, we will use two JavaScript methods sort() method and the reduce() method to find out the longest string the array. Both the approach are described below with the example."
},
{
"code": null,
"e": 706,
"s": 348,
"text": "Approach 1: In this approach we will use .sort() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. If the answer is positive then ‘b’ is greater else ‘a’ is greater. This method arranges the elements in the decreasing order of their length and we can access the first element by [0]."
},
{
"code": null,
"e": 2155,
"s": 706,
"text": "Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ] </b> </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ]; // It compares the length of an element with // every other element and after sorting // them in decreasing order it returns the // first element. function gfg_Run() { el_down.innerHTML = \"'\" + arr.sort(function(a, b) { return b.length - a.length; })[0] + \"' is the longest string\" + \" in the array.\"; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ] </b> </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ]; // It compares the length of an element with // every other element and after sorting // them in decreasing order it returns the // first element. function gfg_Run() { el_down.innerHTML = \"'\" + arr.sort(function(a, b) { return b.length - a.length; })[0] + \"' is the longest string\" + \" in the array.\"; } </script></body> </html>",
"e": 3552,
"s": 2155,
"text": null
},
{
"code": null,
"e": 3560,
"s": 3552,
"text": "Output:"
},
{
"code": null,
"e": 3808,
"s": 3560,
"text": "Approach 2: In this approach we will use .reduce() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. It returns the elements which has its length greater than every element."
},
{
"code": null,
"e": 5235,
"s": 3808,
"text": "Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ] </b> </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ]; // It compares the length of a element with // every other element and return it if its // greater than every other element. function gfg_Run() { el_down.innerHTML = \"'\" + arr.reduce(function (a, b) { return a.length > b.length ? a : b; }) + \"' is the longest string\" + \" in the array.\"; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to get the longest string in an array using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks{ font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the longest string in the array.<br> <b>Array = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ] </b> </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [ \"A_Copmuter_Science_Portal\", \"GeeksforGeeks\", \"GFG\", \"geeks\" ]; // It compares the length of a element with // every other element and return it if its // greater than every other element. function gfg_Run() { el_down.innerHTML = \"'\" + arr.reduce(function (a, b) { return a.length > b.length ? a : b; }) + \"' is the longest string\" + \" in the array.\"; } </script></body> </html>",
"e": 6610,
"s": 5235,
"text": null
},
{
"code": null,
"e": 6618,
"s": 6610,
"text": "Output:"
},
{
"code": null,
"e": 6634,
"s": 6618,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 6652,
"s": 6634,
"text": "javascript-string"
},
{
"code": null,
"e": 6663,
"s": 6652,
"text": "JavaScript"
},
{
"code": null,
"e": 6680,
"s": 6663,
"text": "Web Technologies"
},
{
"code": null,
"e": 6707,
"s": 6680,
"text": "Web technologies Questions"
}
] |
Android AsyncTask example and explanation | Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.
onPreExecute() − Before doing background operation we should show something on screen like progressbar or any animation to user. we can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods .
onPreExecute() − Before doing background operation we should show something on screen like progressbar or any animation to user. we can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods .
doInBackground(Params) − In this method we have to do background operation on background thread. Operations in this method should not touch on any mainthread activities or fragments.
doInBackground(Params) − In this method we have to do background operation on background thread. Operations in this method should not touch on any mainthread activities or fragments.
onProgressUpdate(Progress...) − While doing background operation, if you want to update some information on UI, we can use this method.
onProgressUpdate(Progress...) − While doing background operation, if you want to update some information on UI, we can use this method.
onPostExecute(Result) − In this method we can update ui of background operation result.
onPostExecute(Result) − In this method we can update ui of background operation result.
TypeOfVarArgParams − It contains information about what type of params used for execution.
TypeOfVarArgParams − It contains information about what type of params used for execution.
ProgressValue − It contains information about progress units. While doing background operation we can update information on ui using onProgressUpdate().
ProgressValue − It contains information about progress units. While doing background operation we can update information on ui using onProgressUpdate().
ResultValue −It contains information about result type.
ResultValue −It contains information about result type.
This example demonstrate about how to use asyncTask in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/rootview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:background = "#c1c1c1"
android:gravity = "center_horizontal"
tools:context = ".MainActivity">
<Button
android:id = "@+id/asyncTask"
android:text = "Download"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<ImageView
android:id = "@+id/image"
android:layout_width = "300dp"
android:layout_height = "300dp" />
</LinearLayout>
In the above xml we have created a button, when user click on the button it going to download image and append image to imageview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
URL ImageUrl = null;
InputStream is = null;
Bitmap bmImg = null;
ImageView imageView= null;
ProgressDialog p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.asyncTask);
imageView=findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskExample asyncTask=new AsyncTaskExample();
asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-diamond.png");
}
});
}
private class AsyncTaskExample extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("Please wait...It is downloading");
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
ImageUrl = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
return bmImg;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(imageView!=null) {
p.hide();
imageView.setImageBitmap(bitmap);
}else {
p.show();
}
}
}
}
In the above code we are downloading image using asyncTask and appending image to imageview.
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In the above AndroidManifest.xml file we have added internet permission to access internet to download image.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Now click on download button it will show progress on UI and download image at background as shown below
After downloading image, it will update on UI as shown below
Click here to download the project code | [
{
"code": null,
"e": 1459,
"s": 1187,
"text": "Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread."
},
{
"code": null,
"e": 1729,
"s": 1459,
"text": "onPreExecute() − Before doing background operation we should show something on screen like progressbar or any animation to user. we can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods ."
},
{
"code": null,
"e": 1999,
"s": 1729,
"text": "onPreExecute() − Before doing background operation we should show something on screen like progressbar or any animation to user. we can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods ."
},
{
"code": null,
"e": 2182,
"s": 1999,
"text": "doInBackground(Params) − In this method we have to do background operation on background thread. Operations in this method should not touch on any mainthread activities or fragments."
},
{
"code": null,
"e": 2365,
"s": 2182,
"text": "doInBackground(Params) − In this method we have to do background operation on background thread. Operations in this method should not touch on any mainthread activities or fragments."
},
{
"code": null,
"e": 2501,
"s": 2365,
"text": "onProgressUpdate(Progress...) − While doing background operation, if you want to update some information on UI, we can use this method."
},
{
"code": null,
"e": 2637,
"s": 2501,
"text": "onProgressUpdate(Progress...) − While doing background operation, if you want to update some information on UI, we can use this method."
},
{
"code": null,
"e": 2725,
"s": 2637,
"text": "onPostExecute(Result) − In this method we can update ui of background operation result."
},
{
"code": null,
"e": 2813,
"s": 2725,
"text": "onPostExecute(Result) − In this method we can update ui of background operation result."
},
{
"code": null,
"e": 2904,
"s": 2813,
"text": "TypeOfVarArgParams − It contains information about what type of params used for execution."
},
{
"code": null,
"e": 2995,
"s": 2904,
"text": "TypeOfVarArgParams − It contains information about what type of params used for execution."
},
{
"code": null,
"e": 3148,
"s": 2995,
"text": "ProgressValue − It contains information about progress units. While doing background operation we can update information on ui using onProgressUpdate()."
},
{
"code": null,
"e": 3301,
"s": 3148,
"text": "ProgressValue − It contains information about progress units. While doing background operation we can update information on ui using onProgressUpdate()."
},
{
"code": null,
"e": 3357,
"s": 3301,
"text": "ResultValue −It contains information about result type."
},
{
"code": null,
"e": 3413,
"s": 3357,
"text": "ResultValue −It contains information about result type."
},
{
"code": null,
"e": 3477,
"s": 3413,
"text": "This example demonstrate about how to use asyncTask in android."
},
{
"code": null,
"e": 3606,
"s": 3477,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 3671,
"s": 3606,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 4387,
"s": 3671,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:id = \"@+id/rootview\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:orientation = \"vertical\"\n android:background = \"#c1c1c1\"\n android:gravity = \"center_horizontal\"\n tools:context = \".MainActivity\">\n<Button\n android:id = \"@+id/asyncTask\"\n android:text = \"Download\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n<ImageView\n android:id = \"@+id/image\"\n android:layout_width = \"300dp\"\n android:layout_height = \"300dp\" />\n</LinearLayout>"
},
{
"code": null,
"e": 4518,
"s": 4387,
"text": "In the above xml we have created a button, when user click on the button it going to download image and append image to imageview."
},
{
"code": null,
"e": 4575,
"s": 4518,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 7027,
"s": 4575,
"text": "package com.example.andy.myapplication;\nimport android.app.ProgressDialog;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\npublic class MainActivity extends AppCompatActivity {\n URL ImageUrl = null;\n InputStream is = null;\n Bitmap bmImg = null;\n ImageView imageView= null;\n ProgressDialog p;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button button=findViewById(R.id.asyncTask);\n imageView=findViewById(R.id.image);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AsyncTaskExample asyncTask=new AsyncTaskExample();\n asyncTask.execute(\"https://www.tutorialspoint.com/images/tp-logo-diamond.png\");\n }\n });\n }\n private class AsyncTaskExample extends AsyncTask<String, String, Bitmap> {\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n p = new ProgressDialog(MainActivity.this);\n p.setMessage(\"Please wait...It is downloading\");\n p.setIndeterminate(false);\n p.setCancelable(false);\n p.show();\n }\n @Override\n protected Bitmap doInBackground(String... strings) {\n try {\n ImageUrl = new URL(strings[0]);\n HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();\n conn.setDoInput(true);\n conn.connect();\n is = conn.getInputStream();\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inPreferredConfig = Bitmap.Config.RGB_565;\n bmImg = BitmapFactory.decodeStream(is, null, options);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return bmImg;\n }\n @Override\n protected void onPostExecute(Bitmap bitmap) {\n super.onPostExecute(bitmap);\n if(imageView!=null) {\n p.hide();\n imageView.setImageBitmap(bitmap);\n }else {\n p.show();\n }\n }\n }\n}"
},
{
"code": null,
"e": 7120,
"s": 7027,
"text": "In the above code we are downloading image using asyncTask and appending image to imageview."
},
{
"code": null,
"e": 7168,
"s": 7120,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 7947,
"s": 7168,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\npackage = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 8057,
"s": 7947,
"text": "In the above AndroidManifest.xml file we have added internet permission to access internet to download image."
},
{
"code": null,
"e": 8419,
"s": 8057,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 8524,
"s": 8419,
"text": "Now click on download button it will show progress on UI and download image at background as shown below"
},
{
"code": null,
"e": 8585,
"s": 8524,
"text": "After downloading image, it will update on UI as shown below"
},
{
"code": null,
"e": 8625,
"s": 8585,
"text": "Click here to download the project code"
}
] |
Ruby | Array push() function | 06 Dec, 2019
Array#push() : push() is a Array class method which appends the given object(s) on to the end of this array.
Syntax: Array.push()
Parameter: Array
Return: appends the given object(s) on to the end of this array.
Example #1 :
# Ruby code for push() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [34, 5, 7] # push method exampleputs "push() method form : #{a.push(3)}\n\n" puts "push() method form : #{b.push()}\n\n" puts "push() method form : #{c.push(2)}\n\n"
Output :
push() method form : [18, 22, 33, nil, 5, 6, 3]
push() method form : [1, 4, 1, 1, 88, 9]
push() method form : [34, 5, 7, 2]
Example #2 :
# Ruby code for push() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = [nil, "abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # push method exampleputs "push() method form : #{a.push(2)}\n\n" puts "push() method form : #{b.push(1)}\n\n" puts "push() method form : #{c.push(0)}\n\n"
Output :
push() method form : ["abc", "nil", "dog", 2]
push() method form : ["cow", nil, "dog", 1]
push() method form : [nil, "abc", "nil", "dog", 0]
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby For Beginners
Ruby | Array class find_index() operation
Ruby | String concat Method
Ruby on Rails Introduction
Ruby | Array shift() function
Ruby | Types of Variables | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "Array#push() : push() is a Array class method which appends the given object(s) on to the end of this array."
},
{
"code": null,
"e": 158,
"s": 137,
"text": "Syntax: Array.push()"
},
{
"code": null,
"e": 175,
"s": 158,
"text": "Parameter: Array"
},
{
"code": null,
"e": 240,
"s": 175,
"text": "Return: appends the given object(s) on to the end of this array."
},
{
"code": null,
"e": 253,
"s": 240,
"text": "Example #1 :"
},
{
"code": "# Ruby code for push() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [34, 5, 7] # push method exampleputs \"push() method form : #{a.push(3)}\\n\\n\" puts \"push() method form : #{b.push()}\\n\\n\" puts \"push() method form : #{c.push(2)}\\n\\n\"",
"e": 562,
"s": 253,
"text": null
},
{
"code": null,
"e": 571,
"s": 562,
"text": "Output :"
},
{
"code": null,
"e": 699,
"s": 571,
"text": "push() method form : [18, 22, 33, nil, 5, 6, 3]\n\npush() method form : [1, 4, 1, 1, 88, 9]\n\npush() method form : [34, 5, 7, 2]\n\n"
},
{
"code": null,
"e": 712,
"s": 699,
"text": "Example #2 :"
},
{
"code": "# Ruby code for push() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [nil, \"abc\", \"nil\", \"dog\"] # declaring arrayb = [\"cow\", nil, \"dog\"] # push method exampleputs \"push() method form : #{a.push(2)}\\n\\n\" puts \"push() method form : #{b.push(1)}\\n\\n\" puts \"push() method form : #{c.push(0)}\\n\\n\"",
"e": 1038,
"s": 712,
"text": null
},
{
"code": null,
"e": 1047,
"s": 1038,
"text": "Output :"
},
{
"code": null,
"e": 1192,
"s": 1047,
"text": "push() method form : [\"abc\", \"nil\", \"dog\", 2]\n\npush() method form : [\"cow\", nil, \"dog\", 1]\n\npush() method form : [nil, \"abc\", \"nil\", \"dog\", 0]\n\n"
},
{
"code": null,
"e": 1209,
"s": 1192,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 1222,
"s": 1209,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1227,
"s": 1222,
"text": "Ruby"
},
{
"code": null,
"e": 1325,
"s": 1227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1371,
"s": 1325,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1414,
"s": 1371,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1458,
"s": 1414,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1477,
"s": 1458,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 1519,
"s": 1477,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 1547,
"s": 1519,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 1574,
"s": 1547,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 1604,
"s": 1574,
"text": "Ruby | Array shift() function"
}
] |
How to add a custom right-click menu to a webpage ? | 01 Oct, 2020
A right-click menu or context menu in a browser is a menu with multiple choices that appears on right-click mouse operation. It provides multiple functionalities relevant to that particular context. Sometimes, we want the context menu to have more options or features but we cannot modify the default context menu. So, we have to create a custom menu. Adding a custom context menu to your website or webpage makes it look more customized and relevant to the context and offers you the freedom to add desired features to it.
In this article, we will be creating a custom context menu for a webpage. It mainly involves two steps.
Preventing the default context menu from popping up when the right mouse button is clicked.
Creating our own custom context menu with HTML and CSS and displaying it on right-click.
Let us go through them in a step by step manner.
HTML code: The following HTML code snippet only shows the HTML page with the default menu which is displayed on right-click event.
HTML
<!DOCTYPE html><html> <body> <h1 style="text-align: center;"> Welcome to GeeksforGeeks. </h1> <h1 style="text-align: center;"> Hi, We are creating a custom context menu here. </h1></body> </html>
If we right-click on this page, the default menu will pop up.
JavaScript code is used to block this default menu and then we will create our custom context menu. To block the default menu, we will add an event handler for processing right-click events on the webpage. We will use the oncontextmenu property to listen to the right-click events.
We will create a rightClick() function. In this function, we will call the preventDefault() method of the mouse click event which will cancel the default behavior of the right-click event. We can also return “false” to cancel the event. Now, the default menu will not pop-up on right-click mouse button.
HTML code: The following HTML code demonstrates how to prevent the default right click event.
HTML
<!DOCTYPE html><html> <body> <h1 style="text-align: center;"> Welcome to GeeksforGeeks. </h1> <h1 style="text-align: center;"> Hi, We are creating a custom context menu here. </h1> <script type="text/javascript"> document.oncontextmenu = rightClick; function rightClick(clickEvent) { clickEvent.preventDefault(); // return false; } </script></body> </html>
The default menu is blocked. Let us create our own custom context menu. The context menu we are going to create will be an HTML list. We will also add some CSS to make it look good.
We are creating an unordered list inside a “div” tag with id and class. Add some options to the list. We will keep it hidden by setting the value of “display” property to none.
HTML
<div id="contextMenu" class="context-menu" style="display: none"> <ul> <li><a href="#">Element-1</a></li> <li><a href="#">Element-2</a></li> <li><a href="#">Element-3</a></li> <li><a href="#">Element-4</a></li> <li><a href="#">Element-5</a></li> <li><a href="#">Element-6</a></li> <li><a href="#">Element-7</a></li> </ul></div>
We will add some JavaScript code to show up the context menu on right-click. We will also modify the rightClick() function to add the functionality of showing and hiding the menu on mouse-click events.
We will add an event handler for the click event and bind it with the hideMenu() function so that if the user clicks anywhere on the page and the context menu is already being displayed, it hides. Also, we have to place the menu where the right button is clicked. To do this, we will use two properties pageX and pageY of the mouse click event which will give us the coordinates where the right button was clicked. We will hide the context menu on the mouse button click if it is already being displayed.
JavaScript code:
HTML
<script> document.onclick = hideMenu; document.oncontextmenu = rightClick; function hideMenu() { document.getElementById("contextMenu") .style.display = "none" } function rightClick(e) { e.preventDefault(); if (document.getElementById("contextMenu") .style.display == "block") hideMenu(); else{ var menu = document.getElementById("contextMenu") menu.style.display = 'block'; menu.style.left = e.pageX + "px"; menu.style.top = e.pageY + "px"; } }</script>
Output: The following output shows the custom context-menu appearing on the right-click.
On right-click, the menu appears but this is not what we want. We want it to appear where the button was clicked and it should actually look like a menu.
CSS code: We will add some CSS properties for the proper positioning and styling of the menu.
HTML
<style type="text/css"> .context-menu { position: absolute; text-align: center; background: lightgray; border: 1px solid black; } .context-menu ul { padding: 0px; margin: 0px; min-width: 150px; list-style: none; } .context-menu ul li { padding-bottom: 7px; padding-top: 7px; border: 1px solid black; } .context-menu ul li a { text-decoration: none; color: black; } .context-menu ul li:hover { background: darkgray; }</style>
Final code: The following is the combination of the above code snippets.
HTML
<!DOCTYPE html><html> <head> <style type="text/css"> .context-menu { position: absolute; text-align: center; background: lightgray; border: 1px solid black; } .context-menu ul { padding: 0px; margin: 0px; min-width: 150px; list-style: none; } .context-menu ul li { padding-bottom: 7px; padding-top: 7px; border: 1px solid black; } .context-menu ul li a { text-decoration: none; color: black; } .context-menu ul li:hover { background: darkgray; } </style> </head> <body> <h1 style="text-align: center;"> Welcome to GeeksforGeeks. </h1> <h1 style="text-align: center;"> Hi, We are creating a custom context menu here. </h1> <div id="contextMenu" class="context-menu" style="display:none"> <ul> <li><a href="#">Element-1</a></li> <li><a href="#">Element-2</a></li> <li><a href="#">Element-3</a></li> <li><a href="#">Element-4</a></li> <li><a href="#">Element-5</a></li> <li><a href="#">Element-6</a></li> <li><a href="#">Element-7</a></li> </ul> </div> <script> document.onclick = hideMenu; document.oncontextmenu = rightClick; function hideMenu() { document.getElementById( "contextMenu").style.display = "none" } function rightClick(e) { e.preventDefault(); if (document.getElementById( "contextMenu").style.display == "block") hideMenu(); else { var menu = document .getElementById("contextMenu") menu.style.display = 'block'; menu.style.left = e.pageX + "px"; menu.style.top = e.pageY + "px"; } } </script></body> </html>
This was a basic context menu that we created. You can do much more by adding some cool hover effects, shadow effects, coloring, borders, etc.
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 576,
"s": 52,
"text": "A right-click menu or context menu in a browser is a menu with multiple choices that appears on right-click mouse operation. It provides multiple functionalities relevant to that particular context. Sometimes, we want the context menu to have more options or features but we cannot modify the default context menu. So, we have to create a custom menu. Adding a custom context menu to your website or webpage makes it look more customized and relevant to the context and offers you the freedom to add desired features to it."
},
{
"code": null,
"e": 680,
"s": 576,
"text": "In this article, we will be creating a custom context menu for a webpage. It mainly involves two steps."
},
{
"code": null,
"e": 772,
"s": 680,
"text": "Preventing the default context menu from popping up when the right mouse button is clicked."
},
{
"code": null,
"e": 861,
"s": 772,
"text": "Creating our own custom context menu with HTML and CSS and displaying it on right-click."
},
{
"code": null,
"e": 910,
"s": 861,
"text": "Let us go through them in a step by step manner."
},
{
"code": null,
"e": 1041,
"s": 910,
"text": "HTML code: The following HTML code snippet only shows the HTML page with the default menu which is displayed on right-click event."
},
{
"code": null,
"e": 1046,
"s": 1041,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"text-align: center;\"> Welcome to GeeksforGeeks. </h1> <h1 style=\"text-align: center;\"> Hi, We are creating a custom context menu here. </h1></body> </html>",
"e": 1278,
"s": 1046,
"text": null
},
{
"code": null,
"e": 1340,
"s": 1278,
"text": "If we right-click on this page, the default menu will pop up."
},
{
"code": null,
"e": 1622,
"s": 1340,
"text": "JavaScript code is used to block this default menu and then we will create our custom context menu. To block the default menu, we will add an event handler for processing right-click events on the webpage. We will use the oncontextmenu property to listen to the right-click events."
},
{
"code": null,
"e": 1926,
"s": 1622,
"text": "We will create a rightClick() function. In this function, we will call the preventDefault() method of the mouse click event which will cancel the default behavior of the right-click event. We can also return “false” to cancel the event. Now, the default menu will not pop-up on right-click mouse button."
},
{
"code": null,
"e": 2020,
"s": 1926,
"text": "HTML code: The following HTML code demonstrates how to prevent the default right click event."
},
{
"code": null,
"e": 2025,
"s": 2020,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"text-align: center;\"> Welcome to GeeksforGeeks. </h1> <h1 style=\"text-align: center;\"> Hi, We are creating a custom context menu here. </h1> <script type=\"text/javascript\"> document.oncontextmenu = rightClick; function rightClick(clickEvent) { clickEvent.preventDefault(); // return false; } </script></body> </html>",
"e": 2469,
"s": 2025,
"text": null
},
{
"code": null,
"e": 2651,
"s": 2469,
"text": "The default menu is blocked. Let us create our own custom context menu. The context menu we are going to create will be an HTML list. We will also add some CSS to make it look good."
},
{
"code": null,
"e": 2828,
"s": 2651,
"text": "We are creating an unordered list inside a “div” tag with id and class. Add some options to the list. We will keep it hidden by setting the value of “display” property to none."
},
{
"code": null,
"e": 2833,
"s": 2828,
"text": "HTML"
},
{
"code": "<div id=\"contextMenu\" class=\"context-menu\" style=\"display: none\"> <ul> <li><a href=\"#\">Element-1</a></li> <li><a href=\"#\">Element-2</a></li> <li><a href=\"#\">Element-3</a></li> <li><a href=\"#\">Element-4</a></li> <li><a href=\"#\">Element-5</a></li> <li><a href=\"#\">Element-6</a></li> <li><a href=\"#\">Element-7</a></li> </ul></div>",
"e": 3220,
"s": 2833,
"text": null
},
{
"code": null,
"e": 3422,
"s": 3220,
"text": "We will add some JavaScript code to show up the context menu on right-click. We will also modify the rightClick() function to add the functionality of showing and hiding the menu on mouse-click events."
},
{
"code": null,
"e": 3927,
"s": 3422,
"text": "We will add an event handler for the click event and bind it with the hideMenu() function so that if the user clicks anywhere on the page and the context menu is already being displayed, it hides. Also, we have to place the menu where the right button is clicked. To do this, we will use two properties pageX and pageY of the mouse click event which will give us the coordinates where the right button was clicked. We will hide the context menu on the mouse button click if it is already being displayed."
},
{
"code": null,
"e": 3944,
"s": 3927,
"text": "JavaScript code:"
},
{
"code": null,
"e": 3949,
"s": 3944,
"text": "HTML"
},
{
"code": "<script> document.onclick = hideMenu; document.oncontextmenu = rightClick; function hideMenu() { document.getElementById(\"contextMenu\") .style.display = \"none\" } function rightClick(e) { e.preventDefault(); if (document.getElementById(\"contextMenu\") .style.display == \"block\") hideMenu(); else{ var menu = document.getElementById(\"contextMenu\") menu.style.display = 'block'; menu.style.left = e.pageX + \"px\"; menu.style.top = e.pageY + \"px\"; } }</script>",
"e": 4554,
"s": 3949,
"text": null
},
{
"code": null,
"e": 4643,
"s": 4554,
"text": "Output: The following output shows the custom context-menu appearing on the right-click."
},
{
"code": null,
"e": 4797,
"s": 4643,
"text": "On right-click, the menu appears but this is not what we want. We want it to appear where the button was clicked and it should actually look like a menu."
},
{
"code": null,
"e": 4891,
"s": 4797,
"text": "CSS code: We will add some CSS properties for the proper positioning and styling of the menu."
},
{
"code": null,
"e": 4896,
"s": 4891,
"text": "HTML"
},
{
"code": "<style type=\"text/css\"> .context-menu { position: absolute; text-align: center; background: lightgray; border: 1px solid black; } .context-menu ul { padding: 0px; margin: 0px; min-width: 150px; list-style: none; } .context-menu ul li { padding-bottom: 7px; padding-top: 7px; border: 1px solid black; } .context-menu ul li a { text-decoration: none; color: black; } .context-menu ul li:hover { background: darkgray; }</style>",
"e": 5457,
"s": 4896,
"text": null
},
{
"code": null,
"e": 5530,
"s": 5457,
"text": "Final code: The following is the combination of the above code snippets."
},
{
"code": null,
"e": 5535,
"s": 5530,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> .context-menu { position: absolute; text-align: center; background: lightgray; border: 1px solid black; } .context-menu ul { padding: 0px; margin: 0px; min-width: 150px; list-style: none; } .context-menu ul li { padding-bottom: 7px; padding-top: 7px; border: 1px solid black; } .context-menu ul li a { text-decoration: none; color: black; } .context-menu ul li:hover { background: darkgray; } </style> </head> <body> <h1 style=\"text-align: center;\"> Welcome to GeeksforGeeks. </h1> <h1 style=\"text-align: center;\"> Hi, We are creating a custom context menu here. </h1> <div id=\"contextMenu\" class=\"context-menu\" style=\"display:none\"> <ul> <li><a href=\"#\">Element-1</a></li> <li><a href=\"#\">Element-2</a></li> <li><a href=\"#\">Element-3</a></li> <li><a href=\"#\">Element-4</a></li> <li><a href=\"#\">Element-5</a></li> <li><a href=\"#\">Element-6</a></li> <li><a href=\"#\">Element-7</a></li> </ul> </div> <script> document.onclick = hideMenu; document.oncontextmenu = rightClick; function hideMenu() { document.getElementById( \"contextMenu\").style.display = \"none\" } function rightClick(e) { e.preventDefault(); if (document.getElementById( \"contextMenu\").style.display == \"block\") hideMenu(); else { var menu = document .getElementById(\"contextMenu\") menu.style.display = 'block'; menu.style.left = e.pageX + \"px\"; menu.style.top = e.pageY + \"px\"; } } </script></body> </html>",
"e": 7598,
"s": 5535,
"text": null
},
{
"code": null,
"e": 7741,
"s": 7598,
"text": "This was a basic context menu that we created. You can do much more by adding some cool hover effects, shadow effects, coloring, borders, etc."
},
{
"code": null,
"e": 7750,
"s": 7741,
"text": "CSS-Misc"
},
{
"code": null,
"e": 7760,
"s": 7750,
"text": "HTML-Misc"
},
{
"code": null,
"e": 7776,
"s": 7760,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 7780,
"s": 7776,
"text": "CSS"
},
{
"code": null,
"e": 7785,
"s": 7780,
"text": "HTML"
},
{
"code": null,
"e": 7796,
"s": 7785,
"text": "JavaScript"
},
{
"code": null,
"e": 7813,
"s": 7796,
"text": "Web Technologies"
},
{
"code": null,
"e": 7818,
"s": 7813,
"text": "HTML"
},
{
"code": null,
"e": 7916,
"s": 7818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7953,
"s": 7916,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 7992,
"s": 7953,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 8031,
"s": 7992,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 8095,
"s": 8031,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 8156,
"s": 8095,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 8180,
"s": 8156,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 8233,
"s": 8180,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 8293,
"s": 8233,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 8354,
"s": 8293,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How static variables in member functions work in C++? | The static variables in member functions are declared using the keyword static. The space for the static variables is allocated only one time and this is used for the entirety of the program. Also, there is only one copy of these static variables in the whole program.
A program that demonstrates static variables in member functions in C++ is given as follows.
Live Demo
#include <iostream>
using namespace std;
class Base {
public :
int func() {
static int a;
static int b = 12;
cout << "The default value of static variable a is: " << a;
cout << "\nThe value of static variable b is: " << b;
}
};
int main() {
Base b;
b.func();
return 0;
}
The output of the above program is as follows.
The default value of static variable a is: 0
The value of static variable b is: 12
Now let us understand the above program.
The member function func() in class Base contains two static variables a and b. The default value of a is 0 and the value of b is12. Then these values are displayed. The code snippet that shows this is as follows.
class Base {
public :
int func() {
static int a;
static int b = 12;
cout << "The default value of static variable a is: " << a;
cout << "\nThe value of static variable b is: " << b;
}
};
In the main() function, an object b of class Base is created. Then the function func() is called. The code snippet that shows this is as follows.
int main() {
Base b;
b.func();
return 0;
} | [
{
"code": null,
"e": 1456,
"s": 1187,
"text": "The static variables in member functions are declared using the keyword static. The space for the static variables is allocated only one time and this is used for the entirety of the program. Also, there is only one copy of these static variables in the whole program."
},
{
"code": null,
"e": 1549,
"s": 1456,
"text": "A program that demonstrates static variables in member functions in C++ is given as follows."
},
{
"code": null,
"e": 1560,
"s": 1549,
"text": " Live Demo"
},
{
"code": null,
"e": 1873,
"s": 1560,
"text": "#include <iostream>\nusing namespace std;\nclass Base {\n public :\n int func() {\n static int a;\n static int b = 12;\n cout << \"The default value of static variable a is: \" << a;\n cout << \"\\nThe value of static variable b is: \" << b;\n }\n};\nint main() {\n Base b;\n b.func();\n return 0;\n}"
},
{
"code": null,
"e": 1920,
"s": 1873,
"text": "The output of the above program is as follows."
},
{
"code": null,
"e": 2003,
"s": 1920,
"text": "The default value of static variable a is: 0\nThe value of static variable b is: 12"
},
{
"code": null,
"e": 2044,
"s": 2003,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2258,
"s": 2044,
"text": "The member function func() in class Base contains two static variables a and b. The default value of a is 0 and the value of b is12. Then these values are displayed. The code snippet that shows this is as follows."
},
{
"code": null,
"e": 2478,
"s": 2258,
"text": "class Base {\n public :\n int func() {\n static int a;\n static int b = 12;\n cout << \"The default value of static variable a is: \" << a;\n cout << \"\\nThe value of static variable b is: \" << b;\n }\n};"
},
{
"code": null,
"e": 2624,
"s": 2478,
"text": "In the main() function, an object b of class Base is created. Then the function func() is called. The code snippet that shows this is as follows."
},
{
"code": null,
"e": 2676,
"s": 2624,
"text": "int main() {\n Base b;\n b.func();\n return 0;\n}"
}
] |
C# Example for Hierarchical Inheritance | More than one class is inherited from the base class in Hierarchical Inheritance.
In the example, our base class is Father −
class Father {
public void display() {
Console.WriteLine("Display...");
}
}
It has Son and Daughter as the derived class. Let us how to add a derived class in Inheritance −
class Son : Father {
public void displayOne() {
Console.WriteLine("Display One");
}
}
The following the complete example of implementing Hierarchical Inheritance in C# −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inheritance {
class Test {
static void Main(string[] args) {
Father f = new Father();
f.display();
Son s = new Son();
s.display();
s.displayOne();
Daughter d = new Daughter();
d.displayTwo();
Console.ReadKey();
}
class Father {
public void display() {
Console.WriteLine("Display...");
}
}
class Son : Father {
public void displayOne() {
Console.WriteLine("Display One");
}
}
class Daughter : Father {
public void displayTwo() {
Console.WriteLine("Display Two");
}
}
}
} | [
{
"code": null,
"e": 1269,
"s": 1187,
"text": "More than one class is inherited from the base class in Hierarchical Inheritance."
},
{
"code": null,
"e": 1312,
"s": 1269,
"text": "In the example, our base class is Father −"
},
{
"code": null,
"e": 1400,
"s": 1312,
"text": "class Father {\n public void display() {\n Console.WriteLine(\"Display...\");\n }\n}"
},
{
"code": null,
"e": 1497,
"s": 1400,
"text": "It has Son and Daughter as the derived class. Let us how to add a derived class in Inheritance −"
},
{
"code": null,
"e": 1595,
"s": 1497,
"text": "class Son : Father {\n public void displayOne() {\n Console.WriteLine(\"Display One\");\n }\n}"
},
{
"code": null,
"e": 1679,
"s": 1595,
"text": "The following the complete example of implementing Hierarchical Inheritance in C# −"
},
{
"code": null,
"e": 2461,
"s": 1679,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Inheritance {\n class Test {\n static void Main(string[] args) {\n Father f = new Father();\n f.display();\n Son s = new Son();\n s.display();\n s.displayOne();\n Daughter d = new Daughter();\n d.displayTwo();\n Console.ReadKey();\n }\n class Father {\n public void display() {\n Console.WriteLine(\"Display...\");\n }\n }\n class Son : Father {\n public void displayOne() {\n Console.WriteLine(\"Display One\");\n }\n }\n class Daughter : Father {\n public void displayTwo() {\n Console.WriteLine(\"Display Two\");\n }\n }\n }\n}"
}
] |
Program for K Most Recently Used (MRU) Apps | 29 Aug, 2021
Given an integer K and an array arr[] of N integers which contains the ids of the opened apps in a system where
arr[0] is the app currently in usearr[1] is the app which was most recently used andarr[N – 1] is the app which was least recently used.
arr[0] is the app currently in use
arr[1] is the app which was most recently used and
arr[N – 1] is the app which was least recently used.
The task is to print the contents of the array when the user using the system presses Alt + Tab exactly K number of times. Note that after pressing Alt + Tab key, app opening pointer will move through apps from 0th index towards right, depending upon the number of presses, so the app on which the press ends will shift to 0th index, because that will become the most recently opened app.Examples:
Input: arr[] = {3, 5, 2, 4, 1}, K = 3 Output: 4 3 5 2 1 User want to switch to the app with id 4, it’ll become the currently active app and the previously active app (with id 3) will be the most recently used app.Input: arr[] = {5, 7, 2, 3, 4, 1, 6}, K = 10 Output: 3 5 7 2 4 1 6
Approach: Get the index of the app to which the user wants to switch i.e. appIndex = K % N. Now, the current active app will be arr[appIndex] and all the other apps in the index range [0, appIndex – 1] will have to be shifted by 1 element towards the right.Below is the implementation of the above approach:
C++14
C#
Javascript
Java
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to update the array// in most recently used fashionvoid mostRecentlyUsedApps(int* arr, int N, int K){ int app_index = 0; // Finding the end index after K presses app_index = (K % N); // Shifting elements by 1 towards the found index // on which the K press ends int x = app_index, app_id = arr[app_index]; while (x > 0) { arr[x] = arr[--x]; } // Update the current active app arr[0] = app_id;} // Utility function to print// the contents of the arrayvoid printArray(int* arr, int N){ for (int i = 0; i < N; i++) cout << arr[i] << " ";} // Driver codeint main(){ int K = 3; int arr[] = { 3, 5, 2, 4, 1 }; int N = sizeof(arr) / sizeof(arr[0]); mostRecentlyUsedApps(arr, N, K); printArray(arr, N); return 0;}
// C# implementation of the approachusing System; class GFG{ // Function to update the array// in most recently used fashionstatic void mostRecentlyUsedApps(int []arr, int N, int K){ int app_index = 0; // Finding the end index after K presses app_index = (K % N); // Shifting elements by 1 towards the found index // on which the K press ends int x = app_index, app_id = arr[app_index]; while (x > 0) { arr[x] = arr[--x]; } // Update the current active app arr[0] = app_id;} // Utility function to print// the contents of the arraystatic void printArray(int []arr, int N){ for (int i = 0; i < N; i++) Console.Write(arr[i]+" ");} // Driver codestatic void Main(){ int K = 3; int []arr = { 3, 5, 2, 4, 1 }; int N = arr.Length; mostRecentlyUsedApps(arr, N, K); printArray(arr, N);}} // This code is contributed by mits
<script>// Javascript implementation of the approach // Function to update the array// in most recently used fashionfunction mostRecentlyUsedApps(arr, N, K) { let app_index = 0; // Finding the end index after K presses app_index = (K % N); // Shifting elements by 1 towards the found index // on which the K press ends let x = app_index, app_id = arr[app_index]; while (x > 0) { arr[x] = arr[--x]; } // Update the current active app arr[0] = app_id;} // Utility function to print// the contents of the arrayfunction printArray(arr, N) { for (let i = 0; i < N; i++) document.write(arr[i] + " ");} // Driver code let K = 3;let arr = [3, 5, 2, 4, 1];let N = arr.length; mostRecentlyUsedApps(arr, N, K);printArray(arr, N); // This code is contributed by gfgking.</script>
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { int[] num = { 3, 5, 2, 4, 1 }; int size = num.length; // 8,6,7,9,0,2,1,12,89 int d = 3; int appIndex = d % size; int appId = num[appIndex]; for (int i = appIndex; i > 0; i--) { num[i] = num[i - 1]; } num[0] = appId; for (int i = 0; i < num.length; i++) { System.out.print(" " + num[i]); } }}
4 3 5 2 1
Time Complexity: O(N)
Mithun Kumar
gfgking
pradyumnadas
Microsoft
programming-puzzle
Arrays
Technical Scripter
Microsoft
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Find Second largest element in an array | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 167,
"s": 53,
"text": "Given an integer K and an array arr[] of N integers which contains the ids of the opened apps in a system where "
},
{
"code": null,
"e": 304,
"s": 167,
"text": "arr[0] is the app currently in usearr[1] is the app which was most recently used andarr[N – 1] is the app which was least recently used."
},
{
"code": null,
"e": 339,
"s": 304,
"text": "arr[0] is the app currently in use"
},
{
"code": null,
"e": 390,
"s": 339,
"text": "arr[1] is the app which was most recently used and"
},
{
"code": null,
"e": 443,
"s": 390,
"text": "arr[N – 1] is the app which was least recently used."
},
{
"code": null,
"e": 843,
"s": 443,
"text": "The task is to print the contents of the array when the user using the system presses Alt + Tab exactly K number of times. Note that after pressing Alt + Tab key, app opening pointer will move through apps from 0th index towards right, depending upon the number of presses, so the app on which the press ends will shift to 0th index, because that will become the most recently opened app.Examples: "
},
{
"code": null,
"e": 1125,
"s": 843,
"text": "Input: arr[] = {3, 5, 2, 4, 1}, K = 3 Output: 4 3 5 2 1 User want to switch to the app with id 4, it’ll become the currently active app and the previously active app (with id 3) will be the most recently used app.Input: arr[] = {5, 7, 2, 3, 4, 1, 6}, K = 10 Output: 3 5 7 2 4 1 6 "
},
{
"code": null,
"e": 1437,
"s": 1127,
"text": "Approach: Get the index of the app to which the user wants to switch i.e. appIndex = K % N. Now, the current active app will be arr[appIndex] and all the other apps in the index range [0, appIndex – 1] will have to be shifted by 1 element towards the right.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1443,
"s": 1437,
"text": "C++14"
},
{
"code": null,
"e": 1446,
"s": 1443,
"text": "C#"
},
{
"code": null,
"e": 1457,
"s": 1446,
"text": "Javascript"
},
{
"code": null,
"e": 1462,
"s": 1457,
"text": "Java"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to update the array// in most recently used fashionvoid mostRecentlyUsedApps(int* arr, int N, int K){ int app_index = 0; // Finding the end index after K presses app_index = (K % N); // Shifting elements by 1 towards the found index // on which the K press ends int x = app_index, app_id = arr[app_index]; while (x > 0) { arr[x] = arr[--x]; } // Update the current active app arr[0] = app_id;} // Utility function to print// the contents of the arrayvoid printArray(int* arr, int N){ for (int i = 0; i < N; i++) cout << arr[i] << \" \";} // Driver codeint main(){ int K = 3; int arr[] = { 3, 5, 2, 4, 1 }; int N = sizeof(arr) / sizeof(arr[0]); mostRecentlyUsedApps(arr, N, K); printArray(arr, N); return 0;}",
"e": 2331,
"s": 1462,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to update the array// in most recently used fashionstatic void mostRecentlyUsedApps(int []arr, int N, int K){ int app_index = 0; // Finding the end index after K presses app_index = (K % N); // Shifting elements by 1 towards the found index // on which the K press ends int x = app_index, app_id = arr[app_index]; while (x > 0) { arr[x] = arr[--x]; } // Update the current active app arr[0] = app_id;} // Utility function to print// the contents of the arraystatic void printArray(int []arr, int N){ for (int i = 0; i < N; i++) Console.Write(arr[i]+\" \");} // Driver codestatic void Main(){ int K = 3; int []arr = { 3, 5, 2, 4, 1 }; int N = arr.Length; mostRecentlyUsedApps(arr, N, K); printArray(arr, N);}} // This code is contributed by mits",
"e": 3220,
"s": 2331,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to update the array// in most recently used fashionfunction mostRecentlyUsedApps(arr, N, K) { let app_index = 0; // Finding the end index after K presses app_index = (K % N); // Shifting elements by 1 towards the found index // on which the K press ends let x = app_index, app_id = arr[app_index]; while (x > 0) { arr[x] = arr[--x]; } // Update the current active app arr[0] = app_id;} // Utility function to print// the contents of the arrayfunction printArray(arr, N) { for (let i = 0; i < N; i++) document.write(arr[i] + \" \");} // Driver code let K = 3;let arr = [3, 5, 2, 4, 1];let N = arr.length; mostRecentlyUsedApps(arr, N, K);printArray(arr, N); // This code is contributed by gfgking.</script>",
"e": 4038,
"s": 3220,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { int[] num = { 3, 5, 2, 4, 1 }; int size = num.length; // 8,6,7,9,0,2,1,12,89 int d = 3; int appIndex = d % size; int appId = num[appIndex]; for (int i = appIndex; i > 0; i--) { num[i] = num[i - 1]; } num[0] = appId; for (int i = 0; i < num.length; i++) { System.out.print(\" \" + num[i]); } }}",
"e": 4567,
"s": 4038,
"text": null
},
{
"code": null,
"e": 4578,
"s": 4567,
"text": "4 3 5 2 1 "
},
{
"code": null,
"e": 4601,
"s": 4578,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 4614,
"s": 4601,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 4622,
"s": 4614,
"text": "gfgking"
},
{
"code": null,
"e": 4635,
"s": 4622,
"text": "pradyumnadas"
},
{
"code": null,
"e": 4645,
"s": 4635,
"text": "Microsoft"
},
{
"code": null,
"e": 4664,
"s": 4645,
"text": "programming-puzzle"
},
{
"code": null,
"e": 4671,
"s": 4664,
"text": "Arrays"
},
{
"code": null,
"e": 4690,
"s": 4671,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4700,
"s": 4690,
"text": "Microsoft"
},
{
"code": null,
"e": 4707,
"s": 4700,
"text": "Arrays"
},
{
"code": null,
"e": 4805,
"s": 4707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4837,
"s": 4805,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4851,
"s": 4837,
"text": "Linear Search"
},
{
"code": null,
"e": 4936,
"s": 4851,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 4959,
"s": 4936,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 5015,
"s": 4959,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 5042,
"s": 5015,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 5074,
"s": 5042,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5119,
"s": 5074,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 5167,
"s": 5119,
"text": "Search an element in a sorted and rotated array"
}
] |
Image Processing in Java – Colored image to Negative Image Conversion | 14 Nov, 2021
Prerequisites:
Image Processing in Java – Read and Write
Image Processing In Java – Get and Set Pixels
Image Processing in Java – Colored image to Grayscale Image Conversion
In this set, we will be converting a colored image to a negative image.
Colored Image (RGB Color Model) – The RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors.
Negative Image – A negative image is a total inversion, in which light areas appear dark and vice versa. A negative color image is additionally color-reversed, with red areas appearing cyan, greens appearing magenta, and blues appearing yellow, and vice versa.
Image negative is produced by subtracting each pixel from the maximum intensity value. For example in an 8-bit grayscale image, the max intensity value is 255, thus each pixel is subtracted from 255 to produce the output image.
Note: In a negative image the Alpha component of the image will be the same as the original image, but the RGB will be changed i.e, all three RGB components will be having a value of 255-original component value.
Get the RGB value of the pixel.Calculate new RGB values as follows: R = 255 – RG = 255 – GB = 255 – BReplace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image.
Get the RGB value of the pixel.
Calculate new RGB values as follows: R = 255 – RG = 255 – GB = 255 – B
R = 255 – R
G = 255 – G
B = 255 – B
Replace the R, G, and B values of the pixel with the values calculated in step 2.
Repeat Step 1 to Step 3 for each pixel of the image.
Java
// Java program to demonstrate// colored to negative conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class Negative { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // Get image width and height int width = img.getWidth(); int height = img.getHeight(); // Convert to negative for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int r = (p >> 16) & 0xff; int g = (p >> 8) & 0xff; int b = p & 0xff; // subtract RGB from 255 r = 255 - r; g = 255 - g; b = 255 - b; // set new RGB value p = (a << 24) | (r << 16) | (g << 8) | b; img.setRGB(x, y, p); } } // write image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png"); ImageIO.write(img, "png", f); } catch (IOException e) { System.out.println(e); } }}
Note: This code will not run on online IDE as it needs an image on disk.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
Image-Processing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Nov, 2021"
},
{
"code": null,
"e": 69,
"s": 54,
"text": "Prerequisites:"
},
{
"code": null,
"e": 111,
"s": 69,
"text": "Image Processing in Java – Read and Write"
},
{
"code": null,
"e": 157,
"s": 111,
"text": "Image Processing In Java – Get and Set Pixels"
},
{
"code": null,
"e": 228,
"s": 157,
"text": "Image Processing in Java – Colored image to Grayscale Image Conversion"
},
{
"code": null,
"e": 301,
"s": 228,
"text": "In this set, we will be converting a colored image to a negative image. "
},
{
"code": null,
"e": 493,
"s": 301,
"text": "Colored Image (RGB Color Model) – The RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. "
},
{
"code": null,
"e": 754,
"s": 493,
"text": "Negative Image – A negative image is a total inversion, in which light areas appear dark and vice versa. A negative color image is additionally color-reversed, with red areas appearing cyan, greens appearing magenta, and blues appearing yellow, and vice versa."
},
{
"code": null,
"e": 982,
"s": 754,
"text": "Image negative is produced by subtracting each pixel from the maximum intensity value. For example in an 8-bit grayscale image, the max intensity value is 255, thus each pixel is subtracted from 255 to produce the output image."
},
{
"code": null,
"e": 1195,
"s": 982,
"text": "Note: In a negative image the Alpha component of the image will be the same as the original image, but the RGB will be changed i.e, all three RGB components will be having a value of 255-original component value."
},
{
"code": null,
"e": 1430,
"s": 1195,
"text": "Get the RGB value of the pixel.Calculate new RGB values as follows: R = 255 – RG = 255 – GB = 255 – BReplace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image."
},
{
"code": null,
"e": 1462,
"s": 1430,
"text": "Get the RGB value of the pixel."
},
{
"code": null,
"e": 1533,
"s": 1462,
"text": "Calculate new RGB values as follows: R = 255 – RG = 255 – GB = 255 – B"
},
{
"code": null,
"e": 1545,
"s": 1533,
"text": "R = 255 – R"
},
{
"code": null,
"e": 1557,
"s": 1545,
"text": "G = 255 – G"
},
{
"code": null,
"e": 1569,
"s": 1557,
"text": "B = 255 – B"
},
{
"code": null,
"e": 1651,
"s": 1569,
"text": "Replace the R, G, and B values of the pixel with the values calculated in step 2."
},
{
"code": null,
"e": 1704,
"s": 1651,
"text": "Repeat Step 1 to Step 3 for each pixel of the image."
},
{
"code": null,
"e": 1709,
"s": 1704,
"text": "Java"
},
{
"code": "// Java program to demonstrate// colored to negative conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class Negative { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // Get image width and height int width = img.getWidth(); int height = img.getHeight(); // Convert to negative for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int r = (p >> 16) & 0xff; int g = (p >> 8) & 0xff; int b = p & 0xff; // subtract RGB from 255 r = 255 - r; g = 255 - g; b = 255 - b; // set new RGB value p = (a << 24) | (r << 16) | (g << 8) | b; img.setRGB(x, y, p); } } // write image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/GFG.png\"); ImageIO.write(img, \"png\", f); } catch (IOException e) { System.out.println(e); } }}",
"e": 3264,
"s": 1709,
"text": null
},
{
"code": null,
"e": 3338,
"s": 3264,
"text": "Note: This code will not run on online IDE as it needs an image on disk. "
},
{
"code": null,
"e": 3761,
"s": 3338,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3777,
"s": 3761,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 3794,
"s": 3777,
"text": "Image-Processing"
},
{
"code": null,
"e": 3799,
"s": 3794,
"text": "Java"
},
{
"code": null,
"e": 3804,
"s": 3799,
"text": "Java"
},
{
"code": null,
"e": 3902,
"s": 3804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3953,
"s": 3902,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3984,
"s": 3953,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4003,
"s": 3984,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4033,
"s": 4003,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4051,
"s": 4033,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4066,
"s": 4051,
"text": "Stream In Java"
},
{
"code": null,
"e": 4086,
"s": 4066,
"text": "Collections in Java"
},
{
"code": null,
"e": 4110,
"s": 4086,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 4142,
"s": 4110,
"text": "Multidimensional Arrays in Java"
}
] |
Python Pillow – Flip and Rotate Images | 16 Oct, 2021
Prerequisites: Pillow
Python Pillow or PIL is the Python library that provides image editing and manipulating features. The Image Module in it provides a number of functions to flip and rotate images. image.transpose() is the function used to rotate and flip images with necessary keywords as parameters.
Syntax:
image.transpose(appropriate keyword)
In the examples given below, we will be exploring all possible rotations using an appropriate keyword.
Image used:
Anticlockwise: To flip an image in anti-clockwise direction the keyword that needs to be passed is Image.TRANSPOSE.
Syntax:
img.transpose(Image.TRANSPOSE)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # flip anti-clockwiseflip_img = img.transpose(Image.TRANSPOSE) flip_img.show()
Output :
Clockwise: To flip an image in the clockwise direction the keyword that needs to be passed is Image.TRANSVERSE.
Syntax:
img.transpose(Image.TRANSVERSE)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # flip clockwiseflip_img= img.transpose(Image.TRANSVERSE) flip_img.show()
Output :
Horizontal Flip: For horizontal flip, pass Image.FLIP_LEFT_RIGHT as the keyword.
Syntax :
img.transpose(Image.FLIP_LEFT_RIGHT)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # flip horizontalflip_img = img.transpose(Image.FLIP_LEFT_RIGHT) flip_img.show()
Output :
Vertical flip: To flip vertically pass image.FLIP_TOP_BOTTOM as keyword
Syntax:
img.transpose(Image.FLIP_TOP_BOTTOM)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # flip verticalflip_img = img.transpose(Image.FLIP_TOP_BOTTOM) flip_img.show()
Output :
Image rotation is done by specific angles and for that again specific keywords need to passed as discussed below:
Rotate by 90 degrees: The keyword used for this is Image.ROTATE_90
Syntax :
img.transpose(Image.ROTATE_90)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # rotate by 90 degreesrot_img = img.transpose(Image.ROTATE_90) rot_img.show()
Output :
Rotate by 180 degrees: To rotate by 180 degrees the keyword used is Image.ROTATE_180
Syntax :
img.transpose(Image.ROTATE_180)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # rotate by 180 degreesrot_img = img.transpose(Image.ROTATE_180) rot_img.show()
Output:
Rotate by 270 degrees: To rotate by 270 degrees the keyword used is Image.ROTATE_270
Syntax :
img.transpose(Image.ROTATE_270)
Example:
Python
from PIL import Image img = Image.open('geek.jpg') # rotate by 270 degreesrot_img = img.transpose(Image.ROTATE_270) rot_img.show()
Output:
anikaseth98
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "Prerequisites: Pillow"
},
{
"code": null,
"e": 333,
"s": 50,
"text": "Python Pillow or PIL is the Python library that provides image editing and manipulating features. The Image Module in it provides a number of functions to flip and rotate images. image.transpose() is the function used to rotate and flip images with necessary keywords as parameters."
},
{
"code": null,
"e": 341,
"s": 333,
"text": "Syntax:"
},
{
"code": null,
"e": 378,
"s": 341,
"text": "image.transpose(appropriate keyword)"
},
{
"code": null,
"e": 481,
"s": 378,
"text": "In the examples given below, we will be exploring all possible rotations using an appropriate keyword."
},
{
"code": null,
"e": 493,
"s": 481,
"text": "Image used:"
},
{
"code": null,
"e": 609,
"s": 493,
"text": "Anticlockwise: To flip an image in anti-clockwise direction the keyword that needs to be passed is Image.TRANSPOSE."
},
{
"code": null,
"e": 617,
"s": 609,
"text": "Syntax:"
},
{
"code": null,
"e": 648,
"s": 617,
"text": "img.transpose(Image.TRANSPOSE)"
},
{
"code": null,
"e": 657,
"s": 648,
"text": "Example:"
},
{
"code": null,
"e": 664,
"s": 657,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # flip anti-clockwiseflip_img = img.transpose(Image.TRANSPOSE) flip_img.show()",
"e": 795,
"s": 664,
"text": null
},
{
"code": null,
"e": 804,
"s": 795,
"text": "Output :"
},
{
"code": null,
"e": 916,
"s": 804,
"text": "Clockwise: To flip an image in the clockwise direction the keyword that needs to be passed is Image.TRANSVERSE."
},
{
"code": null,
"e": 924,
"s": 916,
"text": "Syntax:"
},
{
"code": null,
"e": 957,
"s": 924,
"text": " img.transpose(Image.TRANSVERSE)"
},
{
"code": null,
"e": 966,
"s": 957,
"text": "Example:"
},
{
"code": null,
"e": 973,
"s": 966,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # flip clockwiseflip_img= img.transpose(Image.TRANSVERSE) flip_img.show()",
"e": 1100,
"s": 973,
"text": null
},
{
"code": null,
"e": 1112,
"s": 1103,
"text": "Output :"
},
{
"code": null,
"e": 1197,
"s": 1116,
"text": "Horizontal Flip: For horizontal flip, pass Image.FLIP_LEFT_RIGHT as the keyword."
},
{
"code": null,
"e": 1208,
"s": 1199,
"text": "Syntax :"
},
{
"code": null,
"e": 1248,
"s": 1210,
"text": " img.transpose(Image.FLIP_LEFT_RIGHT)"
},
{
"code": null,
"e": 1259,
"s": 1250,
"text": "Example:"
},
{
"code": null,
"e": 1268,
"s": 1261,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # flip horizontalflip_img = img.transpose(Image.FLIP_LEFT_RIGHT) flip_img.show()",
"e": 1401,
"s": 1268,
"text": null
},
{
"code": null,
"e": 1413,
"s": 1404,
"text": "Output :"
},
{
"code": null,
"e": 1489,
"s": 1417,
"text": "Vertical flip: To flip vertically pass image.FLIP_TOP_BOTTOM as keyword"
},
{
"code": null,
"e": 1499,
"s": 1491,
"text": "Syntax:"
},
{
"code": null,
"e": 1538,
"s": 1501,
"text": "img.transpose(Image.FLIP_TOP_BOTTOM)"
},
{
"code": null,
"e": 1549,
"s": 1540,
"text": "Example:"
},
{
"code": null,
"e": 1558,
"s": 1551,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # flip verticalflip_img = img.transpose(Image.FLIP_TOP_BOTTOM) flip_img.show()",
"e": 1689,
"s": 1558,
"text": null
},
{
"code": null,
"e": 1701,
"s": 1692,
"text": "Output :"
},
{
"code": null,
"e": 1819,
"s": 1705,
"text": "Image rotation is done by specific angles and for that again specific keywords need to passed as discussed below:"
},
{
"code": null,
"e": 1888,
"s": 1821,
"text": "Rotate by 90 degrees: The keyword used for this is Image.ROTATE_90"
},
{
"code": null,
"e": 1899,
"s": 1890,
"text": "Syntax :"
},
{
"code": null,
"e": 1932,
"s": 1901,
"text": "img.transpose(Image.ROTATE_90)"
},
{
"code": null,
"e": 1943,
"s": 1934,
"text": "Example:"
},
{
"code": null,
"e": 1952,
"s": 1945,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # rotate by 90 degreesrot_img = img.transpose(Image.ROTATE_90) rot_img.show()",
"e": 2082,
"s": 1952,
"text": null
},
{
"code": null,
"e": 2094,
"s": 2085,
"text": "Output :"
},
{
"code": null,
"e": 2183,
"s": 2098,
"text": "Rotate by 180 degrees: To rotate by 180 degrees the keyword used is Image.ROTATE_180"
},
{
"code": null,
"e": 2194,
"s": 2185,
"text": "Syntax :"
},
{
"code": null,
"e": 2229,
"s": 2196,
"text": " img.transpose(Image.ROTATE_180)"
},
{
"code": null,
"e": 2240,
"s": 2231,
"text": "Example:"
},
{
"code": null,
"e": 2249,
"s": 2242,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # rotate by 180 degreesrot_img = img.transpose(Image.ROTATE_180) rot_img.show()",
"e": 2381,
"s": 2249,
"text": null
},
{
"code": null,
"e": 2392,
"s": 2384,
"text": "Output:"
},
{
"code": null,
"e": 2481,
"s": 2396,
"text": "Rotate by 270 degrees: To rotate by 270 degrees the keyword used is Image.ROTATE_270"
},
{
"code": null,
"e": 2492,
"s": 2483,
"text": "Syntax :"
},
{
"code": null,
"e": 2526,
"s": 2494,
"text": "img.transpose(Image.ROTATE_270)"
},
{
"code": null,
"e": 2537,
"s": 2528,
"text": "Example:"
},
{
"code": null,
"e": 2546,
"s": 2539,
"text": "Python"
},
{
"code": "from PIL import Image img = Image.open('geek.jpg') # rotate by 270 degreesrot_img = img.transpose(Image.ROTATE_270) rot_img.show()",
"e": 2678,
"s": 2546,
"text": null
},
{
"code": null,
"e": 2689,
"s": 2681,
"text": "Output:"
},
{
"code": null,
"e": 2705,
"s": 2693,
"text": "anikaseth98"
},
{
"code": null,
"e": 2712,
"s": 2705,
"text": "Picked"
},
{
"code": null,
"e": 2723,
"s": 2712,
"text": "Python-pil"
},
{
"code": null,
"e": 2730,
"s": 2723,
"text": "Python"
}
] |
Self Organizing Maps – Kohonen Maps | 16 Feb, 2022
Self Organizing Map (or Kohonen Map or SOM) is a type of Artificial Neural Network which is also inspired by biological models of neural systems from the 1970s. It follows an unsupervised learning approach and trained its network through a competitive learning algorithm. SOM is used for clustering and mapping (or dimensionality reduction) techniques to map multidimensional data onto lower-dimensional which allows people to reduce complex problems for easy interpretation. SOM has two layers, one is the Input layer and the other one is the Output layer. The architecture of the Self Organizing Map with two clusters and n input features of any sample is given below:
Let’s say an input data of size (m, n) where m is the number of training examples and n is the number of features in each example. First, it initializes the weights of size (n, C) where C is the number of clusters. Then iterating over the input data, for each training example, it updates the winning vector (weight vector with the shortest distance (e.g Euclidean distance) from training example). Weight updation rule is given by :
wij = wij(old) + alpha(t) * (xik - wij(old))
where alpha is a learning rate at time t, j denotes the winning vector, i denotes the ith feature of training example and k denotes the kth training example from the input data. After training the SOM network, trained weights are used for clustering new examples. A new example falls in the cluster of winning vectors.
The steps involved are :
Weight initialization
For 1 to N number of epochs
Select a training example
Compute the winning vector
Update the winning vector
Repeat steps 3, 4, 5 for all training examples.
Clustering the test sample
Below is the implementation of the above approach:
Python3
import math class SOM: # Function here computes the winning vector # by Euclidean distance def winner(self, weights, sample): D0 = 0 D1 = 0 for i in range(len(sample)): D0 = D0 + math.pow((sample[i] - weights[0][i]), 2) D1 = D1 + math.pow((sample[i] - weights[1][i]), 2) if D0 > D1: return 0 else: return 1 # Function here updates the winning vector def update(self, weights, sample, J, alpha): for i in range(len(weights)): weights[J][i] = weights[J][i] + alpha * (sample[i] - weights[J][i]) return weights # Driver code def main(): # Training Examples ( m, n ) T = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] m, n = len(T), len(T[0]) # weight initialization ( n, C ) weights = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training ob = SOM() epochs = 3 alpha = 0.5 for i in range(epochs): for j in range(m): # training sample sample = T[j] # Compute winner vector J = ob.winner(weights, sample) # Update winning vector weights = ob.update(weights, sample, J, alpha) # classify test sample s = [0, 0, 0, 1] J = ob.winner(weights, s) print("Test Sample s belongs to Cluster : ", J) print("Trained weights : ", weights) if __name__ == "__main__": main()
singghakshay
glintarman
punamsingh628700
Deep-Learning
Advanced Computer Subject
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
Reinforcement learning
Supervised and Unsupervised learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 726,
"s": 54,
"text": "Self Organizing Map (or Kohonen Map or SOM) is a type of Artificial Neural Network which is also inspired by biological models of neural systems from the 1970s. It follows an unsupervised learning approach and trained its network through a competitive learning algorithm. SOM is used for clustering and mapping (or dimensionality reduction) techniques to map multidimensional data onto lower-dimensional which allows people to reduce complex problems for easy interpretation. SOM has two layers, one is the Input layer and the other one is the Output layer. The architecture of the Self Organizing Map with two clusters and n input features of any sample is given below: "
},
{
"code": null,
"e": 1161,
"s": 726,
"text": "Let’s say an input data of size (m, n) where m is the number of training examples and n is the number of features in each example. First, it initializes the weights of size (n, C) where C is the number of clusters. Then iterating over the input data, for each training example, it updates the winning vector (weight vector with the shortest distance (e.g Euclidean distance) from training example). Weight updation rule is given by : "
},
{
"code": null,
"e": 1207,
"s": 1161,
"text": "wij = wij(old) + alpha(t) * (xik - wij(old))"
},
{
"code": null,
"e": 1527,
"s": 1207,
"text": "where alpha is a learning rate at time t, j denotes the winning vector, i denotes the ith feature of training example and k denotes the kth training example from the input data. After training the SOM network, trained weights are used for clustering new examples. A new example falls in the cluster of winning vectors. "
},
{
"code": null,
"e": 1554,
"s": 1527,
"text": "The steps involved are : "
},
{
"code": null,
"e": 1576,
"s": 1554,
"text": "Weight initialization"
},
{
"code": null,
"e": 1604,
"s": 1576,
"text": "For 1 to N number of epochs"
},
{
"code": null,
"e": 1630,
"s": 1604,
"text": "Select a training example"
},
{
"code": null,
"e": 1657,
"s": 1630,
"text": "Compute the winning vector"
},
{
"code": null,
"e": 1683,
"s": 1657,
"text": "Update the winning vector"
},
{
"code": null,
"e": 1731,
"s": 1683,
"text": "Repeat steps 3, 4, 5 for all training examples."
},
{
"code": null,
"e": 1758,
"s": 1731,
"text": "Clustering the test sample"
},
{
"code": null,
"e": 1810,
"s": 1758,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1818,
"s": 1810,
"text": "Python3"
},
{
"code": "import math class SOM: # Function here computes the winning vector # by Euclidean distance def winner(self, weights, sample): D0 = 0 D1 = 0 for i in range(len(sample)): D0 = D0 + math.pow((sample[i] - weights[0][i]), 2) D1 = D1 + math.pow((sample[i] - weights[1][i]), 2) if D0 > D1: return 0 else: return 1 # Function here updates the winning vector def update(self, weights, sample, J, alpha): for i in range(len(weights)): weights[J][i] = weights[J][i] + alpha * (sample[i] - weights[J][i]) return weights # Driver code def main(): # Training Examples ( m, n ) T = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] m, n = len(T), len(T[0]) # weight initialization ( n, C ) weights = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training ob = SOM() epochs = 3 alpha = 0.5 for i in range(epochs): for j in range(m): # training sample sample = T[j] # Compute winner vector J = ob.winner(weights, sample) # Update winning vector weights = ob.update(weights, sample, J, alpha) # classify test sample s = [0, 0, 0, 1] J = ob.winner(weights, s) print(\"Test Sample s belongs to Cluster : \", J) print(\"Trained weights : \", weights) if __name__ == \"__main__\": main()",
"e": 3263,
"s": 1818,
"text": null
},
{
"code": null,
"e": 3276,
"s": 3263,
"text": "singghakshay"
},
{
"code": null,
"e": 3287,
"s": 3276,
"text": "glintarman"
},
{
"code": null,
"e": 3304,
"s": 3287,
"text": "punamsingh628700"
},
{
"code": null,
"e": 3318,
"s": 3304,
"text": "Deep-Learning"
},
{
"code": null,
"e": 3344,
"s": 3318,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 3351,
"s": 3344,
"text": "Python"
},
{
"code": null,
"e": 3449,
"s": 3351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3472,
"s": 3449,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 3495,
"s": 3472,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3521,
"s": 3495,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3544,
"s": 3521,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 3581,
"s": 3544,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 3609,
"s": 3581,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3659,
"s": 3609,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3681,
"s": 3659,
"text": "Python map() function"
},
{
"code": null,
"e": 3725,
"s": 3681,
"text": "How to get column names in Pandas dataframe"
}
] |
Python String format_map() Method | 05 Aug, 2021
Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key’s value.
Syntax:
string.format_map(z)
Parameters:
Here z is a variable in which the input dictionary is stored and string is the key of the input dictionary. input_dict: Takes a single parameter which is the input dictionary.
Returns:
Returns key’s values of the input dictionary.
Python3
# input stored in variable a.a = {'x':'John', 'y':'Wick'} # Use of format_map() functionprint("{x}'s last name is {y}".format_map(a))
Output:
John's last name is Wick
Python3
# input stored in variable a.a = {'x':"geeksforgeeks", 'y':'b'} # Use of format_map() functionprint('{x} {y}'.format_map(a))
Output:
geeksforgeeks b
Python3
# Input dictionaryprofession = { 'name':['Barry', 'Bruce'], 'profession':['Engineer', 'Doctor'], 'age':[30, 31] } # Use of format_map() function print('{name[0]} is an {profession[0]} and he' ' is {age[0]} years old.'.format_map(profession)) print('{name[1]} is an {profession[1]} and he' ' is {age[1]} years old.'.format_map(profession))
Output:
Barry is an Engineer and he is 30 years old.
Bruce is an Doctor and he is 31 years old.
The format_map() function can be used in any practical application.
Python3
# Python code showing practical # use of format_map() functiondef chk_msg(n): # input stored in variable a. a = {'name':"George", 'mesg':n} # use of format_map() function print('{name} has {mesg} new messages'.format_map(a)) chk_msg(10)
Output:
George has 10 new messages
AmiyaRanjanRout
Python-Built-in-functions
python-dict
python-string
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key’s value."
},
{
"code": null,
"e": 155,
"s": 146,
"text": "Syntax: "
},
{
"code": null,
"e": 176,
"s": 155,
"text": "string.format_map(z)"
},
{
"code": null,
"e": 189,
"s": 176,
"text": "Parameters: "
},
{
"code": null,
"e": 365,
"s": 189,
"text": "Here z is a variable in which the input dictionary is stored and string is the key of the input dictionary. input_dict: Takes a single parameter which is the input dictionary."
},
{
"code": null,
"e": 375,
"s": 365,
"text": "Returns: "
},
{
"code": null,
"e": 421,
"s": 375,
"text": "Returns key’s values of the input dictionary."
},
{
"code": null,
"e": 429,
"s": 421,
"text": "Python3"
},
{
"code": "# input stored in variable a.a = {'x':'John', 'y':'Wick'} # Use of format_map() functionprint(\"{x}'s last name is {y}\".format_map(a))",
"e": 564,
"s": 429,
"text": null
},
{
"code": null,
"e": 573,
"s": 564,
"text": "Output: "
},
{
"code": null,
"e": 598,
"s": 573,
"text": "John's last name is Wick"
},
{
"code": null,
"e": 606,
"s": 598,
"text": "Python3"
},
{
"code": "# input stored in variable a.a = {'x':\"geeksforgeeks\", 'y':'b'} # Use of format_map() functionprint('{x} {y}'.format_map(a))",
"e": 732,
"s": 606,
"text": null
},
{
"code": null,
"e": 741,
"s": 732,
"text": "Output: "
},
{
"code": null,
"e": 757,
"s": 741,
"text": "geeksforgeeks b"
},
{
"code": null,
"e": 765,
"s": 757,
"text": "Python3"
},
{
"code": "# Input dictionaryprofession = { 'name':['Barry', 'Bruce'], 'profession':['Engineer', 'Doctor'], 'age':[30, 31] } # Use of format_map() function print('{name[0]} is an {profession[0]} and he' ' is {age[0]} years old.'.format_map(profession)) print('{name[1]} is an {profession[1]} and he' ' is {age[1]} years old.'.format_map(profession))",
"e": 1171,
"s": 765,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1171,
"text": "Output: "
},
{
"code": null,
"e": 1268,
"s": 1180,
"text": "Barry is an Engineer and he is 30 years old.\nBruce is an Doctor and he is 31 years old."
},
{
"code": null,
"e": 1336,
"s": 1268,
"text": "The format_map() function can be used in any practical application."
},
{
"code": null,
"e": 1344,
"s": 1336,
"text": "Python3"
},
{
"code": "# Python code showing practical # use of format_map() functiondef chk_msg(n): # input stored in variable a. a = {'name':\"George\", 'mesg':n} # use of format_map() function print('{name} has {mesg} new messages'.format_map(a)) chk_msg(10)",
"e": 1611,
"s": 1344,
"text": null
},
{
"code": null,
"e": 1620,
"s": 1611,
"text": "Output: "
},
{
"code": null,
"e": 1647,
"s": 1620,
"text": "George has 10 new messages"
},
{
"code": null,
"e": 1663,
"s": 1647,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 1689,
"s": 1663,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 1701,
"s": 1689,
"text": "python-dict"
},
{
"code": null,
"e": 1715,
"s": 1701,
"text": "python-string"
},
{
"code": null,
"e": 1722,
"s": 1715,
"text": "Python"
},
{
"code": null,
"e": 1734,
"s": 1722,
"text": "python-dict"
}
] |
Reading a Text File With SQL Server | 15 Oct, 2021
Here we will see, how to read a text file with SQL Server. We can read the text file using the OPENROWSET(BULK ) function.
It is a table-valued function that can read data from any file. This function returns a single column table having all the contents of the file. This single large value is known as a SINGLE_CLOB (single character large object)
Syntax:
SELECT * FROM OPENROWSET (BULK 'file_path', SINGLE_CLOB) as correlation_name;
This query will read the content of the text file and return it as a single column in a table named Bulkcolumn. The correlation name is mandatory to specify. We have the text file named “Geek.txt”. Content of text file:
Hii!! My name is Romy kumari.
I am an engineer.
Welcome to GeeksforGeeks platform.
Query:
SELECT * FROM OPENROWSET(BULK 'E:\Geek.txt', SINGLE_CLOB) AS Contents;
Output:
The entire content is returned as a single column.
Read text file from SQL server such that one row represents data in one line from a text file
Step to read each line of the text file in a single row:
Create a table in your database.
Insert data from a text file into the table using the ‘INSERT’ keyword.
Using WITH clause set ROWTERMINATOR as ‘\n’ (represents newline character). This split the content of the file into separate rows as soon as the new line is encountered in the file.
Step 1: Create Database
Use the below SQL statement to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks.
Query:
USE geeks;
Step 3: Table definition
We have the following demo table in our geek’s database.
CREATE TABLE demo(
Content VARCHAR(1000)
);
Step 4: Insert data from a text file into the table
Use the following command to insert data from a text file.
Syntax:
BULK INSERT dbo.table_name
FROM 'file_path'
WITH
(
ROWTERMINATOR ='\n'
)
Query:
BULK INSERT dbo.demo
FROM 'E:\Geek.txt'
WITH
(
ROWTERMINATOR ='\n'
);
Step 5: See the content of the table
Query:
SELECT * FROM demo;
Output:
Here, NULL represents an empty line.
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 176,
"s": 53,
"text": "Here we will see, how to read a text file with SQL Server. We can read the text file using the OPENROWSET(BULK ) function."
},
{
"code": null,
"e": 405,
"s": 176,
"text": "It is a table-valued function that can read data from any file. This function returns a single column table having all the contents of the file. This single large value is known as a SINGLE_CLOB (single character large object)"
},
{
"code": null,
"e": 413,
"s": 405,
"text": "Syntax:"
},
{
"code": null,
"e": 491,
"s": 413,
"text": "SELECT * FROM OPENROWSET (BULK 'file_path', SINGLE_CLOB) as correlation_name;"
},
{
"code": null,
"e": 711,
"s": 491,
"text": "This query will read the content of the text file and return it as a single column in a table named Bulkcolumn. The correlation name is mandatory to specify. We have the text file named “Geek.txt”. Content of text file:"
},
{
"code": null,
"e": 795,
"s": 711,
"text": "Hii!! My name is Romy kumari.\nI am an engineer.\n\nWelcome to GeeksforGeeks platform."
},
{
"code": null,
"e": 802,
"s": 795,
"text": "Query:"
},
{
"code": null,
"e": 873,
"s": 802,
"text": "SELECT * FROM OPENROWSET(BULK 'E:\\Geek.txt', SINGLE_CLOB) AS Contents;"
},
{
"code": null,
"e": 881,
"s": 873,
"text": "Output:"
},
{
"code": null,
"e": 932,
"s": 881,
"text": "The entire content is returned as a single column."
},
{
"code": null,
"e": 1026,
"s": 932,
"text": "Read text file from SQL server such that one row represents data in one line from a text file"
},
{
"code": null,
"e": 1083,
"s": 1026,
"text": "Step to read each line of the text file in a single row:"
},
{
"code": null,
"e": 1116,
"s": 1083,
"text": "Create a table in your database."
},
{
"code": null,
"e": 1188,
"s": 1116,
"text": "Insert data from a text file into the table using the ‘INSERT’ keyword."
},
{
"code": null,
"e": 1370,
"s": 1188,
"text": "Using WITH clause set ROWTERMINATOR as ‘\\n’ (represents newline character). This split the content of the file into separate rows as soon as the new line is encountered in the file."
},
{
"code": null,
"e": 1394,
"s": 1370,
"text": "Step 1: Create Database"
},
{
"code": null,
"e": 1457,
"s": 1394,
"text": "Use the below SQL statement to create a database called geeks."
},
{
"code": null,
"e": 1464,
"s": 1457,
"text": "Query:"
},
{
"code": null,
"e": 1487,
"s": 1464,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 1514,
"s": 1487,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 1583,
"s": 1514,
"text": "Use the below SQL statement to switch the database context to geeks."
},
{
"code": null,
"e": 1590,
"s": 1583,
"text": "Query:"
},
{
"code": null,
"e": 1601,
"s": 1590,
"text": "USE geeks;"
},
{
"code": null,
"e": 1626,
"s": 1601,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 1683,
"s": 1626,
"text": "We have the following demo table in our geek’s database."
},
{
"code": null,
"e": 1727,
"s": 1683,
"text": "CREATE TABLE demo(\nContent VARCHAR(1000)\n);"
},
{
"code": null,
"e": 1779,
"s": 1727,
"text": "Step 4: Insert data from a text file into the table"
},
{
"code": null,
"e": 1838,
"s": 1779,
"text": "Use the following command to insert data from a text file."
},
{
"code": null,
"e": 1846,
"s": 1838,
"text": "Syntax:"
},
{
"code": null,
"e": 1943,
"s": 1846,
"text": "BULK INSERT dbo.table_name\n FROM 'file_path'\n WITH \n (\n ROWTERMINATOR ='\\n'\n )"
},
{
"code": null,
"e": 1950,
"s": 1943,
"text": "Query:"
},
{
"code": null,
"e": 2044,
"s": 1950,
"text": "BULK INSERT dbo.demo\n FROM 'E:\\Geek.txt'\n WITH \n (\n ROWTERMINATOR ='\\n'\n );"
},
{
"code": null,
"e": 2081,
"s": 2044,
"text": "Step 5: See the content of the table"
},
{
"code": null,
"e": 2088,
"s": 2081,
"text": "Query:"
},
{
"code": null,
"e": 2108,
"s": 2088,
"text": "SELECT * FROM demo;"
},
{
"code": null,
"e": 2116,
"s": 2108,
"text": "Output:"
},
{
"code": null,
"e": 2153,
"s": 2116,
"text": "Here, NULL represents an empty line."
},
{
"code": null,
"e": 2160,
"s": 2153,
"text": "Picked"
},
{
"code": null,
"e": 2171,
"s": 2160,
"text": "SQL-Server"
},
{
"code": null,
"e": 2185,
"s": 2171,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 2189,
"s": 2185,
"text": "SQL"
},
{
"code": null,
"e": 2198,
"s": 2189,
"text": "TrueGeek"
},
{
"code": null,
"e": 2202,
"s": 2198,
"text": "SQL"
}
] |
Suffix Tree Application 5 – Longest Common Substring | 11 Oct, 2021
Given two strings X and Y, find the Longest Common Substring of X and Y.Naive [O(N*M2)] and Dynamic Programming [O(N*M)] approaches are already discussed here. In this article, we will discuss a linear time approach to find LCS using suffix tree (The 5th Suffix Tree Application). Here we will build generalized suffix tree for two strings X and Y as discussed already at: Generalized Suffix Tree 1Lets take same example (X = xabxa, and Y = babxba) we saw in Generalized Suffix Tree 1. We built following suffix tree for X and Y there:
This is generalized suffix tree for xabxa#babxba$ In above, leaves with suffix indices in [0,4] are suffixes of string xabxa and leaves with suffix indices in [6,11] are suffixes of string babxa. Why ?? Because in concatenated string xabxa#babxba$, index of string xabxa is 0 and it’s length is 5, so indices of it’s suffixes would be 0, 1, 2, 3 and 4. Similarly index of string babxba is 6 and it’s length is 6, so indices of it’s suffixes would be 6, 7, 8, 9, 10 and 11.With this, we can see that in the generalized suffix tree figure above, there are some internal nodes having leaves below it from
both strings X and Y (i.e. there is at least one leaf with suffix index in [0,4] and one leaf with suffix index in [6, 11]
string X only (i.e. all leaf nodes have suffix indices in [0,4])
string Y only (i.e. all leaf nodes have suffix indices in [6,11])
Following figure shows the internal nodes marked as “XY”, “X” or “Y” depending on which string the leaves belong to, that they have below themselves.
What these “XY”, “X” or “Y” marking mean ? Path label from root to an internal node gives a substring of X or Y or both. For node marked as XY, substring from root to that node belongs to both strings X and Y. For node marked as X, substring from root to that node belongs to string X only. For node marked as Y, substring from root to that node belongs to string Y only.By looking at above figure, can you see how to get LCS of X and Y ? By now, it should be clear that how to get common substring of X and Y at least. If we traverse the path from root to nodes marked as XY, we will get common substring of X and Y.Now we need to find the longest one among all those common substrings. Can you think how to get LCS now ? Recall how did we get Longest Repeated Substring in a given string using suffix tree already. The path label from root to the deepest node marked as XY will give the LCS of X and Y. The deepest node is highlighted in above figure and path label “abx” from root to that node is the LCS of X and Y.
C
// A C program to implement Ukkonen's Suffix Tree Construction// Here we build generalized suffix tree for two strings// And then we find longest common substring of the two input strings#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX_CHAR 256 struct SuffixTreeNode { struct SuffixTreeNode *children[MAX_CHAR]; //pointer to other node via suffix link struct SuffixTreeNode *suffixLink; /*(start, end) interval specifies the edge, by which the node is connected to its parent node. Each edge will connect two nodes, one parent and one child, and (start, end) interval of a given edge will be stored in the child node. Lets say there are two nods A and B connected by an edge with indices (5, 8) then this indices (5, 8) will be stored in node B. */ int start; int *end; /*for leaf nodes, it stores the index of suffix for the path from root to leaf*/ int suffixIndex;}; typedef struct SuffixTreeNode Node; char text[100]; //Input stringNode *root = NULL; //Pointer to root node /*lastNewNode will point to newly created internal node, waiting for it's suffix link to be set, which might get a new suffix link (other than root) in next extension of same phase. lastNewNode will be set to NULL when last newly created internal node (if there is any) got it's suffix link reset to new internal node created in next extension of same phase. */Node *lastNewNode = NULL;Node *activeNode = NULL; /*activeEdge is represented as input string character index (not the character itself)*/int activeEdge = -1;int activeLength = 0; // remainingSuffixCount tells how many suffixes yet to// be added in treeint remainingSuffixCount = 0;int leafEnd = -1;int *rootEnd = NULL;int *splitEnd = NULL;int size = -1; //Length of input stringint size1 = 0; //Size of 1st string Node *newNode(int start, int *end){ Node *node =(Node*) malloc(sizeof(Node)); int i; for (i = 0; i < MAX_CHAR; i++) node->children[i] = NULL; /*For root node, suffixLink will be set to NULL For internal nodes, suffixLink will be set to root by default in current extension and may change in next extension*/ node->suffixLink = root; node->start = start; node->end = end; /*suffixIndex will be set to -1 by default and actual suffix index will be set later for leaves at the end of all phases*/ node->suffixIndex = -1; return node;} int edgeLength(Node *n) { if(n == root) return 0; return *(n->end) - (n->start) + 1;} int walkDown(Node *currNode){ /*activePoint change for walk down (APCFWD) using Skip/Count Trick (Trick 1). If activeLength is greater than current edge length, set next internal node as activeNode and adjust activeEdge and activeLength accordingly to represent same activePoint*/ if (activeLength >= edgeLength(currNode)) { activeEdge += edgeLength(currNode); activeLength -= edgeLength(currNode); activeNode = currNode; return 1; } return 0;} void extendSuffixTree(int pos){ /*Extension Rule 1, this takes care of extending all leaves created so far in tree*/ leafEnd = pos; /*Increment remainingSuffixCount indicating that a new suffix added to the list of suffixes yet to be added in tree*/ remainingSuffixCount++; /*set lastNewNode to NULL while starting a new phase, indicating there is no internal node waiting for it's suffix link reset in current phase*/ lastNewNode = NULL; //Add all suffixes (yet to be added) one by one in tree while(remainingSuffixCount > 0) { if (activeLength == 0) activeEdge = pos; //APCFALZ // There is no outgoing edge starting with // activeEdge from activeNode if (activeNode->children] == NULL) { //Extension Rule 2 (A new leaf edge gets created) activeNode->children] = newNode(pos, &leafEnd); /*A new leaf edge is created in above line starting from an existing node (the current activeNode), and if there is any internal node waiting for it's suffix link get reset, point the suffix link from that last internal node to current activeNode. Then set lastNewNode to NULL indicating no more node waiting for suffix link reset.*/ if (lastNewNode != NULL) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } } // There is an outgoing edge starting with activeEdge // from activeNode else { // Get the next node at the end of edge starting // with activeEdge Node *next = activeNode->children]; if (walkDown(next))//Do walkdown { //Start from next node (the new activeNode) continue; } /*Extension Rule 3 (current character being processed is already on the edge)*/ if (text[next->start + activeLength] == text[pos]) { //If a newly created node waiting for it's //suffix link to be set, then set suffix link //of that waiting node to current active node if(lastNewNode != NULL && activeNode != root) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } //APCFER3 activeLength++; /*STOP all further processing in this phase and move on to next phase*/ break; } /*We will be here when activePoint is in middle of the edge being traversed and current character being processed is not on the edge (we fall off the tree). In this case, we add a new internal node and a new leaf edge going out of that new node. This is Extension Rule 2, where a new leaf edge and a new internal node get created*/ splitEnd = (int*) malloc(sizeof(int)); *splitEnd = next->start + activeLength - 1; //New internal node Node *split = newNode(next->start, splitEnd); activeNode->children] = split; //New leaf coming out of new internal node split->children] = newNode(pos, &leafEnd); next->start += activeLength; split->children] = next; /*We got a new internal node here. If there is any internal node created in last extensions of same phase which is still waiting for it's suffix link reset, do it now.*/ if (lastNewNode != NULL) { /*suffixLink of lastNewNode points to current newly created internal node*/ lastNewNode->suffixLink = split; } /*Make the current newly created internal node waiting for it's suffix link reset (which is pointing to root at present). If we come across any other internal node (existing or newly created) in next extension of same phase, when a new leaf edge gets added (i.e. when Extension Rule 2 applies is any of the next extension of same phase) at that point, suffixLink of this node will point to that internal node.*/ lastNewNode = split; } /* One suffix got added in tree, decrement the count of suffixes yet to be added.*/ remainingSuffixCount--; if (activeNode == root && activeLength > 0) //APCFER2C1 { activeLength--; activeEdge = pos - remainingSuffixCount + 1; } else if (activeNode != root) //APCFER2C2 { activeNode = activeNode->suffixLink; } }} void print(int i, int j){ int k; for (k=i; k<=j && text[k] != '#'; k++) printf("%c", text[k]); if(k<=j) printf("#");} //Print the suffix tree as well along with setting suffix index//So tree will be printed in DFS manner//Each edge along with it's suffix index will be printedvoid setSuffixIndexByDFS(Node *n, int labelHeight){ if (n == NULL) return; if (n->start != -1) //A non-root node { //Print the label on edge from parent to current node //Uncomment below line to print suffix tree //print(n->start, *(n->end)); } int leaf = 1; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { //Uncomment below two lines to print suffix index // if (leaf == 1 && n->start != -1) // printf(" [%d]\n", n->suffixIndex); //Current node is not a leaf as it has outgoing //edges from it. leaf = 0; setSuffixIndexByDFS(n->children[i], labelHeight + edgeLength(n->children[i])); } } if (leaf == 1) { for(i= n->start; i<= *(n->end); i++) { if(text[i] == '#') { n->end = (int*) malloc(sizeof(int)); *(n->end) = i; } } n->suffixIndex = size - labelHeight; //Uncomment below line to print suffix index // printf(" [%d]\n", n->suffixIndex); }} void freeSuffixTreeByPostOrder(Node *n){ if (n == NULL) return; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { freeSuffixTreeByPostOrder(n->children[i]); } } if (n->suffixIndex == -1) free(n->end); free(n);} /*Build the suffix tree and print the edge labels along withsuffixIndex. suffixIndex for leaf edges will be >= 0 andfor non-leaf edges will be -1*/void buildSuffixTree(){ size = strlen(text); int i; rootEnd = (int*) malloc(sizeof(int)); *rootEnd = - 1; /*Root is a special node with start and end indices as -1, as it has no parent from where an edge comes to root*/ root = newNode(-1, rootEnd); activeNode = root; //First activeNode will be root for (i=0; i<size; i++) extendSuffixTree(i); int labelHeight = 0; setSuffixIndexByDFS(root, labelHeight);} int doTraversal(Node *n, int labelHeight, int* maxHeight,int* substringStartIndex){ if(n == NULL) { return; } int i=0; int ret = -1; if(n->suffixIndex < 0) //If it is internal node { for (i = 0; i < MAX_CHAR; i++) { if(n->children[i] != NULL) { ret = doTraversal(n->children[i], labelHeight + edgeLength(n->children[i]), maxHeight, substringStartIndex); if(n->suffixIndex == -1) n->suffixIndex = ret; else if((n->suffixIndex == -2 && ret == -3) || (n->suffixIndex == -3 && ret == -2) || n->suffixIndex == -4) { n->suffixIndex = -4;//Mark node as XY //Keep track of deepest node if(*maxHeight < labelHeight) { *maxHeight = labelHeight; *substringStartIndex = *(n->end) - labelHeight + 1; } } } } } else if(n->suffixIndex > -1 && n->suffixIndex < size1)//suffix of X return -2;//Mark node as X else if(n->suffixIndex >= size1)//suffix of Y return -3;//Mark node as Y return n->suffixIndex;} void getLongestCommonSubstring(){ int maxHeight = 0; int substringStartIndex = 0; doTraversal(root, 0, &maxHeight, &substringStartIndex); int k; for (k=0; k<maxHeight; k++) printf("%c", text[k + substringStartIndex]); if(k == 0) printf("No common substring"); else printf(", of length: %d",maxHeight); printf("\n");} // driver program to test above functionsint main(int argc, char *argv[]){ size1 = 7; printf("Longest Common Substring in xabxac and abcabxabcd is: "); strcpy(text, "xabxac#abcabxabcd$"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 10; printf("Longest Common Substring in xabxaabxa and babxba is: "); strcpy(text, "xabxaabxa#babxba$"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 14; printf("Longest Common Substring in GeeksforGeeks and GeeksQuiz is: "); strcpy(text, "GeeksforGeeks#GeeksQuiz$"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 26; printf("Longest Common Substring in OldSite:GeeksforGeeks.org"); printf(" and NewSite:GeeksQuiz.com is: "); strcpy(text, "OldSite:GeeksforGeeks.org#NewSite:GeeksQuiz.com$"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 6; printf("Longest Common Substring in abcde and fghie is: "); strcpy(text, "abcde#fghie$"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 6; printf("Longest Common Substring in pqrst and uvwxyz is: "); strcpy(text, "pqrst#uvwxyz$"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); return 0;}
Output:
Longest Common Substring in xabxac and abcabxabcd is: abxa, of length: 4
Longest Common Substring in xabxaabxa and babxba is: abx, of length: 3
Longest Common Substring in GeeksforGeeks and GeeksQuiz is: Geeks, of length: 5
Longest Common Substring in OldSite:GeeksforGeeks.org and
NewSite:GeeksQuiz.com is: Site:Geeks, of length: 10
Longest Common Substring in abcde and fghie is: e, of length: 1
Longest Common Substring in pqrst and uvwxyz is: No common substring
If two strings are of size M and N, then Generalized Suffix Tree construction takes O(M+N) and LCS finding is a DFS on tree which is again O(M+N). So overall complexity is linear in time and space.Followup:
Given a pattern, check if it is substring of X or Y or both. If it is a substring, find all it’s occurrences along with which string (X or Y or both) it belongs to. Extend the implementation to find LCS of more than two stringsSolve problem 1 for more than two stringsGiven a string, find it’s Longest Palindromic Substring
Given a pattern, check if it is substring of X or Y or both. If it is a substring, find all it’s occurrences along with which string (X or Y or both) it belongs to.
Extend the implementation to find LCS of more than two strings
Solve problem 1 for more than two strings
Given a string, find it’s Longest Palindromic Substring
We have published following more articles on suffix tree applications:
Suffix Tree Application 1 – Substring Check
Suffix Tree Application 2 – Searching All Patterns
Suffix Tree Application 3 – Longest Repeated Substring
Suffix Tree Application 4 – Build Linear Time Suffix Array
Suffix Tree Application 6 – Longest Palindromic Substring
Generalized Suffix Tree 1
This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nidhi_biet
sumitgumber28
sagar0719kumar
Suffix-Tree
Advanced Data Structure
Pattern Searching
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 592,
"s": 54,
"text": "Given two strings X and Y, find the Longest Common Substring of X and Y.Naive [O(N*M2)] and Dynamic Programming [O(N*M)] approaches are already discussed here. In this article, we will discuss a linear time approach to find LCS using suffix tree (The 5th Suffix Tree Application). Here we will build generalized suffix tree for two strings X and Y as discussed already at: Generalized Suffix Tree 1Lets take same example (X = xabxa, and Y = babxba) we saw in Generalized Suffix Tree 1. We built following suffix tree for X and Y there: "
},
{
"code": null,
"e": 1196,
"s": 592,
"text": "This is generalized suffix tree for xabxa#babxba$ In above, leaves with suffix indices in [0,4] are suffixes of string xabxa and leaves with suffix indices in [6,11] are suffixes of string babxa. Why ?? Because in concatenated string xabxa#babxba$, index of string xabxa is 0 and it’s length is 5, so indices of it’s suffixes would be 0, 1, 2, 3 and 4. Similarly index of string babxba is 6 and it’s length is 6, so indices of it’s suffixes would be 6, 7, 8, 9, 10 and 11.With this, we can see that in the generalized suffix tree figure above, there are some internal nodes having leaves below it from "
},
{
"code": null,
"e": 1319,
"s": 1196,
"text": "both strings X and Y (i.e. there is at least one leaf with suffix index in [0,4] and one leaf with suffix index in [6, 11]"
},
{
"code": null,
"e": 1384,
"s": 1319,
"text": "string X only (i.e. all leaf nodes have suffix indices in [0,4])"
},
{
"code": null,
"e": 1450,
"s": 1384,
"text": "string Y only (i.e. all leaf nodes have suffix indices in [6,11])"
},
{
"code": null,
"e": 1602,
"s": 1450,
"text": "Following figure shows the internal nodes marked as “XY”, “X” or “Y” depending on which string the leaves belong to, that they have below themselves. "
},
{
"code": null,
"e": 2623,
"s": 1602,
"text": "What these “XY”, “X” or “Y” marking mean ? Path label from root to an internal node gives a substring of X or Y or both. For node marked as XY, substring from root to that node belongs to both strings X and Y. For node marked as X, substring from root to that node belongs to string X only. For node marked as Y, substring from root to that node belongs to string Y only.By looking at above figure, can you see how to get LCS of X and Y ? By now, it should be clear that how to get common substring of X and Y at least. If we traverse the path from root to nodes marked as XY, we will get common substring of X and Y.Now we need to find the longest one among all those common substrings. Can you think how to get LCS now ? Recall how did we get Longest Repeated Substring in a given string using suffix tree already. The path label from root to the deepest node marked as XY will give the LCS of X and Y. The deepest node is highlighted in above figure and path label “abx” from root to that node is the LCS of X and Y. "
},
{
"code": null,
"e": 2625,
"s": 2623,
"text": "C"
},
{
"code": "// A C program to implement Ukkonen's Suffix Tree Construction// Here we build generalized suffix tree for two strings// And then we find longest common substring of the two input strings#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX_CHAR 256 struct SuffixTreeNode { struct SuffixTreeNode *children[MAX_CHAR]; //pointer to other node via suffix link struct SuffixTreeNode *suffixLink; /*(start, end) interval specifies the edge, by which the node is connected to its parent node. Each edge will connect two nodes, one parent and one child, and (start, end) interval of a given edge will be stored in the child node. Lets say there are two nods A and B connected by an edge with indices (5, 8) then this indices (5, 8) will be stored in node B. */ int start; int *end; /*for leaf nodes, it stores the index of suffix for the path from root to leaf*/ int suffixIndex;}; typedef struct SuffixTreeNode Node; char text[100]; //Input stringNode *root = NULL; //Pointer to root node /*lastNewNode will point to newly created internal node, waiting for it's suffix link to be set, which might get a new suffix link (other than root) in next extension of same phase. lastNewNode will be set to NULL when last newly created internal node (if there is any) got it's suffix link reset to new internal node created in next extension of same phase. */Node *lastNewNode = NULL;Node *activeNode = NULL; /*activeEdge is represented as input string character index (not the character itself)*/int activeEdge = -1;int activeLength = 0; // remainingSuffixCount tells how many suffixes yet to// be added in treeint remainingSuffixCount = 0;int leafEnd = -1;int *rootEnd = NULL;int *splitEnd = NULL;int size = -1; //Length of input stringint size1 = 0; //Size of 1st string Node *newNode(int start, int *end){ Node *node =(Node*) malloc(sizeof(Node)); int i; for (i = 0; i < MAX_CHAR; i++) node->children[i] = NULL; /*For root node, suffixLink will be set to NULL For internal nodes, suffixLink will be set to root by default in current extension and may change in next extension*/ node->suffixLink = root; node->start = start; node->end = end; /*suffixIndex will be set to -1 by default and actual suffix index will be set later for leaves at the end of all phases*/ node->suffixIndex = -1; return node;} int edgeLength(Node *n) { if(n == root) return 0; return *(n->end) - (n->start) + 1;} int walkDown(Node *currNode){ /*activePoint change for walk down (APCFWD) using Skip/Count Trick (Trick 1). If activeLength is greater than current edge length, set next internal node as activeNode and adjust activeEdge and activeLength accordingly to represent same activePoint*/ if (activeLength >= edgeLength(currNode)) { activeEdge += edgeLength(currNode); activeLength -= edgeLength(currNode); activeNode = currNode; return 1; } return 0;} void extendSuffixTree(int pos){ /*Extension Rule 1, this takes care of extending all leaves created so far in tree*/ leafEnd = pos; /*Increment remainingSuffixCount indicating that a new suffix added to the list of suffixes yet to be added in tree*/ remainingSuffixCount++; /*set lastNewNode to NULL while starting a new phase, indicating there is no internal node waiting for it's suffix link reset in current phase*/ lastNewNode = NULL; //Add all suffixes (yet to be added) one by one in tree while(remainingSuffixCount > 0) { if (activeLength == 0) activeEdge = pos; //APCFALZ // There is no outgoing edge starting with // activeEdge from activeNode if (activeNode->children] == NULL) { //Extension Rule 2 (A new leaf edge gets created) activeNode->children] = newNode(pos, &leafEnd); /*A new leaf edge is created in above line starting from an existing node (the current activeNode), and if there is any internal node waiting for it's suffix link get reset, point the suffix link from that last internal node to current activeNode. Then set lastNewNode to NULL indicating no more node waiting for suffix link reset.*/ if (lastNewNode != NULL) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } } // There is an outgoing edge starting with activeEdge // from activeNode else { // Get the next node at the end of edge starting // with activeEdge Node *next = activeNode->children]; if (walkDown(next))//Do walkdown { //Start from next node (the new activeNode) continue; } /*Extension Rule 3 (current character being processed is already on the edge)*/ if (text[next->start + activeLength] == text[pos]) { //If a newly created node waiting for it's //suffix link to be set, then set suffix link //of that waiting node to current active node if(lastNewNode != NULL && activeNode != root) { lastNewNode->suffixLink = activeNode; lastNewNode = NULL; } //APCFER3 activeLength++; /*STOP all further processing in this phase and move on to next phase*/ break; } /*We will be here when activePoint is in middle of the edge being traversed and current character being processed is not on the edge (we fall off the tree). In this case, we add a new internal node and a new leaf edge going out of that new node. This is Extension Rule 2, where a new leaf edge and a new internal node get created*/ splitEnd = (int*) malloc(sizeof(int)); *splitEnd = next->start + activeLength - 1; //New internal node Node *split = newNode(next->start, splitEnd); activeNode->children] = split; //New leaf coming out of new internal node split->children] = newNode(pos, &leafEnd); next->start += activeLength; split->children] = next; /*We got a new internal node here. If there is any internal node created in last extensions of same phase which is still waiting for it's suffix link reset, do it now.*/ if (lastNewNode != NULL) { /*suffixLink of lastNewNode points to current newly created internal node*/ lastNewNode->suffixLink = split; } /*Make the current newly created internal node waiting for it's suffix link reset (which is pointing to root at present). If we come across any other internal node (existing or newly created) in next extension of same phase, when a new leaf edge gets added (i.e. when Extension Rule 2 applies is any of the next extension of same phase) at that point, suffixLink of this node will point to that internal node.*/ lastNewNode = split; } /* One suffix got added in tree, decrement the count of suffixes yet to be added.*/ remainingSuffixCount--; if (activeNode == root && activeLength > 0) //APCFER2C1 { activeLength--; activeEdge = pos - remainingSuffixCount + 1; } else if (activeNode != root) //APCFER2C2 { activeNode = activeNode->suffixLink; } }} void print(int i, int j){ int k; for (k=i; k<=j && text[k] != '#'; k++) printf(\"%c\", text[k]); if(k<=j) printf(\"#\");} //Print the suffix tree as well along with setting suffix index//So tree will be printed in DFS manner//Each edge along with it's suffix index will be printedvoid setSuffixIndexByDFS(Node *n, int labelHeight){ if (n == NULL) return; if (n->start != -1) //A non-root node { //Print the label on edge from parent to current node //Uncomment below line to print suffix tree //print(n->start, *(n->end)); } int leaf = 1; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { //Uncomment below two lines to print suffix index // if (leaf == 1 && n->start != -1) // printf(\" [%d]\\n\", n->suffixIndex); //Current node is not a leaf as it has outgoing //edges from it. leaf = 0; setSuffixIndexByDFS(n->children[i], labelHeight + edgeLength(n->children[i])); } } if (leaf == 1) { for(i= n->start; i<= *(n->end); i++) { if(text[i] == '#') { n->end = (int*) malloc(sizeof(int)); *(n->end) = i; } } n->suffixIndex = size - labelHeight; //Uncomment below line to print suffix index // printf(\" [%d]\\n\", n->suffixIndex); }} void freeSuffixTreeByPostOrder(Node *n){ if (n == NULL) return; int i; for (i = 0; i < MAX_CHAR; i++) { if (n->children[i] != NULL) { freeSuffixTreeByPostOrder(n->children[i]); } } if (n->suffixIndex == -1) free(n->end); free(n);} /*Build the suffix tree and print the edge labels along withsuffixIndex. suffixIndex for leaf edges will be >= 0 andfor non-leaf edges will be -1*/void buildSuffixTree(){ size = strlen(text); int i; rootEnd = (int*) malloc(sizeof(int)); *rootEnd = - 1; /*Root is a special node with start and end indices as -1, as it has no parent from where an edge comes to root*/ root = newNode(-1, rootEnd); activeNode = root; //First activeNode will be root for (i=0; i<size; i++) extendSuffixTree(i); int labelHeight = 0; setSuffixIndexByDFS(root, labelHeight);} int doTraversal(Node *n, int labelHeight, int* maxHeight,int* substringStartIndex){ if(n == NULL) { return; } int i=0; int ret = -1; if(n->suffixIndex < 0) //If it is internal node { for (i = 0; i < MAX_CHAR; i++) { if(n->children[i] != NULL) { ret = doTraversal(n->children[i], labelHeight + edgeLength(n->children[i]), maxHeight, substringStartIndex); if(n->suffixIndex == -1) n->suffixIndex = ret; else if((n->suffixIndex == -2 && ret == -3) || (n->suffixIndex == -3 && ret == -2) || n->suffixIndex == -4) { n->suffixIndex = -4;//Mark node as XY //Keep track of deepest node if(*maxHeight < labelHeight) { *maxHeight = labelHeight; *substringStartIndex = *(n->end) - labelHeight + 1; } } } } } else if(n->suffixIndex > -1 && n->suffixIndex < size1)//suffix of X return -2;//Mark node as X else if(n->suffixIndex >= size1)//suffix of Y return -3;//Mark node as Y return n->suffixIndex;} void getLongestCommonSubstring(){ int maxHeight = 0; int substringStartIndex = 0; doTraversal(root, 0, &maxHeight, &substringStartIndex); int k; for (k=0; k<maxHeight; k++) printf(\"%c\", text[k + substringStartIndex]); if(k == 0) printf(\"No common substring\"); else printf(\", of length: %d\",maxHeight); printf(\"\\n\");} // driver program to test above functionsint main(int argc, char *argv[]){ size1 = 7; printf(\"Longest Common Substring in xabxac and abcabxabcd is: \"); strcpy(text, \"xabxac#abcabxabcd$\"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 10; printf(\"Longest Common Substring in xabxaabxa and babxba is: \"); strcpy(text, \"xabxaabxa#babxba$\"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 14; printf(\"Longest Common Substring in GeeksforGeeks and GeeksQuiz is: \"); strcpy(text, \"GeeksforGeeks#GeeksQuiz$\"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 26; printf(\"Longest Common Substring in OldSite:GeeksforGeeks.org\"); printf(\" and NewSite:GeeksQuiz.com is: \"); strcpy(text, \"OldSite:GeeksforGeeks.org#NewSite:GeeksQuiz.com$\"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 6; printf(\"Longest Common Substring in abcde and fghie is: \"); strcpy(text, \"abcde#fghie$\"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); size1 = 6; printf(\"Longest Common Substring in pqrst and uvwxyz is: \"); strcpy(text, \"pqrst#uvwxyz$\"); buildSuffixTree(); getLongestCommonSubstring(); //Free the dynamically allocated memory freeSuffixTreeByPostOrder(root); return 0;}",
"e": 16358,
"s": 2625,
"text": null
},
{
"code": null,
"e": 16366,
"s": 16358,
"text": "Output:"
},
{
"code": null,
"e": 16834,
"s": 16366,
"text": "Longest Common Substring in xabxac and abcabxabcd is: abxa, of length: 4\nLongest Common Substring in xabxaabxa and babxba is: abx, of length: 3\nLongest Common Substring in GeeksforGeeks and GeeksQuiz is: Geeks, of length: 5\nLongest Common Substring in OldSite:GeeksforGeeks.org and \nNewSite:GeeksQuiz.com is: Site:Geeks, of length: 10\nLongest Common Substring in abcde and fghie is: e, of length: 1\nLongest Common Substring in pqrst and uvwxyz is: No common substring"
},
{
"code": null,
"e": 17043,
"s": 16834,
"text": "If two strings are of size M and N, then Generalized Suffix Tree construction takes O(M+N) and LCS finding is a DFS on tree which is again O(M+N). So overall complexity is linear in time and space.Followup: "
},
{
"code": null,
"e": 17370,
"s": 17043,
"text": "Given a pattern, check if it is substring of X or Y or both. If it is a substring, find all it’s occurrences along with which string (X or Y or both) it belongs to. Extend the implementation to find LCS of more than two stringsSolve problem 1 for more than two stringsGiven a string, find it’s Longest Palindromic Substring "
},
{
"code": null,
"e": 17537,
"s": 17370,
"text": "Given a pattern, check if it is substring of X or Y or both. If it is a substring, find all it’s occurrences along with which string (X or Y or both) it belongs to. "
},
{
"code": null,
"e": 17600,
"s": 17537,
"text": "Extend the implementation to find LCS of more than two strings"
},
{
"code": null,
"e": 17642,
"s": 17600,
"text": "Solve problem 1 for more than two strings"
},
{
"code": null,
"e": 17700,
"s": 17642,
"text": "Given a string, find it’s Longest Palindromic Substring "
},
{
"code": null,
"e": 17773,
"s": 17700,
"text": "We have published following more articles on suffix tree applications: "
},
{
"code": null,
"e": 17819,
"s": 17773,
"text": "Suffix Tree Application 1 – Substring Check "
},
{
"code": null,
"e": 17872,
"s": 17819,
"text": "Suffix Tree Application 2 – Searching All Patterns "
},
{
"code": null,
"e": 17929,
"s": 17872,
"text": "Suffix Tree Application 3 – Longest Repeated Substring "
},
{
"code": null,
"e": 17990,
"s": 17929,
"text": "Suffix Tree Application 4 – Build Linear Time Suffix Array "
},
{
"code": null,
"e": 18050,
"s": 17990,
"text": "Suffix Tree Application 6 – Longest Palindromic Substring "
},
{
"code": null,
"e": 18078,
"s": 18050,
"text": "Generalized Suffix Tree 1 "
},
{
"code": null,
"e": 18248,
"s": 18078,
"text": "This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 18259,
"s": 18248,
"text": "nidhi_biet"
},
{
"code": null,
"e": 18273,
"s": 18259,
"text": "sumitgumber28"
},
{
"code": null,
"e": 18288,
"s": 18273,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 18300,
"s": 18288,
"text": "Suffix-Tree"
},
{
"code": null,
"e": 18324,
"s": 18300,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 18342,
"s": 18324,
"text": "Pattern Searching"
},
{
"code": null,
"e": 18360,
"s": 18342,
"text": "Pattern Searching"
}
] |
Time Series Analysis with R | Towards Data Science | Time Series data is data that is observed at a fixed interval time and it could be measured daily, monthly, annually, etc. Time series has a lot of applications, especially on finance and also weather forecasting. In this article, I will introduce to you how to analyze and also forecast time series data using R. For the data itself, I will give you an example from Bank Indonesia consumer price index (CPI) data from December 2002 until April 2020.
Before we begin the analysis, I will give you what steps that we have to do. The steps are like this,
First, We have to gather and pre-process the data, and also, we should know the domain knowledge of the data that we use,
Then, We analyze the time series, visually and statistically,
Then, We identify the perfect model based on its autocorrelation,
Then, We diagnose the model whether it meets the independence assumption and finally,
We can use the model for doing forecasting
As I said before, we will do time series analysis on Indonesia’s CPI data starts from December 2002 until April 2020. We can get the data from Bank Indonesia. Unfortunately, we have to copy the data first from the website onto the spreadsheet, then make a .csv data from it. The data looks like this after we import it,
library(tidyverse)data <- read.csv("data.csv")colnames(data) <- c("Time", "InflationRate")head(data)
Before we can make an analysis, we have to pre-process it first. Especially on the “InflationRate” column where we have to remove the ‘%’ symbol and convert it to numeric type like this,
# Pre-process the datadata$InflationRate <- gsub(" %$", "", data$InflationRate)data$InflationRate <- as.numeric(data$InflationRate)data <- data[order(nrow(data):1), ]tail(data)
Then, the data that we have will look like this,
With that, we can make a time-series object from the “InflationRate” column using ts function
cpi <- ts(data$InflationRate, frequency = 12, start = c(2002, 12))
With cpi variable, we can conduct the time series analysis.
First, let’s introduce the consumer price index (CPI). CPI is an index that measures the price change of consumer goods at a certain time from its base year. The formula looks like this,
Each CPI values is measured every month. Here is the code and also the plot as the results from this code,
library(ggplot2)# Make the DataFrametidy_data <- data.frame( date = seq(as.Date("2002-12-01"), as.Date("2020-04-01"), by = "month"), cpi = cpi)tidy_data# Make the plotp <- ggplot(tidy_data, aes(x=date, y=cpi)) + geom_line(color="red", size=1.1) + theme_minimal() + xlab("") + ylab("Consumer Price Index") + ggtitle("Indonesia's Consumer Price Index", subtitle = "From December 2002 Until April 2020")p# Get the statistical summary# Returns data frame and sort based on the CPItidy_data %>% arrange(desc(cpi))tidy_data %>% arrange(cpi)
Based on the graph, We cannot see any trend or seasonal pattern. Despite it looks seasonal, the peak of each year is not in the same month, so it’s not seasonal. Then, this graph also don’t have an increasing or decreasing trend on it. Therefore, this graph is stationary because the statistical properties of the data, such as mean and variance, don’t have any effect because of the time.
Beside of the graph, we can measure statistical summary from the data. We can see that the maximum inflation occurs in November 2005 with the rate of CPI is 18.38. Then, the minimum inflation occurs in November 2009 with the rate of CPI is 2.41. With that information, we can conclude that the data doesn’t have a seasonal pattern on it.
After we analyze the data, then we can do modelling based on the data. There are 2 models that we will consider for this case, there are Auto Regression (AR) model and also the Moving Average (MA) model. Before we use the model, we have to identify which model that perfectly fits on the data based on its autocorrelation and which lag suits the model. To identify this, we will make the Auto Correlation Function (ACF) plot and also Partial Auto Correlation Function (PACF) plot like this one below and here is the code,
acf(cpi, plot = T, main = "ACF Plot of CPI", xaxt="n")pacf(cpi, plot = T, main = "ACF Plot of CPI", xaxt="n")
Based on the plot above, how we can choose the perfect model for this data. To choose between AR and MA model, we can see this summary below,
The summary says that AR(p) will fit the model if the ACF plot tails off and PACF plot cuts off to nearly 0 after lag p. Then, the MA(q) model will fit if the ACF plot cuts off to nearly 0 after lag Q and the PACF plot tails off. If both plots are tailing off, then we can use the ARMA(p, q) model to it. For those who still confused about tail off and cut off, tail off means that the value is decreasing gradually and not drop to nearly 0. Then cut off means that the autocorrelation decrease to nearly 0 after the previous lag.
Based on that information, we can see that the ACF plot decreases gradually (tail off) and the PACF plot decreases to nearly 0 after lag-1. Therefore, for this model, we will use the AR(1) model for the next step.
To make sure that the model can be used for forecasting and the other measurement, we have to test the model using Ljung Box Test. Here is the code to do that,
library(FitAR)acf(ar1$residuals)res <- LjungBoxTest(ar1$residuals, k=2, StartLag=1)plot(res[,3],main= "Ljung-Box Q Test", ylab= "P-values", xlab= "Lag")qqnorm(ar1$residuals)qqline(ar1$residuals)
Based on these plots, we can see that the Q-test plot have p-values above 0.05, then the ACF plot shows no significance between another lag, and finally, we can see that the QQ-Plot is almost fit into the line, so we can assume that is already normal. Therefore, we can use the model to do the forecast.
After we make the model and taking the test, now we can do the forecasting by using this code below,
library(forecast)futurVal <- forecast(ar1, h=10, level=c(99.5))plot(futurVal)
And here is the result,
Forecasting is the last work that I can show you. I hope, with this study case on time series analysis, you can make a time series analysis based on your problem. This article is just showing the fundamentals on how to do the analysis and not tackling a problem that is using the ARIMA model and the data that I used still stationary data. I hope that I can share with you talking on how to analyze non-stationary time series data later on.
[1] Chatterjee, S. , Time Series Analysis Using ARIMA Model In R (2018), datascienceplus.com.[2] Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: principles and practice, 2nd edition, OTexts. | [
{
"code": null,
"e": 623,
"s": 172,
"text": "Time Series data is data that is observed at a fixed interval time and it could be measured daily, monthly, annually, etc. Time series has a lot of applications, especially on finance and also weather forecasting. In this article, I will introduce to you how to analyze and also forecast time series data using R. For the data itself, I will give you an example from Bank Indonesia consumer price index (CPI) data from December 2002 until April 2020."
},
{
"code": null,
"e": 725,
"s": 623,
"text": "Before we begin the analysis, I will give you what steps that we have to do. The steps are like this,"
},
{
"code": null,
"e": 847,
"s": 725,
"text": "First, We have to gather and pre-process the data, and also, we should know the domain knowledge of the data that we use,"
},
{
"code": null,
"e": 909,
"s": 847,
"text": "Then, We analyze the time series, visually and statistically,"
},
{
"code": null,
"e": 975,
"s": 909,
"text": "Then, We identify the perfect model based on its autocorrelation,"
},
{
"code": null,
"e": 1061,
"s": 975,
"text": "Then, We diagnose the model whether it meets the independence assumption and finally,"
},
{
"code": null,
"e": 1104,
"s": 1061,
"text": "We can use the model for doing forecasting"
},
{
"code": null,
"e": 1424,
"s": 1104,
"text": "As I said before, we will do time series analysis on Indonesia’s CPI data starts from December 2002 until April 2020. We can get the data from Bank Indonesia. Unfortunately, we have to copy the data first from the website onto the spreadsheet, then make a .csv data from it. The data looks like this after we import it,"
},
{
"code": null,
"e": 1525,
"s": 1424,
"text": "library(tidyverse)data <- read.csv(\"data.csv\")colnames(data) <- c(\"Time\", \"InflationRate\")head(data)"
},
{
"code": null,
"e": 1712,
"s": 1525,
"text": "Before we can make an analysis, we have to pre-process it first. Especially on the “InflationRate” column where we have to remove the ‘%’ symbol and convert it to numeric type like this,"
},
{
"code": null,
"e": 1889,
"s": 1712,
"text": "# Pre-process the datadata$InflationRate <- gsub(\" %$\", \"\", data$InflationRate)data$InflationRate <- as.numeric(data$InflationRate)data <- data[order(nrow(data):1), ]tail(data)"
},
{
"code": null,
"e": 1938,
"s": 1889,
"text": "Then, the data that we have will look like this,"
},
{
"code": null,
"e": 2032,
"s": 1938,
"text": "With that, we can make a time-series object from the “InflationRate” column using ts function"
},
{
"code": null,
"e": 2099,
"s": 2032,
"text": "cpi <- ts(data$InflationRate, frequency = 12, start = c(2002, 12))"
},
{
"code": null,
"e": 2159,
"s": 2099,
"text": "With cpi variable, we can conduct the time series analysis."
},
{
"code": null,
"e": 2346,
"s": 2159,
"text": "First, let’s introduce the consumer price index (CPI). CPI is an index that measures the price change of consumer goods at a certain time from its base year. The formula looks like this,"
},
{
"code": null,
"e": 2453,
"s": 2346,
"text": "Each CPI values is measured every month. Here is the code and also the plot as the results from this code,"
},
{
"code": null,
"e": 2997,
"s": 2453,
"text": "library(ggplot2)# Make the DataFrametidy_data <- data.frame( date = seq(as.Date(\"2002-12-01\"), as.Date(\"2020-04-01\"), by = \"month\"), cpi = cpi)tidy_data# Make the plotp <- ggplot(tidy_data, aes(x=date, y=cpi)) + geom_line(color=\"red\", size=1.1) + theme_minimal() + xlab(\"\") + ylab(\"Consumer Price Index\") + ggtitle(\"Indonesia's Consumer Price Index\", subtitle = \"From December 2002 Until April 2020\")p# Get the statistical summary# Returns data frame and sort based on the CPItidy_data %>% arrange(desc(cpi))tidy_data %>% arrange(cpi)"
},
{
"code": null,
"e": 3387,
"s": 2997,
"text": "Based on the graph, We cannot see any trend or seasonal pattern. Despite it looks seasonal, the peak of each year is not in the same month, so it’s not seasonal. Then, this graph also don’t have an increasing or decreasing trend on it. Therefore, this graph is stationary because the statistical properties of the data, such as mean and variance, don’t have any effect because of the time."
},
{
"code": null,
"e": 3725,
"s": 3387,
"text": "Beside of the graph, we can measure statistical summary from the data. We can see that the maximum inflation occurs in November 2005 with the rate of CPI is 18.38. Then, the minimum inflation occurs in November 2009 with the rate of CPI is 2.41. With that information, we can conclude that the data doesn’t have a seasonal pattern on it."
},
{
"code": null,
"e": 4247,
"s": 3725,
"text": "After we analyze the data, then we can do modelling based on the data. There are 2 models that we will consider for this case, there are Auto Regression (AR) model and also the Moving Average (MA) model. Before we use the model, we have to identify which model that perfectly fits on the data based on its autocorrelation and which lag suits the model. To identify this, we will make the Auto Correlation Function (ACF) plot and also Partial Auto Correlation Function (PACF) plot like this one below and here is the code,"
},
{
"code": null,
"e": 4357,
"s": 4247,
"text": "acf(cpi, plot = T, main = \"ACF Plot of CPI\", xaxt=\"n\")pacf(cpi, plot = T, main = \"ACF Plot of CPI\", xaxt=\"n\")"
},
{
"code": null,
"e": 4499,
"s": 4357,
"text": "Based on the plot above, how we can choose the perfect model for this data. To choose between AR and MA model, we can see this summary below,"
},
{
"code": null,
"e": 5030,
"s": 4499,
"text": "The summary says that AR(p) will fit the model if the ACF plot tails off and PACF plot cuts off to nearly 0 after lag p. Then, the MA(q) model will fit if the ACF plot cuts off to nearly 0 after lag Q and the PACF plot tails off. If both plots are tailing off, then we can use the ARMA(p, q) model to it. For those who still confused about tail off and cut off, tail off means that the value is decreasing gradually and not drop to nearly 0. Then cut off means that the autocorrelation decrease to nearly 0 after the previous lag."
},
{
"code": null,
"e": 5244,
"s": 5030,
"text": "Based on that information, we can see that the ACF plot decreases gradually (tail off) and the PACF plot decreases to nearly 0 after lag-1. Therefore, for this model, we will use the AR(1) model for the next step."
},
{
"code": null,
"e": 5404,
"s": 5244,
"text": "To make sure that the model can be used for forecasting and the other measurement, we have to test the model using Ljung Box Test. Here is the code to do that,"
},
{
"code": null,
"e": 5599,
"s": 5404,
"text": "library(FitAR)acf(ar1$residuals)res <- LjungBoxTest(ar1$residuals, k=2, StartLag=1)plot(res[,3],main= \"Ljung-Box Q Test\", ylab= \"P-values\", xlab= \"Lag\")qqnorm(ar1$residuals)qqline(ar1$residuals)"
},
{
"code": null,
"e": 5903,
"s": 5599,
"text": "Based on these plots, we can see that the Q-test plot have p-values above 0.05, then the ACF plot shows no significance between another lag, and finally, we can see that the QQ-Plot is almost fit into the line, so we can assume that is already normal. Therefore, we can use the model to do the forecast."
},
{
"code": null,
"e": 6004,
"s": 5903,
"text": "After we make the model and taking the test, now we can do the forecasting by using this code below,"
},
{
"code": null,
"e": 6082,
"s": 6004,
"text": "library(forecast)futurVal <- forecast(ar1, h=10, level=c(99.5))plot(futurVal)"
},
{
"code": null,
"e": 6106,
"s": 6082,
"text": "And here is the result,"
},
{
"code": null,
"e": 6547,
"s": 6106,
"text": "Forecasting is the last work that I can show you. I hope, with this study case on time series analysis, you can make a time series analysis based on your problem. This article is just showing the fundamentals on how to do the analysis and not tackling a problem that is using the ARIMA model and the data that I used still stationary data. I hope that I can share with you talking on how to analyze non-stationary time series data later on."
}
] |
Can we serialize static variables in Java? | In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).
But, static variables belong to class therefore, you cannot serialize static variables in Java. Still if you try to do so, the program gets compiled successfully but it raises an exception at the time of execution.
In the following java program, the class Student has a static variable and we are trying to serialize and desterilize its object in the another class named ExampleSerialize.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
private static String name;
public Student(String name){
this.name = name;
}
public static String getName() {
return name;
}
public static void setAge(String name) {
Student.name = name;
}
}
public class ExampleSerialize{
public static void main(String args[]) throws Exception{
Student std1 = new Student("Krishna", 30);
FileOutputStream fos = new FileOutputStream("e:\\student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std1);
FileInputStream fis = new FileInputStream("e:\\student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student std2 = (Student) ois.readObject();
System.out.println(std2.getName());
}
}
This program gets executed successfully but, while running you will get a run time exception as shown below −
Exception in thread "main" java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to java.io.ObjectOutput
at sample.TestSerialize.main(TestSerialize.java:31) | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI)."
},
{
"code": null,
"e": 1463,
"s": 1248,
"text": "But, static variables belong to class therefore, you cannot serialize static variables in Java. Still if you try to do so, the program gets compiled successfully but it raises an exception at the time of execution."
},
{
"code": null,
"e": 1637,
"s": 1463,
"text": "In the following java program, the class Student has a static variable and we are trying to serialize and desterilize its object in the another class named ExampleSerialize."
},
{
"code": null,
"e": 2650,
"s": 1637,
"text": "import java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.ObjectInput;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutput;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nclass Student implements Serializable{\n private static String name;\n public Student(String name){\n this.name = name;\n }\n public static String getName() {\n return name;\n }\n public static void setAge(String name) {\n Student.name = name;\n }\n}\npublic class ExampleSerialize{\n public static void main(String args[]) throws Exception{\n Student std1 = new Student(\"Krishna\", 30);\n FileOutputStream fos = new FileOutputStream(\"e:\\\\student.ser\");\n ObjectOutputStream oos = new ObjectOutputStream(fos);\n oos.writeObject(std1);\n\n FileInputStream fis = new FileInputStream(\"e:\\\\student.ser\");\n ObjectInputStream ois = new ObjectInputStream(fis);\n Student std2 = (Student) ois.readObject();\n System.out.println(std2.getName());\n }\n}"
},
{
"code": null,
"e": 2760,
"s": 2650,
"text": "This program gets executed successfully but, while running you will get a run time exception as shown below −"
},
{
"code": null,
"e": 2933,
"s": 2760,
"text": "Exception in thread \"main\" java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to java.io.ObjectOutput\nat sample.TestSerialize.main(TestSerialize.java:31)"
}
] |
C/C++ Program for Finding the Number Occurring Odd Number of Times? | A C++ program to find a number which occurs odd number of times in a given array of positive integers. In this array, all numbers occur even number of times.
Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7
Use two loops in which the outer loop traversed all elements one by one and inner loop counts the number of occurrences of the element traversed by the outer loop.
#include <iostream>
using namespace std;
int Odd(int arr[], int n){
for (int i = 0; i < n; i++) {
int ctr = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
ctr++;
}
if (ctr % 2 != 0)
return arr[i];
}
return -1;
}
int main() {
int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
int n = 9;
cout <<Odd(arr, n);
return 0;
} | [
{
"code": null,
"e": 1220,
"s": 1062,
"text": "A C++ program to find a number which occurs odd number of times in a given array of positive integers. In this array, all numbers occur even number of times."
},
{
"code": null,
"e": 1273,
"s": 1220,
"text": "Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}\nOutput: 7"
},
{
"code": null,
"e": 1437,
"s": 1273,
"text": "Use two loops in which the outer loop traversed all elements one by one and inner loop counts the number of occurrences of the element traversed by the outer loop."
},
{
"code": null,
"e": 1829,
"s": 1437,
"text": "#include <iostream>\nusing namespace std;\nint Odd(int arr[], int n){\n for (int i = 0; i < n; i++) {\n int ctr = 0;\n for (int j = 0; j < n; j++) {\n if (arr[i] == arr[j])\n ctr++;\n }\n if (ctr % 2 != 0)\n return arr[i];\n }\n return -1;\n}\nint main() {\n int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};\n int n = 9;\n cout <<Odd(arr, n);\n return 0;\n}"
}
] |
Console.TreatControlCAsInput Property in C# with examples - GeeksforGeeks | 14 Mar, 2019
Console.TreatControlCAsInput Property is used to get or set a value indicating whether the combination of the Control modifier key and C console key (Ctrl+C) is treated as ordinary input or as an interruption that is handled by the operating system.
Syntax:
public static bool TreatControlCAsInput { get; set; }
Property Value: This property returns true if Ctrl+C is treated as ordinary input. Otherwise false, it means if the input is Ctrl+C then the program is terminated.
Exception: This property will give IOException if the program is not able to get or set the input mode of the console input buffer.
Below programs illustrate the use of the above-discussed property:
Example 1:
// C# program to illustrate the use of// Console.TreatControlCAsInput Propertyusing System; class GFG { // Main Method public static void Main() { ConsoleKeyInfo c; // Prevent program from terminating // if CTL+C is pressed. Console.TreatControlCAsInput = true; Console.WriteLine("Press any key with combination of CTL, "+ "ALT, and SHIFT or Press the Esc to quit: \n"); do { c = Console.ReadKey(); Console.Write(" - pressed key is "); // only prints the pressed keys Console.WriteLine(c.Key.ToString()); // condition for Exit } while (c.Key != ConsoleKey.Escape); }}
Output:
Example 2:
// C# program to illustrate the use of// Console.TreatControlCAsInput Propertyusing System; class GFG { // Main Method public static void Main() { ConsoleKeyInfo c; // Prevent program from terminating // if CTL+C is pressed. Console.TreatControlCAsInput = true; Console.WriteLine("Press any key with combination of CTL, "+ "ALT, and SHIFT or Press the Esc to quit: \n"); do { c = Console.ReadKey(); Console.Write("pressed key is "); // conditions- if ((c.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT + "); if ((c.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL + "); if ((c.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT + "); // prints the pressed keys Console.WriteLine(c.Key.ToString()); // condition for Exit } while (c.Key != ConsoleKey.Escape); }}
Output:
When false
using System; class GFG { // Main Method public static void Main() { ConsoleKeyInfo c; // Prevent program from terminating // if CTL+C is pressed. Console.TreatControlCAsInput = false; Console.WriteLine("Press any key with combination of CTL,"+ " ALT, and SHIFT or Press the Esc to quit: \n"); do { c = Console.ReadKey(); Console.Write(" - pressed key is "); // only prints the pressed keys Console.WriteLine(c.Key.ToString()); // condition for Exit } while (c.Key != ConsoleKey.Escape); }}
Output :
Press any key with combination of CTL, ALT, and SHIFT or Press the Esc to quit:
a - pressed key is A
b - pressed key is B
g - pressed key is G
// Here after these input we press Ctrl+C,
// then the program is terminated.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.treatcontrolcasinput?view=netframework-4.7.2
CSharp-Console-Class
CSharp-method
Picked
C#
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
Partial Classes in C#
HashSet in C# with Examples
C# | Inheritance
C# | How to insert an element in an Array?
C# | List Class
Lambda Expressions in C#
C# | Generics - Introduction
What is Regular Expression in C#? | [
{
"code": null,
"e": 24222,
"s": 24194,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 24472,
"s": 24222,
"text": "Console.TreatControlCAsInput Property is used to get or set a value indicating whether the combination of the Control modifier key and C console key (Ctrl+C) is treated as ordinary input or as an interruption that is handled by the operating system."
},
{
"code": null,
"e": 24480,
"s": 24472,
"text": "Syntax:"
},
{
"code": null,
"e": 24534,
"s": 24480,
"text": "public static bool TreatControlCAsInput { get; set; }"
},
{
"code": null,
"e": 24698,
"s": 24534,
"text": "Property Value: This property returns true if Ctrl+C is treated as ordinary input. Otherwise false, it means if the input is Ctrl+C then the program is terminated."
},
{
"code": null,
"e": 24830,
"s": 24698,
"text": "Exception: This property will give IOException if the program is not able to get or set the input mode of the console input buffer."
},
{
"code": null,
"e": 24897,
"s": 24830,
"text": "Below programs illustrate the use of the above-discussed property:"
},
{
"code": null,
"e": 24908,
"s": 24897,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the use of// Console.TreatControlCAsInput Propertyusing System; class GFG { // Main Method public static void Main() { ConsoleKeyInfo c; // Prevent program from terminating // if CTL+C is pressed. Console.TreatControlCAsInput = true; Console.WriteLine(\"Press any key with combination of CTL, \"+ \"ALT, and SHIFT or Press the Esc to quit: \\n\"); do { c = Console.ReadKey(); Console.Write(\" - pressed key is \"); // only prints the pressed keys Console.WriteLine(c.Key.ToString()); // condition for Exit } while (c.Key != ConsoleKey.Escape); }}",
"e": 25635,
"s": 24908,
"text": null
},
{
"code": null,
"e": 25643,
"s": 25635,
"text": "Output:"
},
{
"code": null,
"e": 25654,
"s": 25643,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the use of// Console.TreatControlCAsInput Propertyusing System; class GFG { // Main Method public static void Main() { ConsoleKeyInfo c; // Prevent program from terminating // if CTL+C is pressed. Console.TreatControlCAsInput = true; Console.WriteLine(\"Press any key with combination of CTL, \"+ \"ALT, and SHIFT or Press the Esc to quit: \\n\"); do { c = Console.ReadKey(); Console.Write(\"pressed key is \"); // conditions- if ((c.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write(\"SHIFT + \"); if ((c.Modifiers & ConsoleModifiers.Control) != 0) Console.Write(\"CTL + \"); if ((c.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write(\"ALT + \"); // prints the pressed keys Console.WriteLine(c.Key.ToString()); // condition for Exit } while (c.Key != ConsoleKey.Escape); }}",
"e": 26719,
"s": 25654,
"text": null
},
{
"code": null,
"e": 26727,
"s": 26719,
"text": "Output:"
},
{
"code": null,
"e": 26738,
"s": 26727,
"text": "When false"
},
{
"code": "using System; class GFG { // Main Method public static void Main() { ConsoleKeyInfo c; // Prevent program from terminating // if CTL+C is pressed. Console.TreatControlCAsInput = false; Console.WriteLine(\"Press any key with combination of CTL,\"+ \" ALT, and SHIFT or Press the Esc to quit: \\n\"); do { c = Console.ReadKey(); Console.Write(\" - pressed key is \"); // only prints the pressed keys Console.WriteLine(c.Key.ToString()); // condition for Exit } while (c.Key != ConsoleKey.Escape); }}",
"e": 27396,
"s": 26738,
"text": null
},
{
"code": null,
"e": 27405,
"s": 27396,
"text": "Output :"
},
{
"code": null,
"e": 27630,
"s": 27405,
"text": "Press any key with combination of CTL, ALT, and SHIFT or Press the Esc to quit:\n\na - pressed key is A\nb - pressed key is B\ng - pressed key is G\n\n// Here after these input we press Ctrl+C, \n// then the program is terminated.\n"
},
{
"code": null,
"e": 27641,
"s": 27630,
"text": "Reference:"
},
{
"code": null,
"e": 27745,
"s": 27641,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.treatcontrolcasinput?view=netframework-4.7.2"
},
{
"code": null,
"e": 27766,
"s": 27745,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 27780,
"s": 27766,
"text": "CSharp-method"
},
{
"code": null,
"e": 27787,
"s": 27780,
"text": "Picked"
},
{
"code": null,
"e": 27790,
"s": 27787,
"text": "C#"
},
{
"code": null,
"e": 27809,
"s": 27790,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27907,
"s": 27809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27916,
"s": 27907,
"text": "Comments"
},
{
"code": null,
"e": 27929,
"s": 27916,
"text": "Old Comments"
},
{
"code": null,
"e": 27952,
"s": 27929,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27992,
"s": 27952,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28014,
"s": 27992,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28042,
"s": 28014,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28059,
"s": 28042,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28102,
"s": 28059,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28118,
"s": 28102,
"text": "C# | List Class"
},
{
"code": null,
"e": 28143,
"s": 28118,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 28172,
"s": 28143,
"text": "C# | Generics - Introduction"
}
] |
Using Computer Vision and Machine Learning to Monitor Activity While Working From Home | by Raymond Lo, PhD | Towards Data Science | One of the biggest challenges staying home during this lockdown most of the world is facing is the sudden restriction of physical activities especially when confined in a small space. To help address this, I thought it would be interesting to see if I could use computer vision to help motivate myself to be more active.
In this post, I will share my approach, along with a full sample source code, that illustrates the potential to help monitor and improve the quality of life for many who stay at home. The idea is having a low cost, GPU-enabled, vision-based system ($99 NVIDIA Jetson Nano) that performs most of the computer vision processing on the edge (e.g., face detection, emotion classification, people detection, and pose estimation) all-in-one easy to setup package. Then, this system can process the data it collects locally to a remote cloud for post-processing and redistributed to servers that provide a dashboard for one or many’s health.
To address privacy concerns, I discuss ways to protect a user’s privacy by only uploading the post-processed data, which contains the classified emotion data, facial features, and body pose data instead of the actual camera feed. While there is more you can do to obscure the data, this example will point you in the right direction.
This proof of concept is a simple application that shows a dashboard of my activity based on my body pose and emotion. The entire system runs on a $99 NVIDIA Jetson Nano developer board along with a webcam that costs approximately $40. This setup is something that would help people to focus on their work while tracking their activity.
Let’s take a look at how you can build the same system that I did.
The first setup I took is to establish a webcam server so that I can add as many cameras to the system as needed, and also can process these frames in a distributed and scalable way.
In Linux, we can easily set up automatic webcam streams with a program called ‘Motion’. The program allows you to create a smart security camera that detects motion and more importantly streams motion JPEG (MJPEG) as a server. This feature is very useful in allowing us to run these applications asynchronously without bogging down each camera stream on any particular machine.
To install motion on NVIDIA Jetson Nano, you can simply use this command line.
sudo apt-get install motion
Then, we edit the motion configuration file to set the resolution and the frame rate. By default, the motion application is configured to detect motion and capture frames, and that’s not what we want in our use case.
nano /etc/motion/motion.conf
Here you will need to change the resolution and frame rate to 640x320 and 15 fps for both camera feed (framerate) and streaming feed (stream_maxrate).
If you have a more powerful machine such as the Jetson Xavier, you can set the resolution and frame rate higher for better tracking for far distance objects.
Then, we turn off the auto snapshot and video capture feature (i.e., set output_pictures to off). This is important or your hard drive will be filled with new captures quickly.
After configuring Motion, you’ll need to allow it to run as a service at bootup.
nano /etc/defaultmotion
And you edit this line to
start_motion_daemon=yes
Now you’ll need to edit the main config file, located at /etc/motion/motion.conf, and set the Motion daemon to on. After restarting your computer, Motion should now be running automatically.
The following commands control the Motion service:
Start the Motion service:
sudo service motion start
Stop the Motion service:
sudo service motion stop
Restart the Motion service:
sudo service motion restart
To preview the feed, simply open your browser and go to this link:
http://localhost:8080
At this point, you will be able to see the preview of the camera feed. Now it’s time for us to actually use it.
One of the main goals of this system is to have better insight into one’s activity at home. In order to do this, we will create a pose estimation program that tracks a person’s pose. More importantly, the pose estimation allows you to create a layer of privacy by omitting your camera’s feed and only shows the processed data.
To get started, you will have to install the Tensorflow and the OpenPose libraries. GitHub member karaage0703 did an amazing job putting the setup scripts together for NVIDIA Jetson Nano. Here you can follow the Github instructions to set up the tools, and below is a link to the GitHub repository.
github clone https://github.com/karaage0703/jetson-nano-tools
Particularly, you want to run the ‘install-tensorflow.sh’ and ‘install-pose-estimation.sh’ scripts to install Tensorflow and Pose Estimation Library on your machine.
$ cd ~/jetson-nano-tools$ ./install-tensorflow.sh$ ./install-pose-estimation.sh
This process could take up to 30 minutes, and so take a break and stretch after executing the command. Once you have the tools in place, let’s look at the Python script I wrote that allows you to capture, process, and visualize the data.
I created a Python script that uses the toolset just installed, and here is the result with the skeleton overlay on top of the camera feed.
You can check out the scripts I wrote here:
git clone https://github.com/raymondlo84/nvidia-jetson-ai-monitor
The ‘run_webcam_ip.py’ script has two key functions that are based on the CMU Perceptual Computing Lab’s OpenPose project.
“OpenPose represents the first real-time multi-person system to jointly detect human body, hand, facial, and foot keypoints (in total 135 keypoints) on single images.”
This library is a very powerful tool, with a single camera feed it can detect full human skeletons with GPU acceleration. With such, imagine now how you can track the human body pose that provides you the proper feedback. For example, you can create a neck angle detector and help to fix your body posture during work.
from tf_pose.estimator import TfPoseEstimatorfrom tf_pose.networks import get_graph_path, model_wh
The script’s main loop performs the inference on each frame captured by the IP camera. Then, these two lines will perform the inference and drawing the results on the frame
humans = e.inference(image, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)image = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)
The NVIDIA Jetson’s GPU can perform pose estimation at approximately 7–8 fps at 320x160 resolution and using the mobilenet_thin model. That is very impressive for a machine that uses no more than 10W of power at full load. With the body pose estimated, one can now create a prediction on how active one is. This is similar to a FitBit but instead of using an accelerometer or gyroscope, we are using a video feed from our camera.
At this point everything we set out to do has been achieved but why not do even more with the captured video? Let’s see how to detect emotions from facial reactions in order to build a happy meter all with GPUs. For this to work, we’ll need to add in code that determines the face and emotion of a person. The amazing news is that these two systems both utilize Tensorflow on GPUs, and thus we will not require to allocate a significant amount of memory and only requires minimal overheads on top. Again, there are additional optimizations such as smartly selecting the bounding box for face detection based on body pose to get the additional speed up.
Currently, the processing rate is approximately 7 frames per second with face detection and emotion analysis at 320x160 resolution. However, with the distributed setup, I can easily double or triple the rate by offloading the work onto another node on a GPU cluster setup. Even with 3 updates per second, the system will have approximately 259,200 samples per day. This is not a trivial amount of data.
To perform the emotion analysis, I will be including the Keras library and face recognition package this time.
import face_recognitionimport kerasfrom keras.models import load_modelfrom keras.preprocessing.image import img_to_array
Then, this line extracts the position of the detected face from the image.
face_locations = face_recognition.face_locations(small_image, model=’cnn’)
And the parameter mode=‘cnn’ enables us to use the CUDA GPU-accelerated code and also gives better accuracy at different view angles or under occlusions.
Once it detected the face from the image, the face image runs through the predict function based on our pre-trained model (_mini_XCEPTION.106–0.65.hdf5) and classifies the face under one of the seven categories: angry, disgust, scared, happy, sad, surprised, or neutral.
emotion_dict = [“Angry”, “Disgust”, “Scared”, “Happy”, “Sad”, “Surprised”, “Neutral”]model = load_model(“emotion_detector_models/_mini_XCEPTION.106–0.65.hdf5”, compile=False)model_result = model.predict(face_image)
Basically, the actual work was approximately 5 lines of code, and I also provided additional sample code (webcam_face_detect.py) to run this part separately for your own testing.
One key takeaway from my experiment is how well these CV+ML algorithms can be stacked together with the GPU setup. By default, a significant amount of memory is taken up by the Tensorflow’s core, and thus it would be wise to make the best use of the resource anyways. Now, with the CPU completely free up from the processing, we have over 300% of CPU processing resources to be utilized for many other tasks such as bookkeeping of the processed data.
Here we have a low-cost monitoring system that monitors a body pose, does face detection, and returns a rudimentary emotion analysis. These three features represent the foundation of a novel vision-based health dashboard all on GPUs. The best part is that this can be built with a $99 machine. Imagine the possibilities!
With pose estimation, face detection, and emotion analysis, I can extract the motion parameters such as average motion per day, and tracking my own emotional data without having my images shared with the cloud. This data is nowhere near perfect, but this kind of feedback can be proven to be very useful for improving posture during long sessions in front of the computer (e.g., the neck issue). Also, with some minor modifications, this can quickly turn into a sleep monitor and has other potential fitness uses that can be expanded upon.
Currently, I live in Silicon Valley and serve as the OpenVINO Edge AI Software Evangelist at Intel. Previously, I was the co-founder and CTO of Meta where I shipped two Augmented Reality Developer Kits. As the Head of R&D in Meta, I had worked with hundreds of amazing engineers creating state-of-the-art technology and CV algorithms such as SLAM, 3D hand tracking, and new UX for AR/XR. During my Ph.D. study, I also published and developed real-time GPGPU applications on HDR video processing, and created augmented reality prototypes with 3D depth-sensing cameras. I always believe the accessibility and simplicity of the technology are needed to create disruptive changes. Right now, I see the rapid growth of AI edge computing can bring many smart applications at a very affordable cost. And this post is just the beginning of this ever-growing trend. | [
{
"code": null,
"e": 493,
"s": 172,
"text": "One of the biggest challenges staying home during this lockdown most of the world is facing is the sudden restriction of physical activities especially when confined in a small space. To help address this, I thought it would be interesting to see if I could use computer vision to help motivate myself to be more active."
},
{
"code": null,
"e": 1128,
"s": 493,
"text": "In this post, I will share my approach, along with a full sample source code, that illustrates the potential to help monitor and improve the quality of life for many who stay at home. The idea is having a low cost, GPU-enabled, vision-based system ($99 NVIDIA Jetson Nano) that performs most of the computer vision processing on the edge (e.g., face detection, emotion classification, people detection, and pose estimation) all-in-one easy to setup package. Then, this system can process the data it collects locally to a remote cloud for post-processing and redistributed to servers that provide a dashboard for one or many’s health."
},
{
"code": null,
"e": 1462,
"s": 1128,
"text": "To address privacy concerns, I discuss ways to protect a user’s privacy by only uploading the post-processed data, which contains the classified emotion data, facial features, and body pose data instead of the actual camera feed. While there is more you can do to obscure the data, this example will point you in the right direction."
},
{
"code": null,
"e": 1799,
"s": 1462,
"text": "This proof of concept is a simple application that shows a dashboard of my activity based on my body pose and emotion. The entire system runs on a $99 NVIDIA Jetson Nano developer board along with a webcam that costs approximately $40. This setup is something that would help people to focus on their work while tracking their activity."
},
{
"code": null,
"e": 1866,
"s": 1799,
"text": "Let’s take a look at how you can build the same system that I did."
},
{
"code": null,
"e": 2049,
"s": 1866,
"text": "The first setup I took is to establish a webcam server so that I can add as many cameras to the system as needed, and also can process these frames in a distributed and scalable way."
},
{
"code": null,
"e": 2427,
"s": 2049,
"text": "In Linux, we can easily set up automatic webcam streams with a program called ‘Motion’. The program allows you to create a smart security camera that detects motion and more importantly streams motion JPEG (MJPEG) as a server. This feature is very useful in allowing us to run these applications asynchronously without bogging down each camera stream on any particular machine."
},
{
"code": null,
"e": 2506,
"s": 2427,
"text": "To install motion on NVIDIA Jetson Nano, you can simply use this command line."
},
{
"code": null,
"e": 2534,
"s": 2506,
"text": "sudo apt-get install motion"
},
{
"code": null,
"e": 2751,
"s": 2534,
"text": "Then, we edit the motion configuration file to set the resolution and the frame rate. By default, the motion application is configured to detect motion and capture frames, and that’s not what we want in our use case."
},
{
"code": null,
"e": 2780,
"s": 2751,
"text": "nano /etc/motion/motion.conf"
},
{
"code": null,
"e": 2931,
"s": 2780,
"text": "Here you will need to change the resolution and frame rate to 640x320 and 15 fps for both camera feed (framerate) and streaming feed (stream_maxrate)."
},
{
"code": null,
"e": 3089,
"s": 2931,
"text": "If you have a more powerful machine such as the Jetson Xavier, you can set the resolution and frame rate higher for better tracking for far distance objects."
},
{
"code": null,
"e": 3266,
"s": 3089,
"text": "Then, we turn off the auto snapshot and video capture feature (i.e., set output_pictures to off). This is important or your hard drive will be filled with new captures quickly."
},
{
"code": null,
"e": 3347,
"s": 3266,
"text": "After configuring Motion, you’ll need to allow it to run as a service at bootup."
},
{
"code": null,
"e": 3371,
"s": 3347,
"text": "nano /etc/defaultmotion"
},
{
"code": null,
"e": 3397,
"s": 3371,
"text": "And you edit this line to"
},
{
"code": null,
"e": 3421,
"s": 3397,
"text": "start_motion_daemon=yes"
},
{
"code": null,
"e": 3612,
"s": 3421,
"text": "Now you’ll need to edit the main config file, located at /etc/motion/motion.conf, and set the Motion daemon to on. After restarting your computer, Motion should now be running automatically."
},
{
"code": null,
"e": 3663,
"s": 3612,
"text": "The following commands control the Motion service:"
},
{
"code": null,
"e": 3689,
"s": 3663,
"text": "Start the Motion service:"
},
{
"code": null,
"e": 3715,
"s": 3689,
"text": "sudo service motion start"
},
{
"code": null,
"e": 3740,
"s": 3715,
"text": "Stop the Motion service:"
},
{
"code": null,
"e": 3765,
"s": 3740,
"text": "sudo service motion stop"
},
{
"code": null,
"e": 3793,
"s": 3765,
"text": "Restart the Motion service:"
},
{
"code": null,
"e": 3821,
"s": 3793,
"text": "sudo service motion restart"
},
{
"code": null,
"e": 3888,
"s": 3821,
"text": "To preview the feed, simply open your browser and go to this link:"
},
{
"code": null,
"e": 3910,
"s": 3888,
"text": "http://localhost:8080"
},
{
"code": null,
"e": 4022,
"s": 3910,
"text": "At this point, you will be able to see the preview of the camera feed. Now it’s time for us to actually use it."
},
{
"code": null,
"e": 4349,
"s": 4022,
"text": "One of the main goals of this system is to have better insight into one’s activity at home. In order to do this, we will create a pose estimation program that tracks a person’s pose. More importantly, the pose estimation allows you to create a layer of privacy by omitting your camera’s feed and only shows the processed data."
},
{
"code": null,
"e": 4648,
"s": 4349,
"text": "To get started, you will have to install the Tensorflow and the OpenPose libraries. GitHub member karaage0703 did an amazing job putting the setup scripts together for NVIDIA Jetson Nano. Here you can follow the Github instructions to set up the tools, and below is a link to the GitHub repository."
},
{
"code": null,
"e": 4710,
"s": 4648,
"text": "github clone https://github.com/karaage0703/jetson-nano-tools"
},
{
"code": null,
"e": 4876,
"s": 4710,
"text": "Particularly, you want to run the ‘install-tensorflow.sh’ and ‘install-pose-estimation.sh’ scripts to install Tensorflow and Pose Estimation Library on your machine."
},
{
"code": null,
"e": 4956,
"s": 4876,
"text": "$ cd ~/jetson-nano-tools$ ./install-tensorflow.sh$ ./install-pose-estimation.sh"
},
{
"code": null,
"e": 5194,
"s": 4956,
"text": "This process could take up to 30 minutes, and so take a break and stretch after executing the command. Once you have the tools in place, let’s look at the Python script I wrote that allows you to capture, process, and visualize the data."
},
{
"code": null,
"e": 5334,
"s": 5194,
"text": "I created a Python script that uses the toolset just installed, and here is the result with the skeleton overlay on top of the camera feed."
},
{
"code": null,
"e": 5378,
"s": 5334,
"text": "You can check out the scripts I wrote here:"
},
{
"code": null,
"e": 5444,
"s": 5378,
"text": "git clone https://github.com/raymondlo84/nvidia-jetson-ai-monitor"
},
{
"code": null,
"e": 5567,
"s": 5444,
"text": "The ‘run_webcam_ip.py’ script has two key functions that are based on the CMU Perceptual Computing Lab’s OpenPose project."
},
{
"code": null,
"e": 5735,
"s": 5567,
"text": "“OpenPose represents the first real-time multi-person system to jointly detect human body, hand, facial, and foot keypoints (in total 135 keypoints) on single images.”"
},
{
"code": null,
"e": 6054,
"s": 5735,
"text": "This library is a very powerful tool, with a single camera feed it can detect full human skeletons with GPU acceleration. With such, imagine now how you can track the human body pose that provides you the proper feedback. For example, you can create a neck angle detector and help to fix your body posture during work."
},
{
"code": null,
"e": 6153,
"s": 6054,
"text": "from tf_pose.estimator import TfPoseEstimatorfrom tf_pose.networks import get_graph_path, model_wh"
},
{
"code": null,
"e": 6326,
"s": 6153,
"text": "The script’s main loop performs the inference on each frame captured by the IP camera. Then, these two lines will perform the inference and drawing the results on the frame"
},
{
"code": null,
"e": 6493,
"s": 6326,
"text": "humans = e.inference(image, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)image = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)"
},
{
"code": null,
"e": 6923,
"s": 6493,
"text": "The NVIDIA Jetson’s GPU can perform pose estimation at approximately 7–8 fps at 320x160 resolution and using the mobilenet_thin model. That is very impressive for a machine that uses no more than 10W of power at full load. With the body pose estimated, one can now create a prediction on how active one is. This is similar to a FitBit but instead of using an accelerometer or gyroscope, we are using a video feed from our camera."
},
{
"code": null,
"e": 7576,
"s": 6923,
"text": "At this point everything we set out to do has been achieved but why not do even more with the captured video? Let’s see how to detect emotions from facial reactions in order to build a happy meter all with GPUs. For this to work, we’ll need to add in code that determines the face and emotion of a person. The amazing news is that these two systems both utilize Tensorflow on GPUs, and thus we will not require to allocate a significant amount of memory and only requires minimal overheads on top. Again, there are additional optimizations such as smartly selecting the bounding box for face detection based on body pose to get the additional speed up."
},
{
"code": null,
"e": 7979,
"s": 7576,
"text": "Currently, the processing rate is approximately 7 frames per second with face detection and emotion analysis at 320x160 resolution. However, with the distributed setup, I can easily double or triple the rate by offloading the work onto another node on a GPU cluster setup. Even with 3 updates per second, the system will have approximately 259,200 samples per day. This is not a trivial amount of data."
},
{
"code": null,
"e": 8090,
"s": 7979,
"text": "To perform the emotion analysis, I will be including the Keras library and face recognition package this time."
},
{
"code": null,
"e": 8211,
"s": 8090,
"text": "import face_recognitionimport kerasfrom keras.models import load_modelfrom keras.preprocessing.image import img_to_array"
},
{
"code": null,
"e": 8286,
"s": 8211,
"text": "Then, this line extracts the position of the detected face from the image."
},
{
"code": null,
"e": 8361,
"s": 8286,
"text": "face_locations = face_recognition.face_locations(small_image, model=’cnn’)"
},
{
"code": null,
"e": 8515,
"s": 8361,
"text": "And the parameter mode=‘cnn’ enables us to use the CUDA GPU-accelerated code and also gives better accuracy at different view angles or under occlusions."
},
{
"code": null,
"e": 8786,
"s": 8515,
"text": "Once it detected the face from the image, the face image runs through the predict function based on our pre-trained model (_mini_XCEPTION.106–0.65.hdf5) and classifies the face under one of the seven categories: angry, disgust, scared, happy, sad, surprised, or neutral."
},
{
"code": null,
"e": 9001,
"s": 8786,
"text": "emotion_dict = [“Angry”, “Disgust”, “Scared”, “Happy”, “Sad”, “Surprised”, “Neutral”]model = load_model(“emotion_detector_models/_mini_XCEPTION.106–0.65.hdf5”, compile=False)model_result = model.predict(face_image)"
},
{
"code": null,
"e": 9180,
"s": 9001,
"text": "Basically, the actual work was approximately 5 lines of code, and I also provided additional sample code (webcam_face_detect.py) to run this part separately for your own testing."
},
{
"code": null,
"e": 9631,
"s": 9180,
"text": "One key takeaway from my experiment is how well these CV+ML algorithms can be stacked together with the GPU setup. By default, a significant amount of memory is taken up by the Tensorflow’s core, and thus it would be wise to make the best use of the resource anyways. Now, with the CPU completely free up from the processing, we have over 300% of CPU processing resources to be utilized for many other tasks such as bookkeeping of the processed data."
},
{
"code": null,
"e": 9952,
"s": 9631,
"text": "Here we have a low-cost monitoring system that monitors a body pose, does face detection, and returns a rudimentary emotion analysis. These three features represent the foundation of a novel vision-based health dashboard all on GPUs. The best part is that this can be built with a $99 machine. Imagine the possibilities!"
},
{
"code": null,
"e": 10492,
"s": 9952,
"text": "With pose estimation, face detection, and emotion analysis, I can extract the motion parameters such as average motion per day, and tracking my own emotional data without having my images shared with the cloud. This data is nowhere near perfect, but this kind of feedback can be proven to be very useful for improving posture during long sessions in front of the computer (e.g., the neck issue). Also, with some minor modifications, this can quickly turn into a sleep monitor and has other potential fitness uses that can be expanded upon."
}
] |
Java Program For Converting Roman Numerals To Decimal Lying Between 1 to 3999 - GeeksforGeeks | 08 Feb, 2022
Given a Roman numeral, the task is to find its corresponding decimal value.
Example :
Input: IX
Output: 9
IX is a Roman symbol which represents 9
Input: XL
Output: 40
XL is a Roman symbol which represents 40
Input: MCMIV
Output: 1904
M is a thousand,
CM is nine hundred and
IV is four
Roman numerals are based on the following symbols.
SYMBOL VALUE
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50
XC 90
C 100
CD 400
D 500
CM 900
M 1000
Approach: A number in Roman Numerals is a string of these symbols written in descending order(e.g. M’s first, followed by D’s, etc.). However, in a few specific cases, to avoid four characters being repeated in succession(such as IIII or XXXX), subtractive notation is often used as follows:
I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX (one less than 10).
X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is XC (ten less than a hundred).
C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand).
Algorithm to convert Roman Numerals to Integer Number:
Split the Roman Numeral string into Roman Symbols (character).Convert each symbol of Roman Numerals into the value it represents.Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total.
Split the Roman Numeral string into Roman Symbols (character).
Convert each symbol of Roman Numerals into the value it represents.
Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total.
If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total.
If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.
else subtract this value by adding the value of next symbol to the running total.
Following is the implementation of the above algorithm:
Java
// Java Program to convert Roman// Numerals to Numbersimport java.util.*; public class RomanToNumber{ // This function returns // value of a Roman symbol int value(char r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given romal numeral int romanToDecimal(String str) { // Initialize result int res = 0; for (int i = 0; i < str.length(); i++) { // Getting value of symbol s[i] int s1 = value(str.charAt(i)); // Getting value of symbol s[i+1] if (i + 1 < str.length()) { int s2 = value(str.charAt(i + 1)); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res; } // Driver Code public static void main(String args[]) { RomanToNumber ob = new RomanToNumber(); // Considering inputs given are valid String str = "MCMIV"; System.out.println( "Integer form of Roman Numeral" + " is " + ob.romanToDecimal(str)); }}
Output:
Integer form of Roman Numeral is 1904
Complexity Analysis:
Time Complexity: O(n), where n is the length of the string. Only one traversal of the string is required.
Space Complexity: O(1). As no extra space is required.
Another solution –
Java
// Java Program to convert Roman// Numerals to Numbersimport java.util.Map;import java.util.HashMap;class GFG{ private static final Map<Character, Integer> roman = new HashMap<Character, Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000);}}; // This function returns value// of a Roman symbolprivate static int romanToInt(String s){ int sum = 0; int n = s.length(); for(int i = 0; i < n; i++) { // If present value is less than // next value, subtract present // from next value and add the // resultant to the sum variable. if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) { sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i)); i++; } else { sum += roman.get(s.charAt(i)); } } return sum;} // Driver Codepublic static void main(String[] args){ // Considering inputs given are valid String input = "MCMIV"; System.out.print( "Integer form of Roman Numeral is " + romanToInt(input));}}// This code is contributed by rahuldevgarg
Output:
Integer form of Roman Numeral is 1904
Time complexity – O(N)Auxiliary Space – O(1)
Please refer complete article on Converting Roman Numerals to Decimal lying between 1 to 3999 for more details!
surinderdawra388
Amazon
base-conversion
Facebook
Microsoft
Twitter
Zoho
Algorithms
Java Programs
Strings
Zoho
Amazon
Microsoft
Facebook
Twitter
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 24586,
"s": 24558,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 24662,
"s": 24586,
"text": "Given a Roman numeral, the task is to find its corresponding decimal value."
},
{
"code": null,
"e": 24673,
"s": 24662,
"text": "Example : "
},
{
"code": null,
"e": 24877,
"s": 24673,
"text": "Input: IX\nOutput: 9\nIX is a Roman symbol which represents 9 \n\nInput: XL\nOutput: 40\nXL is a Roman symbol which represents 40\n\nInput: MCMIV\nOutput: 1904\nM is a thousand, \nCM is nine hundred and \nIV is four"
},
{
"code": null,
"e": 24930,
"s": 24877,
"text": "Roman numerals are based on the following symbols. "
},
{
"code": null,
"e": 25186,
"s": 24930,
"text": "SYMBOL VALUE\n I 1\n IV 4\n V 5\n IX 9\n X 10\n XL 40\n L 50\n XC 90\n C 100\n CD 400\n D 500\n CM 900 \n M 1000"
},
{
"code": null,
"e": 25479,
"s": 25186,
"text": "Approach: A number in Roman Numerals is a string of these symbols written in descending order(e.g. M’s first, followed by D’s, etc.). However, in a few specific cases, to avoid four characters being repeated in succession(such as IIII or XXXX), subtractive notation is often used as follows: "
},
{
"code": null,
"e": 25586,
"s": 25479,
"text": "I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX (one less than 10)."
},
{
"code": null,
"e": 25702,
"s": 25586,
"text": "X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is XC (ten less than a hundred)."
},
{
"code": null,
"e": 25865,
"s": 25702,
"text": "C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)."
},
{
"code": null,
"e": 25922,
"s": 25865,
"text": "Algorithm to convert Roman Numerals to Integer Number: "
},
{
"code": null,
"e": 26306,
"s": 25922,
"text": "Split the Roman Numeral string into Roman Symbols (character).Convert each symbol of Roman Numerals into the value it represents.Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total."
},
{
"code": null,
"e": 26369,
"s": 26306,
"text": "Split the Roman Numeral string into Roman Symbols (character)."
},
{
"code": null,
"e": 26437,
"s": 26369,
"text": "Convert each symbol of Roman Numerals into the value it represents."
},
{
"code": null,
"e": 26692,
"s": 26437,
"text": "Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total."
},
{
"code": null,
"e": 26896,
"s": 26692,
"text": "If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.else subtract this value by adding the value of next symbol to the running total."
},
{
"code": null,
"e": 27019,
"s": 26896,
"text": "If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total."
},
{
"code": null,
"e": 27101,
"s": 27019,
"text": "else subtract this value by adding the value of next symbol to the running total."
},
{
"code": null,
"e": 27158,
"s": 27101,
"text": "Following is the implementation of the above algorithm: "
},
{
"code": null,
"e": 27163,
"s": 27158,
"text": "Java"
},
{
"code": "// Java Program to convert Roman// Numerals to Numbersimport java.util.*; public class RomanToNumber{ // This function returns // value of a Roman symbol int value(char r) { if (r == 'I') return 1; if (r == 'V') return 5; if (r == 'X') return 10; if (r == 'L') return 50; if (r == 'C') return 100; if (r == 'D') return 500; if (r == 'M') return 1000; return -1; } // Finds decimal value of a // given romal numeral int romanToDecimal(String str) { // Initialize result int res = 0; for (int i = 0; i < str.length(); i++) { // Getting value of symbol s[i] int s1 = value(str.charAt(i)); // Getting value of symbol s[i+1] if (i + 1 < str.length()) { int s2 = value(str.charAt(i + 1)); // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1; } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1; i++; } } else { res = res + s1; } } return res; } // Driver Code public static void main(String args[]) { RomanToNumber ob = new RomanToNumber(); // Considering inputs given are valid String str = \"MCMIV\"; System.out.println( \"Integer form of Roman Numeral\" + \" is \" + ob.romanToDecimal(str)); }}",
"e": 29012,
"s": 27163,
"text": null
},
{
"code": null,
"e": 29023,
"s": 29015,
"text": "Output:"
},
{
"code": null,
"e": 29061,
"s": 29023,
"text": "Integer form of Roman Numeral is 1904"
},
{
"code": null,
"e": 29085,
"s": 29063,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 29193,
"s": 29087,
"text": "Time Complexity: O(n), where n is the length of the string. Only one traversal of the string is required."
},
{
"code": null,
"e": 29248,
"s": 29193,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 29269,
"s": 29250,
"text": "Another solution –"
},
{
"code": null,
"e": 29276,
"s": 29271,
"text": "Java"
},
{
"code": "// Java Program to convert Roman// Numerals to Numbersimport java.util.Map;import java.util.HashMap;class GFG{ private static final Map<Character, Integer> roman = new HashMap<Character, Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000);}}; // This function returns value// of a Roman symbolprivate static int romanToInt(String s){ int sum = 0; int n = s.length(); for(int i = 0; i < n; i++) { // If present value is less than // next value, subtract present // from next value and add the // resultant to the sum variable. if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) { sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i)); i++; } else { sum += roman.get(s.charAt(i)); } } return sum;} // Driver Codepublic static void main(String[] args){ // Considering inputs given are valid String input = \"MCMIV\"; System.out.print( \"Integer form of Roman Numeral is \" + romanToInt(input));}}// This code is contributed by rahuldevgarg",
"e": 30559,
"s": 29276,
"text": null
},
{
"code": null,
"e": 30570,
"s": 30562,
"text": "Output:"
},
{
"code": null,
"e": 30608,
"s": 30570,
"text": "Integer form of Roman Numeral is 1904"
},
{
"code": null,
"e": 30655,
"s": 30610,
"text": "Time complexity – O(N)Auxiliary Space – O(1)"
},
{
"code": null,
"e": 30768,
"s": 30655,
"text": "Please refer complete article on Converting Roman Numerals to Decimal lying between 1 to 3999 for more details! "
},
{
"code": null,
"e": 30785,
"s": 30768,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30792,
"s": 30785,
"text": "Amazon"
},
{
"code": null,
"e": 30808,
"s": 30792,
"text": "base-conversion"
},
{
"code": null,
"e": 30817,
"s": 30808,
"text": "Facebook"
},
{
"code": null,
"e": 30827,
"s": 30817,
"text": "Microsoft"
},
{
"code": null,
"e": 30835,
"s": 30827,
"text": "Twitter"
},
{
"code": null,
"e": 30840,
"s": 30835,
"text": "Zoho"
},
{
"code": null,
"e": 30851,
"s": 30840,
"text": "Algorithms"
},
{
"code": null,
"e": 30865,
"s": 30851,
"text": "Java Programs"
},
{
"code": null,
"e": 30873,
"s": 30865,
"text": "Strings"
},
{
"code": null,
"e": 30878,
"s": 30873,
"text": "Zoho"
},
{
"code": null,
"e": 30885,
"s": 30878,
"text": "Amazon"
},
{
"code": null,
"e": 30895,
"s": 30885,
"text": "Microsoft"
},
{
"code": null,
"e": 30904,
"s": 30895,
"text": "Facebook"
},
{
"code": null,
"e": 30912,
"s": 30904,
"text": "Twitter"
},
{
"code": null,
"e": 30920,
"s": 30912,
"text": "Strings"
},
{
"code": null,
"e": 30931,
"s": 30920,
"text": "Algorithms"
},
{
"code": null,
"e": 31029,
"s": 30931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31038,
"s": 31029,
"text": "Comments"
},
{
"code": null,
"e": 31051,
"s": 31038,
"text": "Old Comments"
},
{
"code": null,
"e": 31076,
"s": 31051,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31105,
"s": 31076,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 31161,
"s": 31105,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 31195,
"s": 31161,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 31238,
"s": 31195,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 31266,
"s": 31238,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 31310,
"s": 31266,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 31336,
"s": 31310,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31370,
"s": 31336,
"text": "Convert Double to Integer in Java"
}
] |
Files createTempDirectory() Method in Java with Examples - GeeksforGeeks | 23 Jun, 2021
The createTempDirectory() method of java.nio.file.Files Class is used to create a new directory using the given prefix and attributes. The given prefix acts as the name of the formed directory, may be null. The directory is set with given attributes.
Based on the type of arguments passed, the Files class provides 2 types of createTempDirectory() method.
Methods:
1. public static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs): This method is used to create a new directory in an already existing directory, using the given prefix to generate its name. The path of the newly formed directory is associated with the default FileSystem. Which is the same as the path of the specified directory. The candidate names are generated using the prefix. The File.deleteOnExit() method is used to delete the directory automatically. The attrs parameter is used to set attributes of the directory. Each attribute is identified by its name. If there is more than one attributes is specified with the same name then all the occurrences except the last one are ignored.
Parameters:
dir – the path to the already existing directory in which the new directory has to be created
prefix – the name of the directory, may be null
attrs – set attributes of the directory(optional)
Returns: path of the newly formed directory
Exception:
IllegalArgumentException – if the prefix is not an appropriate candidate directory name
UnsupportedOperationException – if any of the specified attributes can not be set to the directory
IOException – if an I/O error occurs
SecurityException – if checkWrite method is invoked by the security manager or write permission is denied while creating a directory.
Java
// Java Program to show the usage of// public static Path createTempDirectoryimport java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Driver classpublic class GFG { // main method public static void main(String[] args) { // prefix used to create candidate names String prefix = "TempDirectory"; // path of the directory in which temporary // directory has to created Path dir = (Path)Paths.get("/usr", "local", "bin", "directory"); try { // creating temporary directory ans storing its // path in tempDir variable Path tempDir = Files.createTempDirectory(dir, prefix); // printing the path of the created temporary // directory System.out.println( "Temporary Directory created at:\n" + tempDir.toString()); // deleting the temporary directory after the // virtual machine terminates tempDir.toFile().deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } }}
Output:
Temporary Directory created at:
/usr/local/bin/directory/TempDirectory1472243991754401317
2. public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs): This method is used to create a new directory using the given prefix and attributes. The given prefix acts as the name of the formed directory, may be null. The candidate names are generated using the prefix. The directory is set with given attributes. The path of the newly formed directory is associated with the default FileSystem. The attrs parameter is used to set attributes of the directory. Each attribute is identified by its name. If there is more than one attributes is specified with the same name then all the occurrence except the last one is ignored.
Parameters:
prefix – the name of the directory, may be null
attrs – set attributes of the directory(optional)
Returns: path of the newly formed directory
Exception:
IllegalArgumentException – if the prefix is not an appropriate candidate directory name
UnsupportedOperationException – if any of the specified attributes can not be set to the directory
IOException – if an I/O error occurs
SecurityException – if checkWrite method is invoked by the security manager or write permission is denied while creating a directory
Java
// Java Program to show the usage of// public static Path createTempDirectory(// String prefix, FileAttribute<?>... attrs)// Methodimport java.nio.file.Files;import java.nio.file.Path; // Driver classpublic class GFG { // main method public static void main(String[] args) { // prefix used to create candidate names String prefix = "TempDirectory"; try { // creating temporary directory and storing its // path in tempDir variable Path tempDir = Files.createTempDirectory(prefix); // printing the path of the created temporary // directory System.out.println( "Temporary Directory created at:\n" + tempDir.toString()); // deleting the temporary directory after the // virtual machine terminates tempDir.toFile().deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } }}
Output:
Temporary Directory created at:
/var/folders/13/jsq29lh11bn7kgwnzpggqytr0000gn/T/TempDirectory4403940384431706243
surinderdawra388
Java-Files
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java | [
{
"code": null,
"e": 24562,
"s": 24534,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 24814,
"s": 24562,
"text": "The createTempDirectory() method of java.nio.file.Files Class is used to create a new directory using the given prefix and attributes. The given prefix acts as the name of the formed directory, may be null. The directory is set with given attributes. "
},
{
"code": null,
"e": 24919,
"s": 24814,
"text": "Based on the type of arguments passed, the Files class provides 2 types of createTempDirectory() method."
},
{
"code": null,
"e": 24928,
"s": 24919,
"text": "Methods:"
},
{
"code": null,
"e": 25651,
"s": 24928,
"text": "1. public static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs): This method is used to create a new directory in an already existing directory, using the given prefix to generate its name. The path of the newly formed directory is associated with the default FileSystem. Which is the same as the path of the specified directory. The candidate names are generated using the prefix. The File.deleteOnExit() method is used to delete the directory automatically. The attrs parameter is used to set attributes of the directory. Each attribute is identified by its name. If there is more than one attributes is specified with the same name then all the occurrences except the last one are ignored."
},
{
"code": null,
"e": 25663,
"s": 25651,
"text": "Parameters:"
},
{
"code": null,
"e": 25757,
"s": 25663,
"text": "dir – the path to the already existing directory in which the new directory has to be created"
},
{
"code": null,
"e": 25805,
"s": 25757,
"text": "prefix – the name of the directory, may be null"
},
{
"code": null,
"e": 25855,
"s": 25805,
"text": "attrs – set attributes of the directory(optional)"
},
{
"code": null,
"e": 25899,
"s": 25855,
"text": "Returns: path of the newly formed directory"
},
{
"code": null,
"e": 25910,
"s": 25899,
"text": "Exception:"
},
{
"code": null,
"e": 25998,
"s": 25910,
"text": "IllegalArgumentException – if the prefix is not an appropriate candidate directory name"
},
{
"code": null,
"e": 26097,
"s": 25998,
"text": "UnsupportedOperationException – if any of the specified attributes can not be set to the directory"
},
{
"code": null,
"e": 26134,
"s": 26097,
"text": "IOException – if an I/O error occurs"
},
{
"code": null,
"e": 26268,
"s": 26134,
"text": "SecurityException – if checkWrite method is invoked by the security manager or write permission is denied while creating a directory."
},
{
"code": null,
"e": 26273,
"s": 26268,
"text": "Java"
},
{
"code": "// Java Program to show the usage of// public static Path createTempDirectoryimport java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Driver classpublic class GFG { // main method public static void main(String[] args) { // prefix used to create candidate names String prefix = \"TempDirectory\"; // path of the directory in which temporary // directory has to created Path dir = (Path)Paths.get(\"/usr\", \"local\", \"bin\", \"directory\"); try { // creating temporary directory ans storing its // path in tempDir variable Path tempDir = Files.createTempDirectory(dir, prefix); // printing the path of the created temporary // directory System.out.println( \"Temporary Directory created at:\\n\" + tempDir.toString()); // deleting the temporary directory after the // virtual machine terminates tempDir.toFile().deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 27462,
"s": 26273,
"text": null
},
{
"code": null,
"e": 27472,
"s": 27462,
"text": " Output: "
},
{
"code": null,
"e": 27563,
"s": 27472,
"text": "Temporary Directory created at: \n/usr/local/bin/directory/TempDirectory1472243991754401317"
},
{
"code": null,
"e": 28215,
"s": 27563,
"text": "2. public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs): This method is used to create a new directory using the given prefix and attributes. The given prefix acts as the name of the formed directory, may be null. The candidate names are generated using the prefix. The directory is set with given attributes. The path of the newly formed directory is associated with the default FileSystem. The attrs parameter is used to set attributes of the directory. Each attribute is identified by its name. If there is more than one attributes is specified with the same name then all the occurrence except the last one is ignored."
},
{
"code": null,
"e": 28228,
"s": 28215,
"text": "Parameters: "
},
{
"code": null,
"e": 28276,
"s": 28228,
"text": "prefix – the name of the directory, may be null"
},
{
"code": null,
"e": 28326,
"s": 28276,
"text": "attrs – set attributes of the directory(optional)"
},
{
"code": null,
"e": 28370,
"s": 28326,
"text": "Returns: path of the newly formed directory"
},
{
"code": null,
"e": 28382,
"s": 28370,
"text": "Exception: "
},
{
"code": null,
"e": 28470,
"s": 28382,
"text": "IllegalArgumentException – if the prefix is not an appropriate candidate directory name"
},
{
"code": null,
"e": 28569,
"s": 28470,
"text": "UnsupportedOperationException – if any of the specified attributes can not be set to the directory"
},
{
"code": null,
"e": 28606,
"s": 28569,
"text": "IOException – if an I/O error occurs"
},
{
"code": null,
"e": 28739,
"s": 28606,
"text": "SecurityException – if checkWrite method is invoked by the security manager or write permission is denied while creating a directory"
},
{
"code": null,
"e": 28744,
"s": 28739,
"text": "Java"
},
{
"code": "// Java Program to show the usage of// public static Path createTempDirectory(// String prefix, FileAttribute<?>... attrs)// Methodimport java.nio.file.Files;import java.nio.file.Path; // Driver classpublic class GFG { // main method public static void main(String[] args) { // prefix used to create candidate names String prefix = \"TempDirectory\"; try { // creating temporary directory and storing its // path in tempDir variable Path tempDir = Files.createTempDirectory(prefix); // printing the path of the created temporary // directory System.out.println( \"Temporary Directory created at:\\n\" + tempDir.toString()); // deleting the temporary directory after the // virtual machine terminates tempDir.toFile().deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 29768,
"s": 28744,
"text": null
},
{
"code": null,
"e": 29777,
"s": 29768,
"text": "Output: "
},
{
"code": null,
"e": 29892,
"s": 29777,
"text": "Temporary Directory created at: \n/var/folders/13/jsq29lh11bn7kgwnzpggqytr0000gn/T/TempDirectory4403940384431706243"
},
{
"code": null,
"e": 29911,
"s": 29894,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29922,
"s": 29911,
"text": "Java-Files"
},
{
"code": null,
"e": 29927,
"s": 29922,
"text": "Java"
},
{
"code": null,
"e": 29932,
"s": 29927,
"text": "Java"
},
{
"code": null,
"e": 30030,
"s": 29932,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30062,
"s": 30030,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30092,
"s": 30062,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30111,
"s": 30092,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30162,
"s": 30111,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30180,
"s": 30162,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30211,
"s": 30180,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30243,
"s": 30211,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30267,
"s": 30243,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 30287,
"s": 30267,
"text": "Stack Class in Java"
}
] |
EJB - Web Services | EJB 3.0 provides an option to expose session EJB as a webservice. @WebService annotation is used to mark a class as a web service end point and @WebMethod is used to expose a method as web method to client.
@Stateless
@WebService(serviceName="LibraryService")
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
...
@WebMethod(operationName="getBooks")
public List<Book> getBooks() {
return entityManager.createQuery("From Books").getResultList();
}
...
}
Let us create a test EJB application to test blob/clob support in EJB 3.0.
Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand clob/blob objects in EJB concepts.
Create LibraryPersistentBean.java under package com.tutorialspoint.stateless. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged.
Clean and Build the application to make sure business logic is working as per the requirements.
Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
package com.tutorialspoint.stateless;
import com.tutorialspoint.entity.Book;
import java.util.List;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
@WebService(serviceName="LibraryService")
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
public LibraryPersistentBean() {
}
@PersistenceContext(unitName="EjbComponentPU")
private EntityManager entityManager;
public void addBook(Book book) {
entityManager.persist(book);
}
@WebMethod(operationName="getBooks")
public List <Book> getBooks() {
return entityManager.createQuery("From Book").getResultList();
}
}
10:51:37,271 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibraryPersistentBean ejbName: LibraryPersistentBean
10:51:37,287 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
10:51:37,349 INFO [EJBContainer] STARTED EJB: com.tuturialspoint.messagebean.LibraryMessageBean ejbName: BookMessageHandler
10:51:37,443 INFO [DefaultEndpointRegistry] register: jboss.ws:context=EjbComponent,endpoint=LibraryPersistentBean
10:51:38,191 INFO [WSDLFilePublisher] WSDL published to: file:/D:/Jboss-5.0.1/server/default/data/wsdl/EjbComponent.jar/
LibraryService3853081455302946642.wsdl
In NetBeans IDE, select ,File > New Project >.Select project type under category ,Java, Project type as Java Application. Click Next > button.Enter project name and location. Click Finish > button. We have chosen name as EJBWebServiceClient.
Right click on the project name in Project explorer window. Select New > WebService Client.
Add EJB component project's LibraryPersistentBean created earlier under WSDL and Client Location using Add Project button in compile tab.
Click Finish Button. Verify the following structure in project explorer.
package ejbwebserviceclient;
public class EJBWebServiceClient {
public static void main(String[] args) {
}
}
Select Web Service getBooks web method as shown in the figure below and drag it to code window of EJBWebServiceClient.
You will see the output similar to as shown below.
Update the EJBWebServiceClient code to use this method.
package ejbwebserviceclient;
public class EJBWebServiceClient {
public static void main(String[] args) {
for(com.tutorialspoint.stateless.Book book:getBooks()) {
System.out.println(book.getName());
}
}
private static java.util.List
<com.tutorialspoint.stateless.Book> getBooks() {
com.tutorialspoint.stateless.LibraryService service =
new com.tutorialspoint.stateless.LibraryService();
com.tutorialspoint.stateless.LibraryPersistentBean port =
service.getLibraryPersistentBeanPort();
return port.getBooks();
}
}
Right click on the project name in Project explorer window. Select Run. Netbeans will build the client and run it. Verify the following output.
ant -f D:\\SVN\\EJBWebServiceClient run
init:
Deleting: D:\SVN\EJBWebServiceClient\build\built-jar.properties
deps-jar:
Updating property file: D:\SVN\EJBWebServiceClient\build\built-jar.properties
wsimport-init:
wsimport-client-LibraryPersistentBean:
files are up to date
classLoader = java.net.URLClassLoader@4ce46c
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@182cdac
wsimport-client-generate:
Compiling 1 source file to D:\SVN\EJBWebServiceClient\build\classes
compile:
run:
learn java
Learn Spring
learn JSF
Learn HTML
Learn JBoss
Learn EJB
Learn Hibernate
Learn IBatis
Times Now
learn html5
Learn images
Learn Testing
Forbes
test1
BUILD SUCCESSFUL (total time: 1 second)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2254,
"s": 2047,
"text": "EJB 3.0 provides an option to expose session EJB as a webservice. @WebService annotation is used to mark a class as a web service end point and @WebMethod is used to expose a method as web method to client."
},
{
"code": null,
"e": 2555,
"s": 2254,
"text": "@Stateless\n@WebService(serviceName=\"LibraryService\")\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n\t\n ...\n @WebMethod(operationName=\"getBooks\")\n public List<Book> getBooks() { \n return entityManager.createQuery(\"From Books\").getResultList();\n }\n ...\n}"
},
{
"code": null,
"e": 2630,
"s": 2555,
"text": "Let us create a test EJB application to test blob/clob support in EJB 3.0."
},
{
"code": null,
"e": 2903,
"s": 2630,
"text": "Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand clob/blob objects in EJB concepts."
},
{
"code": null,
"e": 3059,
"s": 2903,
"text": "Create LibraryPersistentBean.java under package com.tutorialspoint.stateless. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged."
},
{
"code": null,
"e": 3155,
"s": 3059,
"text": "Clean and Build the application to make sure business logic is working as per the requirements."
},
{
"code": null,
"e": 3322,
"s": 3155,
"text": "Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet."
},
{
"code": null,
"e": 4105,
"s": 3322,
"text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.util.List;\nimport javax.ejb.Stateless;\nimport javax.jws.WebMethod;\nimport javax.jws.WebService;\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\n\n@Stateless\n@WebService(serviceName=\"LibraryService\")\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n \n public LibraryPersistentBean() {\n }\n\n @PersistenceContext(unitName=\"EjbComponentPU\")\n private EntityManager entityManager; \n\n public void addBook(Book book) {\n entityManager.persist(book);\n } \n \n @WebMethod(operationName=\"getBooks\")\n public List <Book> getBooks() {\n return entityManager.createQuery(\"From Book\").getResultList();\n }\n}"
},
{
"code": null,
"e": 4926,
"s": 4105,
"text": "10:51:37,271 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibraryPersistentBean ejbName: LibraryPersistentBean\n10:51:37,287 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n\n\tLibraryPersistentBean/remote - EJB3.x Default Remote Business Interface\n\tLibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface\n\n10:51:37,349 INFO [EJBContainer] STARTED EJB: com.tuturialspoint.messagebean.LibraryMessageBean ejbName: BookMessageHandler\n10:51:37,443 INFO [DefaultEndpointRegistry] register: jboss.ws:context=EjbComponent,endpoint=LibraryPersistentBean\n10:51:38,191 INFO [WSDLFilePublisher] WSDL published to: file:/D:/Jboss-5.0.1/server/default/data/wsdl/EjbComponent.jar/\nLibraryService3853081455302946642.wsdl\n"
},
{
"code": null,
"e": 5168,
"s": 4926,
"text": "In NetBeans IDE, select ,File > New Project >.Select project type under category ,Java, Project type as Java Application. Click Next > button.Enter project name and location. Click Finish > button. We have chosen name as EJBWebServiceClient."
},
{
"code": null,
"e": 5260,
"s": 5168,
"text": "Right click on the project name in Project explorer window. Select New > WebService Client."
},
{
"code": null,
"e": 5398,
"s": 5260,
"text": "Add EJB component project's LibraryPersistentBean created earlier under WSDL and Client Location using Add Project button in compile tab."
},
{
"code": null,
"e": 5471,
"s": 5398,
"text": "Click Finish Button. Verify the following structure in project explorer."
},
{
"code": null,
"e": 5590,
"s": 5471,
"text": "package ejbwebserviceclient;\n\npublic class EJBWebServiceClient {\n public static void main(String[] args) { \n }\n}"
},
{
"code": null,
"e": 5709,
"s": 5590,
"text": "Select Web Service getBooks web method as shown in the figure below and drag it to code window of EJBWebServiceClient."
},
{
"code": null,
"e": 5760,
"s": 5709,
"text": "You will see the output similar to as shown below."
},
{
"code": null,
"e": 5816,
"s": 5760,
"text": "Update the EJBWebServiceClient code to use this method."
},
{
"code": null,
"e": 6419,
"s": 5816,
"text": "package ejbwebserviceclient;\n\npublic class EJBWebServiceClient {\n\n public static void main(String[] args) {\n for(com.tutorialspoint.stateless.Book book:getBooks()) {\n System.out.println(book.getName());\n } \n }\n\n private static java.util.List\n <com.tutorialspoint.stateless.Book> getBooks() {\n com.tutorialspoint.stateless.LibraryService service = \n new com.tutorialspoint.stateless.LibraryService();\n com.tutorialspoint.stateless.LibraryPersistentBean port = \n service.getLibraryPersistentBeanPort();\n return port.getBooks();\n } \n}\n"
},
{
"code": null,
"e": 6563,
"s": 6419,
"text": "Right click on the project name in Project explorer window. Select Run. Netbeans will build the client and run it. Verify the following output."
},
{
"code": null,
"e": 7255,
"s": 6563,
"text": "ant -f D:\\\\SVN\\\\EJBWebServiceClient run\ninit:\nDeleting: D:\\SVN\\EJBWebServiceClient\\build\\built-jar.properties\ndeps-jar:\nUpdating property file: D:\\SVN\\EJBWebServiceClient\\build\\built-jar.properties\nwsimport-init:\nwsimport-client-LibraryPersistentBean:\nfiles are up to date\nclassLoader = java.net.URLClassLoader@4ce46c\nSharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@182cdac\nwsimport-client-generate:\nCompiling 1 source file to D:\\SVN\\EJBWebServiceClient\\build\\classes\ncompile:\nrun:\nlearn java\nLearn Spring\nlearn JSF\nLearn HTML\nLearn JBoss\nLearn EJB\nLearn Hibernate\nLearn IBatis\nTimes Now\nlearn html5\nLearn images\nLearn Testing\nForbes\ntest1\nBUILD SUCCESSFUL (total time: 1 second)\n"
},
{
"code": null,
"e": 7262,
"s": 7255,
"text": " Print"
},
{
"code": null,
"e": 7273,
"s": 7262,
"text": " Add Notes"
}
] |
What do you mean by glue in Cucumber? | The glue is a part of Cucumber options that describes the location and
path of the step definition file.
Test Runner file.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.AbstractTestNGCucumberTests;
@CucumberOptions(
features = "src/test/java/features",
glue="stepDefinations"
)
public class TestRunner extends AbstractTestNGCucumberTests { } | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "The glue is a part of Cucumber options that describes the location and\npath of the step definition file."
},
{
"code": null,
"e": 1185,
"s": 1167,
"text": "Test Runner file."
},
{
"code": null,
"e": 1497,
"s": 1185,
"text": "import org.junit.runner.RunWith;\nimport cucumber.api.CucumberOptions;\nimport cucumber.api.junit.Cucumber;\nimport cucumber.api.testng.AbstractTestNGCucumberTests;\n@CucumberOptions(\n features = \"src/test/java/features\",\n glue=\"stepDefinations\"\n)\npublic class TestRunner extends AbstractTestNGCucumberTests { }"
}
] |
External Storage in Android with Example - GeeksforGeeks | 02 Nov, 2020
Android gives various options for storing apps data which uses a file system similar to the disk-based system on computer platforms
App-Specific storage: Store data files within internal volume directories or external. These data files are meant only for the app’s use. It uses internal storage directories to save sensitive information such as a username and password that other app should not access.
Shared Storage: Store data files such as images, audio, video, documents, etc. that the app may need to share with other apps.
Shared Preferences: Store primitive data type such as integer, float, boolean, string, long in key-value pairs.
Databases: Store structured data such as user-information(name, age, phone, email, address, etc.) into private databases.
Developers are advised to use the options available to store data depending upon the space required, reliable data access, and privacy of data. The data files saved over external storage devices are publicly accessible on shared external storage using USB mass storage transfer. Data files stored over external storage using a FileOutputStream object and can be read using a FileInputStream object.
In order to avoid crashing the app first, we need to check storage SD Card is available for reading and write operations. The method getExternalStorageState() is used to determine the state of mounted storage media such as SD Card is missing, read-only or readable, and writable. Below is the code snippet which we will use to check the availability of external storage.
Java
boolean isAvailable= false;boolean isWritable= false;boolean isReadable= false;String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) { // Operation possible - Read and Write isAvailable= true; isWritable= true; isReadable= true;} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // Operation possible - Read Only isAvailable= true; isWritable= false; isReadable= true;} else { // SD card not available isAvailable = false; isWritable= false; isReadable= false; }
getExternalStoragePublicDirectory(): This is the present recommended method to keep files public and these files are not deleted even when the app is uninstalled from the system. For eg: Images clicked by the camera are still available even after we uninstall the camera.
getExternalFilesDir(String type): This method is used to store private data that are specific to the app only. And data are removed as we uninstall the app.
getExternalStorageDirectory(): This method is not recommended. It is now absolute and it is used to access external storage in older versions, API Level less than 7.
In this example, we would store text data into the external storage and fetch to see that data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Access Permission to External Storage
To read and write data to external storage, the app required WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system permission. These permissions are added to the AndroidManifest.xml file. Add these permissions just after the package name.
XML
<manifest ... > <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application ... > <activity android:name=".MainActivity" ... > ... </activity> </application></manifest>
Step 3: Before creating the layout and corresponding java files let’s add a few string attributes which we are using in our layout files
Go to app > res > values > string.xml and insert the following code snippet
XML
<resources> ... <string name="text_view_data">Enter the Text Data</string> <string name="edit_text_data">Enter your information</string> <string name="view_button">View Information</string> <string name="save_button_public">Save Publicly</string> <string name="save_button_private">Save Privately</string> <string name="text_view_saved_data">Saved Text Data</string> <string name="saved_information">Click to view saved information</string> <string name="back_button">Go Back</string> <string name="show_button_public">Public Data</string> <string name="show_button_private">Private Data</string> ...</resources>
Now go to app > res > values > colors.xml and change the color attributes as following in order to make App Bar more attractive.
XML
<resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> <color name="buttonColor">#0F9D58</color> <color name="textColor">#FFFFFF</color></resources>
Again go to app > res > drawable and create a new Drawable Resource File and name it as button_layout. In this, we are modifying our button style for a better UX/UI.
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:bottomLeftRadius="25dp" android:bottomRightRadius="25dp" android:radius="50dp" android:topLeftRadius="25dp" android:topRightRadius="25dp" /> <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp" /> <size android:width="64dp" android:height="16dp" /> <solid android:color="@color/buttonColor" /> </shape>
Step 4: Working with the activity_main.xml file
Go to res > layout > activity_main.xml and write down the following code. In this layout file, we are creating a multiline EditText View for getting the data from users and Buttons to save that data over internal and external storage media.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/saveButton_public" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_below="@+id/editText_data" android:layout_marginEnd="48dp" android:layout_marginTop="8dp" android:background="@drawable/button_layout" android:onClick="savePublicly" android:padding="8dp" android:text="@string/save_button_public" android:textAllCaps="false" android:textColor="@color/textColor" /> <Button android:id="@+id/saveButton_private" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_below="@+id/editText_data" android:layout_marginStart="48dp" android:layout_marginTop="8dp" android:layout_toEndOf="@+id/saveButton_public" android:background="@drawable/button_layout" android:onClick="savePrivately" android:padding="8dp" android:text="@string/save_button_private" android:textAllCaps="false" android:textColor="@color/textColor" /> <Button android:id="@+id/viewButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/saveButton_public" android:layout_centerHorizontal="true" android:layout_marginTop="16dp" android:background="@drawable/button_layout" android:onClick="viewInformation" android:padding="8dp" android:text="@string/view_button" android:textAllCaps="false" android:textColor="@color/textColor" /> <EditText android:id="@+id/editText_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView_data" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:autofillHints="" android:hint="@string/edit_text_data" android:inputType="textMultiLine" /> <TextView android:id="@+id/textView_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:text="@string/text_view_data" android:textAllCaps="true" android:textStyle="bold" /> </RelativeLayout>
Step 5: Working with the MainActivity.java file
In MainActivity we define the functions that handled the onClick behavior of the buttons. And fetch the data from the EditText and save it in external storage publicly and privately. We also display a Toast message of the path where the data is stored.
Java
import android.Manifest;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import java.io.File;import java.io.FileOutputStream;import java.io.IOException; public class MainActivity extends AppCompatActivity { // After API 23 the permission request for accessing external storage is changed // Before API 23 permission request is asked by the user during installation of app // After API 23 permission request is asked at runtime private int EXTERNAL_STORAGE_PERMISSION_CODE = 23; EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // findViewById return a view, we need to cast it to EditText View editText = (EditText) findViewById(R.id.editText_data); } public void savePublicly(View view) { // Requesting Permission to access External Storage ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CODE); String editTextData = editText.getText().toString(); // getExternalStoragePublicDirectory() represents root of external storage, we are using DOWNLOADS // We can use following directories: MUSIC, PODCASTS, ALARMS, RINGTONES, NOTIFICATIONS, PICTURES, MOVIES File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // Storing the data in file with name as geeksData.txt File file = new File(folder, "geeksData.txt"); writeTextData(file, editTextData); editText.setText(""); } public void savePrivately(View view) { String editTextData = editText.getText().toString(); // Creating folder with name GeekForGeeks File folder = getExternalFilesDir("GeeksForGeeks"); // Creating file with name gfg.txt File file = new File(folder, "gfg.txt"); writeTextData(file, editTextData); editText.setText(""); } public void viewInformation(View view) { // Creating an intent to start a new activity Intent intent = new Intent(MainActivity.this, ViewInformationActivity.class); startActivity(intent); } // writeTextData() method save the data into the file in byte format // It also toast a message "Done/filepath_where_the_file_is_saved" private void writeTextData(File file, String data) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(data.getBytes()); Toast.makeText(this, "Done" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
Step 6: Create a new Empty Activity
We will create a new activity and name it ViewInformationActivity. We use this activity to display the saved data from the external storage. So, first, we create a layout for this activity similar to the MainActivity layout. activity_view_information.xml layout code snippet:
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ViewInformationActivity"> <Button android:id="@+id/showButton_public" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_below="@+id/textView_get_saved_data" android:layout_marginEnd="48dp" android:layout_marginTop="8dp" android:background="@drawable/button_layout" android:onClick="showPublicData" android:padding="8dp" android:text="@string/show_button_public" android:textAllCaps="false" android:textColor="@color/textColor" /> <Button android:id="@+id/showButton_private" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_below="@+id/textView_get_saved_data" android:layout_marginStart="48dp" android:layout_marginTop="8dp" android:layout_toEndOf="@+id/showButton_public" android:background="@drawable/button_layout" android:onClick="showPrivateData" android:padding="8dp" android:text="@string/show_button_private" android:textAllCaps="false" android:textColor="@color/textColor" /> <Button android:id="@+id/goBackButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/showButton_public" android:layout_centerHorizontal="true" android:layout_marginTop="16dp" android:background="@drawable/button_layout" android:onClick="back" android:padding="8dp" android:text="@string/back_button" android:textAllCaps="false" android:textColor="@color/textColor" /> <TextView android:id="@+id/textView_get_saved_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView_saved_data" android:layout_marginTop="8dp" android:gravity="center" android:hint="@string/saved_information" /> <TextView android:id="@+id/textView_saved_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:gravity="center" android:text="@string/text_view_saved_data" android:textAllCaps="true" android:textStyle="bold" /> </RelativeLayout>
Now, we will create a corresponding java code for ViewInformationActivity. In this, we define methods showPublicData() and showPrivateData() over buttons that will fetch the data from the files saved to external storage and add the data to buffer, and then populate the data to TextView in order to show them. ViewInformationAcitity.java code snippet:
Java
import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import java.io.File;import java.io.FileInputStream;import java.io.IOException; public class ViewInformationActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_information); // findViewById returns a view, we need to cast it into TextView textView = (TextView) findViewById(R.id.textView_get_saved_data); } public void showPublicData(View view) { // Accessing the saved data from the downloads folder File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // geeksData represent the file data that is saved publicly File file = new File(folder, "geeksData.txt"); String data = getdata(file); if (data != null) { textView.setText(data); } else { textView.setText("No Data Found"); } } public void showPrivateData(View view) { // GeeksForGeeks represent the folder name to access privately saved data File folder = getExternalFilesDir("GeeksForGeeks"); // gft.txt is the file that is saved privately File file = new File(folder, "gfg.txt"); String data = getdata(file); if (data != null) { textView.setText(data); } else { textView.setText("No Data Found"); } } public void back(View view) { Intent intent = new Intent(ViewInformationActivity.this, MainActivity.class); startActivity(intent); } // getdata() is the method which reads the data // the data that is saved in byte format in the file private String getdata(File myfile) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(myfile); int i = -1; StringBuffer buffer = new StringBuffer(); while ((i = fileInputStream.read()) != -1) { buffer.append((char) i); } return buffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Services in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 25879,
"s": 25851,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 26011,
"s": 25879,
"text": "Android gives various options for storing apps data which uses a file system similar to the disk-based system on computer platforms"
},
{
"code": null,
"e": 26282,
"s": 26011,
"text": "App-Specific storage: Store data files within internal volume directories or external. These data files are meant only for the app’s use. It uses internal storage directories to save sensitive information such as a username and password that other app should not access."
},
{
"code": null,
"e": 26409,
"s": 26282,
"text": "Shared Storage: Store data files such as images, audio, video, documents, etc. that the app may need to share with other apps."
},
{
"code": null,
"e": 26521,
"s": 26409,
"text": "Shared Preferences: Store primitive data type such as integer, float, boolean, string, long in key-value pairs."
},
{
"code": null,
"e": 26644,
"s": 26521,
"text": "Databases: Store structured data such as user-information(name, age, phone, email, address, etc.) into private databases."
},
{
"code": null,
"e": 27043,
"s": 26644,
"text": "Developers are advised to use the options available to store data depending upon the space required, reliable data access, and privacy of data. The data files saved over external storage devices are publicly accessible on shared external storage using USB mass storage transfer. Data files stored over external storage using a FileOutputStream object and can be read using a FileInputStream object."
},
{
"code": null,
"e": 27414,
"s": 27043,
"text": "In order to avoid crashing the app first, we need to check storage SD Card is available for reading and write operations. The method getExternalStorageState() is used to determine the state of mounted storage media such as SD Card is missing, read-only or readable, and writable. Below is the code snippet which we will use to check the availability of external storage."
},
{
"code": null,
"e": 27419,
"s": 27414,
"text": "Java"
},
{
"code": "boolean isAvailable= false;boolean isWritable= false;boolean isReadable= false;String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) { // Operation possible - Read and Write isAvailable= true; isWritable= true; isReadable= true;} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // Operation possible - Read Only isAvailable= true; isWritable= false; isReadable= true;} else { // SD card not available isAvailable = false; isWritable= false; isReadable= false; }",
"e": 27984,
"s": 27419,
"text": null
},
{
"code": null,
"e": 28256,
"s": 27984,
"text": "getExternalStoragePublicDirectory(): This is the present recommended method to keep files public and these files are not deleted even when the app is uninstalled from the system. For eg: Images clicked by the camera are still available even after we uninstall the camera."
},
{
"code": null,
"e": 28413,
"s": 28256,
"text": "getExternalFilesDir(String type): This method is used to store private data that are specific to the app only. And data are removed as we uninstall the app."
},
{
"code": null,
"e": 28579,
"s": 28413,
"text": "getExternalStorageDirectory(): This method is not recommended. It is now absolute and it is used to access external storage in older versions, API Level less than 7."
},
{
"code": null,
"e": 28840,
"s": 28579,
"text": "In this example, we would store text data into the external storage and fetch to see that data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 28869,
"s": 28840,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 29031,
"s": 28869,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 29077,
"s": 29031,
"text": "Step 2: Access Permission to External Storage"
},
{
"code": null,
"e": 29318,
"s": 29077,
"text": "To read and write data to external storage, the app required WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system permission. These permissions are added to the AndroidManifest.xml file. Add these permissions just after the package name."
},
{
"code": null,
"e": 29322,
"s": 29318,
"text": "XML"
},
{
"code": "<manifest ... > <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/> <application ... > <activity android:name=\".MainActivity\" ... > ... </activity> </application></manifest>",
"e": 29634,
"s": 29322,
"text": null
},
{
"code": null,
"e": 29771,
"s": 29634,
"text": "Step 3: Before creating the layout and corresponding java files let’s add a few string attributes which we are using in our layout files"
},
{
"code": null,
"e": 29847,
"s": 29771,
"text": "Go to app > res > values > string.xml and insert the following code snippet"
},
{
"code": null,
"e": 29851,
"s": 29847,
"text": "XML"
},
{
"code": "<resources> ... <string name=\"text_view_data\">Enter the Text Data</string> <string name=\"edit_text_data\">Enter your information</string> <string name=\"view_button\">View Information</string> <string name=\"save_button_public\">Save Publicly</string> <string name=\"save_button_private\">Save Privately</string> <string name=\"text_view_saved_data\">Saved Text Data</string> <string name=\"saved_information\">Click to view saved information</string> <string name=\"back_button\">Go Back</string> <string name=\"show_button_public\">Public Data</string> <string name=\"show_button_private\">Private Data</string> ...</resources>",
"e": 30498,
"s": 29851,
"text": null
},
{
"code": null,
"e": 30627,
"s": 30498,
"text": "Now go to app > res > values > colors.xml and change the color attributes as following in order to make App Bar more attractive."
},
{
"code": null,
"e": 30631,
"s": 30627,
"text": "XML"
},
{
"code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> <color name=\"buttonColor\">#0F9D58</color> <color name=\"textColor\">#FFFFFF</color></resources>",
"e": 30889,
"s": 30631,
"text": null
},
{
"code": null,
"e": 31055,
"s": 30889,
"text": "Again go to app > res > drawable and create a new Drawable Resource File and name it as button_layout. In this, we are modifying our button style for a better UX/UI."
},
{
"code": null,
"e": 31059,
"s": 31055,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <corners android:bottomLeftRadius=\"25dp\" android:bottomRightRadius=\"25dp\" android:radius=\"50dp\" android:topLeftRadius=\"25dp\" android:topRightRadius=\"25dp\" /> <padding android:bottom=\"0dp\" android:left=\"0dp\" android:right=\"0dp\" android:top=\"0dp\" /> <size android:width=\"64dp\" android:height=\"16dp\" /> <solid android:color=\"@color/buttonColor\" /> </shape>",
"e": 31645,
"s": 31059,
"text": null
},
{
"code": null,
"e": 31693,
"s": 31645,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 31934,
"s": 31693,
"text": "Go to res > layout > activity_main.xml and write down the following code. In this layout file, we are creating a multiline EditText View for getting the data from users and Buttons to save that data over internal and external storage media."
},
{
"code": null,
"e": 31938,
"s": 31934,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/saveButton_public\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_below=\"@+id/editText_data\" android:layout_marginEnd=\"48dp\" android:layout_marginTop=\"8dp\" android:background=\"@drawable/button_layout\" android:onClick=\"savePublicly\" android:padding=\"8dp\" android:text=\"@string/save_button_public\" android:textAllCaps=\"false\" android:textColor=\"@color/textColor\" /> <Button android:id=\"@+id/saveButton_private\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_below=\"@+id/editText_data\" android:layout_marginStart=\"48dp\" android:layout_marginTop=\"8dp\" android:layout_toEndOf=\"@+id/saveButton_public\" android:background=\"@drawable/button_layout\" android:onClick=\"savePrivately\" android:padding=\"8dp\" android:text=\"@string/save_button_private\" android:textAllCaps=\"false\" android:textColor=\"@color/textColor\" /> <Button android:id=\"@+id/viewButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/saveButton_public\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"16dp\" android:background=\"@drawable/button_layout\" android:onClick=\"viewInformation\" android:padding=\"8dp\" android:text=\"@string/view_button\" android:textAllCaps=\"false\" android:textColor=\"@color/textColor\" /> <EditText android:id=\"@+id/editText_data\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/textView_data\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"8dp\" android:autofillHints=\"\" android:hint=\"@string/edit_text_data\" android:inputType=\"textMultiLine\" /> <TextView android:id=\"@+id/textView_data\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"8dp\" android:text=\"@string/text_view_data\" android:textAllCaps=\"true\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 34778,
"s": 31938,
"text": null
},
{
"code": null,
"e": 34826,
"s": 34778,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 35079,
"s": 34826,
"text": "In MainActivity we define the functions that handled the onClick behavior of the buttons. And fetch the data from the EditText and save it in external storage publicly and privately. We also display a Toast message of the path where the data is stored."
},
{
"code": null,
"e": 35084,
"s": 35079,
"text": "Java"
},
{
"code": "import android.Manifest;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import java.io.File;import java.io.FileOutputStream;import java.io.IOException; public class MainActivity extends AppCompatActivity { // After API 23 the permission request for accessing external storage is changed // Before API 23 permission request is asked by the user during installation of app // After API 23 permission request is asked at runtime private int EXTERNAL_STORAGE_PERMISSION_CODE = 23; EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // findViewById return a view, we need to cast it to EditText View editText = (EditText) findViewById(R.id.editText_data); } public void savePublicly(View view) { // Requesting Permission to access External Storage ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CODE); String editTextData = editText.getText().toString(); // getExternalStoragePublicDirectory() represents root of external storage, we are using DOWNLOADS // We can use following directories: MUSIC, PODCASTS, ALARMS, RINGTONES, NOTIFICATIONS, PICTURES, MOVIES File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // Storing the data in file with name as geeksData.txt File file = new File(folder, \"geeksData.txt\"); writeTextData(file, editTextData); editText.setText(\"\"); } public void savePrivately(View view) { String editTextData = editText.getText().toString(); // Creating folder with name GeekForGeeks File folder = getExternalFilesDir(\"GeeksForGeeks\"); // Creating file with name gfg.txt File file = new File(folder, \"gfg.txt\"); writeTextData(file, editTextData); editText.setText(\"\"); } public void viewInformation(View view) { // Creating an intent to start a new activity Intent intent = new Intent(MainActivity.this, ViewInformationActivity.class); startActivity(intent); } // writeTextData() method save the data into the file in byte format // It also toast a message \"Done/filepath_where_the_file_is_saved\" private void writeTextData(File file, String data) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(data.getBytes()); Toast.makeText(this, \"Done\" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }}",
"e": 38367,
"s": 35084,
"text": null
},
{
"code": null,
"e": 38403,
"s": 38367,
"text": "Step 6: Create a new Empty Activity"
},
{
"code": null,
"e": 38679,
"s": 38403,
"text": "We will create a new activity and name it ViewInformationActivity. We use this activity to display the saved data from the external storage. So, first, we create a layout for this activity similar to the MainActivity layout. activity_view_information.xml layout code snippet:"
},
{
"code": null,
"e": 38683,
"s": 38679,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".ViewInformationActivity\"> <Button android:id=\"@+id/showButton_public\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_below=\"@+id/textView_get_saved_data\" android:layout_marginEnd=\"48dp\" android:layout_marginTop=\"8dp\" android:background=\"@drawable/button_layout\" android:onClick=\"showPublicData\" android:padding=\"8dp\" android:text=\"@string/show_button_public\" android:textAllCaps=\"false\" android:textColor=\"@color/textColor\" /> <Button android:id=\"@+id/showButton_private\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_below=\"@+id/textView_get_saved_data\" android:layout_marginStart=\"48dp\" android:layout_marginTop=\"8dp\" android:layout_toEndOf=\"@+id/showButton_public\" android:background=\"@drawable/button_layout\" android:onClick=\"showPrivateData\" android:padding=\"8dp\" android:text=\"@string/show_button_private\" android:textAllCaps=\"false\" android:textColor=\"@color/textColor\" /> <Button android:id=\"@+id/goBackButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/showButton_public\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"16dp\" android:background=\"@drawable/button_layout\" android:onClick=\"back\" android:padding=\"8dp\" android:text=\"@string/back_button\" android:textAllCaps=\"false\" android:textColor=\"@color/textColor\" /> <TextView android:id=\"@+id/textView_get_saved_data\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/textView_saved_data\" android:layout_marginTop=\"8dp\" android:gravity=\"center\" android:hint=\"@string/saved_information\" /> <TextView android:id=\"@+id/textView_saved_data\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:gravity=\"center\" android:text=\"@string/text_view_saved_data\" android:textAllCaps=\"true\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 41438,
"s": 38683,
"text": null
},
{
"code": null,
"e": 41790,
"s": 41438,
"text": "Now, we will create a corresponding java code for ViewInformationActivity. In this, we define methods showPublicData() and showPrivateData() over buttons that will fetch the data from the files saved to external storage and add the data to buffer, and then populate the data to TextView in order to show them. ViewInformationAcitity.java code snippet:"
},
{
"code": null,
"e": 41795,
"s": 41790,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import java.io.File;import java.io.FileInputStream;import java.io.IOException; public class ViewInformationActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_information); // findViewById returns a view, we need to cast it into TextView textView = (TextView) findViewById(R.id.textView_get_saved_data); } public void showPublicData(View view) { // Accessing the saved data from the downloads folder File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // geeksData represent the file data that is saved publicly File file = new File(folder, \"geeksData.txt\"); String data = getdata(file); if (data != null) { textView.setText(data); } else { textView.setText(\"No Data Found\"); } } public void showPrivateData(View view) { // GeeksForGeeks represent the folder name to access privately saved data File folder = getExternalFilesDir(\"GeeksForGeeks\"); // gft.txt is the file that is saved privately File file = new File(folder, \"gfg.txt\"); String data = getdata(file); if (data != null) { textView.setText(data); } else { textView.setText(\"No Data Found\"); } } public void back(View view) { Intent intent = new Intent(ViewInformationActivity.this, MainActivity.class); startActivity(intent); } // getdata() is the method which reads the data // the data that is saved in byte format in the file private String getdata(File myfile) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(myfile); int i = -1; StringBuffer buffer = new StringBuffer(); while ((i = fileInputStream.read()) != -1) { buffer.append((char) i); } return buffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }}",
"e": 44460,
"s": 41795,
"text": null
},
{
"code": null,
"e": 44468,
"s": 44460,
"text": "android"
},
{
"code": null,
"e": 44492,
"s": 44468,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 44500,
"s": 44492,
"text": "Android"
},
{
"code": null,
"e": 44505,
"s": 44500,
"text": "Java"
},
{
"code": null,
"e": 44524,
"s": 44505,
"text": "Technical Scripter"
},
{
"code": null,
"e": 44529,
"s": 44524,
"text": "Java"
},
{
"code": null,
"e": 44537,
"s": 44529,
"text": "Android"
},
{
"code": null,
"e": 44635,
"s": 44537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44693,
"s": 44635,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 44731,
"s": 44693,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 44774,
"s": 44731,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 44807,
"s": 44774,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 44838,
"s": 44807,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 44853,
"s": 44838,
"text": "Arrays in Java"
},
{
"code": null,
"e": 44897,
"s": 44853,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 44919,
"s": 44897,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 44970,
"s": 44919,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Number of swaps to sort when only adjacent swapping allowed - GeeksforGeeks | 04 Apr, 2022
Given an array arr[] of non negative integers. We can perform a swap operation on any two adjacent elements in the array. Find the minimum number of swaps needed to sort the array in ascending order.
Examples :
Input : arr[] = {3, 2, 1}
Output : 3
We need to do following swaps
(3, 2), (3, 1) and (1, 2)
Input : arr[] = {1, 20, 6, 4, 5}
Output : 5
There is an interesting solution to this problem. It can be solved using the fact that number of swaps needed is equal to number of inversions. So we basically need to count inversions in array.The fact can be established using below observations: 1) A sorted array has no inversions. 2) An adjacent swap can reduce one inversion. Doing x adjacent swaps can reduce x inversions in an array.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of swaps required// to sort an array when only swapping of adjacent// elements is allowed.#include <bits/stdc++.h> /* This function merges two sorted arrays and returns inversion count in the arrays.*/int merge(int arr[], int temp[], int left, int mid, int right){ int inv_count = 0; int i = left; /* i is index for left subarray*/ int j = mid; /* j is index for right subarray*/ int k = left; /* k is index for resultant merged subarray*/ while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above explanation/ diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left)/2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count;} /* This function sorts the input array and returns the number of inversions in the array */int countSwaps(int arr[], int n){ int temp[n]; return _mergeSort(arr, temp, 0, n - 1);} /* Driver program to test above functions */int main(int argv, char** args){ int arr[] = {1, 20, 6, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); printf("Number of swaps is %d \n", countSwaps(arr, n)); return 0;}
// Java program to count number of// swaps required to sort an array// when only swapping of adjacent// elements is allowed.import java.io.*; class GFG { // This function merges two sorted// arrays and returns inversion// count in the arrays.static int merge(int arr[], int temp[], int left, int mid, int right){ int inv_count = 0; /* i is index for left subarray*/ int i = left; /* j is index for right subarray*/ int j = mid; /* k is index for resultant merged subarray*/ int k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above / explanation diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} // An auxiliary recursive function that// sorts the input array and returns// the number of inversions in the array.static int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for // each of the parts mid = (right + left)/2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count;} // This function sorts the input// array and returns the number// of inversions in the arraystatic int countSwaps(int arr[], int n){ int temp[] = new int[n]; return _mergeSort(arr, temp, 0, n - 1);} // Driver Codepublic static void main (String[] args){ int arr[] = {1, 20, 6, 4, 5}; int n = arr.length; System.out.println("Number of swaps is " + countSwaps(arr, n)); }} // This code is contributed by vt_m
# python 3 program to count number of swaps required# to sort an array when only swapping of adjacent# elements is allowed.#include <bits/stdc++.h> #This function merges two sorted arrays and returns inversion count in the arrays.*/def merge(arr, temp, left, mid, right): inv_count = 0 i = left #i is index for left subarray*/ j = mid #j is index for right subarray*/ k = left #k is index for resultant merged subarray*/ while ((i <= mid - 1) and (j <= right)): if (arr[i] <= arr[j]): temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 #this is tricky -- see above explanation/ # diagram for merge()*/ inv_count = inv_count + (mid - i) #Copy the remaining elements of left subarray # (if there are any) to temp*/ while (i <= mid - 1): temp[k] = arr[i] k += 1 i += 1 #Copy the remaining elements of right subarray # (if there are any) to temp*/ while (j <= right): temp[k] = arr[j] k += 1 j += 1 # Copy back the merged elements to original array*/ for i in range(left,right+1,1): arr[i] = temp[i] return inv_count #An auxiliary recursive function that sorts the input# array and returns the number of inversions in the# array. */def _mergeSort(arr, temp, left, right): inv_count = 0 if (right > left): # Divide the array into two parts and call #_mergeSortAndCountInv() # for each of the parts */ mid = int((right + left)/2) #Inversion count will be sum of inversions in # left-part, right-part and number of inversions # in merging */ inv_count = _mergeSort(arr, temp, left, mid) inv_count += _mergeSort(arr, temp, mid+1, right) # Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right) return inv_count #This function sorts the input array and returns the#number of inversions in the array */def countSwaps(arr, n): temp = [0 for i in range(n)] return _mergeSort(arr, temp, 0, n - 1) # Driver program to test above functions */if __name__ == '__main__': arr = [1, 20, 6, 4, 5] n = len(arr) print("Number of swaps is",countSwaps(arr, n)) # This code is contributed by# Surendra_Gangwar
// C# program to count number of// swaps required to sort an array// when only swapping of adjacent// elements is allowed.using System; class GFG{ // This function merges two// sorted arrays and returns// inversion count in the arrays.static int merge(int []arr, int []temp, int left, int mid, int right){ int inv_count = 0; /* i is index for left subarray*/ int i = left; /* j is index for right subarray*/ int j = mid; /* k is index for resultant merged subarray*/ int k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above / explanation diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} // An auxiliary recursive function// that sorts the input array and// returns the number of inversions// in the array.static int _mergeSort(int []arr, int []temp, int left, int right){ int mid, inv_count = 0; if (right > left) { // Divide the array into two parts // and call _mergeSortAndCountInv() // for each of the parts mid = (right + left) / 2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count;} // This function sorts the input// array and returns the number// of inversions in the arraystatic int countSwaps(int []arr, int n){ int []temp = new int[n]; return _mergeSort(arr, temp, 0, n - 1);} // Driver Codepublic static void Main (){ int []arr = {1, 20, 6, 4, 5}; int n = arr.Length; Console.Write("Number of swaps is " + countSwaps(arr, n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to count number of swaps required// to sort an array when only swapping of adjacent// elements is allowed. /* This function merges two sorted arrays and returns inversion count in the arrays.*/function merge(&$arr, &$temp, $left, $mid, $right){ $inv_count = 0; $i = $left; /* i is index for left subarray*/ $j = $mid; /* j is index for right subarray*/ $k = $left; /* k is index for resultant merged subarray*/ while (($i <= $mid - 1) && ($j <= $right)) { if ($arr[$i] <= $arr[$j]) $temp[$k++] = $arr[$i++]; else { $temp[$k++] = $arr[$j++]; /* this is tricky -- see above explanation/ diagram for merge()*/ $inv_count = $inv_count + ($mid - $i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while ($i <= $mid - 1) $temp[$k++] = $arr[$i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while ($j <= $right) $temp[$k++] = $arr[$j++]; /*Copy back the merged elements to original array*/ for ($i=$left; $i <= $right; $i++) $arr[$i] = $temp[$i]; return $inv_count;} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */function _mergeSort(&$arr, &$temp, $left, $right){ $inv_count = 0; if ($right > $left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ $mid = intval(($right + $left)/2); /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ $inv_count = _mergeSort($arr, $temp, $left, $mid); $inv_count += _mergeSort($arr, $temp, $mid+1, $right); /*Merge the two parts*/ $inv_count += merge($arr, $temp, $left, $mid+1, $right); } return $inv_count;} /* This function sorts the input array and returns the number of inversions in the array */function countSwaps(&$arr, $n){ $temp = array_fill(0,$n,NULL); return _mergeSort($arr, $temp, 0, $n - 1);} /* Driver program to test above functions */ $arr = array(1, 20, 6, 4, 5);$n = sizeof($arr)/sizeof($arr[0]);echo "Number of swaps is ". countSwaps($arr, $n);return 0;?>
<script>// Javascript program to count number of// swaps required to sort an array// when only swapping of adjacent// elements is allowed. // This function merges two sorted // arrays and returns inversion // count in the arrays. function merge(arr,temp,left,mid,right) { let inv_count = 0; /* i is index for left subarray*/ let i = left; /* j is index for right subarray*/ let j = mid; /* k is index for resultant merged subarray*/ let k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above / explanation diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // An auxiliary recursive function that // sorts the input array and returns // the number of inversions in the array. function _mergeSort(arr,temp,left,right) { let mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for // each of the parts mid = Math.floor((right + left)/2); /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count; } // This function sorts the input // array and returns the number // of inversions in the array function countSwaps(arr,n) { let temp = new Array(n); for(let i = 0; i < n; i++) { temp[i] = 0; } return _mergeSort(arr, temp, 0, n - 1); } // Driver Code let arr=[1, 20, 6, 4, 5]; let n = arr.length; document.write("Number of swaps is " + countSwaps(arr, n)); // This code is contributed by rag2127</script>
Output:
Number of swaps is 5
Time Complexity : O(n Log n)Related Post : Minimum number of swaps required to sort an array
References : http://stackoverflow.com/questions/20990127/sorting-a-sequence-by-swapping-adjacent-elements-using-minimum-swaps
This article is contributed by Shivam 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
SURENDRA_GANGWAR
ukasp
rag2127
vivekdubey5
simmytarika5
sagartomar9927
inversion
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Find Second largest element in an array
Program to find largest element in an array | [
{
"code": null,
"e": 24936,
"s": 24908,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 25137,
"s": 24936,
"text": "Given an array arr[] of non negative integers. We can perform a swap operation on any two adjacent elements in the array. Find the minimum number of swaps needed to sort the array in ascending order. "
},
{
"code": null,
"e": 25149,
"s": 25137,
"text": "Examples : "
},
{
"code": null,
"e": 25289,
"s": 25149,
"text": "Input : arr[] = {3, 2, 1}\nOutput : 3\nWe need to do following swaps\n(3, 2), (3, 1) and (1, 2)\n\nInput : arr[] = {1, 20, 6, 4, 5}\nOutput : 5"
},
{
"code": null,
"e": 25682,
"s": 25289,
"text": "There is an interesting solution to this problem. It can be solved using the fact that number of swaps needed is equal to number of inversions. So we basically need to count inversions in array.The fact can be established using below observations: 1) A sorted array has no inversions. 2) An adjacent swap can reduce one inversion. Doing x adjacent swaps can reduce x inversions in an array. "
},
{
"code": null,
"e": 25686,
"s": 25682,
"text": "C++"
},
{
"code": null,
"e": 25691,
"s": 25686,
"text": "Java"
},
{
"code": null,
"e": 25699,
"s": 25691,
"text": "Python3"
},
{
"code": null,
"e": 25702,
"s": 25699,
"text": "C#"
},
{
"code": null,
"e": 25706,
"s": 25702,
"text": "PHP"
},
{
"code": null,
"e": 25717,
"s": 25706,
"text": "Javascript"
},
{
"code": "// C++ program to count number of swaps required// to sort an array when only swapping of adjacent// elements is allowed.#include <bits/stdc++.h> /* This function merges two sorted arrays and returns inversion count in the arrays.*/int merge(int arr[], int temp[], int left, int mid, int right){ int inv_count = 0; int i = left; /* i is index for left subarray*/ int j = mid; /* j is index for right subarray*/ int k = left; /* k is index for resultant merged subarray*/ while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above explanation/ diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left)/2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count;} /* This function sorts the input array and returns the number of inversions in the array */int countSwaps(int arr[], int n){ int temp[n]; return _mergeSort(arr, temp, 0, n - 1);} /* Driver program to test above functions */int main(int argv, char** args){ int arr[] = {1, 20, 6, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Number of swaps is %d \\n\", countSwaps(arr, n)); return 0;}",
"e": 28077,
"s": 25717,
"text": null
},
{
"code": "// Java program to count number of// swaps required to sort an array// when only swapping of adjacent// elements is allowed.import java.io.*; class GFG { // This function merges two sorted// arrays and returns inversion// count in the arrays.static int merge(int arr[], int temp[], int left, int mid, int right){ int inv_count = 0; /* i is index for left subarray*/ int i = left; /* j is index for right subarray*/ int j = mid; /* k is index for resultant merged subarray*/ int k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above / explanation diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} // An auxiliary recursive function that// sorts the input array and returns// the number of inversions in the array.static int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for // each of the parts mid = (right + left)/2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count;} // This function sorts the input// array and returns the number// of inversions in the arraystatic int countSwaps(int arr[], int n){ int temp[] = new int[n]; return _mergeSort(arr, temp, 0, n - 1);} // Driver Codepublic static void main (String[] args){ int arr[] = {1, 20, 6, 4, 5}; int n = arr.length; System.out.println(\"Number of swaps is \" + countSwaps(arr, n)); }} // This code is contributed by vt_m",
"e": 30685,
"s": 28077,
"text": null
},
{
"code": "# python 3 program to count number of swaps required# to sort an array when only swapping of adjacent# elements is allowed.#include <bits/stdc++.h> #This function merges two sorted arrays and returns inversion count in the arrays.*/def merge(arr, temp, left, mid, right): inv_count = 0 i = left #i is index for left subarray*/ j = mid #j is index for right subarray*/ k = left #k is index for resultant merged subarray*/ while ((i <= mid - 1) and (j <= right)): if (arr[i] <= arr[j]): temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 #this is tricky -- see above explanation/ # diagram for merge()*/ inv_count = inv_count + (mid - i) #Copy the remaining elements of left subarray # (if there are any) to temp*/ while (i <= mid - 1): temp[k] = arr[i] k += 1 i += 1 #Copy the remaining elements of right subarray # (if there are any) to temp*/ while (j <= right): temp[k] = arr[j] k += 1 j += 1 # Copy back the merged elements to original array*/ for i in range(left,right+1,1): arr[i] = temp[i] return inv_count #An auxiliary recursive function that sorts the input# array and returns the number of inversions in the# array. */def _mergeSort(arr, temp, left, right): inv_count = 0 if (right > left): # Divide the array into two parts and call #_mergeSortAndCountInv() # for each of the parts */ mid = int((right + left)/2) #Inversion count will be sum of inversions in # left-part, right-part and number of inversions # in merging */ inv_count = _mergeSort(arr, temp, left, mid) inv_count += _mergeSort(arr, temp, mid+1, right) # Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right) return inv_count #This function sorts the input array and returns the#number of inversions in the array */def countSwaps(arr, n): temp = [0 for i in range(n)] return _mergeSort(arr, temp, 0, n - 1) # Driver program to test above functions */if __name__ == '__main__': arr = [1, 20, 6, 4, 5] n = len(arr) print(\"Number of swaps is\",countSwaps(arr, n)) # This code is contributed by# Surendra_Gangwar",
"e": 33023,
"s": 30685,
"text": null
},
{
"code": "// C# program to count number of// swaps required to sort an array// when only swapping of adjacent// elements is allowed.using System; class GFG{ // This function merges two// sorted arrays and returns// inversion count in the arrays.static int merge(int []arr, int []temp, int left, int mid, int right){ int inv_count = 0; /* i is index for left subarray*/ int i = left; /* j is index for right subarray*/ int j = mid; /* k is index for resultant merged subarray*/ int k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above / explanation diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} // An auxiliary recursive function// that sorts the input array and// returns the number of inversions// in the array.static int _mergeSort(int []arr, int []temp, int left, int right){ int mid, inv_count = 0; if (right > left) { // Divide the array into two parts // and call _mergeSortAndCountInv() // for each of the parts mid = (right + left) / 2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count;} // This function sorts the input// array and returns the number// of inversions in the arraystatic int countSwaps(int []arr, int n){ int []temp = new int[n]; return _mergeSort(arr, temp, 0, n - 1);} // Driver Codepublic static void Main (){ int []arr = {1, 20, 6, 4, 5}; int n = arr.Length; Console.Write(\"Number of swaps is \" + countSwaps(arr, n)); }} // This code is contributed by nitin mittal.",
"e": 35665,
"s": 33023,
"text": null
},
{
"code": "<?php// PHP program to count number of swaps required// to sort an array when only swapping of adjacent// elements is allowed. /* This function merges two sorted arrays and returns inversion count in the arrays.*/function merge(&$arr, &$temp, $left, $mid, $right){ $inv_count = 0; $i = $left; /* i is index for left subarray*/ $j = $mid; /* j is index for right subarray*/ $k = $left; /* k is index for resultant merged subarray*/ while (($i <= $mid - 1) && ($j <= $right)) { if ($arr[$i] <= $arr[$j]) $temp[$k++] = $arr[$i++]; else { $temp[$k++] = $arr[$j++]; /* this is tricky -- see above explanation/ diagram for merge()*/ $inv_count = $inv_count + ($mid - $i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while ($i <= $mid - 1) $temp[$k++] = $arr[$i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while ($j <= $right) $temp[$k++] = $arr[$j++]; /*Copy back the merged elements to original array*/ for ($i=$left; $i <= $right; $i++) $arr[$i] = $temp[$i]; return $inv_count;} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */function _mergeSort(&$arr, &$temp, $left, $right){ $inv_count = 0; if ($right > $left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ $mid = intval(($right + $left)/2); /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ $inv_count = _mergeSort($arr, $temp, $left, $mid); $inv_count += _mergeSort($arr, $temp, $mid+1, $right); /*Merge the two parts*/ $inv_count += merge($arr, $temp, $left, $mid+1, $right); } return $inv_count;} /* This function sorts the input array and returns the number of inversions in the array */function countSwaps(&$arr, $n){ $temp = array_fill(0,$n,NULL); return _mergeSort($arr, $temp, 0, $n - 1);} /* Driver program to test above functions */ $arr = array(1, 20, 6, 4, 5);$n = sizeof($arr)/sizeof($arr[0]);echo \"Number of swaps is \". countSwaps($arr, $n);return 0;?>",
"e": 38019,
"s": 35665,
"text": null
},
{
"code": "<script>// Javascript program to count number of// swaps required to sort an array// when only swapping of adjacent// elements is allowed. // This function merges two sorted // arrays and returns inversion // count in the arrays. function merge(arr,temp,left,mid,right) { let inv_count = 0; /* i is index for left subarray*/ let i = left; /* j is index for right subarray*/ let j = mid; /* k is index for resultant merged subarray*/ let k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /* this is tricky -- see above / explanation diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // An auxiliary recursive function that // sorts the input array and returns // the number of inversions in the array. function _mergeSort(arr,temp,left,right) { let mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for // each of the parts mid = Math.floor((right + left)/2); /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count; } // This function sorts the input // array and returns the number // of inversions in the array function countSwaps(arr,n) { let temp = new Array(n); for(let i = 0; i < n; i++) { temp[i] = 0; } return _mergeSort(arr, temp, 0, n - 1); } // Driver Code let arr=[1, 20, 6, 4, 5]; let n = arr.length; document.write(\"Number of swaps is \" + countSwaps(arr, n)); // This code is contributed by rag2127</script>",
"e": 40956,
"s": 38019,
"text": null
},
{
"code": null,
"e": 40965,
"s": 40956,
"text": "Output: "
},
{
"code": null,
"e": 40986,
"s": 40965,
"text": "Number of swaps is 5"
},
{
"code": null,
"e": 41080,
"s": 40986,
"text": "Time Complexity : O(n Log n)Related Post : Minimum number of swaps required to sort an array "
},
{
"code": null,
"e": 41206,
"s": 41080,
"text": "References : http://stackoverflow.com/questions/20990127/sorting-a-sequence-by-swapping-adjacent-elements-using-minimum-swaps"
},
{
"code": null,
"e": 41627,
"s": 41206,
"text": "This article is contributed by Shivam 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 41640,
"s": 41627,
"text": "nitin mittal"
},
{
"code": null,
"e": 41657,
"s": 41640,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 41663,
"s": 41657,
"text": "ukasp"
},
{
"code": null,
"e": 41671,
"s": 41663,
"text": "rag2127"
},
{
"code": null,
"e": 41683,
"s": 41671,
"text": "vivekdubey5"
},
{
"code": null,
"e": 41696,
"s": 41683,
"text": "simmytarika5"
},
{
"code": null,
"e": 41711,
"s": 41696,
"text": "sagartomar9927"
},
{
"code": null,
"e": 41721,
"s": 41711,
"text": "inversion"
},
{
"code": null,
"e": 41728,
"s": 41721,
"text": "Arrays"
},
{
"code": null,
"e": 41736,
"s": 41728,
"text": "Sorting"
},
{
"code": null,
"e": 41743,
"s": 41736,
"text": "Arrays"
},
{
"code": null,
"e": 41751,
"s": 41743,
"text": "Sorting"
},
{
"code": null,
"e": 41849,
"s": 41751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41858,
"s": 41849,
"text": "Comments"
},
{
"code": null,
"e": 41871,
"s": 41858,
"text": "Old Comments"
},
{
"code": null,
"e": 41894,
"s": 41871,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 41948,
"s": 41894,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 41969,
"s": 41948,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 42009,
"s": 41969,
"text": "Find Second largest element in an array"
}
] |
How to set the Background Color of the GroupBox in C#? - GeeksforGeeks | 29 Jul, 2019
In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the background color of the GroupBox in the form using the BackColor Property. This property is an ambient property. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the background color of the GroupBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the GroupBox and set the background color of the GroupBox as shown in the below image:Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the GroupBox programmatically with the help of given syntax:
public virtual System.Drawing.Color BackColor { get; set; }
Here, Color indicates the background color of the GroupBox. The following steps show how to set the background color of the GroupBox dynamically:
Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox
GroupBox gbox = new GroupBox();
// Creating a GroupBox
GroupBox gbox = new GroupBox();
Step 2: After creating GroupBox, set the BackColor property of the GroupBox provided by the GroupBox class.// Setting the background color
gbox.BackColor = Color.LemonChiffon;
// Setting the background color
gbox.BackColor = Color.LemonChiffon;
Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form
this.Controls.Add(gbox);
and
// Adding this control
// to the GroupBox
gbox.Controls.Add(c2);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; gbox.BackColor = Color.LemonChiffon; gbox.ForeColor = Color.Maroon; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting properties // of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output:
// Adding groupbox in the form
this.Controls.Add(gbox);
and
// Adding this control
// to the GroupBox
gbox.Controls.Add(c2);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; gbox.BackColor = Color.LemonChiffon; gbox.ForeColor = Color.Maroon; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting properties // of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Linked List Implementation in C#
Lambda Expressions in C#
Convert String to Character Array in C# | [
{
"code": null,
"e": 24222,
"s": 24194,
"text": "\n29 Jul, 2019"
},
{
"code": null,
"e": 24712,
"s": 24222,
"text": "In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the background color of the GroupBox in the form using the BackColor Property. This property is an ambient property. You can set this property in two different ways:"
},
{
"code": null,
"e": 24827,
"s": 24712,
"text": "1. Design-Time: It is the easiest way to set the background color of the GroupBox as shown in the following steps:"
},
{
"code": null,
"e": 24943,
"s": 24827,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 25042,
"s": 24943,
"text": "Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 25197,
"s": 25042,
"text": "Step 3: After drag and drop you will go to the properties of the GroupBox and set the background color of the GroupBox as shown in the below image:Output:"
},
{
"code": null,
"e": 25205,
"s": 25197,
"text": "Output:"
},
{
"code": null,
"e": 25382,
"s": 25205,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the GroupBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25442,
"s": 25382,
"text": "public virtual System.Drawing.Color BackColor { get; set; }"
},
{
"code": null,
"e": 25588,
"s": 25442,
"text": "Here, Color indicates the background color of the GroupBox. The following steps show how to set the background color of the GroupBox dynamically:"
},
{
"code": null,
"e": 25738,
"s": 25588,
"text": "Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n"
},
{
"code": null,
"e": 25795,
"s": 25738,
"text": "// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n"
},
{
"code": null,
"e": 25972,
"s": 25795,
"text": "Step 2: After creating GroupBox, set the BackColor property of the GroupBox provided by the GroupBox class.// Setting the background color\ngbox.BackColor = Color.LemonChiffon;\n"
},
{
"code": null,
"e": 26042,
"s": 25972,
"text": "// Setting the background color\ngbox.BackColor = Color.LemonChiffon;\n"
},
{
"code": null,
"e": 27721,
"s": 26042,
"text": "Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control \n// to the GroupBox\ngbox.Controls.Add(c2);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; gbox.BackColor = Color.LemonChiffon; gbox.ForeColor = Color.Maroon; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting properties // of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output:"
},
{
"code": null,
"e": 27851,
"s": 27721,
"text": "// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control \n// to the GroupBox\ngbox.Controls.Add(c2);\n"
},
{
"code": null,
"e": 27860,
"s": 27851,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; gbox.BackColor = Color.LemonChiffon; gbox.ForeColor = Color.Maroon; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting properties // of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}",
"e": 29265,
"s": 27860,
"text": null
},
{
"code": null,
"e": 29273,
"s": 29265,
"text": "Output:"
},
{
"code": null,
"e": 29304,
"s": 29273,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 29307,
"s": 29304,
"text": "C#"
},
{
"code": null,
"e": 29405,
"s": 29307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29414,
"s": 29405,
"text": "Comments"
},
{
"code": null,
"e": 29427,
"s": 29414,
"text": "Old Comments"
},
{
"code": null,
"e": 29450,
"s": 29427,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29478,
"s": 29450,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29500,
"s": 29478,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29540,
"s": 29500,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29583,
"s": 29540,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 29599,
"s": 29583,
"text": "C# | List Class"
},
{
"code": null,
"e": 29616,
"s": 29599,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29649,
"s": 29616,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 29674,
"s": 29649,
"text": "Lambda Expressions in C#"
}
] |
How to limit string length in PHP ? - GeeksforGeeks | 21 Oct, 2021
A string is a sequence of characters in PHP. The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted.
Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object. The array elements are individual characters stored at individual indices.
str_split($string)
Parameters:
$string – The string to split into array
Example: A for loop iteration is performed over the array object until the desired length. The characters are displayed until the length is equivalent to the desired number of characters.
PHP
<?php $string = "Geeks for geeks is fun"; echo("Original String : "); echo($string . "\n"); echo("Modified String : "); $arr = str_split($string); for($i = 0; $i < 10; $i++) { print($arr[$i]); }?>
Original String : Geeks for geeks is fun
Modified String : Geeks for
Approach 2 (Using mb_strimwidth() function): The mb_strimwidth function is used to get truncated string with specified width. It takes as input the string and the required number of characters. The characters after it are appended with an “!!” string. It returns the string with the trimmed length.
mb_strimwidth(string, start, width, trim_pt)
Parameters:
string – The string which is to be trimmed.
start – The start position offset.
width – The desired trim length.
trim_pt – The string that can be added to truncate the length of string with.
Example:
PHP
<?php // Declaring original string $string = "Geeks for geeks is fun"; echo("Original String : "); echo($string . "\n"); // Trimming length of string $new_string = mb_strimwidth($string, 0, 11, "!!"); print("Modified String : "); print($new_string);?>
Output
Original String : Geeks for geeks is fun
Modified String : Geeks for!!
Approach 3 (Using substr() method ): The substr() function can be used to extract the specified string within the specified limits. The starting and ending indexes are specified and the equivalent number of characters between the start and end length are extracted.
substr(string, start, end)
Parameters:
string – The string to extract the substring from.
start – The starting index to extract the string from.
end – The ending index to extract the string.
Example:
PHP
<?php $string = "Geeks for geeks is fun"; echo("Original String : "); echo($string . "\n"); echo("Modified String : "); if (strlen($string) > 10) $new_string = substr($string, 0, 10) . '!!!'; echo($new_string . "\n");?>
Output:
Original String : Geeks for geeks is fun
Modified String : Geeks for !!!
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
How to generate PDF file using PHP ?
Different ways for passing data to view in Laravel
How to Install php-curl in Ubuntu ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24892,
"s": 24864,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 25073,
"s": 24892,
"text": "A string is a sequence of characters in PHP. The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted. "
},
{
"code": null,
"e": 25270,
"s": 25073,
"text": "Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object. The array elements are individual characters stored at individual indices. "
},
{
"code": null,
"e": 25289,
"s": 25270,
"text": "str_split($string)"
},
{
"code": null,
"e": 25302,
"s": 25289,
"text": "Parameters: "
},
{
"code": null,
"e": 25343,
"s": 25302,
"text": "$string – The string to split into array"
},
{
"code": null,
"e": 25532,
"s": 25343,
"text": "Example: A for loop iteration is performed over the array object until the desired length. The characters are displayed until the length is equivalent to the desired number of characters. "
},
{
"code": null,
"e": 25536,
"s": 25532,
"text": "PHP"
},
{
"code": "<?php $string = \"Geeks for geeks is fun\"; echo(\"Original String : \"); echo($string . \"\\n\"); echo(\"Modified String : \"); $arr = str_split($string); for($i = 0; $i < 10; $i++) { print($arr[$i]); }?>",
"e": 25767,
"s": 25536,
"text": null
},
{
"code": null,
"e": 25837,
"s": 25767,
"text": "Original String : Geeks for geeks is fun\nModified String : Geeks for "
},
{
"code": null,
"e": 26137,
"s": 25837,
"text": "Approach 2 (Using mb_strimwidth() function): The mb_strimwidth function is used to get truncated string with specified width. It takes as input the string and the required number of characters. The characters after it are appended with an “!!” string. It returns the string with the trimmed length. "
},
{
"code": null,
"e": 26182,
"s": 26137,
"text": "mb_strimwidth(string, start, width, trim_pt)"
},
{
"code": null,
"e": 26195,
"s": 26182,
"text": "Parameters: "
},
{
"code": null,
"e": 26239,
"s": 26195,
"text": "string – The string which is to be trimmed."
},
{
"code": null,
"e": 26274,
"s": 26239,
"text": "start – The start position offset."
},
{
"code": null,
"e": 26307,
"s": 26274,
"text": "width – The desired trim length."
},
{
"code": null,
"e": 26385,
"s": 26307,
"text": "trim_pt – The string that can be added to truncate the length of string with."
},
{
"code": null,
"e": 26394,
"s": 26385,
"text": "Example:"
},
{
"code": null,
"e": 26398,
"s": 26394,
"text": "PHP"
},
{
"code": "<?php // Declaring original string $string = \"Geeks for geeks is fun\"; echo(\"Original String : \"); echo($string . \"\\n\"); // Trimming length of string $new_string = mb_strimwidth($string, 0, 11, \"!!\"); print(\"Modified String : \"); print($new_string);?>",
"e": 26677,
"s": 26398,
"text": null
},
{
"code": null,
"e": 26684,
"s": 26677,
"text": "Output"
},
{
"code": null,
"e": 26755,
"s": 26684,
"text": "Original String : Geeks for geeks is fun\nModified String : Geeks for!!"
},
{
"code": null,
"e": 27022,
"s": 26755,
"text": "Approach 3 (Using substr() method ): The substr() function can be used to extract the specified string within the specified limits. The starting and ending indexes are specified and the equivalent number of characters between the start and end length are extracted. "
},
{
"code": null,
"e": 27049,
"s": 27022,
"text": "substr(string, start, end)"
},
{
"code": null,
"e": 27062,
"s": 27049,
"text": "Parameters: "
},
{
"code": null,
"e": 27113,
"s": 27062,
"text": "string – The string to extract the substring from."
},
{
"code": null,
"e": 27168,
"s": 27113,
"text": "start – The starting index to extract the string from."
},
{
"code": null,
"e": 27214,
"s": 27168,
"text": "end – The ending index to extract the string."
},
{
"code": null,
"e": 27223,
"s": 27214,
"text": "Example:"
},
{
"code": null,
"e": 27227,
"s": 27223,
"text": "PHP"
},
{
"code": "<?php $string = \"Geeks for geeks is fun\"; echo(\"Original String : \"); echo($string . \"\\n\"); echo(\"Modified String : \"); if (strlen($string) > 10) $new_string = substr($string, 0, 10) . '!!!'; echo($new_string . \"\\n\");?>",
"e": 27475,
"s": 27227,
"text": null
},
{
"code": null,
"e": 27483,
"s": 27475,
"text": "Output:"
},
{
"code": null,
"e": 27556,
"s": 27483,
"text": "Original String : Geeks for geeks is fun\nModified String : Geeks for !!!"
},
{
"code": null,
"e": 27569,
"s": 27556,
"text": "PHP-function"
},
{
"code": null,
"e": 27583,
"s": 27569,
"text": "PHP-Questions"
},
{
"code": null,
"e": 27594,
"s": 27583,
"text": "PHP-string"
},
{
"code": null,
"e": 27601,
"s": 27594,
"text": "Picked"
},
{
"code": null,
"e": 27605,
"s": 27601,
"text": "PHP"
},
{
"code": null,
"e": 27622,
"s": 27605,
"text": "Web Technologies"
},
{
"code": null,
"e": 27626,
"s": 27622,
"text": "PHP"
},
{
"code": null,
"e": 27724,
"s": 27626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27733,
"s": 27724,
"text": "Comments"
},
{
"code": null,
"e": 27746,
"s": 27733,
"text": "Old Comments"
},
{
"code": null,
"e": 27828,
"s": 27746,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27870,
"s": 27828,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27907,
"s": 27870,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 27958,
"s": 27907,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 27994,
"s": 27958,
"text": "How to Install php-curl in Ubuntu ?"
},
{
"code": null,
"e": 28036,
"s": 27994,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28069,
"s": 28036,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28131,
"s": 28069,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28174,
"s": 28131,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How can we tackle MySQL error ‘ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement’ while importing or exporting the data? | MySQL throws this error because of the two reasons, either no directory is specified under --secure--file--priv variable or we are giving the wrong path in our query while importing or exporting the data. To tackle this error we must have to check the value of –secure—file—priv variable by following query −
mysql> Select @@global.secure_file_priv;
+---------------------------+
| @@global.secure_file_priv |
+---------------------------+
| C:\mysql\bin\mysql-files\ |
+---------------------------+
1 row in set (0.00 sec)
We can see there is path under secure_file_priv variable and all the files would be created under this directory when we export the data.
But, if the above command shows NULL as result then it means there is no path specified and we need to specify the path in my.ini file before exporting the data. Suppose if we will write secure_file_priv = mysql-files/ in our my.ini file then secure_file_priv will have the path like above as its value. Then all the files will be created under this directory. | [
{
"code": null,
"e": 1371,
"s": 1062,
"text": "MySQL throws this error because of the two reasons, either no directory is specified under --secure--file--priv variable or we are giving the wrong path in our query while importing or exporting the data. To tackle this error we must have to check the value of –secure—file—priv variable by following query −"
},
{
"code": null,
"e": 1586,
"s": 1371,
"text": "mysql> Select @@global.secure_file_priv;\n+---------------------------+\n| @@global.secure_file_priv |\n+---------------------------+\n| C:\\mysql\\bin\\mysql-files\\ |\n+---------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1724,
"s": 1586,
"text": "We can see there is path under secure_file_priv variable and all the files would be created under this directory when we export the data."
},
{
"code": null,
"e": 2085,
"s": 1724,
"text": "But, if the above command shows NULL as result then it means there is no path specified and we need to specify the path in my.ini file before exporting the data. Suppose if we will write secure_file_priv = mysql-files/ in our my.ini file then secure_file_priv will have the path like above as its value. Then all the files will be created under this directory."
}
] |
SQL Tryit Editor v1.6 | SELECT 17 % 5;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 15,
"s": 0,
"text": "SELECT 17 % 5;"
},
{
"code": null,
"e": 17,
"s": 15,
"text": ""
},
{
"code": null,
"e": 80,
"s": 17,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 140,
"s": 80,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 208,
"s": 140,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 246,
"s": 208,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 331,
"s": 246,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 505,
"s": 331,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 556,
"s": 505,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 624,
"s": 556,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 795,
"s": 624,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 895,
"s": 795,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 955,
"s": 895,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
Visualizing Machine Learning Datasets with Google’s FACETS. | by Parul Pandey | Towards Data Science | More data beats clever algorithms, but better data beats more data : Peter Norvig
There has been a lot of uproar about how a large quantity of training data can have a tremendous impact on the results of a machine learning model. However, along with data quantity, it is also the quality that is critical to building a powerful and robust ML system. After all, ‘GARBAGE IN: GARBAGE OUT,’ i.e., what you get from the system, will represent what you feed into the system.
A Machine Learning dataset sometimes consists of data points ranging from thousands to millions, which may contain hundreds or thousands of features. Additionally, real-world data is messy, comprising of missing values, unbalanced data, outliers, etc. Therefore it becomes imperative that we clean the data before proceeding with model building. Visualizing the data can help locate these irregularities and point out where the data needs cleaning. Data Visualisation gives an overview of the entire data irrespective of its quantity and enables to perform EDA quickly and accurately.
The dictionary meaning of facets boils down to a particular aspect or feature of something. In the same way, the FACETS tool helps us understand the various features of data and explore them without having to code explicitly.
Facets is an open-source visualization tool released by Google under the PAIR(People + AI Research) initiative. This tool helps us to understand and analyze the Machine Learning datasets. Facets consist of two visualizations, which help drill down the data and provide great insights without much work at the user’s end.
Facets Overview
As the name suggests, this visualization gives an overview of the entire dataset and gives a sense of the shape of each feature of the data. Facets Overview summarizes statistics for each feature and compares the training and test datasets.
Facets Dive
This feature helps the user dive deep into the individual feature/observation of the data to get more information. It helps in interactively exploring large numbers of data points at once.
These visualizations are implemented as Polymer web components, backed by Typescript code and can be easily embedded into Jupyter notebooks or web pages.
There are two ways in which FACETS can be used with data:
It can be used directly from its demo page, whose link is embedded below.
pair-code.github.io
This website allows anyone to visualize their datasets directly in the browser without the need for any software installation or setup, without the data ever leaving your computer.
It is also possible to use FACETS within Jupyter Notebook/Colaboratoty. This gives more flexibility since the entire EDA and modeling can be done in a single notebook. Please refer to their Github Repository for complete details on installation. However, later in the article, we will see how to get going with FACETS in colab.
Although you can work with the data provided on the demo page, I shall be working with another set of data. I will be doing EDA with FACETS on the Loan Prediction Dataset. The problem statement is to predict whether an applicant who a company has granted a loan will repay it back or not. It is a reasonably known example in the ML community.
The dataset, which has already been divided into Training and Testing set can be accessed from here. Let’s load our data into the Colab.
import pandas as pdtrain = pd.read_csv('train.csv')test = pd.read_csv('test.csv')
Now lets us understand how we can use Facets Overview with this data.
The Overview automatically gives a quick understanding of the distribution of values across the various features of the data. The distribution can also be compared across the training and testing datasets instantly. If some anomaly exists in the data, it just pops out from the data there and then.
Some of the information that can be easily accessed through this feature are:
Statistics like mean, median, and Standard Deviation
Min and Max values of a column
Missing data
Values that have zero values
Since it is possible to view the distributions across the test dataset, we can easily confirm if the training and testing data follow the same distributions.
One would argue that we can achieve these tasks easily with Pandas and why should we invest into another tool. This is true and maybe not required when we have few data points with minimum features. However, the scenario changes when we are talking about a large dataset where it becomes kind of difficult to analyse each and every data point in multiple columns.
Google Colaboaratory makes it very easy to work since we do not need to install other things. By writing a few lines of code, our work gets done.
# Clone the facets github repo to get access to the python feature stats generation code!git clone https://github.com/pair-code/facets.git
To calculate the feature statistics, we need to use the function GenericFeatureStatisticsGenerator() which lies in a Python Script.
# Add the path to the feature stats generation code.import syssys.path.insert(0, '/content/facets/facets_overview/python/')# Create the feature stats for the datasets and stringify it.import base64from generic_feature_statistics_generator import GenericFeatureStatisticsGeneratorgfsg = GenericFeatureStatisticsGenerator()proto = gfsg.ProtoFromDataFrames([{'name': 'train', 'table': train}, {'name': 'test', 'table': test}])protostr = base64.b64encode(proto.SerializeToString()).decode("utf-8")
Now with the following lines of code, we can easily display the visualization right in our notebook.
# Display the facets overview visualization for this datafrom IPython.core.display import display, HTMLHTML_TEMPLATE = """<link rel="import" href="https://raw.githubusercontent.com/PAIR-code/facets/master/facets-dist/facets-jupyter.html" > <facets-overview id="elem"></facets-overview> <script> document.querySelector("#elem").protoInput = "{protostr}"; </script>"""html = HTML_TEMPLATE.format(protostr=protostr)display(HTML(html))
As soon as you type Shift+Enter, you are welcomed by this excellent interactive visualization:
Here, we see the Facets Overview visualization of the five numeric features of the Loan Prediction dataset. The features are sorted by non-uniformity, with the feature with the most non-uniform distribution at the top. Numbers in red indicate possible trouble spots, in this case, numeric features with a high percentage of values set to 0. The histograms at the right allow you to compare the distributions between the training data (blue) and test data (orange).
The above visualization shows one of the eight categorical features of the dataset. The features are sorted by distribution distance, with the feature with the biggest skew between the training (blue) and test (orange) datasets at the top.
Facets Dive provides an easy-to-customize, intuitive interface for exploring the relationship between the data points across the different features. With Facets Dive, you control each data point's position, color, and visual representation based on its feature values. If the data points have images associated with them, the images can be used as visual representations.
To use the Dive visualization, the data has to be transformed into JSON format.
# Display the Dive visualization for the training data.from IPython.core.display import display, HTMLjsonstr = train.to_json(orient='records')HTML_TEMPLATE = """<link rel="import" href="https://raw.githubusercontent.com/PAIR-code/facets/master/facets-dist/facets-jupyter.html"> <facets-dive id="elem" height="600"></facets-dive> <script> var data = {jsonstr}; document.querySelector("#elem").data = data; </script>"""html = HTML_TEMPLATE.format(jsonstr=jsonstr)display(HTML(html))
After you run the code, you should be able to see this:
Now we can easily perform Univariate and Bivariate Analysis and let us see some of the results obtained:
Here we will look at the target variable, i.e., Loan_Status, and other categorical features like gender, Marital Status, Employment Status, and Credit history, independently. Likewise, you can play around with different features also.
Most of the applicants in the dataset are male.
Again a majority of the applicants in the dataset are married and have repaid their debts.
Also, most of the applicants have no dependents and are graduates from semi-urban areas.
Now let’s visualize the ordinal variables, i.e., Dependents, Education, and Property Area.
Following inferences can be made from the above bar plots:
Most of the applicants don’t have any dependents.
Most of the applicants are graduates.
Most of the applicants are from semi-urban areas.
Now you can continue your analysis with the numerical data.
We will find the relationship between the target variable and categorical independent variables.
It can be inferred from the above bar plots that:
The proportion of married applicants is higher for the approved loans.
The distribution of applicants with one or 3+ dependents is similar across both the categories of Loan_Status.
It seems people with a credit history of 1 are more likely to get their loans approved.
The proportion of loans getting approved in the semiurban area is higher than that in rural or urban areas.
FACETS provides an easy and intuitive environment to perform EDA for datasets and helps us derive meaningful results. The only catch is that currently, it only works with Chrome.
Before ending this article, let us also see a fun fact highlighting how a small human labeling error in the CIFAR-10 dataset was caught using the FACETS Dive. While analyzing the dataset, it came to notice that an image of a frog had been incorrectly labeled as a cat. Well, this is indeed some achievement since it would be an impossible task for the human eye. | [
{
"code": null,
"e": 254,
"s": 172,
"text": "More data beats clever algorithms, but better data beats more data : Peter Norvig"
},
{
"code": null,
"e": 642,
"s": 254,
"text": "There has been a lot of uproar about how a large quantity of training data can have a tremendous impact on the results of a machine learning model. However, along with data quantity, it is also the quality that is critical to building a powerful and robust ML system. After all, ‘GARBAGE IN: GARBAGE OUT,’ i.e., what you get from the system, will represent what you feed into the system."
},
{
"code": null,
"e": 1227,
"s": 642,
"text": "A Machine Learning dataset sometimes consists of data points ranging from thousands to millions, which may contain hundreds or thousands of features. Additionally, real-world data is messy, comprising of missing values, unbalanced data, outliers, etc. Therefore it becomes imperative that we clean the data before proceeding with model building. Visualizing the data can help locate these irregularities and point out where the data needs cleaning. Data Visualisation gives an overview of the entire data irrespective of its quantity and enables to perform EDA quickly and accurately."
},
{
"code": null,
"e": 1453,
"s": 1227,
"text": "The dictionary meaning of facets boils down to a particular aspect or feature of something. In the same way, the FACETS tool helps us understand the various features of data and explore them without having to code explicitly."
},
{
"code": null,
"e": 1774,
"s": 1453,
"text": "Facets is an open-source visualization tool released by Google under the PAIR(People + AI Research) initiative. This tool helps us to understand and analyze the Machine Learning datasets. Facets consist of two visualizations, which help drill down the data and provide great insights without much work at the user’s end."
},
{
"code": null,
"e": 1790,
"s": 1774,
"text": "Facets Overview"
},
{
"code": null,
"e": 2031,
"s": 1790,
"text": "As the name suggests, this visualization gives an overview of the entire dataset and gives a sense of the shape of each feature of the data. Facets Overview summarizes statistics for each feature and compares the training and test datasets."
},
{
"code": null,
"e": 2043,
"s": 2031,
"text": "Facets Dive"
},
{
"code": null,
"e": 2232,
"s": 2043,
"text": "This feature helps the user dive deep into the individual feature/observation of the data to get more information. It helps in interactively exploring large numbers of data points at once."
},
{
"code": null,
"e": 2386,
"s": 2232,
"text": "These visualizations are implemented as Polymer web components, backed by Typescript code and can be easily embedded into Jupyter notebooks or web pages."
},
{
"code": null,
"e": 2444,
"s": 2386,
"text": "There are two ways in which FACETS can be used with data:"
},
{
"code": null,
"e": 2518,
"s": 2444,
"text": "It can be used directly from its demo page, whose link is embedded below."
},
{
"code": null,
"e": 2538,
"s": 2518,
"text": "pair-code.github.io"
},
{
"code": null,
"e": 2719,
"s": 2538,
"text": "This website allows anyone to visualize their datasets directly in the browser without the need for any software installation or setup, without the data ever leaving your computer."
},
{
"code": null,
"e": 3047,
"s": 2719,
"text": "It is also possible to use FACETS within Jupyter Notebook/Colaboratoty. This gives more flexibility since the entire EDA and modeling can be done in a single notebook. Please refer to their Github Repository for complete details on installation. However, later in the article, we will see how to get going with FACETS in colab."
},
{
"code": null,
"e": 3390,
"s": 3047,
"text": "Although you can work with the data provided on the demo page, I shall be working with another set of data. I will be doing EDA with FACETS on the Loan Prediction Dataset. The problem statement is to predict whether an applicant who a company has granted a loan will repay it back or not. It is a reasonably known example in the ML community."
},
{
"code": null,
"e": 3527,
"s": 3390,
"text": "The dataset, which has already been divided into Training and Testing set can be accessed from here. Let’s load our data into the Colab."
},
{
"code": null,
"e": 3609,
"s": 3527,
"text": "import pandas as pdtrain = pd.read_csv('train.csv')test = pd.read_csv('test.csv')"
},
{
"code": null,
"e": 3679,
"s": 3609,
"text": "Now lets us understand how we can use Facets Overview with this data."
},
{
"code": null,
"e": 3978,
"s": 3679,
"text": "The Overview automatically gives a quick understanding of the distribution of values across the various features of the data. The distribution can also be compared across the training and testing datasets instantly. If some anomaly exists in the data, it just pops out from the data there and then."
},
{
"code": null,
"e": 4056,
"s": 3978,
"text": "Some of the information that can be easily accessed through this feature are:"
},
{
"code": null,
"e": 4109,
"s": 4056,
"text": "Statistics like mean, median, and Standard Deviation"
},
{
"code": null,
"e": 4140,
"s": 4109,
"text": "Min and Max values of a column"
},
{
"code": null,
"e": 4153,
"s": 4140,
"text": "Missing data"
},
{
"code": null,
"e": 4182,
"s": 4153,
"text": "Values that have zero values"
},
{
"code": null,
"e": 4340,
"s": 4182,
"text": "Since it is possible to view the distributions across the test dataset, we can easily confirm if the training and testing data follow the same distributions."
},
{
"code": null,
"e": 4704,
"s": 4340,
"text": "One would argue that we can achieve these tasks easily with Pandas and why should we invest into another tool. This is true and maybe not required when we have few data points with minimum features. However, the scenario changes when we are talking about a large dataset where it becomes kind of difficult to analyse each and every data point in multiple columns."
},
{
"code": null,
"e": 4850,
"s": 4704,
"text": "Google Colaboaratory makes it very easy to work since we do not need to install other things. By writing a few lines of code, our work gets done."
},
{
"code": null,
"e": 4989,
"s": 4850,
"text": "# Clone the facets github repo to get access to the python feature stats generation code!git clone https://github.com/pair-code/facets.git"
},
{
"code": null,
"e": 5121,
"s": 4989,
"text": "To calculate the feature statistics, we need to use the function GenericFeatureStatisticsGenerator() which lies in a Python Script."
},
{
"code": null,
"e": 5648,
"s": 5121,
"text": "# Add the path to the feature stats generation code.import syssys.path.insert(0, '/content/facets/facets_overview/python/')# Create the feature stats for the datasets and stringify it.import base64from generic_feature_statistics_generator import GenericFeatureStatisticsGeneratorgfsg = GenericFeatureStatisticsGenerator()proto = gfsg.ProtoFromDataFrames([{'name': 'train', 'table': train}, {'name': 'test', 'table': test}])protostr = base64.b64encode(proto.SerializeToString()).decode(\"utf-8\")"
},
{
"code": null,
"e": 5749,
"s": 5648,
"text": "Now with the following lines of code, we can easily display the visualization right in our notebook."
},
{
"code": null,
"e": 6211,
"s": 5749,
"text": "# Display the facets overview visualization for this datafrom IPython.core.display import display, HTMLHTML_TEMPLATE = \"\"\"<link rel=\"import\" href=\"https://raw.githubusercontent.com/PAIR-code/facets/master/facets-dist/facets-jupyter.html\" > <facets-overview id=\"elem\"></facets-overview> <script> document.querySelector(\"#elem\").protoInput = \"{protostr}\"; </script>\"\"\"html = HTML_TEMPLATE.format(protostr=protostr)display(HTML(html))"
},
{
"code": null,
"e": 6306,
"s": 6211,
"text": "As soon as you type Shift+Enter, you are welcomed by this excellent interactive visualization:"
},
{
"code": null,
"e": 6771,
"s": 6306,
"text": "Here, we see the Facets Overview visualization of the five numeric features of the Loan Prediction dataset. The features are sorted by non-uniformity, with the feature with the most non-uniform distribution at the top. Numbers in red indicate possible trouble spots, in this case, numeric features with a high percentage of values set to 0. The histograms at the right allow you to compare the distributions between the training data (blue) and test data (orange)."
},
{
"code": null,
"e": 7011,
"s": 6771,
"text": "The above visualization shows one of the eight categorical features of the dataset. The features are sorted by distribution distance, with the feature with the biggest skew between the training (blue) and test (orange) datasets at the top."
},
{
"code": null,
"e": 7383,
"s": 7011,
"text": "Facets Dive provides an easy-to-customize, intuitive interface for exploring the relationship between the data points across the different features. With Facets Dive, you control each data point's position, color, and visual representation based on its feature values. If the data points have images associated with them, the images can be used as visual representations."
},
{
"code": null,
"e": 7463,
"s": 7383,
"text": "To use the Dive visualization, the data has to be transformed into JSON format."
},
{
"code": null,
"e": 7983,
"s": 7463,
"text": "# Display the Dive visualization for the training data.from IPython.core.display import display, HTMLjsonstr = train.to_json(orient='records')HTML_TEMPLATE = \"\"\"<link rel=\"import\" href=\"https://raw.githubusercontent.com/PAIR-code/facets/master/facets-dist/facets-jupyter.html\"> <facets-dive id=\"elem\" height=\"600\"></facets-dive> <script> var data = {jsonstr}; document.querySelector(\"#elem\").data = data; </script>\"\"\"html = HTML_TEMPLATE.format(jsonstr=jsonstr)display(HTML(html))"
},
{
"code": null,
"e": 8039,
"s": 7983,
"text": "After you run the code, you should be able to see this:"
},
{
"code": null,
"e": 8144,
"s": 8039,
"text": "Now we can easily perform Univariate and Bivariate Analysis and let us see some of the results obtained:"
},
{
"code": null,
"e": 8379,
"s": 8144,
"text": "Here we will look at the target variable, i.e., Loan_Status, and other categorical features like gender, Marital Status, Employment Status, and Credit history, independently. Likewise, you can play around with different features also."
},
{
"code": null,
"e": 8427,
"s": 8379,
"text": "Most of the applicants in the dataset are male."
},
{
"code": null,
"e": 8518,
"s": 8427,
"text": "Again a majority of the applicants in the dataset are married and have repaid their debts."
},
{
"code": null,
"e": 8607,
"s": 8518,
"text": "Also, most of the applicants have no dependents and are graduates from semi-urban areas."
},
{
"code": null,
"e": 8698,
"s": 8607,
"text": "Now let’s visualize the ordinal variables, i.e., Dependents, Education, and Property Area."
},
{
"code": null,
"e": 8757,
"s": 8698,
"text": "Following inferences can be made from the above bar plots:"
},
{
"code": null,
"e": 8807,
"s": 8757,
"text": "Most of the applicants don’t have any dependents."
},
{
"code": null,
"e": 8845,
"s": 8807,
"text": "Most of the applicants are graduates."
},
{
"code": null,
"e": 8895,
"s": 8845,
"text": "Most of the applicants are from semi-urban areas."
},
{
"code": null,
"e": 8955,
"s": 8895,
"text": "Now you can continue your analysis with the numerical data."
},
{
"code": null,
"e": 9052,
"s": 8955,
"text": "We will find the relationship between the target variable and categorical independent variables."
},
{
"code": null,
"e": 9102,
"s": 9052,
"text": "It can be inferred from the above bar plots that:"
},
{
"code": null,
"e": 9173,
"s": 9102,
"text": "The proportion of married applicants is higher for the approved loans."
},
{
"code": null,
"e": 9284,
"s": 9173,
"text": "The distribution of applicants with one or 3+ dependents is similar across both the categories of Loan_Status."
},
{
"code": null,
"e": 9372,
"s": 9284,
"text": "It seems people with a credit history of 1 are more likely to get their loans approved."
},
{
"code": null,
"e": 9480,
"s": 9372,
"text": "The proportion of loans getting approved in the semiurban area is higher than that in rural or urban areas."
},
{
"code": null,
"e": 9659,
"s": 9480,
"text": "FACETS provides an easy and intuitive environment to perform EDA for datasets and helps us derive meaningful results. The only catch is that currently, it only works with Chrome."
}
] |
Differences between HTML <center> Tag and CSS “text-align: center;” Property | 18 May, 2021
If you are designing a simple web page, then not much difference is noticeable, but it is very necessary to understand the basic differences between these two. Since we are only concerned with the text, these elements do not have separate meanings.HTML <center> tag: The <center> tag in HTML is used to set to align of text into the center. This tag is not supported in HTML 5. CSS property is used to set the alignment of the element instead of the center tag in HTML 5. It is a block-level element that is used to display the text enclosed in the tag in the center horizontally. Most common browsers such as Google Chrome, Mozilla Firefox, Internet Explorer support this tag.
Example: The below code was earlier used in HTML 4 and older versions to align text to the center.htmlhtml<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML center Tag</h2> <p> GeeksforGeeks: A computer science portal for Geeks. </p> </center></body> </html>
html
<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML center Tag</h2> <p> GeeksforGeeks: A computer science portal for Geeks. </p> </center></body> </html>
Output:
CSS “text-align: center;” Property: It is a CSS property used to align the text in the center, which can be used in many components, including tables, buttons, etc.
Example: The implementation of “text-align: center” property is given below:htmlhtml<!DOCTYPE html> <html> <head> <title> text-align: center property </title> <style> h1 { color:green; } </style> </head> <body> <h1 style="text-align:center;"> GeeksforGeeks </h1> <h2 style="text-align:center;"> CSS "text-align:center;" Property </h2> <p style="text-align:center;"> GeeksforGeeks: A computer science portal for Geeks. </p> </body> </html>
html
<!DOCTYPE html> <html> <head> <title> text-align: center property </title> <style> h1 { color:green; } </style> </head> <body> <h1 style="text-align:center;"> GeeksforGeeks </h1> <h2 style="text-align:center;"> CSS "text-align:center;" Property </h2> <p style="text-align:center;"> GeeksforGeeks: A computer science portal for Geeks. </p> </body> </html>
Output:
You can notice both the outputs are the same, but in the case of HTML5 code, we use inline CSS to align our text to the center. In the previous code for HTML4 and older versions, we use specifically the <center> tag.Differences between HTML <center> tag and CSS “text-align: center;” property:
Akanksha_Rai
ghoshsuman0129
CSS-Properties
HTML-Tags
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 707,
"s": 28,
"text": "If you are designing a simple web page, then not much difference is noticeable, but it is very necessary to understand the basic differences between these two. Since we are only concerned with the text, these elements do not have separate meanings.HTML <center> tag: The <center> tag in HTML is used to set to align of text into the center. This tag is not supported in HTML 5. CSS property is used to set the alignment of the element instead of the center tag in HTML 5. It is a block-level element that is used to display the text enclosed in the tag in the center horizontally. Most common browsers such as Google Chrome, Mozilla Firefox, Internet Explorer support this tag. "
},
{
"code": null,
"e": 1120,
"s": 707,
"text": "Example: The below code was earlier used in HTML 4 and older versions to align text to the center.htmlhtml<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML center Tag</h2> <p> GeeksforGeeks: A computer science portal for Geeks. </p> </center></body> </html>"
},
{
"code": null,
"e": 1125,
"s": 1120,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML center Tag</h2> <p> GeeksforGeeks: A computer science portal for Geeks. </p> </center></body> </html>",
"e": 1432,
"s": 1125,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1432,
"text": "Output:"
},
{
"code": null,
"e": 1606,
"s": 1440,
"text": "CSS “text-align: center;” Property: It is a CSS property used to align the text in the center, which can be used in many components, including tables, buttons, etc. "
},
{
"code": null,
"e": 2178,
"s": 1606,
"text": "Example: The implementation of “text-align: center” property is given below:htmlhtml<!DOCTYPE html> <html> <head> <title> text-align: center property </title> <style> h1 { color:green; } </style> </head> <body> <h1 style=\"text-align:center;\"> GeeksforGeeks </h1> <h2 style=\"text-align:center;\"> CSS \"text-align:center;\" Property </h2> <p style=\"text-align:center;\"> GeeksforGeeks: A computer science portal for Geeks. </p> </body> </html> "
},
{
"code": null,
"e": 2183,
"s": 2178,
"text": "html"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> text-align: center property </title> <style> h1 { color:green; } </style> </head> <body> <h1 style=\"text-align:center;\"> GeeksforGeeks </h1> <h2 style=\"text-align:center;\"> CSS \"text-align:center;\" Property </h2> <p style=\"text-align:center;\"> GeeksforGeeks: A computer science portal for Geeks. </p> </body> </html> ",
"e": 2671,
"s": 2183,
"text": null
},
{
"code": null,
"e": 2679,
"s": 2671,
"text": "Output:"
},
{
"code": null,
"e": 2974,
"s": 2679,
"text": "You can notice both the outputs are the same, but in the case of HTML5 code, we use inline CSS to align our text to the center. In the previous code for HTML4 and older versions, we use specifically the <center> tag.Differences between HTML <center> tag and CSS “text-align: center;” property: "
},
{
"code": null,
"e": 2987,
"s": 2974,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3002,
"s": 2987,
"text": "ghoshsuman0129"
},
{
"code": null,
"e": 3017,
"s": 3002,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3027,
"s": 3017,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3034,
"s": 3027,
"text": "Picked"
},
{
"code": null,
"e": 3038,
"s": 3034,
"text": "CSS"
},
{
"code": null,
"e": 3043,
"s": 3038,
"text": "HTML"
},
{
"code": null,
"e": 3060,
"s": 3043,
"text": "Web Technologies"
},
{
"code": null,
"e": 3087,
"s": 3060,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3092,
"s": 3087,
"text": "HTML"
},
{
"code": null,
"e": 3190,
"s": 3092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3227,
"s": 3190,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3266,
"s": 3227,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3305,
"s": 3266,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3369,
"s": 3305,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 3430,
"s": 3369,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3454,
"s": 3430,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3507,
"s": 3454,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3567,
"s": 3507,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3628,
"s": 3567,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Function Arguments in R Programming | 01 Jun, 2020
Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R. In this article, we’ll discuss different ways of adding arguments in a function in R programming.
We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis. Below is an implementation of a function with a single argument.
Example:
# Function definition# To check n is divisible by 5 or notdivisbleBy5 <- function(n){ if(n %% 5 == 0) { return("number is divisible by 5") } else { return("number is not divisible by 5") }} # Function calldivisbleBy5(100)divisbleBy5(4)divisbleBy5(20.0)
Output:
[1] "number is divisible by 5"
[1] "number is not divisible by 5"
[1] "number is divisible by 5"
A function in R programming can have multiple arguments too. Below is an implementation of a function with multiple arguments.
Example:
# Function definition# To check a is divisible by b or notdivisible <- function(a, b){ if(a %% b == 0) { return(paste(a, "is divisible by", b)) } else { return(paste(a, "is not divisible by", b)) }} # Function calldivisible(7, 3)divisible(36, 6)divisible(9, 2)
Output:
[1] "7 is not divisible by 3"
[1] "36 is divisible by 6"
[1] "9 is not divisible by 2"
Default value in a function is a value that is not required to specify each time the function is called. If the value is passed by the user, then the user-defined value is used by the function otherwise, the default value is used. Below is an implementation of function with default value.
Example:
# Function definition to check # a is divisible by b or not. # If b is not provided in function call,# Then divisibility of a is checked with 3 as defaultdivisible <- function(a, b = 3){ if(a %% b == 0) { return(paste(a, "is divisible by", b)) } else { return(paste(a, "is not divisible by", b)) }} # Function calldivisible(10, 5)divisible(12)
Output:
[1] "10 is divisible by 5"
[1] "12 is divisible by 3"
Dots argument (...) is also known as ellipsis which allows the function to take an undefined number of arguments. It allows the function to take an arbitrary number of arguments. Below is an example of a function with an arbitrary number of arguments.
Example:
# Function definition of dots operatorfun <- function(n, ...){ l <- list(n, ...) paste(l, collapse = " ")} # Function callfun(5, 1L, 6i, TRUE, "GeeksForGeeks", "Dots operator")
Output:
[1] "5 1 0+6i TRUE GeeksForGeeks Dots operator"
In R programming, functions can be passed to another functions as arguments. Below is an implementation of function as an argument.
Example:
# Function definition# Function is passed as argumentfun <- function(x, fun2){ return(fun2(x))} # sum is built-in functionfun(c(1:10), sum) # mean is built-in functionfun(rnorm(50), mean)
Output:
[1] 55
[1] 0.2153183
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 380,
"s": 28,
"text": "Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R. In this article, we’ll discuss different ways of adding arguments in a function in R programming."
},
{
"code": null,
"e": 576,
"s": 380,
"text": "We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis. Below is an implementation of a function with a single argument."
},
{
"code": null,
"e": 585,
"s": 576,
"text": "Example:"
},
{
"code": "# Function definition# To check n is divisible by 5 or notdivisbleBy5 <- function(n){ if(n %% 5 == 0) { return(\"number is divisible by 5\") } else { return(\"number is not divisible by 5\") }} # Function calldivisbleBy5(100)divisbleBy5(4)divisbleBy5(20.0)",
"e": 853,
"s": 585,
"text": null
},
{
"code": null,
"e": 861,
"s": 853,
"text": "Output:"
},
{
"code": null,
"e": 959,
"s": 861,
"text": "[1] \"number is divisible by 5\"\n[1] \"number is not divisible by 5\"\n[1] \"number is divisible by 5\"\n"
},
{
"code": null,
"e": 1086,
"s": 959,
"text": "A function in R programming can have multiple arguments too. Below is an implementation of a function with multiple arguments."
},
{
"code": null,
"e": 1095,
"s": 1086,
"text": "Example:"
},
{
"code": "# Function definition# To check a is divisible by b or notdivisible <- function(a, b){ if(a %% b == 0) { return(paste(a, \"is divisible by\", b)) } else { return(paste(a, \"is not divisible by\", b)) }} # Function calldivisible(7, 3)divisible(36, 6)divisible(9, 2)",
"e": 1370,
"s": 1095,
"text": null
},
{
"code": null,
"e": 1379,
"s": 1370,
"text": " Output:"
},
{
"code": null,
"e": 1467,
"s": 1379,
"text": "[1] \"7 is not divisible by 3\"\n[1] \"36 is divisible by 6\"\n[1] \"9 is not divisible by 2\"\n"
},
{
"code": null,
"e": 1757,
"s": 1467,
"text": "Default value in a function is a value that is not required to specify each time the function is called. If the value is passed by the user, then the user-defined value is used by the function otherwise, the default value is used. Below is an implementation of function with default value."
},
{
"code": null,
"e": 1766,
"s": 1757,
"text": "Example:"
},
{
"code": "# Function definition to check # a is divisible by b or not. # If b is not provided in function call,# Then divisibility of a is checked with 3 as defaultdivisible <- function(a, b = 3){ if(a %% b == 0) { return(paste(a, \"is divisible by\", b)) } else { return(paste(a, \"is not divisible by\", b)) }} # Function calldivisible(10, 5)divisible(12)",
"e": 2124,
"s": 1766,
"text": null
},
{
"code": null,
"e": 2132,
"s": 2124,
"text": "Output:"
},
{
"code": null,
"e": 2187,
"s": 2132,
"text": "[1] \"10 is divisible by 5\"\n[1] \"12 is divisible by 3\"\n"
},
{
"code": null,
"e": 2439,
"s": 2187,
"text": "Dots argument (...) is also known as ellipsis which allows the function to take an undefined number of arguments. It allows the function to take an arbitrary number of arguments. Below is an example of a function with an arbitrary number of arguments."
},
{
"code": null,
"e": 2448,
"s": 2439,
"text": "Example:"
},
{
"code": "# Function definition of dots operatorfun <- function(n, ...){ l <- list(n, ...) paste(l, collapse = \" \")} # Function callfun(5, 1L, 6i, TRUE, \"GeeksForGeeks\", \"Dots operator\")",
"e": 2629,
"s": 2448,
"text": null
},
{
"code": null,
"e": 2637,
"s": 2629,
"text": "Output:"
},
{
"code": null,
"e": 2686,
"s": 2637,
"text": "[1] \"5 1 0+6i TRUE GeeksForGeeks Dots operator\"\n"
},
{
"code": null,
"e": 2818,
"s": 2686,
"text": "In R programming, functions can be passed to another functions as arguments. Below is an implementation of function as an argument."
},
{
"code": null,
"e": 2827,
"s": 2818,
"text": "Example:"
},
{
"code": "# Function definition# Function is passed as argumentfun <- function(x, fun2){ return(fun2(x))} # sum is built-in functionfun(c(1:10), sum) # mean is built-in functionfun(rnorm(50), mean)",
"e": 3018,
"s": 2827,
"text": null
},
{
"code": null,
"e": 3026,
"s": 3018,
"text": "Output:"
},
{
"code": null,
"e": 3048,
"s": 3026,
"text": "[1] 55\n[1] 0.2153183\n"
},
{
"code": null,
"e": 3055,
"s": 3048,
"text": "Picked"
},
{
"code": null,
"e": 3066,
"s": 3055,
"text": "R Language"
}
] |
Python | Ways to convert hex into binary | 29 Jun, 2019
Conversion of hex to binary is a very common programming question. In this article, we will see a few methods to solve the above problem.
Method #1: Using bin and zfill
# Python code to demonstrate # conversion of a hex string# to the binary string # Initialising hex stringini_string = "1a"scale = 16 # Printing initial stringprint ("Initial string", ini_string) # Code to convert hex to binaryres = bin(int(ini_string, scale)).zfill(8) # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial string 1aResultant string 00b11010
Method #2: Using Naive Method
# Python code to demonstrate # conversion of hex string# to binary string import math # Initialising hex stringini_string = "1a" # Printing initial stringprint ("Initial string", ini_string) # Code to convert hex to binaryn = int(ini_string, 16) bStr = ''while n > 0: bStr = str(n % 2) + bStr n = n >> 1 res = bStr # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial string 1aResultant string 11010
Method #3: Using .format
# Python code to demonstrate # conversion of hex string# to binary string import math # Initialising hex stringini_string = "1a" # Printing initial stringprint ("Initial string", ini_string) # Code to convert hex to binaryres = "{0:08b}".format(int(ini_string, 16)) # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial string 1aResultant string 00011010
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jun, 2019"
},
{
"code": null,
"e": 191,
"s": 53,
"text": "Conversion of hex to binary is a very common programming question. In this article, we will see a few methods to solve the above problem."
},
{
"code": null,
"e": 222,
"s": 191,
"text": "Method #1: Using bin and zfill"
},
{
"code": "# Python code to demonstrate # conversion of a hex string# to the binary string # Initialising hex stringini_string = \"1a\"scale = 16 # Printing initial stringprint (\"Initial string\", ini_string) # Code to convert hex to binaryres = bin(int(ini_string, scale)).zfill(8) # Print the resultant stringprint (\"Resultant string\", str(res))",
"e": 560,
"s": 222,
"text": null
},
{
"code": null,
"e": 568,
"s": 560,
"text": "Output:"
},
{
"code": null,
"e": 611,
"s": 568,
"text": "Initial string 1aResultant string 00b11010"
},
{
"code": null,
"e": 642,
"s": 611,
"text": " Method #2: Using Naive Method"
},
{
"code": "# Python code to demonstrate # conversion of hex string# to binary string import math # Initialising hex stringini_string = \"1a\" # Printing initial stringprint (\"Initial string\", ini_string) # Code to convert hex to binaryn = int(ini_string, 16) bStr = ''while n > 0: bStr = str(n % 2) + bStr n = n >> 1 res = bStr # Print the resultant stringprint (\"Resultant string\", str(res))",
"e": 1036,
"s": 642,
"text": null
},
{
"code": null,
"e": 1044,
"s": 1036,
"text": "Output:"
},
{
"code": null,
"e": 1084,
"s": 1044,
"text": "Initial string 1aResultant string 11010"
},
{
"code": null,
"e": 1110,
"s": 1084,
"text": " Method #3: Using .format"
},
{
"code": "# Python code to demonstrate # conversion of hex string# to binary string import math # Initialising hex stringini_string = \"1a\" # Printing initial stringprint (\"Initial string\", ini_string) # Code to convert hex to binaryres = \"{0:08b}\".format(int(ini_string, 16)) # Print the resultant stringprint (\"Resultant string\", str(res))",
"e": 1446,
"s": 1110,
"text": null
},
{
"code": null,
"e": 1454,
"s": 1446,
"text": "Output:"
},
{
"code": null,
"e": 1497,
"s": 1454,
"text": "Initial string 1aResultant string 00011010"
},
{
"code": null,
"e": 1504,
"s": 1497,
"text": "Python"
},
{
"code": null,
"e": 1520,
"s": 1504,
"text": "Python Programs"
}
] |
Formatted I/O in C++ | 24 Oct, 2019
C++ helps you to format the I/O operations like determining the number of digits to be displayed after the decimal point, specifying number base etc.
Example:
If we want to add + sign as the prefix of out output, we can use the formatting to do so:stream.setf(ios::showpos)
If input=100, output will be +100
stream.setf(ios::showpos)
If input=100, output will be +100
If we want to add trailing zeros in out output to be shown when needed using the formatting:stream.setf(ios::showpoint)
If input=100.0, output will be 100.000
stream.setf(ios::showpoint)
If input=100.0, output will be 100.000
Note: Here, stream is referred to the streams defined in c++ like cin, cout, cerr, clog.
There are two ways to do so:
Using the ios class or various ios member functions.Using manipulators(special functions)
Using the ios class or various ios member functions.
Using manipulators(special functions)
Formatting using the ios members:The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags.Few standard ios class functions are:width(): The width method is used to set the required field width. The output will be displayed in the given widthprecision(): The precision method is used to set the number of the decimal point to a float valuefill(): The fill method is used to set a character to fill in the blank space of a fieldsetf(): The setf method is used to set various flags for formatting outputunsetf(): The unsetf method is used To remove the flag settingWorking:#include<bits/stdc++.h>using namespace std; // The width() function defines width // of the next value to be displayed // in the output at the console.void IOS_width(){ cout << "--------------------------\n"; cout << "Implementing ios::width\n\n"; char c = 'A'; // Adjusting width will be 5. cout.width(5); cout << c <<"\n"; int temp = 10; // Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. cout<<temp; cout << "\n--------------------------\n";} void IOS_precision(){ cout << "\n--------------------------\n"; cout << "Implementing ios::precision\n\n"; cout << "Implementing ios::width"; cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout<<3.1422; cout << "\n--------------------------\n";} // The fill() function fills the unused // white spaces in a value (to be printed// at the console), with a character of choice.void IOS_fill(){ cout << "\n--------------------------\n"; cout << "Implementing ios::fill\n\n"; char ch = 'a'; // Calling the fill function to fill // the white spaces in a value with a // character our of choice. cout.fill('*'); cout.width(10); cout<<ch <<"\n"; int i = 1; // Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. cout.width(5); cout<<i; cout << "\n--------------------------\n";} void IOS_setf(){ cout << "\n--------------------------\n"; cout << "Implementing ios::setf\n\n"; int val1=100,val2=200; cout.setf(ios::showpos); cout<<val1<<" "<<val2; cout << "\n--------------------------\n";} void IOS_unsetf(){ cout << "\n--------------------------\n"; cout << "Implementing ios::unsetf\n\n"; cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag cout.unsetf(ios::showpos); cout<<200.0; cout << "\n--------------------------\n";} // Driver Methodint main(){ IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); return 0;} Output:--------------------------
Implementing ios::width
A
10
--------------------------
--------------------------
Implementing ios::fill
*********a
****1
--------------------------
--------------------------
Implementing ios::setf
+100 +200
--------------------------
--------------------------
Implementing ios::unsetf
200.000
--------------------------
Formatting using ManipulatorsThe second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression.The standard manipulators are shown below:boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flagdec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flagendl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.and: The and manipulator of stream manipulators in C++ is used to Flush the streamends: The ends manipulator of stream manipulators in C++ is used to Output a nullfixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flagflush: The flush manipulator of stream manipulators in C++ is used to Flush a streamhex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flaginternal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flagleft: The left manipulator of stream manipulators in C++ is used to Turns on the left flagnoboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flagnoshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flagnoshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flagnoshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flagnoskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flagnounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flagnouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flagoct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flagresetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in fright: The right manipulator of stream manipulators in C++ is used to Turns on the right flagscientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flagsetbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to basesetfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to chsetiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in fsetprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precisionsetw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to wshowbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flagshowpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flagshowpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flagskipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flagunitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flaguppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flagws: The ws manipulator of stream manipulators in C++ is used to skip leading white spaceTo access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program.Example:#include <iomanip>#include <iostream>using namespace std; void Example(){ // performs ssame as setf( ) cout << setiosflags(ios::showpos); cout << 123<<"\n"; // hexadecimal base (i.e., radix 16) cout << hex << 100 << endl; // Set the field width cout << setfill('*') << setw(10) << 2343.0; } int main(){ Example(); return 0;}Output:+123
64
*****+2343
The manipulator setiosflags( ) .
Formatting using the ios members:The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags.Few standard ios class functions are:width(): The width method is used to set the required field width. The output will be displayed in the given widthprecision(): The precision method is used to set the number of the decimal point to a float valuefill(): The fill method is used to set a character to fill in the blank space of a fieldsetf(): The setf method is used to set various flags for formatting outputunsetf(): The unsetf method is used To remove the flag settingWorking:#include<bits/stdc++.h>using namespace std; // The width() function defines width // of the next value to be displayed // in the output at the console.void IOS_width(){ cout << "--------------------------\n"; cout << "Implementing ios::width\n\n"; char c = 'A'; // Adjusting width will be 5. cout.width(5); cout << c <<"\n"; int temp = 10; // Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. cout<<temp; cout << "\n--------------------------\n";} void IOS_precision(){ cout << "\n--------------------------\n"; cout << "Implementing ios::precision\n\n"; cout << "Implementing ios::width"; cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout<<3.1422; cout << "\n--------------------------\n";} // The fill() function fills the unused // white spaces in a value (to be printed// at the console), with a character of choice.void IOS_fill(){ cout << "\n--------------------------\n"; cout << "Implementing ios::fill\n\n"; char ch = 'a'; // Calling the fill function to fill // the white spaces in a value with a // character our of choice. cout.fill('*'); cout.width(10); cout<<ch <<"\n"; int i = 1; // Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. cout.width(5); cout<<i; cout << "\n--------------------------\n";} void IOS_setf(){ cout << "\n--------------------------\n"; cout << "Implementing ios::setf\n\n"; int val1=100,val2=200; cout.setf(ios::showpos); cout<<val1<<" "<<val2; cout << "\n--------------------------\n";} void IOS_unsetf(){ cout << "\n--------------------------\n"; cout << "Implementing ios::unsetf\n\n"; cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag cout.unsetf(ios::showpos); cout<<200.0; cout << "\n--------------------------\n";} // Driver Methodint main(){ IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); return 0;} Output:--------------------------
Implementing ios::width
A
10
--------------------------
--------------------------
Implementing ios::fill
*********a
****1
--------------------------
--------------------------
Implementing ios::setf
+100 +200
--------------------------
--------------------------
Implementing ios::unsetf
200.000
--------------------------
The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags.
Few standard ios class functions are:
width(): The width method is used to set the required field width. The output will be displayed in the given widthprecision(): The precision method is used to set the number of the decimal point to a float valuefill(): The fill method is used to set a character to fill in the blank space of a fieldsetf(): The setf method is used to set various flags for formatting outputunsetf(): The unsetf method is used To remove the flag setting
width(): The width method is used to set the required field width. The output will be displayed in the given width
precision(): The precision method is used to set the number of the decimal point to a float value
fill(): The fill method is used to set a character to fill in the blank space of a field
setf(): The setf method is used to set various flags for formatting output
unsetf(): The unsetf method is used To remove the flag setting
Working:
#include<bits/stdc++.h>using namespace std; // The width() function defines width // of the next value to be displayed // in the output at the console.void IOS_width(){ cout << "--------------------------\n"; cout << "Implementing ios::width\n\n"; char c = 'A'; // Adjusting width will be 5. cout.width(5); cout << c <<"\n"; int temp = 10; // Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. cout<<temp; cout << "\n--------------------------\n";} void IOS_precision(){ cout << "\n--------------------------\n"; cout << "Implementing ios::precision\n\n"; cout << "Implementing ios::width"; cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout<<3.1422; cout << "\n--------------------------\n";} // The fill() function fills the unused // white spaces in a value (to be printed// at the console), with a character of choice.void IOS_fill(){ cout << "\n--------------------------\n"; cout << "Implementing ios::fill\n\n"; char ch = 'a'; // Calling the fill function to fill // the white spaces in a value with a // character our of choice. cout.fill('*'); cout.width(10); cout<<ch <<"\n"; int i = 1; // Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. cout.width(5); cout<<i; cout << "\n--------------------------\n";} void IOS_setf(){ cout << "\n--------------------------\n"; cout << "Implementing ios::setf\n\n"; int val1=100,val2=200; cout.setf(ios::showpos); cout<<val1<<" "<<val2; cout << "\n--------------------------\n";} void IOS_unsetf(){ cout << "\n--------------------------\n"; cout << "Implementing ios::unsetf\n\n"; cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag cout.unsetf(ios::showpos); cout<<200.0; cout << "\n--------------------------\n";} // Driver Methodint main(){ IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); return 0;}
--------------------------
Implementing ios::width
A
10
--------------------------
--------------------------
Implementing ios::fill
*********a
****1
--------------------------
--------------------------
Implementing ios::setf
+100 +200
--------------------------
--------------------------
Implementing ios::unsetf
200.000
--------------------------
Formatting using ManipulatorsThe second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression.The standard manipulators are shown below:boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flagdec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flagendl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.and: The and manipulator of stream manipulators in C++ is used to Flush the streamends: The ends manipulator of stream manipulators in C++ is used to Output a nullfixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flagflush: The flush manipulator of stream manipulators in C++ is used to Flush a streamhex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flaginternal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flagleft: The left manipulator of stream manipulators in C++ is used to Turns on the left flagnoboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flagnoshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flagnoshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flagnoshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flagnoskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flagnounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flagnouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flagoct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flagresetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in fright: The right manipulator of stream manipulators in C++ is used to Turns on the right flagscientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flagsetbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to basesetfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to chsetiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in fsetprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precisionsetw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to wshowbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flagshowpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flagshowpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flagskipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flagunitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flaguppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flagws: The ws manipulator of stream manipulators in C++ is used to skip leading white spaceTo access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program.Example:#include <iomanip>#include <iostream>using namespace std; void Example(){ // performs ssame as setf( ) cout << setiosflags(ios::showpos); cout << 123<<"\n"; // hexadecimal base (i.e., radix 16) cout << hex << 100 << endl; // Set the field width cout << setfill('*') << setw(10) << 2343.0; } int main(){ Example(); return 0;}Output:+123
64
*****+2343
The manipulator setiosflags( ) .
boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flagdec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flagendl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.and: The and manipulator of stream manipulators in C++ is used to Flush the streamends: The ends manipulator of stream manipulators in C++ is used to Output a nullfixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flagflush: The flush manipulator of stream manipulators in C++ is used to Flush a streamhex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flaginternal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flagleft: The left manipulator of stream manipulators in C++ is used to Turns on the left flagnoboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flagnoshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flagnoshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flagnoshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flagnoskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flagnounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flagnouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flagoct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flagresetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in fright: The right manipulator of stream manipulators in C++ is used to Turns on the right flagscientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flagsetbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to basesetfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to chsetiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in fsetprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precisionsetw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to wshowbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flagshowpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flagshowpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flagskipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flagunitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flaguppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flagws: The ws manipulator of stream manipulators in C++ is used to skip leading white space
boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flag
dec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flag
endl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.
and: The and manipulator of stream manipulators in C++ is used to Flush the stream
ends: The ends manipulator of stream manipulators in C++ is used to Output a null
fixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flag
flush: The flush manipulator of stream manipulators in C++ is used to Flush a stream
hex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flag
internal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flag
left: The left manipulator of stream manipulators in C++ is used to Turns on the left flag
noboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flag
noshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flag
noshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flag
noshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flag
noskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flag
nounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flag
nouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flag
oct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flag
resetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in f
right: The right manipulator of stream manipulators in C++ is used to Turns on the right flag
scientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flag
setbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to base
setfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to ch
setiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in f
setprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precision
setw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to w
showbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flag
showpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flag
showpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flag
skipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flag
unitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flag
uppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flag
ws: The ws manipulator of stream manipulators in C++ is used to skip leading white space
To access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program.
Example:
#include <iomanip>#include <iostream>using namespace std; void Example(){ // performs ssame as setf( ) cout << setiosflags(ios::showpos); cout << 123<<"\n"; // hexadecimal base (i.e., radix 16) cout << hex << 100 << endl; // Set the field width cout << setfill('*') << setw(10) << 2343.0; } int main(){ Example(); return 0;}
+123
64
*****+2343
The manipulator setiosflags( ) .
Akanksha_Rai
cpp-input-output
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Oct, 2019"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "C++ helps you to format the I/O operations like determining the number of digits to be displayed after the decimal point, specifying number base etc."
},
{
"code": null,
"e": 211,
"s": 202,
"text": "Example:"
},
{
"code": null,
"e": 363,
"s": 211,
"text": "If we want to add + sign as the prefix of out output, we can use the formatting to do so:stream.setf(ios::showpos) \nIf input=100, output will be +100 "
},
{
"code": null,
"e": 426,
"s": 363,
"text": "stream.setf(ios::showpos) \nIf input=100, output will be +100 "
},
{
"code": null,
"e": 586,
"s": 426,
"text": "If we want to add trailing zeros in out output to be shown when needed using the formatting:stream.setf(ios::showpoint) \nIf input=100.0, output will be 100.000"
},
{
"code": null,
"e": 654,
"s": 586,
"text": "stream.setf(ios::showpoint) \nIf input=100.0, output will be 100.000"
},
{
"code": null,
"e": 743,
"s": 654,
"text": "Note: Here, stream is referred to the streams defined in c++ like cin, cout, cerr, clog."
},
{
"code": null,
"e": 772,
"s": 743,
"text": "There are two ways to do so:"
},
{
"code": null,
"e": 862,
"s": 772,
"text": "Using the ios class or various ios member functions.Using manipulators(special functions)"
},
{
"code": null,
"e": 915,
"s": 862,
"text": "Using the ios class or various ios member functions."
},
{
"code": null,
"e": 953,
"s": 915,
"text": "Using manipulators(special functions)"
},
{
"code": null,
"e": 8488,
"s": 953,
"text": "Formatting using the ios members:The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags.Few standard ios class functions are:width(): The width method is used to set the required field width. The output will be displayed in the given widthprecision(): The precision method is used to set the number of the decimal point to a float valuefill(): The fill method is used to set a character to fill in the blank space of a fieldsetf(): The setf method is used to set various flags for formatting outputunsetf(): The unsetf method is used To remove the flag settingWorking:#include<bits/stdc++.h>using namespace std; // The width() function defines width // of the next value to be displayed // in the output at the console.void IOS_width(){ cout << \"--------------------------\\n\"; cout << \"Implementing ios::width\\n\\n\"; char c = 'A'; // Adjusting width will be 5. cout.width(5); cout << c <<\"\\n\"; int temp = 10; // Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. cout<<temp; cout << \"\\n--------------------------\\n\";} void IOS_precision(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::precision\\n\\n\"; cout << \"Implementing ios::width\"; cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout<<3.1422; cout << \"\\n--------------------------\\n\";} // The fill() function fills the unused // white spaces in a value (to be printed// at the console), with a character of choice.void IOS_fill(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::fill\\n\\n\"; char ch = 'a'; // Calling the fill function to fill // the white spaces in a value with a // character our of choice. cout.fill('*'); cout.width(10); cout<<ch <<\"\\n\"; int i = 1; // Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. cout.width(5); cout<<i; cout << \"\\n--------------------------\\n\";} void IOS_setf(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::setf\\n\\n\"; int val1=100,val2=200; cout.setf(ios::showpos); cout<<val1<<\" \"<<val2; cout << \"\\n--------------------------\\n\";} void IOS_unsetf(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::unsetf\\n\\n\"; cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag cout.unsetf(ios::showpos); cout<<200.0; cout << \"\\n--------------------------\\n\";} // Driver Methodint main(){ IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); return 0;} Output:--------------------------\nImplementing ios::width\n\n A\n10\n--------------------------\n\n--------------------------\nImplementing ios::fill\n\n*********a\n****1\n--------------------------\n\n--------------------------\nImplementing ios::setf\n\n+100 +200\n--------------------------\n\n--------------------------\nImplementing ios::unsetf\n\n200.000\n--------------------------\nFormatting using ManipulatorsThe second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression.The standard manipulators are shown below:boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flagdec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flagendl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.and: The and manipulator of stream manipulators in C++ is used to Flush the streamends: The ends manipulator of stream manipulators in C++ is used to Output a nullfixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flagflush: The flush manipulator of stream manipulators in C++ is used to Flush a streamhex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flaginternal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flagleft: The left manipulator of stream manipulators in C++ is used to Turns on the left flagnoboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flagnoshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flagnoshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flagnoshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flagnoskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flagnounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flagnouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flagoct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flagresetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in fright: The right manipulator of stream manipulators in C++ is used to Turns on the right flagscientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flagsetbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to basesetfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to chsetiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in fsetprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precisionsetw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to wshowbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flagshowpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flagshowpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flagskipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flagunitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flaguppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flagws: The ws manipulator of stream manipulators in C++ is used to skip leading white spaceTo access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program.Example:#include <iomanip>#include <iostream>using namespace std; void Example(){ // performs ssame as setf( ) cout << setiosflags(ios::showpos); cout << 123<<\"\\n\"; // hexadecimal base (i.e., radix 16) cout << hex << 100 << endl; // Set the field width cout << setfill('*') << setw(10) << 2343.0; } int main(){ Example(); return 0;}Output:+123\n64\n*****+2343\nThe manipulator setiosflags( ) ."
},
{
"code": null,
"e": 11956,
"s": 8488,
"text": "Formatting using the ios members:The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags.Few standard ios class functions are:width(): The width method is used to set the required field width. The output will be displayed in the given widthprecision(): The precision method is used to set the number of the decimal point to a float valuefill(): The fill method is used to set a character to fill in the blank space of a fieldsetf(): The setf method is used to set various flags for formatting outputunsetf(): The unsetf method is used To remove the flag settingWorking:#include<bits/stdc++.h>using namespace std; // The width() function defines width // of the next value to be displayed // in the output at the console.void IOS_width(){ cout << \"--------------------------\\n\"; cout << \"Implementing ios::width\\n\\n\"; char c = 'A'; // Adjusting width will be 5. cout.width(5); cout << c <<\"\\n\"; int temp = 10; // Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. cout<<temp; cout << \"\\n--------------------------\\n\";} void IOS_precision(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::precision\\n\\n\"; cout << \"Implementing ios::width\"; cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout<<3.1422; cout << \"\\n--------------------------\\n\";} // The fill() function fills the unused // white spaces in a value (to be printed// at the console), with a character of choice.void IOS_fill(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::fill\\n\\n\"; char ch = 'a'; // Calling the fill function to fill // the white spaces in a value with a // character our of choice. cout.fill('*'); cout.width(10); cout<<ch <<\"\\n\"; int i = 1; // Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. cout.width(5); cout<<i; cout << \"\\n--------------------------\\n\";} void IOS_setf(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::setf\\n\\n\"; int val1=100,val2=200; cout.setf(ios::showpos); cout<<val1<<\" \"<<val2; cout << \"\\n--------------------------\\n\";} void IOS_unsetf(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::unsetf\\n\\n\"; cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag cout.unsetf(ios::showpos); cout<<200.0; cout << \"\\n--------------------------\\n\";} // Driver Methodint main(){ IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); return 0;} Output:--------------------------\nImplementing ios::width\n\n A\n10\n--------------------------\n\n--------------------------\nImplementing ios::fill\n\n*********a\n****1\n--------------------------\n\n--------------------------\nImplementing ios::setf\n\n+100 +200\n--------------------------\n\n--------------------------\nImplementing ios::unsetf\n\n200.000\n--------------------------\n"
},
{
"code": null,
"e": 12323,
"s": 11956,
"text": "The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format. The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags."
},
{
"code": null,
"e": 12361,
"s": 12323,
"text": "Few standard ios class functions are:"
},
{
"code": null,
"e": 12797,
"s": 12361,
"text": "width(): The width method is used to set the required field width. The output will be displayed in the given widthprecision(): The precision method is used to set the number of the decimal point to a float valuefill(): The fill method is used to set a character to fill in the blank space of a fieldsetf(): The setf method is used to set various flags for formatting outputunsetf(): The unsetf method is used To remove the flag setting"
},
{
"code": null,
"e": 12912,
"s": 12797,
"text": "width(): The width method is used to set the required field width. The output will be displayed in the given width"
},
{
"code": null,
"e": 13010,
"s": 12912,
"text": "precision(): The precision method is used to set the number of the decimal point to a float value"
},
{
"code": null,
"e": 13099,
"s": 13010,
"text": "fill(): The fill method is used to set a character to fill in the blank space of a field"
},
{
"code": null,
"e": 13174,
"s": 13099,
"text": "setf(): The setf method is used to set various flags for formatting output"
},
{
"code": null,
"e": 13237,
"s": 13174,
"text": "unsetf(): The unsetf method is used To remove the flag setting"
},
{
"code": null,
"e": 13246,
"s": 13237,
"text": "Working:"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // The width() function defines width // of the next value to be displayed // in the output at the console.void IOS_width(){ cout << \"--------------------------\\n\"; cout << \"Implementing ios::width\\n\\n\"; char c = 'A'; // Adjusting width will be 5. cout.width(5); cout << c <<\"\\n\"; int temp = 10; // Width of the next value to be // displayed in the output will // not be adjusted to 5 columns. cout<<temp; cout << \"\\n--------------------------\\n\";} void IOS_precision(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::precision\\n\\n\"; cout << \"Implementing ios::width\"; cout.setf(ios::fixed, ios::floatfield); cout.precision(2); cout<<3.1422; cout << \"\\n--------------------------\\n\";} // The fill() function fills the unused // white spaces in a value (to be printed// at the console), with a character of choice.void IOS_fill(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::fill\\n\\n\"; char ch = 'a'; // Calling the fill function to fill // the white spaces in a value with a // character our of choice. cout.fill('*'); cout.width(10); cout<<ch <<\"\\n\"; int i = 1; // Once you call the fill() function, // you don't have to call it again to // fill the white space in a value with // the same character. cout.width(5); cout<<i; cout << \"\\n--------------------------\\n\";} void IOS_setf(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::setf\\n\\n\"; int val1=100,val2=200; cout.setf(ios::showpos); cout<<val1<<\" \"<<val2; cout << \"\\n--------------------------\\n\";} void IOS_unsetf(){ cout << \"\\n--------------------------\\n\"; cout << \"Implementing ios::unsetf\\n\\n\"; cout.setf(ios::showpos|ios::showpoint); // Clear the showflag flag without // affecting the showpoint flag cout.unsetf(ios::showpos); cout<<200.0; cout << \"\\n--------------------------\\n\";} // Driver Methodint main(){ IOS_width(); IOS_precision; IOS_fill(); IOS_setf(); IOS_unsetf(); return 0;} ",
"e": 15466,
"s": 13246,
"text": null
},
{
"code": null,
"e": 15829,
"s": 15466,
"text": "--------------------------\nImplementing ios::width\n\n A\n10\n--------------------------\n\n--------------------------\nImplementing ios::fill\n\n*********a\n****1\n--------------------------\n\n--------------------------\nImplementing ios::setf\n\n+100 +200\n--------------------------\n\n--------------------------\nImplementing ios::unsetf\n\n200.000\n--------------------------\n"
},
{
"code": null,
"e": 19897,
"s": 15829,
"text": "Formatting using ManipulatorsThe second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression.The standard manipulators are shown below:boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flagdec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flagendl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.and: The and manipulator of stream manipulators in C++ is used to Flush the streamends: The ends manipulator of stream manipulators in C++ is used to Output a nullfixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flagflush: The flush manipulator of stream manipulators in C++ is used to Flush a streamhex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flaginternal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flagleft: The left manipulator of stream manipulators in C++ is used to Turns on the left flagnoboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flagnoshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flagnoshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flagnoshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flagnoskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flagnounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flagnouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flagoct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flagresetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in fright: The right manipulator of stream manipulators in C++ is used to Turns on the right flagscientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flagsetbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to basesetfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to chsetiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in fsetprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precisionsetw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to wshowbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flagshowpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flagshowpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flagskipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flagunitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flaguppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flagws: The ws manipulator of stream manipulators in C++ is used to skip leading white spaceTo access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program.Example:#include <iomanip>#include <iostream>using namespace std; void Example(){ // performs ssame as setf( ) cout << setiosflags(ios::showpos); cout << 123<<\"\\n\"; // hexadecimal base (i.e., radix 16) cout << hex << 100 << endl; // Set the field width cout << setfill('*') << setw(10) << 2343.0; } int main(){ Example(); return 0;}Output:+123\n64\n*****+2343\nThe manipulator setiosflags( ) ."
},
{
"code": null,
"e": 23179,
"s": 19897,
"text": "boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flagdec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flagendl: The endl manipulator of stream manipulators in C++ is used to Output a newline character.and: The and manipulator of stream manipulators in C++ is used to Flush the streamends: The ends manipulator of stream manipulators in C++ is used to Output a nullfixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flagflush: The flush manipulator of stream manipulators in C++ is used to Flush a streamhex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flaginternal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flagleft: The left manipulator of stream manipulators in C++ is used to Turns on the left flagnoboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flagnoshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flagnoshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flagnoshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flagnoskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flagnounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flagnouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flagoct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flagresetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in fright: The right manipulator of stream manipulators in C++ is used to Turns on the right flagscientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flagsetbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to basesetfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to chsetiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in fsetprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precisionsetw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to wshowbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flagshowpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flagshowpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flagskipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flagunitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flaguppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flagws: The ws manipulator of stream manipulators in C++ is used to skip leading white space"
},
{
"code": null,
"e": 23281,
"s": 23179,
"text": "boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flag"
},
{
"code": null,
"e": 23368,
"s": 23281,
"text": "dec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flag"
},
{
"code": null,
"e": 23464,
"s": 23368,
"text": "endl: The endl manipulator of stream manipulators in C++ is used to Output a newline character."
},
{
"code": null,
"e": 23547,
"s": 23464,
"text": "and: The and manipulator of stream manipulators in C++ is used to Flush the stream"
},
{
"code": null,
"e": 23629,
"s": 23547,
"text": "ends: The ends manipulator of stream manipulators in C++ is used to Output a null"
},
{
"code": null,
"e": 23723,
"s": 23629,
"text": "fixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flag"
},
{
"code": null,
"e": 23808,
"s": 23723,
"text": "flush: The flush manipulator of stream manipulators in C++ is used to Flush a stream"
},
{
"code": null,
"e": 23892,
"s": 23808,
"text": "hex: The hex manipulator of stream manipulators in C++ is used to Turns on hex flag"
},
{
"code": null,
"e": 23991,
"s": 23892,
"text": "internal: The internal manipulator of stream manipulators in C++ is used to Turns on internal flag"
},
{
"code": null,
"e": 24082,
"s": 23991,
"text": "left: The left manipulator of stream manipulators in C++ is used to Turns on the left flag"
},
{
"code": null,
"e": 24190,
"s": 24082,
"text": "noboolalpha: The noboolalpha manipulator of stream manipulators in C++ is used to Turns off bool alpha flag"
},
{
"code": null,
"e": 24294,
"s": 24190,
"text": "noshowbase: The noshowbase manipulator of stream manipulators in C++ is used to Turns off showcase flag"
},
{
"code": null,
"e": 24402,
"s": 24294,
"text": "noshowpoint: The noshowpoint manipulator of stream manipulators in C++ is used to Turns off show point flag"
},
{
"code": null,
"e": 24503,
"s": 24402,
"text": "noshowpos: The noshowpos manipulator of stream manipulators in C++ is used to Turns off showpos flag"
},
{
"code": null,
"e": 24601,
"s": 24503,
"text": "noskipws: The noskipws manipulator of stream manipulators in C++ is used to Turns off skipws flag"
},
{
"code": null,
"e": 24708,
"s": 24601,
"text": "nounitbuf: The nounitbuf manipulator of stream manipulators in C++ is used to Turns off the unit buff flag"
},
{
"code": null,
"e": 24819,
"s": 24708,
"text": "nouppercase: The nouppercase manipulator of stream manipulators in C++ is used to Turns off the uppercase flag"
},
{
"code": null,
"e": 24903,
"s": 24819,
"text": "oct: The oct manipulator of stream manipulators in C++ is used to Turns on oct flag"
},
{
"code": null,
"e": 25035,
"s": 24903,
"text": "resetiosflags(fmtflags f): The resetiosflags manipulator of stream manipulators in C++ is used to Turns off the flag specified in f"
},
{
"code": null,
"e": 25129,
"s": 25035,
"text": "right: The right manipulator of stream manipulators in C++ is used to Turns on the right flag"
},
{
"code": null,
"e": 25234,
"s": 25129,
"text": "scientific: The scientific manipulator of stream manipulators in C++ is used to Turns on scientific flag"
},
{
"code": null,
"e": 25346,
"s": 25234,
"text": "setbase(int base): The setbase manipulator of stream manipulators in C++ is used to Set the number base to base"
},
{
"code": null,
"e": 25457,
"s": 25346,
"text": "setfill(int ch): The setfill manipulator of stream manipulators in C++ is used to Set the fill character to ch"
},
{
"code": null,
"e": 25584,
"s": 25457,
"text": "setiosflags(fmtflags f): The setiosflags manipulator of stream manipulators in C++ is used to Turns on the flag specified in f"
},
{
"code": null,
"e": 25713,
"s": 25584,
"text": "setprecision(int p): The setprecision manipulator of stream manipulators in C++ is used to Set the number of digits of precision"
},
{
"code": null,
"e": 25813,
"s": 25713,
"text": "setw(int w): The setw manipulator of stream manipulators in C++ is used to Set the field width to w"
},
{
"code": null,
"e": 25912,
"s": 25813,
"text": "showbase: The showbase manipulator of stream manipulators in C++ is used to Turns on showbase flag"
},
{
"code": null,
"e": 26015,
"s": 25912,
"text": "showpoint: The showpoint manipulator of stream manipulators in C++ is used to Turns on show point flag"
},
{
"code": null,
"e": 26111,
"s": 26015,
"text": "showpos: The showpos manipulator of stream manipulators in C++ is used to Turns on showpos flag"
},
{
"code": null,
"e": 26204,
"s": 26111,
"text": "skipws: The skipws manipulator of stream manipulators in C++ is used to Turns on skipws flag"
},
{
"code": null,
"e": 26299,
"s": 26204,
"text": "unitbuf: The unitbuf manipulator of stream manipulators in C++ is used to turn on unitbuf flag"
},
{
"code": null,
"e": 26404,
"s": 26299,
"text": "uppercase: The uppercase manipulator of stream manipulators in C++ is used to turn on the uppercase flag"
},
{
"code": null,
"e": 26493,
"s": 26404,
"text": "ws: The ws manipulator of stream manipulators in C++ is used to skip leading white space"
},
{
"code": null,
"e": 26612,
"s": 26493,
"text": "To access manipulators that take parameters (such as setw( )), you must include “iomanip” header file in your program."
},
{
"code": null,
"e": 26621,
"s": 26612,
"text": "Example:"
},
{
"code": "#include <iomanip>#include <iostream>using namespace std; void Example(){ // performs ssame as setf( ) cout << setiosflags(ios::showpos); cout << 123<<\"\\n\"; // hexadecimal base (i.e., radix 16) cout << hex << 100 << endl; // Set the field width cout << setfill('*') << setw(10) << 2343.0; } int main(){ Example(); return 0;}",
"e": 26988,
"s": 26621,
"text": null
},
{
"code": null,
"e": 27008,
"s": 26988,
"text": "+123\n64\n*****+2343\n"
},
{
"code": null,
"e": 27041,
"s": 27008,
"text": "The manipulator setiosflags( ) ."
},
{
"code": null,
"e": 27054,
"s": 27041,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27071,
"s": 27054,
"text": "cpp-input-output"
},
{
"code": null,
"e": 27084,
"s": 27071,
"text": "C++ Programs"
}
] |
Python | Slicing list from Kth element to last element | 28 Jan, 2019
Python list slicing slices the list from start index till end – 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let’s discuss ways in which last element can be included during a list slice.
Method #1 : Using NoneDuring list slicing, giving the desired first index K and specifying ‘None’ as the second argument in slicing works internally as slicing all the elements from K in list till end including it.
# Python3 code to demonstrate # list slicing from K to end# using None # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # index to begin slicingK = 2 # using None # to perform list slicing from K to endres = test_list[K : None] # printing result print ("The sliced list is : " + str(res))
The original list is : [5, 6, 2, 3, 9]
The sliced list is : [2, 3, 9]
Method #2 : Leaving the last element emptyUsually, not specifying any element as end element of slicing instructs python to include whole list after K in list. But the main drawback in using this is code readability. Hence above method is preferred more than this.
# Python3 code to demonstrate # list slicing from K to end# without specifying last element # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # index to begin slicingK = 2 # without specifying last element # to perform list slicing from K to endres = test_list[K :] # printing result print ("The sliced list is : " + str(res))
The original list is : [5, 6, 2, 3, 9]
The sliced list is : [2, 3, 9]
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Python list slicing slices the list from start index till end – 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let’s discuss ways in which last element can be included during a list slice."
},
{
"code": null,
"e": 537,
"s": 322,
"text": "Method #1 : Using NoneDuring list slicing, giving the desired first index K and specifying ‘None’ as the second argument in slicing works internally as slicing all the elements from K in list till end including it."
},
{
"code": "# Python3 code to demonstrate # list slicing from K to end# using None # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # index to begin slicingK = 2 # using None # to perform list slicing from K to endres = test_list[K : None] # printing result print (\"The sliced list is : \" + str(res))",
"e": 905,
"s": 537,
"text": null
},
{
"code": null,
"e": 976,
"s": 905,
"text": "The original list is : [5, 6, 2, 3, 9]\nThe sliced list is : [2, 3, 9]\n"
},
{
"code": null,
"e": 1243,
"s": 978,
"text": "Method #2 : Leaving the last element emptyUsually, not specifying any element as end element of slicing instructs python to include whole list after K in list. But the main drawback in using this is code readability. Hence above method is preferred more than this."
},
{
"code": "# Python3 code to demonstrate # list slicing from K to end# without specifying last element # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # index to begin slicingK = 2 # without specifying last element # to perform list slicing from K to endres = test_list[K :] # printing result print (\"The sliced list is : \" + str(res))",
"e": 1650,
"s": 1243,
"text": null
},
{
"code": null,
"e": 1721,
"s": 1650,
"text": "The original list is : [5, 6, 2, 3, 9]\nThe sliced list is : [2, 3, 9]\n"
},
{
"code": null,
"e": 1742,
"s": 1721,
"text": "Python list-programs"
},
{
"code": null,
"e": 1754,
"s": 1742,
"text": "python-list"
},
{
"code": null,
"e": 1761,
"s": 1754,
"text": "Python"
},
{
"code": null,
"e": 1777,
"s": 1761,
"text": "Python Programs"
},
{
"code": null,
"e": 1789,
"s": 1777,
"text": "python-list"
},
{
"code": null,
"e": 1887,
"s": 1789,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1905,
"s": 1887,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1947,
"s": 1905,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1969,
"s": 1947,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2001,
"s": 1969,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2027,
"s": 2001,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2049,
"s": 2027,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2088,
"s": 2049,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2126,
"s": 2088,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2163,
"s": 2126,
"text": "Python Program for Fibonacci numbers"
}
] |
Difference between die() and exit() functions in PHP | 10 Apr, 2022
PHP exit() Function: In PHP, the exit() function prints a message and exits the application. It’s often used to print a different message in the event of a mistake. Use exit() when there is not an error and have to stop the execution.
Syntax:
exit("Message goes here");
or
exit();
Example:
exit("This request is processed");
Program 1:
PHP
<?php exit ("This is an exit function in php"); echo "This will not printed because " . "we have executed exit function";?>
Output:
This is an exit function in php
Program 2:
PHP
<?php $a = 10; $b = 10.0; if($a == $b) { exit('variables are equal'); } else { exit('variables are not equal'); }?>
Output:
variables are equal
PHP die() Function: In PHP, die() is the same as exit(). A program’s result will be an empty screen. Use die() when there is an error and have to stop the execution.
Syntax:
die("Message goes here");
or
die();
Example:
die('Oops! Something went wrong');
Program:
PHP
<?php $num = 1; // die can only print string values, // hence there will be no output die($num);?>
Output:
No Output
Note: The output for the above program will be an empty screen because it is similar to exit(), die() can print only string values.
Differences between die() and exit() Functions:
die()
exit()
mayank007rawa
PHP-Questions
Picked
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Apr, 2022"
},
{
"code": null,
"e": 263,
"s": 28,
"text": "PHP exit() Function: In PHP, the exit() function prints a message and exits the application. It’s often used to print a different message in the event of a mistake. Use exit() when there is not an error and have to stop the execution."
},
{
"code": null,
"e": 271,
"s": 263,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 271,
"text": "exit(\"Message goes here\");\nor\nexit();"
},
{
"code": null,
"e": 318,
"s": 309,
"text": "Example:"
},
{
"code": null,
"e": 353,
"s": 318,
"text": "exit(\"This request is processed\");"
},
{
"code": null,
"e": 364,
"s": 353,
"text": "Program 1:"
},
{
"code": null,
"e": 368,
"s": 364,
"text": "PHP"
},
{
"code": "<?php exit (\"This is an exit function in php\"); echo \"This will not printed because \" . \"we have executed exit function\";?>",
"e": 499,
"s": 368,
"text": null
},
{
"code": null,
"e": 507,
"s": 499,
"text": "Output:"
},
{
"code": null,
"e": 539,
"s": 507,
"text": "This is an exit function in php"
},
{
"code": null,
"e": 550,
"s": 539,
"text": "Program 2:"
},
{
"code": null,
"e": 554,
"s": 550,
"text": "PHP"
},
{
"code": "<?php $a = 10; $b = 10.0; if($a == $b) { exit('variables are equal'); } else { exit('variables are not equal'); }?>",
"e": 682,
"s": 554,
"text": null
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Output:"
},
{
"code": null,
"e": 710,
"s": 690,
"text": "variables are equal"
},
{
"code": null,
"e": 876,
"s": 710,
"text": "PHP die() Function: In PHP, die() is the same as exit(). A program’s result will be an empty screen. Use die() when there is an error and have to stop the execution."
},
{
"code": null,
"e": 884,
"s": 876,
"text": "Syntax:"
},
{
"code": null,
"e": 922,
"s": 884,
"text": "die(\"Message goes here\"); \nor \ndie();"
},
{
"code": null,
"e": 931,
"s": 922,
"text": "Example:"
},
{
"code": null,
"e": 966,
"s": 931,
"text": "die('Oops! Something went wrong');"
},
{
"code": null,
"e": 975,
"s": 966,
"text": "Program:"
},
{
"code": null,
"e": 979,
"s": 975,
"text": "PHP"
},
{
"code": "<?php $num = 1; // die can only print string values, // hence there will be no output die($num);?>",
"e": 1091,
"s": 979,
"text": null
},
{
"code": null,
"e": 1099,
"s": 1091,
"text": "Output:"
},
{
"code": null,
"e": 1109,
"s": 1099,
"text": "No Output"
},
{
"code": null,
"e": 1241,
"s": 1109,
"text": "Note: The output for the above program will be an empty screen because it is similar to exit(), die() can print only string values."
},
{
"code": null,
"e": 1289,
"s": 1241,
"text": "Differences between die() and exit() Functions:"
},
{
"code": null,
"e": 1295,
"s": 1289,
"text": "die()"
},
{
"code": null,
"e": 1302,
"s": 1295,
"text": "exit()"
},
{
"code": null,
"e": 1316,
"s": 1302,
"text": "mayank007rawa"
},
{
"code": null,
"e": 1330,
"s": 1316,
"text": "PHP-Questions"
},
{
"code": null,
"e": 1337,
"s": 1330,
"text": "Picked"
},
{
"code": null,
"e": 1356,
"s": 1337,
"text": "Difference Between"
},
{
"code": null,
"e": 1360,
"s": 1356,
"text": "PHP"
},
{
"code": null,
"e": 1377,
"s": 1360,
"text": "Web Technologies"
},
{
"code": null,
"e": 1381,
"s": 1377,
"text": "PHP"
}
] |
Remove NA Values from Vector in R | 31 Aug, 2021
In this article, we are going to discuss how to remove NA values from the vector.
We can remove those NA values from the vector by using is.na(). is.na() is used to get the na values based on the vector index. !is.na() will get the values except na.
Syntax:
vector[!is.na(vector)]
where the vector is the input vector
Example: R program to remove NA values using above method
R
# create a vectora=c(1,2,NA,4,5,NA,4,5,6,NA) # display aa # remove NAa[!is.na(a)]
Output:
[1] 1 2 NA 4 5 NA 4 5 6 NA
[1] 1 2 4 5 4 5 6
we can also remove na values by computing the sum, mean, variance.
Syntax:
sum(vector, na.rm = TRUE)
where
na.rm is used to remove na
if na.rm=TRUE it will not consider na
if na.rm=FALSE it will consider na
Syntax:
mean(vector, na.rm = TRUE)
Syntax:
var(vector, na.rm = TRUE)
Example: R program to remove na by using sum, var, and mean
R
# create a vectora=c(1,2,NA,4,5,NA,4,5,6,NA) # display aa # remove NA by computing variancevar(a, na.rm = TRUE) # remove NA by computing sumsum(a, na.rm = TRUE) # remove NA by computing meanmean(a, na.rm = TRUE)
Output:
[1] 1 2 NA 4 5 NA 4 5 6 NA
[1] 3.142857
[1] 27
[1] 3.857143
omit() method is used to remove the NA values directly by resulting in the non-NA values and omitted NA values indexes.
Syntax:
na.omit(vector)
where the vector is the input vector
Return type:
Returns the non-NA values
Returns the indexes of NA values which are removed from the vector
Note: Indexing starts with 1
Example: R program to consider a vector and remove NA values
R
# create a vector with integers along with NAa=c(1,2,NA,4,5,NA,4,5,6,NA) # displayprint(a) print("_______________________") # remove NA using omit() functiona=na.omit(a) # display vectorprint(a)
Output:
[1] 1 2 NA 4 5 NA 4 5 6 NA
[1] "_______________________"
[1] 1 2 4 5 4 5 6
attr(,"na.action")
[1] 3 6 10
attr(,"class")
[1] "omit"
gulshankumarar231
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 110,
"s": 28,
"text": "In this article, we are going to discuss how to remove NA values from the vector."
},
{
"code": null,
"e": 278,
"s": 110,
"text": "We can remove those NA values from the vector by using is.na(). is.na() is used to get the na values based on the vector index. !is.na() will get the values except na."
},
{
"code": null,
"e": 286,
"s": 278,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 286,
"text": "vector[!is.na(vector)]"
},
{
"code": null,
"e": 346,
"s": 309,
"text": "where the vector is the input vector"
},
{
"code": null,
"e": 404,
"s": 346,
"text": "Example: R program to remove NA values using above method"
},
{
"code": null,
"e": 406,
"s": 404,
"text": "R"
},
{
"code": "# create a vectora=c(1,2,NA,4,5,NA,4,5,6,NA) # display aa # remove NAa[!is.na(a)]",
"e": 488,
"s": 406,
"text": null
},
{
"code": null,
"e": 496,
"s": 488,
"text": "Output:"
},
{
"code": null,
"e": 530,
"s": 496,
"text": "[1] 1 2 NA 4 5 NA 4 5 6 NA"
},
{
"code": null,
"e": 548,
"s": 530,
"text": "[1] 1 2 4 5 4 5 6"
},
{
"code": null,
"e": 615,
"s": 548,
"text": "we can also remove na values by computing the sum, mean, variance."
},
{
"code": null,
"e": 623,
"s": 615,
"text": "Syntax:"
},
{
"code": null,
"e": 649,
"s": 623,
"text": "sum(vector, na.rm = TRUE)"
},
{
"code": null,
"e": 656,
"s": 649,
"text": "where "
},
{
"code": null,
"e": 683,
"s": 656,
"text": "na.rm is used to remove na"
},
{
"code": null,
"e": 721,
"s": 683,
"text": "if na.rm=TRUE it will not consider na"
},
{
"code": null,
"e": 756,
"s": 721,
"text": "if na.rm=FALSE it will consider na"
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Syntax:"
},
{
"code": null,
"e": 791,
"s": 764,
"text": "mean(vector, na.rm = TRUE)"
},
{
"code": null,
"e": 799,
"s": 791,
"text": "Syntax:"
},
{
"code": null,
"e": 825,
"s": 799,
"text": "var(vector, na.rm = TRUE)"
},
{
"code": null,
"e": 885,
"s": 825,
"text": "Example: R program to remove na by using sum, var, and mean"
},
{
"code": null,
"e": 887,
"s": 885,
"text": "R"
},
{
"code": "# create a vectora=c(1,2,NA,4,5,NA,4,5,6,NA) # display aa # remove NA by computing variancevar(a, na.rm = TRUE) # remove NA by computing sumsum(a, na.rm = TRUE) # remove NA by computing meanmean(a, na.rm = TRUE)",
"e": 1099,
"s": 887,
"text": null
},
{
"code": null,
"e": 1107,
"s": 1099,
"text": "Output:"
},
{
"code": null,
"e": 1174,
"s": 1107,
"text": "[1] 1 2 NA 4 5 NA 4 5 6 NA\n[1] 3.142857\n[1] 27\n[1] 3.857143"
},
{
"code": null,
"e": 1294,
"s": 1174,
"text": "omit() method is used to remove the NA values directly by resulting in the non-NA values and omitted NA values indexes."
},
{
"code": null,
"e": 1303,
"s": 1294,
"text": "Syntax: "
},
{
"code": null,
"e": 1319,
"s": 1303,
"text": "na.omit(vector)"
},
{
"code": null,
"e": 1356,
"s": 1319,
"text": "where the vector is the input vector"
},
{
"code": null,
"e": 1369,
"s": 1356,
"text": "Return type:"
},
{
"code": null,
"e": 1395,
"s": 1369,
"text": "Returns the non-NA values"
},
{
"code": null,
"e": 1462,
"s": 1395,
"text": "Returns the indexes of NA values which are removed from the vector"
},
{
"code": null,
"e": 1491,
"s": 1462,
"text": "Note: Indexing starts with 1"
},
{
"code": null,
"e": 1552,
"s": 1491,
"text": "Example: R program to consider a vector and remove NA values"
},
{
"code": null,
"e": 1554,
"s": 1552,
"text": "R"
},
{
"code": "# create a vector with integers along with NAa=c(1,2,NA,4,5,NA,4,5,6,NA) # displayprint(a) print(\"_______________________\") # remove NA using omit() functiona=na.omit(a) # display vectorprint(a)",
"e": 1749,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1757,
"s": 1749,
"text": "Output:"
},
{
"code": null,
"e": 1897,
"s": 1757,
"text": "[1] 1 2 NA 4 5 NA 4 5 6 NA\n[1] \"_______________________\"\n[1] 1 2 4 5 4 5 6\nattr(,\"na.action\")\n[1] 3 6 10\nattr(,\"class\")\n[1] \"omit\""
},
{
"code": null,
"e": 1915,
"s": 1897,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 1922,
"s": 1915,
"text": "Picked"
},
{
"code": null,
"e": 1940,
"s": 1922,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 1950,
"s": 1940,
"text": "R-Vectors"
},
{
"code": null,
"e": 1961,
"s": 1950,
"text": "R Language"
},
{
"code": null,
"e": 1972,
"s": 1961,
"text": "R Programs"
},
{
"code": null,
"e": 2070,
"s": 1972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2122,
"s": 2070,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2180,
"s": 2122,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2215,
"s": 2180,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2253,
"s": 2215,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2302,
"s": 2253,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2360,
"s": 2302,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2409,
"s": 2360,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2452,
"s": 2409,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2490,
"s": 2452,
"text": "Merge DataFrames by Column Names in R"
}
] |
Retrieve Image and File stored as a BLOB from MySQL Table using Python | 25 Feb, 2021
Prerequisites: MySQL server should be installed
In this post, we will be talking about how we can store files like images, text files, and other file formats into a MySQL table from a python script. Sometimes, just like other information, we need to store images and files into our database and provide it the security equivalent to other data.
In MySQL, we can use BLOB datatype to store the files. A BLOB is a binary large object that can hold a variable amount of data. We can represent the files in binary format and then store them in our database. The four BLOB types are TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the values they can hold.
We will use mysql-connect to use MySQL drivers in our python script. First, install the requirements:
python3 -m pip install mysql-connect-python
Next, create a database and a table as shown below:
CREATE DATABASE STUDENTDB;
USE STUDENTDB;
CREATE TABLE PROFILE ( ID BIGINT PRIMARY KEY, NAME VARCHAR(50) NOT NULL, PICTURE LONGBLOB NOT NULL );
We can see the database schema using:
DESC PROFILE;
Now, let’s add some data into the database:
Python3
# Import the required modulesimport mysql.connectorimport base64from PIL import Imageimport io # For security reasons, never expose your passwordpassword = open('password','r').readline() # Create a connectionmydb = mysql.connector.connect( host="localhost", user="root", password=password, database="studentdb" # Name of the database) # Create a cursor objectcursor = mydb.cursor() # Open a file in binary modefile = open('image.png','rb').read() # We must encode the file to get base64 stringfile = base64.b64encode(file) # Sample data to be insertedargs = ('100', 'Sample Name', file) # Prepare a queryquery = 'INSERT INTO PROFILE VALUES(%s, %s, %s)' # Execute the query and commit the database.cursor.execute(query,args)mydb.commit()
Now moving back to our MySQL database, we can see the inserted row.
We can make an SQL query to retrieve the image. The returned data will be in base64 format. So first we need to decode the data. We can transmit this data to the user or utilize it in other ways. In this post, we will simply show the image on the screen.
Python3
# Import the required modulesimport mysql.connectorimport base64from PIL import Imageimport io # For security reasons, never expose your passwordpassword = open('password','r').readline() # Create a connectionmydb = mysql.connector.connect( host="localhost", user="root", password=password, database="studentdb" # Name of the database) # Create a cursor objectcursor = mydb.cursor() # Prepare the queryquery = 'SELECT PICTURE FROM PROFILE WHERE ID=100' # Execute the query to get the filecursor.execute(query) data = cursor.fetchall() # The returned data will be a list of listimage = data[0][0] # Decode the stringbinary_data = base64.b64decode(image) # Convert the bytes into a PIL imageimage = Image.open(io.BytesIO(binary_data)) # Display the imageimage.show()
Output:
Picked
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 100,
"s": 52,
"text": "Prerequisites: MySQL server should be installed"
},
{
"code": null,
"e": 397,
"s": 100,
"text": "In this post, we will be talking about how we can store files like images, text files, and other file formats into a MySQL table from a python script. Sometimes, just like other information, we need to store images and files into our database and provide it the security equivalent to other data."
},
{
"code": null,
"e": 741,
"s": 397,
"text": "In MySQL, we can use BLOB datatype to store the files. A BLOB is a binary large object that can hold a variable amount of data. We can represent the files in binary format and then store them in our database. The four BLOB types are TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the values they can hold."
},
{
"code": null,
"e": 843,
"s": 741,
"text": "We will use mysql-connect to use MySQL drivers in our python script. First, install the requirements:"
},
{
"code": null,
"e": 887,
"s": 843,
"text": "python3 -m pip install mysql-connect-python"
},
{
"code": null,
"e": 939,
"s": 887,
"text": "Next, create a database and a table as shown below:"
},
{
"code": null,
"e": 966,
"s": 939,
"text": "CREATE DATABASE STUDENTDB;"
},
{
"code": null,
"e": 981,
"s": 966,
"text": "USE STUDENTDB;"
},
{
"code": null,
"e": 1083,
"s": 981,
"text": "CREATE TABLE PROFILE ( ID BIGINT PRIMARY KEY, NAME VARCHAR(50) NOT NULL, PICTURE LONGBLOB NOT NULL );"
},
{
"code": null,
"e": 1121,
"s": 1083,
"text": "We can see the database schema using:"
},
{
"code": null,
"e": 1135,
"s": 1121,
"text": "DESC PROFILE;"
},
{
"code": null,
"e": 1179,
"s": 1135,
"text": "Now, let’s add some data into the database:"
},
{
"code": null,
"e": 1187,
"s": 1179,
"text": "Python3"
},
{
"code": "# Import the required modulesimport mysql.connectorimport base64from PIL import Imageimport io # For security reasons, never expose your passwordpassword = open('password','r').readline() # Create a connectionmydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=password, database=\"studentdb\" # Name of the database) # Create a cursor objectcursor = mydb.cursor() # Open a file in binary modefile = open('image.png','rb').read() # We must encode the file to get base64 stringfile = base64.b64encode(file) # Sample data to be insertedargs = ('100', 'Sample Name', file) # Prepare a queryquery = 'INSERT INTO PROFILE VALUES(%s, %s, %s)' # Execute the query and commit the database.cursor.execute(query,args)mydb.commit()",
"e": 1947,
"s": 1187,
"text": null
},
{
"code": null,
"e": 2015,
"s": 1947,
"text": "Now moving back to our MySQL database, we can see the inserted row."
},
{
"code": null,
"e": 2270,
"s": 2015,
"text": "We can make an SQL query to retrieve the image. The returned data will be in base64 format. So first we need to decode the data. We can transmit this data to the user or utilize it in other ways. In this post, we will simply show the image on the screen."
},
{
"code": null,
"e": 2278,
"s": 2270,
"text": "Python3"
},
{
"code": "# Import the required modulesimport mysql.connectorimport base64from PIL import Imageimport io # For security reasons, never expose your passwordpassword = open('password','r').readline() # Create a connectionmydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=password, database=\"studentdb\" # Name of the database) # Create a cursor objectcursor = mydb.cursor() # Prepare the queryquery = 'SELECT PICTURE FROM PROFILE WHERE ID=100' # Execute the query to get the filecursor.execute(query) data = cursor.fetchall() # The returned data will be a list of listimage = data[0][0] # Decode the stringbinary_data = base64.b64decode(image) # Convert the bytes into a PIL imageimage = Image.open(io.BytesIO(binary_data)) # Display the imageimage.show()",
"e": 3067,
"s": 2278,
"text": null
},
{
"code": null,
"e": 3075,
"s": 3067,
"text": "Output:"
},
{
"code": null,
"e": 3082,
"s": 3075,
"text": "Picked"
},
{
"code": null,
"e": 3095,
"s": 3082,
"text": "Python-mySQL"
},
{
"code": null,
"e": 3102,
"s": 3095,
"text": "Python"
},
{
"code": null,
"e": 3200,
"s": 3102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3218,
"s": 3200,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3260,
"s": 3218,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3282,
"s": 3260,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3317,
"s": 3282,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3343,
"s": 3317,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3375,
"s": 3343,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3404,
"s": 3375,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3431,
"s": 3404,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3452,
"s": 3431,
"text": "Python OOPs Concepts"
}
] |
PostgreSQL – DROP TABLE | 28 Aug, 2020
PostgreSQL has a DROP TABLE statement that is used to remove an existing table or tables from the database.
Syntax: DROP TABLE [IF EXISTS] table_name [CASCADE | RESTRICT];
Let’s analyze the above syntax:
We specify the table name after the DROP TABLE keyword to remove the table permanently from the database.
In case the table that you want to remove is used in views, constraints, or any other objects, the CASCADE allows users to remove those dependent objects together with the table automatically.
RESTRICTrefuses to drop table if there is any object depends on it. PostgreSQL uses RESTRICT by default.
We can put a list of tables after the DROP TABLE to remove multiple tables at once, each table separated by a comma.
We can put a list of tables after the DROP TABLE to remove multiple tables at once, each table separated by a comma.
It is important to note that only superuser, schema owner, and table owner have sufficient privilege to remove the table.
Example 1:We will remove the author table from our database using the below statement:
DROP TABLE author;
PostgreSQL issues an error because the author table does not exist.To avoid this error, you can use the IF EXISTS parameter as follows:
DROP TABLE IF EXISTS author;
This will lead to PostgreSQL issuing a notice instead of an error.
Output:
Example 2:Here we will remove a table that already exists in our database. To check for all available tables in the database use the below command:
\dt
It will list all existing table as below:Here we will remove the categories table using the below statement:
DROP TABLE categories;
Now check the list of tables again to verify the removal using the below command:
\dt
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "PostgreSQL has a DROP TABLE statement that is used to remove an existing table or tables from the database."
},
{
"code": null,
"e": 200,
"s": 136,
"text": "Syntax: DROP TABLE [IF EXISTS] table_name [CASCADE | RESTRICT];"
},
{
"code": null,
"e": 232,
"s": 200,
"text": "Let’s analyze the above syntax:"
},
{
"code": null,
"e": 338,
"s": 232,
"text": "We specify the table name after the DROP TABLE keyword to remove the table permanently from the database."
},
{
"code": null,
"e": 531,
"s": 338,
"text": "In case the table that you want to remove is used in views, constraints, or any other objects, the CASCADE allows users to remove those dependent objects together with the table automatically."
},
{
"code": null,
"e": 636,
"s": 531,
"text": "RESTRICTrefuses to drop table if there is any object depends on it. PostgreSQL uses RESTRICT by default."
},
{
"code": null,
"e": 753,
"s": 636,
"text": "We can put a list of tables after the DROP TABLE to remove multiple tables at once, each table separated by a comma."
},
{
"code": null,
"e": 870,
"s": 753,
"text": "We can put a list of tables after the DROP TABLE to remove multiple tables at once, each table separated by a comma."
},
{
"code": null,
"e": 992,
"s": 870,
"text": "It is important to note that only superuser, schema owner, and table owner have sufficient privilege to remove the table."
},
{
"code": null,
"e": 1079,
"s": 992,
"text": "Example 1:We will remove the author table from our database using the below statement:"
},
{
"code": null,
"e": 1098,
"s": 1079,
"text": "DROP TABLE author;"
},
{
"code": null,
"e": 1234,
"s": 1098,
"text": "PostgreSQL issues an error because the author table does not exist.To avoid this error, you can use the IF EXISTS parameter as follows:"
},
{
"code": null,
"e": 1263,
"s": 1234,
"text": "DROP TABLE IF EXISTS author;"
},
{
"code": null,
"e": 1330,
"s": 1263,
"text": "This will lead to PostgreSQL issuing a notice instead of an error."
},
{
"code": null,
"e": 1338,
"s": 1330,
"text": "Output:"
},
{
"code": null,
"e": 1486,
"s": 1338,
"text": "Example 2:Here we will remove a table that already exists in our database. To check for all available tables in the database use the below command:"
},
{
"code": null,
"e": 1490,
"s": 1486,
"text": "\\dt"
},
{
"code": null,
"e": 1599,
"s": 1490,
"text": "It will list all existing table as below:Here we will remove the categories table using the below statement:"
},
{
"code": null,
"e": 1622,
"s": 1599,
"text": "DROP TABLE categories;"
},
{
"code": null,
"e": 1704,
"s": 1622,
"text": "Now check the list of tables again to verify the removal using the below command:"
},
{
"code": null,
"e": 1708,
"s": 1704,
"text": "\\dt"
},
{
"code": null,
"e": 1716,
"s": 1708,
"text": "Output:"
},
{
"code": null,
"e": 1742,
"s": 1716,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 1753,
"s": 1742,
"text": "PostgreSQL"
}
] |
Python | Fast Fourier Transformation | 26 Aug, 2019
It is an algorithm which plays a very important role in the computation of the Discrete Fourier Transform of a sequence. It converts a space or time signal to signal of the frequency domain.The DFT signal is generated by the distribution of value sequences to different frequency component. Working directly to convert on Fourier transform is computationally too expensive. So, Fast Fourier transform is used as it rapidly computes by factorizing the DFT matrix as the product of sparse factors. As a result, it reduces the DFT computation complexity from O(n2) to O(N log N). And this is a huge difference when working on a large dataset. Also, FFT algorithms are very accurate as compared to the DFT definition directly, in the presence of round-off error.
This transformation is a translation from the configuration space to frequency space and this is very important in terms of exploring both transformations of certain problems for more efficient computation and in exploring the power spectrum of a signal. This translation can be from xn to Xk. It is converting spatial or temporal data into the frequency domain data.
It can perform Discrete Fourier Transform (DFT) in the complex domain.Automatically the sequence is padded with zero to the right because the radix-2 FFT requires the sample point number as a power of 2. For short sequences use this method with default arguments only as with the size of the sequence, the complexity of expressions increases.
Parameters :
-> seq : [iterable] sequence on which DFT is to be applied.
-> dps : [Integer] number of decimal digits for precision.
Returns :
Fast Fourier Transform
Example 1 :
# import sympy from sympy import fft # sequence seq = [15, 21, 13, 44] # ffttransform = fft(seq)print (transform)
Output :
FFT : [93, 2 - 23*I, -37, 2 + 23*I]
Example 2 :
# import sympy from sympy import fft # sequence seq = [15, 21, 13, 44] decimal_point = 4 # ffttransform = fft(seq, decimal_point )print ("FFT : ", transform)
Output :
FFT : [93, 2.0 - 23.0*I, -37, 2.0 + 23.0*I]
Maths
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 813,
"s": 54,
"text": "It is an algorithm which plays a very important role in the computation of the Discrete Fourier Transform of a sequence. It converts a space or time signal to signal of the frequency domain.The DFT signal is generated by the distribution of value sequences to different frequency component. Working directly to convert on Fourier transform is computationally too expensive. So, Fast Fourier transform is used as it rapidly computes by factorizing the DFT matrix as the product of sparse factors. As a result, it reduces the DFT computation complexity from O(n2) to O(N log N). And this is a huge difference when working on a large dataset. Also, FFT algorithms are very accurate as compared to the DFT definition directly, in the presence of round-off error."
},
{
"code": null,
"e": 1181,
"s": 813,
"text": "This transformation is a translation from the configuration space to frequency space and this is very important in terms of exploring both transformations of certain problems for more efficient computation and in exploring the power spectrum of a signal. This translation can be from xn to Xk. It is converting spatial or temporal data into the frequency domain data."
},
{
"code": null,
"e": 1524,
"s": 1181,
"text": "It can perform Discrete Fourier Transform (DFT) in the complex domain.Automatically the sequence is padded with zero to the right because the radix-2 FFT requires the sample point number as a power of 2. For short sequences use this method with default arguments only as with the size of the sequence, the complexity of expressions increases."
},
{
"code": null,
"e": 1694,
"s": 1524,
"text": "\nParameters : \n-> seq : [iterable] sequence on which DFT is to be applied.\n-> dps : [Integer] number of decimal digits for precision.\n\nReturns : \nFast Fourier Transform\n"
},
{
"code": null,
"e": 1706,
"s": 1694,
"text": "Example 1 :"
},
{
"code": "# import sympy from sympy import fft # sequence seq = [15, 21, 13, 44] # ffttransform = fft(seq)print (transform)",
"e": 1822,
"s": 1706,
"text": null
},
{
"code": null,
"e": 1831,
"s": 1822,
"text": "Output :"
},
{
"code": null,
"e": 1867,
"s": 1831,
"text": "FFT : [93, 2 - 23*I, -37, 2 + 23*I]"
},
{
"code": null,
"e": 1879,
"s": 1867,
"text": "Example 2 :"
},
{
"code": "# import sympy from sympy import fft # sequence seq = [15, 21, 13, 44] decimal_point = 4 # ffttransform = fft(seq, decimal_point )print (\"FFT : \", transform)",
"e": 2040,
"s": 1879,
"text": null
},
{
"code": null,
"e": 2049,
"s": 2040,
"text": "Output :"
},
{
"code": null,
"e": 2095,
"s": 2049,
"text": "FFT : [93, 2.0 - 23.0*I, -37, 2.0 + 23.0*I]\n"
},
{
"code": null,
"e": 2101,
"s": 2095,
"text": "Maths"
},
{
"code": null,
"e": 2108,
"s": 2101,
"text": "Python"
},
{
"code": null,
"e": 2206,
"s": 2108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2224,
"s": 2206,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2266,
"s": 2224,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2288,
"s": 2266,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2314,
"s": 2288,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2346,
"s": 2314,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2375,
"s": 2346,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2402,
"s": 2375,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2423,
"s": 2402,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2453,
"s": 2423,
"text": "Iterate over a list in Python"
}
] |
How to undo a faulty merge with revert command in Git? | Let us say we performed a merge commit, shared this 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 the git revert command.
Consider the following diagram, where the repository has two branches – master and a feature branch. Both the branches are diverged and have two commits each. The commits in the feature branch the (C3 and C4) are merged into the master branch and the resulting commit is shared. Let us assume that project compilation fails due to a faulty merge.
We will not use the git reset command to revert the faulty merge as the faulty merge is shared and we do not want to rewrite the history. Unlike the reset command, the git revert command will invert changes introduced by the faulty merge commit and create a commit which will replicate a desired commit.
The syntax for using the revert command is
$git revert -m <parent> HEAD
The -m flag in the above command is mandatory and should be followed by a number greater zero. This is because, the merge commit has two parents - one parent on the master branch and other on the feature branch. To revert the merge commit we should tell git how we want it to revert the changes. The -m option is used to specify the parent commit that the new commit should replicate.
In our example, the faulty merge has two parents; c2 of the master branch is the first parent and C4 of the feature branch is the second parent. The following command will undo changes made by the faulty merge and create a new commit that will replicate the first parent – c2.
$git revert -m 1 HEAD
This is shown in the diagram below
This scenario is illustrated below-
$ 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
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git revert HEAD
error: commit 821624117bbdaab5cc581ef9a29e22ed40bf3679 is a merge but no -m option was given.
fatal: revert failed
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git revert -m HEAD
error: option `mainline' expects a number greater than zero
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ ls
abc.txt lmno.txt mh.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git revert -m 1 HEAD
Removing lmno.txt
hint: Waiting for your editor to close the file... unix2dos: converting file E:/tut_repo/.git/COMMIT_EDITMSG to DOS format...
dos2unix: converting file E:/tut_repo/.git/COMMIT_EDITMSG to Unix format...
[master 12ae6f3] Revert "Merge branch 'feature'"
1 file changed, 1 deletion(-)
delete mode 100644 lmno.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ ls
abc.txt mh.txt | [
{
"code": null,
"e": 1461,
"s": 1187,
"text": "Let us say we performed a merge commit, shared this 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 the git revert command."
},
{
"code": null,
"e": 1808,
"s": 1461,
"text": "Consider the following diagram, where the repository has two branches – master and a feature branch. Both the branches are diverged and have two commits each. The commits in the feature branch the (C3 and C4) are merged into the master branch and the resulting commit is shared. Let us assume that project compilation fails due to a faulty merge."
},
{
"code": null,
"e": 2112,
"s": 1808,
"text": "We will not use the git reset command to revert the faulty merge as the faulty merge is shared and we do not want to rewrite the history. Unlike the reset command, the git revert command will invert changes introduced by the faulty merge commit and create a commit which will replicate a desired commit."
},
{
"code": null,
"e": 2155,
"s": 2112,
"text": "The syntax for using the revert command is"
},
{
"code": null,
"e": 2184,
"s": 2155,
"text": "$git revert -m <parent> HEAD"
},
{
"code": null,
"e": 2569,
"s": 2184,
"text": "The -m flag in the above command is mandatory and should be followed by a number greater zero. This is because, the merge commit has two parents - one parent on the master branch and other on the feature branch. To revert the merge commit we should tell git how we want it to revert the changes. The -m option is used to specify the parent commit that the new commit should replicate."
},
{
"code": null,
"e": 2846,
"s": 2569,
"text": "In our example, the faulty merge has two parents; c2 of the master branch is the first parent and C4 of the feature branch is the second parent. The following command will undo changes made by the faulty merge and create a new commit that will replicate the first parent – c2."
},
{
"code": null,
"e": 2868,
"s": 2846,
"text": "$git revert -m 1 HEAD"
},
{
"code": null,
"e": 2903,
"s": 2868,
"text": "This is shown in the diagram below"
},
{
"code": null,
"e": 2939,
"s": 2903,
"text": "This scenario is illustrated below-"
},
{
"code": null,
"e": 5993,
"s": 2939,
"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\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git revert HEAD\nerror: commit 821624117bbdaab5cc581ef9a29e22ed40bf3679 is a merge but no -m option was given.\nfatal: revert failed\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git revert -m HEAD\nerror: option `mainline' expects a number greater than zero\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ ls\nabc.txt lmno.txt mh.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git revert -m 1 HEAD\nRemoving lmno.txt\nhint: Waiting for your editor to close the file... unix2dos: converting file E:/tut_repo/.git/COMMIT_EDITMSG to DOS format...\ndos2unix: converting file E:/tut_repo/.git/COMMIT_EDITMSG to Unix format...\n[master 12ae6f3] Revert \"Merge branch 'feature'\"\n1 file changed, 1 deletion(-)\ndelete mode 100644 lmno.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ ls\nabc.txt mh.txt"
}
] |
Factorial calculation using fork() in C for Linux | 02 Jun, 2017
Write a Unix C program using the fork() system call that generates the factorial and gives a sequence of series like 1, 2, 6, 24, 120... in the child process.The number of the sequence is provided in the command line.Examples:
Input :gfg@ubuntu:~/$ gcc -o fork fork.c
gfg@ubuntu:~/$ ./fork 6
Output :1
1 2
1 2 6
1 2 6 24
1 2 6 24 120
1 2 6 24 120 720
After deletion sum
1 3 9 33 153 873 Done
Input :gfg@ubuntu:~/$ gcc -o fork fork.c
gfg@ubuntu:~/$ ./fork -2
Output :negative number entered -2
To create child process fork()is used. fork() returns :
< 0 fail to create child (new) process
= 0 for child process
> 0 i.e process ID of the child process to the parent process. When >0 parent process will execute.
Inside Child process: If input is 6, the first six numbers of the factorial sequence will be given as output by the child process. Because the parent and child processes have their own copies of the data, it will be necessary for the child to output the sequence.Inside Parent process: The parent invokes the wait () call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a non-negative number is not passed on the command line.
// C program to illustrate factorial calculation// using fork() in C for Linux#include <stdio.h>#include <unistd.h>#include <sys/wait.h>#include <sys/types.h>#include <string.h>#include <stdlib.h> int main(int argc , char *argv[] ){ pid_t pid; if (argc != 2) { printf("arg missing or exceeding\n"); exit(0); } // atoi converts string to integer if ( atoi ( argv[1] ) <0 ) { printf("negative number entered %d", atoi(argv[1])); exit(0); } pid=fork(); if ( pid<0 ) { printf("failed to create child\n"); exit(0); } else if ( pid==0 ) { //Child Process int ans = 0, i, j, k = 2, n; // atoi converts string to integer n = atoi(argv[1]); int arr[n],sum[n]; arr[0] = 1; // generating factorial series for (i=1 ; i<n; i++) { arr[i] = arr[i-1]*k; k++; } // printing and sum of each sub-series for (j=0; j<n; j++) { sum[j] = 0; for (i=0; i<=j; i++) { printf(" %d ",arr[i]); sum[j]+=arr[i]; } printf("\n"); } for (i=0; i<n; i++) { if ((sum[i]%2) == 0) sum[i] = -1; } printf("After deletion sum\n"); for (i=0; i<n; i++) { if (sum[i] > 0) printf(" %d ", sum[i]); } exit(0); } // parent process else { wait(NULL); // waiting for child process to end printf("Done\n"); }}
Compiling Code code saved with name fork.c
gfg@ubuntu:~/$ gcc -o fork fork.c
Input:
gfg@ubuntu:~/$ ./fork 5
Output:
1
1 2
1 2 6
1 2 6 24
1 2 6 24 120
After deletion sum
1 3 9 33 153 Done
Firstly, command line argument is accepted. Then the number of arguments are passed and checked if the argument is positive.After that, generate the factorial series.Related Article- C program to demonstrate fork() and pipe()
References:
http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html
http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/wait.html
This article is contributed by Kartik Ahuja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
system-programming
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": "\n02 Jun, 2017"
},
{
"code": null,
"e": 279,
"s": 52,
"text": "Write a Unix C program using the fork() system call that generates the factorial and gives a sequence of series like 1, 2, 6, 24, 120... in the child process.The number of the sequence is provided in the command line.Examples:"
},
{
"code": null,
"e": 645,
"s": 279,
"text": "Input :gfg@ubuntu:~/$ gcc -o fork fork.c\n gfg@ubuntu:~/$ ./fork 6\n\nOutput :1 \n 1 2 \n 1 2 6 \n 1 2 6 24 \n 1 2 6 24 120 \n 1 2 6 24 120 720 \n After deletion sum\n 1 3 9 33 153 873 Done\n\nInput :gfg@ubuntu:~/$ gcc -o fork fork.c\n gfg@ubuntu:~/$ ./fork -2\n\nOutput :negative number entered -2\n"
},
{
"code": null,
"e": 701,
"s": 645,
"text": "To create child process fork()is used. fork() returns :"
},
{
"code": null,
"e": 740,
"s": 701,
"text": "< 0 fail to create child (new) process"
},
{
"code": null,
"e": 762,
"s": 740,
"text": "= 0 for child process"
},
{
"code": null,
"e": 862,
"s": 762,
"text": "> 0 i.e process ID of the child process to the parent process. When >0 parent process will execute."
},
{
"code": null,
"e": 1359,
"s": 862,
"text": "Inside Child process: If input is 6, the first six numbers of the factorial sequence will be given as output by the child process. Because the parent and child processes have their own copies of the data, it will be necessary for the child to output the sequence.Inside Parent process: The parent invokes the wait () call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a non-negative number is not passed on the command line."
},
{
"code": "// C program to illustrate factorial calculation// using fork() in C for Linux#include <stdio.h>#include <unistd.h>#include <sys/wait.h>#include <sys/types.h>#include <string.h>#include <stdlib.h> int main(int argc , char *argv[] ){ pid_t pid; if (argc != 2) { printf(\"arg missing or exceeding\\n\"); exit(0); } // atoi converts string to integer if ( atoi ( argv[1] ) <0 ) { printf(\"negative number entered %d\", atoi(argv[1])); exit(0); } pid=fork(); if ( pid<0 ) { printf(\"failed to create child\\n\"); exit(0); } else if ( pid==0 ) { //Child Process int ans = 0, i, j, k = 2, n; // atoi converts string to integer n = atoi(argv[1]); int arr[n],sum[n]; arr[0] = 1; // generating factorial series for (i=1 ; i<n; i++) { arr[i] = arr[i-1]*k; k++; } // printing and sum of each sub-series for (j=0; j<n; j++) { sum[j] = 0; for (i=0; i<=j; i++) { printf(\" %d \",arr[i]); sum[j]+=arr[i]; } printf(\"\\n\"); } for (i=0; i<n; i++) { if ((sum[i]%2) == 0) sum[i] = -1; } printf(\"After deletion sum\\n\"); for (i=0; i<n; i++) { if (sum[i] > 0) printf(\" %d \", sum[i]); } exit(0); } // parent process else { wait(NULL); // waiting for child process to end printf(\"Done\\n\"); }}",
"e": 2976,
"s": 1359,
"text": null
},
{
"code": null,
"e": 3019,
"s": 2976,
"text": "Compiling Code code saved with name fork.c"
},
{
"code": null,
"e": 3054,
"s": 3019,
"text": "gfg@ubuntu:~/$ gcc -o fork fork.c\n"
},
{
"code": null,
"e": 3061,
"s": 3054,
"text": "Input:"
},
{
"code": null,
"e": 3086,
"s": 3061,
"text": "gfg@ubuntu:~/$ ./fork 5\n"
},
{
"code": null,
"e": 3094,
"s": 3086,
"text": "Output:"
},
{
"code": null,
"e": 3191,
"s": 3094,
"text": " 1 \n 1 2 \n 1 2 6 \n 1 2 6 24 \n 1 2 6 24 120 \nAfter deletion sum\n 1 3 9 33 153 Done\n"
},
{
"code": null,
"e": 3417,
"s": 3191,
"text": "Firstly, command line argument is accepted. Then the number of arguments are passed and checked if the argument is positive.After that, generate the factorial series.Related Article- C program to demonstrate fork() and pipe()"
},
{
"code": null,
"e": 3429,
"s": 3417,
"text": "References:"
},
{
"code": null,
"e": 3497,
"s": 3429,
"text": "http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html"
},
{
"code": null,
"e": 3563,
"s": 3497,
"text": "http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/wait.html"
},
{
"code": null,
"e": 3863,
"s": 3563,
"text": "This article is contributed by Kartik Ahuja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3988,
"s": 3863,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4007,
"s": 3988,
"text": "system-programming"
},
{
"code": null,
"e": 4026,
"s": 4007,
"text": "Technical Scripter"
}
] |
RANDOM Shell Variable in Linux with Examples | 10 Nov, 2020
RANDOM is a shell variable that is used to generate random integers in Linux. It is an internal bash command that returns a pseudo-random 16-bit integer in the range 0 – 32767. It returns a different integer at each invocation. To enhance the randomization process, the random variable can be seeded with an initial value which can be the time in epoch, the process ID of the current shell, etc.
Syntax to use time in epoch to initialize the generator:
RANDOM=$(date +%s)
Syntax to use process ID of the current shell to initialize the generator:
RANDOM=$$ #PID of shell is stored in $$ variable
Generating random integer
Random integer can be generated by directly reading from the random variable by using the echo command. It will display a random integer in range 0 to 32767.
echo $RANDOM
Generating ‘n’ random integers
You may use loops to generate more than one random number using the RANDOM shell variable. The following code will generate 5 random values in the range from 0 to 32767.
RANDOM=$$
for i in `seq 5`
do
echo $RANDOM
done
Note: Replace 5 with the number of random values of your choice.
Generating random integer when the upper limit is given
Consider that you want to generate a random integer within Y (where Y is not included). Format to achieve this is:
R=$(($RANDOM%Y))
To include the upper limit Y, the divisor of the modulo operation will be Y+1. The format is:
R=$(($RANDOM%Y+1))
Example:
echo $(($RANDOM%10)) #This will display a random integer between 0 and 9.
echo $(($RANDOM%11)) #This will display a random integer between 0 and 10.
When the input is taken from the user in a shell script from the command line to generate the integer, then the following code can be used:
Y=$1
div=$((Y+1))
RANDOM=$$
R=$(($RANDOM%$div))
echo $R
Y stores the upper limit and echo $R displays the random integer. The output is:
Generating random integer when both upper and lower limit is given
Consider that you want to generate a random integer between X and Y where X is the lower limit (X≠0) and Y is the upper limit. Format to achieve this is:
RANGE=$((Y-X+1))
R=$(($(($RANDOM%$RANGE))+X))
Example:
echo "lower limit:"
read X
echo "upper limit:"
read Y
RANGE=$((Y-X+1))
RANDOM=$$
R=$(($(($RANDOM%$RANGE))+X))
echo "The random integer is $R"
The output is:
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Nov, 2020"
},
{
"code": null,
"e": 449,
"s": 53,
"text": "RANDOM is a shell variable that is used to generate random integers in Linux. It is an internal bash command that returns a pseudo-random 16-bit integer in the range 0 – 32767. It returns a different integer at each invocation. To enhance the randomization process, the random variable can be seeded with an initial value which can be the time in epoch, the process ID of the current shell, etc."
},
{
"code": null,
"e": 506,
"s": 449,
"text": "Syntax to use time in epoch to initialize the generator:"
},
{
"code": null,
"e": 526,
"s": 506,
"text": "RANDOM=$(date +%s)\n"
},
{
"code": null,
"e": 601,
"s": 526,
"text": "Syntax to use process ID of the current shell to initialize the generator:"
},
{
"code": null,
"e": 651,
"s": 601,
"text": "RANDOM=$$ #PID of shell is stored in $$ variable\n"
},
{
"code": null,
"e": 678,
"s": 651,
"text": "Generating random integer"
},
{
"code": null,
"e": 836,
"s": 678,
"text": "Random integer can be generated by directly reading from the random variable by using the echo command. It will display a random integer in range 0 to 32767."
},
{
"code": null,
"e": 850,
"s": 836,
"text": "echo $RANDOM\n"
},
{
"code": null,
"e": 881,
"s": 850,
"text": "Generating ‘n’ random integers"
},
{
"code": null,
"e": 1051,
"s": 881,
"text": "You may use loops to generate more than one random number using the RANDOM shell variable. The following code will generate 5 random values in the range from 0 to 32767."
},
{
"code": null,
"e": 1108,
"s": 1051,
"text": "RANDOM=$$\nfor i in `seq 5`\ndo\n echo $RANDOM\ndone\n"
},
{
"code": null,
"e": 1173,
"s": 1108,
"text": "Note: Replace 5 with the number of random values of your choice."
},
{
"code": null,
"e": 1229,
"s": 1173,
"text": "Generating random integer when the upper limit is given"
},
{
"code": null,
"e": 1344,
"s": 1229,
"text": "Consider that you want to generate a random integer within Y (where Y is not included). Format to achieve this is:"
},
{
"code": null,
"e": 1362,
"s": 1344,
"text": "R=$(($RANDOM%Y))\n"
},
{
"code": null,
"e": 1456,
"s": 1362,
"text": "To include the upper limit Y, the divisor of the modulo operation will be Y+1. The format is:"
},
{
"code": null,
"e": 1476,
"s": 1456,
"text": "R=$(($RANDOM%Y+1))\n"
},
{
"code": null,
"e": 1485,
"s": 1476,
"text": "Example:"
},
{
"code": null,
"e": 1635,
"s": 1485,
"text": "echo $(($RANDOM%10)) #This will display a random integer between 0 and 9.\necho $(($RANDOM%11)) #This will display a random integer between 0 and 10.\n"
},
{
"code": null,
"e": 1775,
"s": 1635,
"text": "When the input is taken from the user in a shell script from the command line to generate the integer, then the following code can be used:"
},
{
"code": null,
"e": 1832,
"s": 1775,
"text": "Y=$1\ndiv=$((Y+1))\nRANDOM=$$\nR=$(($RANDOM%$div))\necho $R\n"
},
{
"code": null,
"e": 1913,
"s": 1832,
"text": "Y stores the upper limit and echo $R displays the random integer. The output is:"
},
{
"code": null,
"e": 1980,
"s": 1913,
"text": "Generating random integer when both upper and lower limit is given"
},
{
"code": null,
"e": 2135,
"s": 1980,
"text": "Consider that you want to generate a random integer between X and Y where X is the lower limit (X≠0) and Y is the upper limit. Format to achieve this is:"
},
{
"code": null,
"e": 2182,
"s": 2135,
"text": "RANGE=$((Y-X+1))\nR=$(($(($RANDOM%$RANGE))+X))\n"
},
{
"code": null,
"e": 2191,
"s": 2182,
"text": "Example:"
},
{
"code": null,
"e": 2334,
"s": 2191,
"text": "echo \"lower limit:\"\nread X\necho \"upper limit:\"\nread Y\nRANGE=$((Y-X+1))\nRANDOM=$$\nR=$(($(($RANDOM%$RANGE))+X))\necho \"The random integer is $R\"\n"
},
{
"code": null,
"e": 2349,
"s": 2334,
"text": "The output is:"
},
{
"code": null,
"e": 2360,
"s": 2349,
"text": "Linux-Unix"
}
] |
jQuery - hover( over, out ) Method | The hover( over, out ) method simulates hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.
Here is the simple syntax to use this method −
selector.hover( over, out )
Here is the description of all the parameters used by this method −
over − The callback function to fire when the mouse is moved over a matched element.
over − The callback function to fire when the mouse is moved over a matched element.
out − The callback function to fire when the mouse is moved off of a matched element.
out − The callback function to fire when the mouse is moved off of a matched element.
Following is a simple example a simple showing the usage of this method −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$('div').hover(
function () {
$(this).css({"background-color":"red"});
},
function () {
$(this).css({"background-color":"blue"});
}
);
});
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Move mouse on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:blue;"></div>
</body>
</html>
This will produce following result −
Move mouse on any square below to see the result − | [
{
"code": null,
"e": 2948,
"s": 2789,
"text": "The hover( over, out ) method simulates hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task."
},
{
"code": null,
"e": 2995,
"s": 2948,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 3024,
"s": 2995,
"text": "selector.hover( over, out )\n"
},
{
"code": null,
"e": 3092,
"s": 3024,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 3177,
"s": 3092,
"text": "over − The callback function to fire when the mouse is moved over a matched element."
},
{
"code": null,
"e": 3262,
"s": 3177,
"text": "over − The callback function to fire when the mouse is moved over a matched element."
},
{
"code": null,
"e": 3348,
"s": 3262,
"text": "out − The callback function to fire when the mouse is moved off of a matched element."
},
{
"code": null,
"e": 3434,
"s": 3348,
"text": "out − The callback function to fire when the mouse is moved off of a matched element."
},
{
"code": null,
"e": 3508,
"s": 3434,
"text": "Following is a simple example a simple showing the usage of this method −"
},
{
"code": null,
"e": 4513,
"s": 3508,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://www.tutorialspoint.com/jquery/jquery-3.6.0.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\n $('div').hover(\n\t\t\t\t\n function () {\n $(this).css({\"background-color\":\"red\"});\n }, \n\t\t\t\t\n function () {\n $(this).css({\"background-color\":\"blue\"});\n }\n );\n\t\t\t\t\n });\n </script>\n\t\t\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Move mouse on any square below to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:blue;\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 4550,
"s": 4513,
"text": "This will produce following result −"
}
] |
Counting the frequencies in a list using dictionary in Python - GeeksforGeeks | 17 Jun, 2021
Given an unsorted list of some elements(may or may not be integers), Find the frequency of each distinct element in the list using a dictionary. Example:
Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,
4, 4, 4, 2, 2, 2, 2]
Output : 1 : 5
2 : 4
3 : 3
4 : 3
5 : 2
Explanation : Here 1 occurs 5 times, 2
occurs 4 times and so on...
The problem can be solved in many ways. A simple approach would be to iterate over the list and use each distinct element of the list as a key of the dictionary and store the corresponding count of that key as values. Below is the Python code for this approach:
Python
# Python program to count the frequency of# elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary freq = {} for item in my_list: if (item in freq): freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print ("% d : % d"%(key, value)) # Driver functionif __name__ == "__main__": my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)
1 : 5
2 : 4
3 : 3
4 : 3
5 : 2
Time Complexity:O(N), where N is the length of the list.
Alternative way: An alternative approach can be to use the list.count() method.
Python
# Python program to count the frequency of# elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = my_list.count(items) for key, value in freq.items(): print ("% d : % d"%(key, value)) # Driver functionif __name__ == "__main__": my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)
1 : 5
2 : 4
3 : 3
4 : 3
5 : 2
Time Complexity:O(N2), where N is the length of the list. The time complexity list.count() is O(N) alone, and when used inside loop it will become O(N2).
Alternative way:An alternative approach can be to use the dict.get() method. This makes the program much more shorter and makes understand how get method is useful instead of if...else.
Python
# Python program to count the frequency of# elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary count = {} for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1 ,4, 4, 4, 2, 2, 2, 2]: count[i] = count.get(i, 0) + 1 return count # Driver functionif __name__ == "__main__": my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] print(CountFrequency(my_list))
{1: 5, 5: 2, 3: 3, 4: 3, 2: 4}
Related Article : Count frequencies of all elements in array in Python using collections module
deepakgupta08112000
vanshgaur14866
frequency-counting
Python dictionary-programs
python-dict
python-list
Python
python-dict
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions | [
{
"code": null,
"e": 24654,
"s": 24626,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24810,
"s": 24654,
"text": "Given an unsorted list of some elements(may or may not be integers), Find the frequency of each distinct element in the list using a dictionary. Example: "
},
{
"code": null,
"e": 25045,
"s": 24810,
"text": "Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,\n 4, 4, 4, 2, 2, 2, 2]\nOutput : 1 : 5\n 2 : 4\n 3 : 3\n 4 : 3\n 5 : 2\nExplanation : Here 1 occurs 5 times, 2 \n occurs 4 times and so on..."
},
{
"code": null,
"e": 25310,
"s": 25047,
"text": "The problem can be solved in many ways. A simple approach would be to iterate over the list and use each distinct element of the list as a key of the dictionary and store the corresponding count of that key as values. Below is the Python code for this approach: "
},
{
"code": null,
"e": 25317,
"s": 25310,
"text": "Python"
},
{
"code": "# Python program to count the frequency of# elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary freq = {} for item in my_list: if (item in freq): freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print (\"% d : % d\"%(key, value)) # Driver functionif __name__ == \"__main__\": my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)",
"e": 25804,
"s": 25317,
"text": null
},
{
"code": null,
"e": 25844,
"s": 25804,
"text": " 1 : 5\n 2 : 4\n 3 : 3\n 4 : 3\n 5 : 2"
},
{
"code": null,
"e": 25903,
"s": 25846,
"text": "Time Complexity:O(N), where N is the length of the list."
},
{
"code": null,
"e": 25985,
"s": 25903,
"text": "Alternative way: An alternative approach can be to use the list.count() method. "
},
{
"code": null,
"e": 25992,
"s": 25985,
"text": "Python"
},
{
"code": "# Python program to count the frequency of# elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = my_list.count(items) for key, value in freq.items(): print (\"% d : % d\"%(key, value)) # Driver functionif __name__ == \"__main__\": my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)",
"e": 26437,
"s": 25992,
"text": null
},
{
"code": null,
"e": 26477,
"s": 26437,
"text": " 1 : 5\n 2 : 4\n 3 : 3\n 4 : 3\n 5 : 2"
},
{
"code": null,
"e": 26634,
"s": 26479,
"text": "Time Complexity:O(N2), where N is the length of the list. The time complexity list.count() is O(N) alone, and when used inside loop it will become O(N2). "
},
{
"code": null,
"e": 26822,
"s": 26634,
"text": "Alternative way:An alternative approach can be to use the dict.get() method. This makes the program much more shorter and makes understand how get method is useful instead of if...else. "
},
{
"code": null,
"e": 26829,
"s": 26822,
"text": "Python"
},
{
"code": "# Python program to count the frequency of# elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary count = {} for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1 ,4, 4, 4, 2, 2, 2, 2]: count[i] = count.get(i, 0) + 1 return count # Driver functionif __name__ == \"__main__\": my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] print(CountFrequency(my_list))",
"e": 27246,
"s": 26829,
"text": null
},
{
"code": null,
"e": 27277,
"s": 27246,
"text": "{1: 5, 5: 2, 3: 3, 4: 3, 2: 4}"
},
{
"code": null,
"e": 27376,
"s": 27279,
"text": "Related Article : Count frequencies of all elements in array in Python using collections module "
},
{
"code": null,
"e": 27396,
"s": 27376,
"text": "deepakgupta08112000"
},
{
"code": null,
"e": 27411,
"s": 27396,
"text": "vanshgaur14866"
},
{
"code": null,
"e": 27430,
"s": 27411,
"text": "frequency-counting"
},
{
"code": null,
"e": 27457,
"s": 27430,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27469,
"s": 27457,
"text": "python-dict"
},
{
"code": null,
"e": 27481,
"s": 27469,
"text": "python-list"
},
{
"code": null,
"e": 27488,
"s": 27481,
"text": "Python"
},
{
"code": null,
"e": 27500,
"s": 27488,
"text": "python-dict"
},
{
"code": null,
"e": 27512,
"s": 27500,
"text": "python-list"
},
{
"code": null,
"e": 27610,
"s": 27512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27619,
"s": 27610,
"text": "Comments"
},
{
"code": null,
"e": 27632,
"s": 27619,
"text": "Old Comments"
},
{
"code": null,
"e": 27650,
"s": 27632,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27685,
"s": 27650,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27707,
"s": 27685,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27739,
"s": 27707,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27769,
"s": 27739,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27811,
"s": 27769,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27837,
"s": 27811,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27874,
"s": 27837,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27917,
"s": 27874,
"text": "Python program to convert a list to string"
}
] |
Add to Array-Form of Integer in Python | Suppose we have a number in array form. So if the number is say 534, then it is stored like [5, 3, 4]. We have to add another value k with the array form of the number. So the final number will be another array of digits.
To solve this, we will follow these steps −
Take each number and make them string, then concatenate the string
convert the string into integer, then add the number
Then convert it into string again, and make an array by taking each digit form the string.
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def addToArrayForm(self, A, K):
num_A = int(''.join(str(i) for i in A))
res = list(str(num_A+K))
res = list(map(int,res))
return res
ob1 = Solution()
print(ob1.addToArrayForm([5,3,4], 78))
[5,3,4]
78
[6,1,2] | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "Suppose we have a number in array form. So if the number is say 534, then it is stored like [5, 3, 4]. We have to add another value k with the array form of the number. So the final number will be another array of digits."
},
{
"code": null,
"e": 1328,
"s": 1284,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1395,
"s": 1328,
"text": "Take each number and make them string, then concatenate the string"
},
{
"code": null,
"e": 1448,
"s": 1395,
"text": "convert the string into integer, then add the number"
},
{
"code": null,
"e": 1539,
"s": 1448,
"text": "Then convert it into string again, and make an array by taking each digit form the string."
},
{
"code": null,
"e": 1609,
"s": 1539,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1620,
"s": 1609,
"text": " Live Demo"
},
{
"code": null,
"e": 1860,
"s": 1620,
"text": "class Solution(object):\n def addToArrayForm(self, A, K):\n num_A = int(''.join(str(i) for i in A))\n res = list(str(num_A+K))\n res = list(map(int,res))\n return res\nob1 = Solution()\nprint(ob1.addToArrayForm([5,3,4], 78))"
},
{
"code": null,
"e": 1871,
"s": 1860,
"text": "[5,3,4]\n78"
},
{
"code": null,
"e": 1879,
"s": 1871,
"text": "[6,1,2]"
}
] |
Maximum number of 2x2 squares that can be fit inside a right isosceles triangle - GeeksforGeeks | 29 Nov, 2021
What is the maximum number of squares of size 2×2 units that can be fit in a right-angled isosceles triangle of a given base (in units). A side of the square must be parallel to the base of the triangle.
Examples:
Input : 8
Output : 6
Please refer below diagram for explanation.
Input : 7
Output : 3
Since the triangle is isosceles, the given base would also be equal to the height. Now in the diagonal part, we would always need an extra length of 2 units in both height and base of the triangle to accommodate a triangle. (The CF and AM segment of the triangle in the image. The part that does not contribute to any square). In the remaining length of base, we can construct length / 2 squares. Since each square is of 2 units, same would be the case of height, there is no need to calculate that again. So, for each level of given length we can construct “(length-2)/2” squares. This gives us a base of “(length-2)” above it. Continuing this process to get the no of squares for all available “length-2” height, we can calculate the squares.
while length > 2
answer += (length - 2 )/2
length = length - 2
For more effective way, we can use the formula of sum of AP n * ( n + 1 ) / 2, where n = length – 2
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of 2 x 2// squares in a right isosceles triangle#include<bits/stdc++.h>using namespace std; int numberOfSquares(int base){ // removing the extra part we would // always need base = (base - 2); // Since each square has base of // length of 2 base = floor(base / 2); return base * (base + 1)/2;} // Driver codeint main(){ int base = 8; cout << numberOfSquares(base); return 0;}// This code is improved by heroichitesh.
// Java program to count number of 2 x 2// squares in a right isosceles triangle class Squares{ public static int numberOfSquares(int base) { // removing the extra part // we would always need base = (base - 2); // Since each square has // base of length of 2 base = Math.floorDiv(base, 2); return base * (base + 1)/2; } // Driver code public static void main(String args[]) { int base = 8; System.out.println(numberOfSquares(base)); }} // This code is contributed by Anshika Goyal and improved by heroichitesh.
# Python3 program to count number# of 2 x 2 squares in a right # isosceles triangledef numberOfSquares(base): # removing the extra part we would # always need base = (base - 2) # Since each square has base of # length of 2 base = base // 2 return base * (base + 1) / 2 # Driver codebase = 8 print(numberOfSquares(base)) # This code is contributed by Anant Agarwal and improved by heroichitesh.
// C# program to count number of 2 x 2// squares in a right isosceles triangleusing System; class GFG { public static int numberOfSquares(int _base) { // removing the extra part // we would always need _base = (_base - 2); // Since each square has // base of length of 2 _base = _base / 2; return _base * (_base + 1)/2; } // Driver code public static void Main() { int _base = 8; Console.WriteLine(numberOfSquares(_base)); }} // This code is contributed by anuj_67.
<?php// PHP program to count number of 2 x 2// squares in a right isosceles triangle function numberOfSquares( $base) { // removing the extra // part we would // always need $base = ($base - 2); // Since each square // has base of // length of 2 $base = intdiv($base, 2); return $base * ($base + 1)/2; } // Driver code$base = 8;echo numberOfSquares($base); // This code is contributed by anuj_67 and improved by heroichitesh.?>
<script> // Program to count number of 2 x 2 // squares in a right isosceles triangle function numberOfSquares(base) { // Removing the extra part we would // always need base = (base - 2); // Since each square has base of // length of 2 base = Math.floor(base / 2); return base * (base + 1) / 2; } // Driver code let base = 8; document.write(numberOfSquares(base)); // This code is contributed by Mayank Tyagi </script>
Output:
6
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
HeroicHitesh
mayanktyagi1709
triangle
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Closest Pair of Points | O(nlogn) Implementation
Convex Hull | Set 2 (Graham Scan)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Given n line segments, find if any two segments intersect
Sum of Manhattan distances between all pairs of points
Convex Hull using Divide and Conquer Algorithm
Program for Point of Intersection of Two Lines
Equation of circle when three points on the circle are given | [
{
"code": null,
"e": 25182,
"s": 25154,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 25387,
"s": 25182,
"text": "What is the maximum number of squares of size 2×2 units that can be fit in a right-angled isosceles triangle of a given base (in units). A side of the square must be parallel to the base of the triangle. "
},
{
"code": null,
"e": 25398,
"s": 25387,
"text": "Examples: "
},
{
"code": null,
"e": 25464,
"s": 25398,
"text": "Input : 8\nOutput : 6\nPlease refer below diagram for explanation."
},
{
"code": null,
"e": 25485,
"s": 25464,
"text": "Input : 7\nOutput : 3"
},
{
"code": null,
"e": 26231,
"s": 25485,
"text": "Since the triangle is isosceles, the given base would also be equal to the height. Now in the diagonal part, we would always need an extra length of 2 units in both height and base of the triangle to accommodate a triangle. (The CF and AM segment of the triangle in the image. The part that does not contribute to any square). In the remaining length of base, we can construct length / 2 squares. Since each square is of 2 units, same would be the case of height, there is no need to calculate that again. So, for each level of given length we can construct “(length-2)/2” squares. This gives us a base of “(length-2)” above it. Continuing this process to get the no of squares for all available “length-2” height, we can calculate the squares. "
},
{
"code": null,
"e": 26302,
"s": 26231,
"text": "while length > 2\n answer += (length - 2 )/2\n length = length - 2"
},
{
"code": null,
"e": 26403,
"s": 26302,
"text": "For more effective way, we can use the formula of sum of AP n * ( n + 1 ) / 2, where n = length – 2 "
},
{
"code": null,
"e": 26407,
"s": 26403,
"text": "C++"
},
{
"code": null,
"e": 26412,
"s": 26407,
"text": "Java"
},
{
"code": null,
"e": 26420,
"s": 26412,
"text": "Python3"
},
{
"code": null,
"e": 26423,
"s": 26420,
"text": "C#"
},
{
"code": null,
"e": 26427,
"s": 26423,
"text": "PHP"
},
{
"code": null,
"e": 26438,
"s": 26427,
"text": "Javascript"
},
{
"code": "// C++ program to count number of 2 x 2// squares in a right isosceles triangle#include<bits/stdc++.h>using namespace std; int numberOfSquares(int base){ // removing the extra part we would // always need base = (base - 2); // Since each square has base of // length of 2 base = floor(base / 2); return base * (base + 1)/2;} // Driver codeint main(){ int base = 8; cout << numberOfSquares(base); return 0;}// This code is improved by heroichitesh.",
"e": 26912,
"s": 26438,
"text": null
},
{
"code": "// Java program to count number of 2 x 2// squares in a right isosceles triangle class Squares{ public static int numberOfSquares(int base) { // removing the extra part // we would always need base = (base - 2); // Since each square has // base of length of 2 base = Math.floorDiv(base, 2); return base * (base + 1)/2; } // Driver code public static void main(String args[]) { int base = 8; System.out.println(numberOfSquares(base)); }} // This code is contributed by Anshika Goyal and improved by heroichitesh.",
"e": 27504,
"s": 26912,
"text": null
},
{
"code": "# Python3 program to count number# of 2 x 2 squares in a right # isosceles triangledef numberOfSquares(base): # removing the extra part we would # always need base = (base - 2) # Since each square has base of # length of 2 base = base // 2 return base * (base + 1) / 2 # Driver codebase = 8 print(numberOfSquares(base)) # This code is contributed by Anant Agarwal and improved by heroichitesh. ",
"e": 27945,
"s": 27504,
"text": null
},
{
"code": "// C# program to count number of 2 x 2// squares in a right isosceles triangleusing System; class GFG { public static int numberOfSquares(int _base) { // removing the extra part // we would always need _base = (_base - 2); // Since each square has // base of length of 2 _base = _base / 2; return _base * (_base + 1)/2; } // Driver code public static void Main() { int _base = 8; Console.WriteLine(numberOfSquares(_base)); }} // This code is contributed by anuj_67.",
"e": 28543,
"s": 27945,
"text": null
},
{
"code": "<?php// PHP program to count number of 2 x 2// squares in a right isosceles triangle function numberOfSquares( $base) { // removing the extra // part we would // always need $base = ($base - 2); // Since each square // has base of // length of 2 $base = intdiv($base, 2); return $base * ($base + 1)/2; } // Driver code$base = 8;echo numberOfSquares($base); // This code is contributed by anuj_67 and improved by heroichitesh.?>",
"e": 29074,
"s": 28543,
"text": null
},
{
"code": "<script> // Program to count number of 2 x 2 // squares in a right isosceles triangle function numberOfSquares(base) { // Removing the extra part we would // always need base = (base - 2); // Since each square has base of // length of 2 base = Math.floor(base / 2); return base * (base + 1) / 2; } // Driver code let base = 8; document.write(numberOfSquares(base)); // This code is contributed by Mayank Tyagi </script>",
"e": 29636,
"s": 29074,
"text": null
},
{
"code": null,
"e": 29645,
"s": 29636,
"text": "Output: "
},
{
"code": null,
"e": 29647,
"s": 29645,
"text": "6"
},
{
"code": null,
"e": 30071,
"s": 29647,
"text": "This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30076,
"s": 30071,
"text": "vt_m"
},
{
"code": null,
"e": 30089,
"s": 30076,
"text": "HeroicHitesh"
},
{
"code": null,
"e": 30105,
"s": 30089,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 30114,
"s": 30105,
"text": "triangle"
},
{
"code": null,
"e": 30124,
"s": 30114,
"text": "Geometric"
},
{
"code": null,
"e": 30134,
"s": 30124,
"text": "Geometric"
},
{
"code": null,
"e": 30232,
"s": 30134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30241,
"s": 30232,
"text": "Comments"
},
{
"code": null,
"e": 30254,
"s": 30241,
"text": "Old Comments"
},
{
"code": null,
"e": 30303,
"s": 30254,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 30356,
"s": 30303,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 30405,
"s": 30356,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 30439,
"s": 30405,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 30490,
"s": 30439,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 30548,
"s": 30490,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 30603,
"s": 30548,
"text": "Sum of Manhattan distances between all pairs of points"
},
{
"code": null,
"e": 30650,
"s": 30603,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 30697,
"s": 30650,
"text": "Program for Point of Intersection of Two Lines"
}
] |
LinkedBlockingQueue poll() method in Java - GeeksforGeeks | 26 Nov, 2018
There is two types of poll() method in LinkedBlockingQueue.
The poll() method of LinkedBlockingQueue returns the head of LinkedBlockingQueue by removing that element from queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is empty then poll method returns null.
Syntax:
public E poll()
Return Value: This method retrieves and removes element from head of this LinkedBlockingQueue. If the queue is empty, then it returns null.
Below programs illustrates poll() method of LinkedBlockingQueue class:
Program 1: Removing elements from the LinkedBlockingQueue using poll() method where LinkedBlockingQueue contains list of names.
// Java Program Demonstrate poll()// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;public class GFG { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacityOfQueue = 4; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add("Ravi"); linkedQueue.add("Suraj"); linkedQueue.add("Harsh"); linkedQueue.add("Sayan"); // print elements of queue System.out.println("Items in Queue are " + linkedQueue); // we want to remove two elements from queue from head // Applying poll() method on queue to remove element String removedItem1 = linkedQueue.poll(); // print removedItem and queue System.out.println("Removed Item is " + removedItem1); // print elements of queue after removing first item System.out.println("Remaining Items in Queue are " + linkedQueue); // Applying poll() method on queue to remove another element String removedItem2 = linkedQueue.poll(); // print removedItem and queue System.out.println("Removed Item is " + removedItem2); // print elements of queue after removing first item System.out.println("Remaining Items in Queue are " + linkedQueue); }}
Items in Queue are [Ravi, Suraj, Harsh, Sayan]
Removed Item is Ravi
Remaining Items in Queue are [Suraj, Harsh, Sayan]
Removed Item is Suraj
Remaining Items in Queue are [Harsh, Sayan]
Program 2: Removing elements from LinkedBlockingQueue which contains list of Employees and if queue is empty print null.
// Java Program Demonstrate poll()// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;public class GFG { public void pollingMethod() { // define capacity of LinkedBlockingQueue int capacityOfQueue = 5; // create object of LinkedBlockingQueue LinkedBlockingQueue<Employee> linkedQueue = new LinkedBlockingQueue<Employee>(capacityOfQueue); // Add element to LinkedBlockingQueue Employee emp1 = new Employee("Ravi", "Tester", "39000"); Employee emp2 = new Employee("Sanjeet", "Manager", "98000"); // Add Employee Objects to linkedQueue linkedQueue.add(emp1); linkedQueue.add(emp2); // remove elements from the queue // and follow this process again and again // until the queue becomes empty while (linkedQueue.size() != 0) { // Remove Employee item from LinkedBlockingQueue Employee removedEmp = linkedQueue.poll(); // print removedItem System.out.println("Removed Item is :"); System.out.println("Employee Name - " + removedEmp.name); System.out.println("Employee Position - " + removedEmp.position); System.out.println("Employee Salary - " + removedEmp.salary); // find size of linkedQueue int size = linkedQueue.size(); // print remaining capacity value System.out.println("\nSize of list :" + size + "\n"); } // Now size of Queue is Zero // Now try to Poll more items // Remove Employee item from LinkedBlockingQueue Employee removedEmp = linkedQueue.poll(); // print removedItem // size is zero so removedItem is null System.out.println("Removed Item is : " + removedEmp); } // create an Employee Object with name, // position and salary as an attribute public class Employee { public String name; public String position; public String salary; Employee(String name, String position, String salary) { this.name = name; this.position = position; this.salary = salary; } @Override public String toString() { return "Employee [name=" + name + ", position=" + position + ", salary=" + salary + "]"; } } // Main Method public static void main(String[] args) { GFG gfg = new GFG(); gfg.pollingMethod(); }}
Removed Item is :
Employee Name - Ravi
Employee Position - Tester
Employee Salary - 39000
Size of list :1
Removed Item is :
Employee Name - Sanjeet
Employee Position - Manager
Employee Salary - 98000
Size of list :0
Removed Item is : null
The poll(long timeout, TimeUnit unit) method of LinkedBlockingQueue returns the head of LinkedBlockingQueue by removing that element from the queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is empty, then poll() method will wait till a specified time for an element to become available.
Syntax:
public E poll(long timeout, TimeUnit unit) throws
Parameters: This method takes two mandatory parameters:
timeout– how long to wait, in units of unit.
unit– a TimeUnit for the timeout parameter.
Return Value: This method retrieves and removes element from head of this LinkedBlockingQueue, or null if the specified waiting time elapses before an element is available.
Exception This method throws InterruptedException if method interrupted while waiting for an element to become available.
Below programs illustrates poll(long timeout, TimeUnit unit) method of LinkedBlockingQueue class:
Program 1: Removing elements from the LinkedBlockingQueue using poll() method where LinkedBlockingQueue contains list of names.
// Java program to demonstrate// poll(long timeout, TimeUnit unit)// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.TimeUnit; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of LinkedBlockingQueue int capacityOfQueue = 4; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add("Ravi"); linkedQueue.add("Suraj"); linkedQueue.add("Harsh"); // print elements of queue System.out.println("Items in Queue are " + linkedQueue); // Try to poll elements from linkedQueue // using poll(long timeout, TimeUnit unit) method System.out.println("Removing item From head: " + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println("Now Queue Contains" + linkedQueue); // using poll(long timeout, TimeUnit unit) method System.out.println("Removing item From head: " + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println("Now Queue Contains" + linkedQueue); // using poll(long timeout, TimeUnit unit) method System.out.println("Removing item From head: " + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println("Now Queue Contains" + linkedQueue); // using poll(long timeout, TimeUnit unit) method System.out.println("Removing item From head: " + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println("Now Queue Contains" + linkedQueue); }}
Items in Queue are [Ravi, Suraj, Harsh]
Removing item From head: Ravi
Now Queue Contains[Suraj, Harsh]
Removing item From head: Suraj
Now Queue Contains[Harsh]
Removing item From head: Harsh
Now Queue Contains[]
Removing item From head: null
Now Queue Contains[]
Reference:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll–
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll-long-java.util.concurrent.TimeUnit-
Java - util package
Java-Collections
Java-Functions
Java-LinkedBlockingQueue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java | [
{
"code": null,
"e": 23626,
"s": 23598,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 23686,
"s": 23626,
"text": "There is two types of poll() method in LinkedBlockingQueue."
},
{
"code": null,
"e": 23954,
"s": 23686,
"text": "The poll() method of LinkedBlockingQueue returns the head of LinkedBlockingQueue by removing that element from queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is empty then poll method returns null."
},
{
"code": null,
"e": 23962,
"s": 23954,
"text": "Syntax:"
},
{
"code": null,
"e": 23978,
"s": 23962,
"text": "public E poll()"
},
{
"code": null,
"e": 24118,
"s": 23978,
"text": "Return Value: This method retrieves and removes element from head of this LinkedBlockingQueue. If the queue is empty, then it returns null."
},
{
"code": null,
"e": 24189,
"s": 24118,
"text": "Below programs illustrates poll() method of LinkedBlockingQueue class:"
},
{
"code": null,
"e": 24317,
"s": 24189,
"text": "Program 1: Removing elements from the LinkedBlockingQueue using poll() method where LinkedBlockingQueue contains list of names."
},
{
"code": "// Java Program Demonstrate poll()// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;public class GFG { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacityOfQueue = 4; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add(\"Ravi\"); linkedQueue.add(\"Suraj\"); linkedQueue.add(\"Harsh\"); linkedQueue.add(\"Sayan\"); // print elements of queue System.out.println(\"Items in Queue are \" + linkedQueue); // we want to remove two elements from queue from head // Applying poll() method on queue to remove element String removedItem1 = linkedQueue.poll(); // print removedItem and queue System.out.println(\"Removed Item is \" + removedItem1); // print elements of queue after removing first item System.out.println(\"Remaining Items in Queue are \" + linkedQueue); // Applying poll() method on queue to remove another element String removedItem2 = linkedQueue.poll(); // print removedItem and queue System.out.println(\"Removed Item is \" + removedItem2); // print elements of queue after removing first item System.out.println(\"Remaining Items in Queue are \" + linkedQueue); }}",
"e": 25819,
"s": 24317,
"text": null
},
{
"code": null,
"e": 26007,
"s": 25819,
"text": "Items in Queue are [Ravi, Suraj, Harsh, Sayan]\n\nRemoved Item is Ravi\nRemaining Items in Queue are [Suraj, Harsh, Sayan]\n\nRemoved Item is Suraj\nRemaining Items in Queue are [Harsh, Sayan]\n"
},
{
"code": null,
"e": 26128,
"s": 26007,
"text": "Program 2: Removing elements from LinkedBlockingQueue which contains list of Employees and if queue is empty print null."
},
{
"code": "// Java Program Demonstrate poll()// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;public class GFG { public void pollingMethod() { // define capacity of LinkedBlockingQueue int capacityOfQueue = 5; // create object of LinkedBlockingQueue LinkedBlockingQueue<Employee> linkedQueue = new LinkedBlockingQueue<Employee>(capacityOfQueue); // Add element to LinkedBlockingQueue Employee emp1 = new Employee(\"Ravi\", \"Tester\", \"39000\"); Employee emp2 = new Employee(\"Sanjeet\", \"Manager\", \"98000\"); // Add Employee Objects to linkedQueue linkedQueue.add(emp1); linkedQueue.add(emp2); // remove elements from the queue // and follow this process again and again // until the queue becomes empty while (linkedQueue.size() != 0) { // Remove Employee item from LinkedBlockingQueue Employee removedEmp = linkedQueue.poll(); // print removedItem System.out.println(\"Removed Item is :\"); System.out.println(\"Employee Name - \" + removedEmp.name); System.out.println(\"Employee Position - \" + removedEmp.position); System.out.println(\"Employee Salary - \" + removedEmp.salary); // find size of linkedQueue int size = linkedQueue.size(); // print remaining capacity value System.out.println(\"\\nSize of list :\" + size + \"\\n\"); } // Now size of Queue is Zero // Now try to Poll more items // Remove Employee item from LinkedBlockingQueue Employee removedEmp = linkedQueue.poll(); // print removedItem // size is zero so removedItem is null System.out.println(\"Removed Item is : \" + removedEmp); } // create an Employee Object with name, // position and salary as an attribute public class Employee { public String name; public String position; public String salary; Employee(String name, String position, String salary) { this.name = name; this.position = position; this.salary = salary; } @Override public String toString() { return \"Employee [name=\" + name + \", position=\" + position + \", salary=\" + salary + \"]\"; } } // Main Method public static void main(String[] args) { GFG gfg = new GFG(); gfg.pollingMethod(); }}",
"e": 28653,
"s": 26128,
"text": null
},
{
"code": null,
"e": 28897,
"s": 28653,
"text": "Removed Item is :\nEmployee Name - Ravi\nEmployee Position - Tester\nEmployee Salary - 39000\n\nSize of list :1\n\nRemoved Item is :\nEmployee Name - Sanjeet\nEmployee Position - Manager\nEmployee Salary - 98000\n\nSize of list :0\n\nRemoved Item is : null\n"
},
{
"code": null,
"e": 29253,
"s": 28897,
"text": "The poll(long timeout, TimeUnit unit) method of LinkedBlockingQueue returns the head of LinkedBlockingQueue by removing that element from the queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is empty, then poll() method will wait till a specified time for an element to become available."
},
{
"code": null,
"e": 29261,
"s": 29253,
"text": "Syntax:"
},
{
"code": null,
"e": 29312,
"s": 29261,
"text": "public E poll(long timeout, TimeUnit unit) throws "
},
{
"code": null,
"e": 29368,
"s": 29312,
"text": "Parameters: This method takes two mandatory parameters:"
},
{
"code": null,
"e": 29413,
"s": 29368,
"text": "timeout– how long to wait, in units of unit."
},
{
"code": null,
"e": 29457,
"s": 29413,
"text": "unit– a TimeUnit for the timeout parameter."
},
{
"code": null,
"e": 29630,
"s": 29457,
"text": "Return Value: This method retrieves and removes element from head of this LinkedBlockingQueue, or null if the specified waiting time elapses before an element is available."
},
{
"code": null,
"e": 29752,
"s": 29630,
"text": "Exception This method throws InterruptedException if method interrupted while waiting for an element to become available."
},
{
"code": null,
"e": 29850,
"s": 29752,
"text": "Below programs illustrates poll(long timeout, TimeUnit unit) method of LinkedBlockingQueue class:"
},
{
"code": null,
"e": 29978,
"s": 29850,
"text": "Program 1: Removing elements from the LinkedBlockingQueue using poll() method where LinkedBlockingQueue contains list of names."
},
{
"code": "// Java program to demonstrate// poll(long timeout, TimeUnit unit)// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.TimeUnit; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of LinkedBlockingQueue int capacityOfQueue = 4; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add(\"Ravi\"); linkedQueue.add(\"Suraj\"); linkedQueue.add(\"Harsh\"); // print elements of queue System.out.println(\"Items in Queue are \" + linkedQueue); // Try to poll elements from linkedQueue // using poll(long timeout, TimeUnit unit) method System.out.println(\"Removing item From head: \" + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println(\"Now Queue Contains\" + linkedQueue); // using poll(long timeout, TimeUnit unit) method System.out.println(\"Removing item From head: \" + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println(\"Now Queue Contains\" + linkedQueue); // using poll(long timeout, TimeUnit unit) method System.out.println(\"Removing item From head: \" + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println(\"Now Queue Contains\" + linkedQueue); // using poll(long timeout, TimeUnit unit) method System.out.println(\"Removing item From head: \" + linkedQueue.poll(5, TimeUnit.SECONDS)); // print queue details System.out.println(\"Now Queue Contains\" + linkedQueue); }}",
"e": 31909,
"s": 29978,
"text": null
},
{
"code": null,
"e": 32177,
"s": 31909,
"text": "Items in Queue are [Ravi, Suraj, Harsh]\n\nRemoving item From head: Ravi\nNow Queue Contains[Suraj, Harsh]\n\nRemoving item From head: Suraj\nNow Queue Contains[Harsh]\n\nRemoving item From head: Harsh\nNow Queue Contains[]\n\nRemoving item From head: null\nNow Queue Contains[]\n"
},
{
"code": null,
"e": 32188,
"s": 32177,
"text": "Reference:"
},
{
"code": null,
"e": 32282,
"s": 32188,
"text": "https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll–"
},
{
"code": null,
"e": 32411,
"s": 32282,
"text": "https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll-long-java.util.concurrent.TimeUnit-"
},
{
"code": null,
"e": 32431,
"s": 32411,
"text": "Java - util package"
},
{
"code": null,
"e": 32448,
"s": 32431,
"text": "Java-Collections"
},
{
"code": null,
"e": 32463,
"s": 32448,
"text": "Java-Functions"
},
{
"code": null,
"e": 32488,
"s": 32463,
"text": "Java-LinkedBlockingQueue"
},
{
"code": null,
"e": 32493,
"s": 32488,
"text": "Java"
},
{
"code": null,
"e": 32498,
"s": 32493,
"text": "Java"
},
{
"code": null,
"e": 32515,
"s": 32498,
"text": "Java-Collections"
},
{
"code": null,
"e": 32613,
"s": 32515,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32622,
"s": 32613,
"text": "Comments"
},
{
"code": null,
"e": 32635,
"s": 32622,
"text": "Old Comments"
},
{
"code": null,
"e": 32650,
"s": 32635,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32694,
"s": 32650,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32716,
"s": 32694,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32752,
"s": 32716,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 32784,
"s": 32752,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32809,
"s": 32784,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32839,
"s": 32809,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32858,
"s": 32839,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32889,
"s": 32858,
"text": "How to iterate any Map in Java"
}
] |
Groovy - Lists contains() | Returns true if this List contains the specified value.
boolean contains(Object value)
Value − The value to find in the list.
True or false depending on if the value is present in the list.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
def lst = [11, 12, 13, 14];
println(lst.contains(12));
println(lst.contains(18));
}
}
When we run the above program, we will get the following result −
true
false
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2294,
"s": 2238,
"text": "Returns true if this List contains the specified value."
},
{
"code": null,
"e": 2326,
"s": 2294,
"text": "boolean contains(Object value)\n"
},
{
"code": null,
"e": 2365,
"s": 2326,
"text": "Value − The value to find in the list."
},
{
"code": null,
"e": 2429,
"s": 2365,
"text": "True or false depending on if the value is present in the list."
},
{
"code": null,
"e": 2483,
"s": 2429,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2650,
"s": 2483,
"text": "class Example { \n static void main(String[] args) { \n def lst = [11, 12, 13, 14]; \n\t\t\n println(lst.contains(12)); \n println(lst.contains(18));\n }\n}"
},
{
"code": null,
"e": 2716,
"s": 2650,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2729,
"s": 2716,
"text": "true \nfalse\n"
},
{
"code": null,
"e": 2762,
"s": 2729,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2780,
"s": 2762,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2815,
"s": 2780,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2833,
"s": 2815,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2840,
"s": 2833,
"text": " Print"
},
{
"code": null,
"e": 2851,
"s": 2840,
"text": " Add Notes"
}
] |
Converting Context Free Grammar to Greibach Normal Form - GeeksforGeeks | 07 Feb, 2019
Prerequisite – Context Free Grammars, Simplifying Context Free Grammars
A context free grammar (CGF) is in Greibach Normal Form (GNF) if all production rules satisfy one of the following conditions:
A non-terminal generating a terminal (e.g.; X->x)
A non-terminal generating a terminal followed by any number of non-terminals (e.g.; X->xX1X2...Xn)
Start symbol generating ε. (e.g.; S-> ε)
Consider the following grammars:
G1 = {S->aA|bB, B->bB|b, A->aA|a}
G2 = {S->aA|bB, B->bB|ε, A->aA|ε}
The grammar G1 is in GNF as production rules satisfy the rules specified for GNF. However, the grammar G2 is not in GNF as the production rules B-> ε and A-> ε do not satisfy the rules specified for GNF (only start symbol can generate ε).Note –
For a given grammar, there can be more than one GNF
GNF produces the same language as generated by CFG
How to convert CFG to GNF –
Step 1. Convert the grammar into CNF.If the given grammar is not in CNF, convert it to CNF. You can refer following article to convert CFG to CNF: Converting Context Free Grammar to Chomsky Normal Form
Step 2. Eliminate left recursion from grammar if it exists.If CFG contains left recursion, eliminate them. You can refer following article to eliminate left recursion: Parsing | Set 1 (Introduction, Ambiguity and Parsers)
Step 3. Convert the production rules into GNF form.If any production rule is not in the GNF form, convert them. Let us take an example to convert CFG to GNF. Consider the given grammar G1:
S → XA|BB
B → b|SB
X → b
A → a
As G1 is already in CNF and there is not left recursion, we can skip step 1and 2 and directly move to step 3.The production rule B->SB is not in GNF, therefore, we substitute S -> XA|BB in production rule B->SB as:
S → XA|BB
B → b|XAB|BBB
X → b
A → a
The production rules S->XA and B->XAB is not in GNF, therefore, we substitute X->b in production rules S->XA and B->XAB as:
S → bA|BB
B → b|bAB|BBB
X → b
A → a
Removing left recursion (B->BBB), we get:
S → bA|BB
B → bC|bABC
C → BBC| ε
X → b
A → a
Removing null production (C-> ε), we get:
S → bA|BB
B → bC|bABC|b|bAB
C → BBC|BB
X → b
A → a
The production rules S->BB is not in GNF, therefore, we substitute B → bC|bABC|b|bAB in production rules S->BB as:
S → bA| bCB|bABCB|bB|bABB
B → bC|bABC|b|bAB
C → BBC|BB
X → b
A → a
The production rules C->BB is not in GNF, therefore, we substitute B → bC|bABC|b|bAB in production rules C->BB as:
S → bA| bCB|bABCB|bB|bABB
B → bC|bABC|b|bAB
C → BBC
C → bCB|bABCB|bB|bABB
X → b
A → a
The production rules C->BBC is not in GNF, therefore, we substitute B → bC|bABC|b|bAB in production rules C->BBC as:
S → bA| bCB|bABCB|bB|bABB
B → bC|bABC|b|bAB
C → bCBC|bABCBC|bBC|bABBC
C → bCB|bABCB|bB|bABB
X → b
A → a
This is the GNF form for the grammar G1.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Difference between DFA and NFA
Regular expression to ∈-NFA
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages | [
{
"code": null,
"e": 31189,
"s": 31161,
"text": "\n07 Feb, 2019"
},
{
"code": null,
"e": 31261,
"s": 31189,
"text": "Prerequisite – Context Free Grammars, Simplifying Context Free Grammars"
},
{
"code": null,
"e": 31388,
"s": 31261,
"text": "A context free grammar (CGF) is in Greibach Normal Form (GNF) if all production rules satisfy one of the following conditions:"
},
{
"code": null,
"e": 31438,
"s": 31388,
"text": "A non-terminal generating a terminal (e.g.; X->x)"
},
{
"code": null,
"e": 31537,
"s": 31438,
"text": "A non-terminal generating a terminal followed by any number of non-terminals (e.g.; X->xX1X2...Xn)"
},
{
"code": null,
"e": 31578,
"s": 31537,
"text": "Start symbol generating ε. (e.g.; S-> ε)"
},
{
"code": null,
"e": 31611,
"s": 31578,
"text": "Consider the following grammars:"
},
{
"code": null,
"e": 31680,
"s": 31611,
"text": "G1 = {S->aA|bB, B->bB|b, A->aA|a} \nG2 = {S->aA|bB, B->bB|ε, A->aA|ε}"
},
{
"code": null,
"e": 31925,
"s": 31680,
"text": "The grammar G1 is in GNF as production rules satisfy the rules specified for GNF. However, the grammar G2 is not in GNF as the production rules B-> ε and A-> ε do not satisfy the rules specified for GNF (only start symbol can generate ε).Note –"
},
{
"code": null,
"e": 31977,
"s": 31925,
"text": "For a given grammar, there can be more than one GNF"
},
{
"code": null,
"e": 32028,
"s": 31977,
"text": "GNF produces the same language as generated by CFG"
},
{
"code": null,
"e": 32056,
"s": 32028,
"text": "How to convert CFG to GNF –"
},
{
"code": null,
"e": 32258,
"s": 32056,
"text": "Step 1. Convert the grammar into CNF.If the given grammar is not in CNF, convert it to CNF. You can refer following article to convert CFG to CNF: Converting Context Free Grammar to Chomsky Normal Form"
},
{
"code": null,
"e": 32480,
"s": 32258,
"text": "Step 2. Eliminate left recursion from grammar if it exists.If CFG contains left recursion, eliminate them. You can refer following article to eliminate left recursion: Parsing | Set 1 (Introduction, Ambiguity and Parsers)"
},
{
"code": null,
"e": 32669,
"s": 32480,
"text": "Step 3. Convert the production rules into GNF form.If any production rule is not in the GNF form, convert them. Let us take an example to convert CFG to GNF. Consider the given grammar G1:"
},
{
"code": null,
"e": 32703,
"s": 32669,
"text": "S → XA|BB \nB → b|SB \nX → b \nA → a"
},
{
"code": null,
"e": 32918,
"s": 32703,
"text": "As G1 is already in CNF and there is not left recursion, we can skip step 1and 2 and directly move to step 3.The production rule B->SB is not in GNF, therefore, we substitute S -> XA|BB in production rule B->SB as:"
},
{
"code": null,
"e": 32957,
"s": 32918,
"text": "S → XA|BB \nB → b|XAB|BBB \nX → b \nA → a"
},
{
"code": null,
"e": 33081,
"s": 32957,
"text": "The production rules S->XA and B->XAB is not in GNF, therefore, we substitute X->b in production rules S->XA and B->XAB as:"
},
{
"code": null,
"e": 33120,
"s": 33081,
"text": "S → bA|BB \nB → b|bAB|BBB \nX → b \nA → a"
},
{
"code": null,
"e": 33162,
"s": 33120,
"text": "Removing left recursion (B->BBB), we get:"
},
{
"code": null,
"e": 33209,
"s": 33162,
"text": "S → bA|BB \nB → bC|bABC\nC → BBC| ε\nX → b \nA → a"
},
{
"code": null,
"e": 33251,
"s": 33209,
"text": "Removing null production (C-> ε), we get:"
},
{
"code": null,
"e": 33304,
"s": 33251,
"text": "S → bA|BB \nB → bC|bABC|b|bAB\nC → BBC|BB\nX → b \nA → a"
},
{
"code": null,
"e": 33419,
"s": 33304,
"text": "The production rules S->BB is not in GNF, therefore, we substitute B → bC|bABC|b|bAB in production rules S->BB as:"
},
{
"code": null,
"e": 33488,
"s": 33419,
"text": "S → bA| bCB|bABCB|bB|bABB \nB → bC|bABC|b|bAB\nC → BBC|BB\nX → b \nA → a"
},
{
"code": null,
"e": 33603,
"s": 33488,
"text": "The production rules C->BB is not in GNF, therefore, we substitute B → bC|bABC|b|bAB in production rules C->BB as:"
},
{
"code": null,
"e": 33691,
"s": 33603,
"text": "S → bA| bCB|bABCB|bB|bABB \nB → bC|bABC|b|bAB\nC → BBC\nC → bCB|bABCB|bB|bABB\nX → b \nA → a"
},
{
"code": null,
"e": 33808,
"s": 33691,
"text": "The production rules C->BBC is not in GNF, therefore, we substitute B → bC|bABC|b|bAB in production rules C->BBC as:"
},
{
"code": null,
"e": 33914,
"s": 33808,
"text": "S → bA| bCB|bABCB|bB|bABB \nB → bC|bABC|b|bAB\nC → bCBC|bABCBC|bBC|bABBC\nC → bCB|bABCB|bB|bABB\nX → b \nA → a"
},
{
"code": null,
"e": 33955,
"s": 33914,
"text": "This is the GNF form for the grammar G1."
},
{
"code": null,
"e": 33963,
"s": 33955,
"text": "GATE CS"
},
{
"code": null,
"e": 33996,
"s": 33963,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 34094,
"s": 33996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34114,
"s": 34094,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 34138,
"s": 34114,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 34151,
"s": 34138,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 34178,
"s": 34151,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 34227,
"s": 34178,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 34258,
"s": 34227,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 34286,
"s": 34258,
"text": "Regular expression to ∈-NFA"
},
{
"code": null,
"e": 34341,
"s": 34286,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 34386,
"s": 34341,
"text": "Design 101 sequence detector (Mealy machine)"
}
] |
LocalDate plusWeeks() method in Java with Examples - GeeksforGeeks | 19 Jun, 2019
The plusWeeks() method of LocalDate class in Java is used to add the number of specified week in this LocalDate and return a copy of LocalDate.For example, 2018-12-24 plus one week would result in 2018-12-31. This instance is immutable and unaffected by this method call.
Syntax:
public LocalDate plusWeeks(long weeksToAdd)
Parameters: This method accepts a single parameter weeksToAdd which represents the weeks to add, may be negative.
Return value: This method returns a LocalDate based on this date with the weeks added, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the plusWeeks() method:
Program 1:
// Java program to demonstrate// LocalDate.plusWeeks() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-12-26"); // print instance System.out.println("LocalDate before" + " adding weeks: " + date); // add 5 weeks LocalDate returnvalue = date.plusWeeks(5); // print result System.out.println("LocalDate after " + " adding weeks: " + returnvalue); }}
Output:
LocalDate before adding weeks: 2018-12-26
LocalDate after adding weeks: 2019-01-30
Program 2:
// Java program to demonstrate// LocalDate.plusWeeks() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-12-24"); // print instance System.out.println("LocalDate before" + " adding weeks: " + date); // add -3 weeks LocalDate returnvalue = date.plusWeeks(-3); // print result System.out.println("LocalDate after " + " adding weeks: " + returnvalue); }}
LocalDate before adding weeks: 2018-12-24
LocalDate after adding weeks: 2018-12-03
Reference :https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusWeeks(long)
nidhi_biet
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Constructors in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 24090,
"s": 24062,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 24362,
"s": 24090,
"text": "The plusWeeks() method of LocalDate class in Java is used to add the number of specified week in this LocalDate and return a copy of LocalDate.For example, 2018-12-24 plus one week would result in 2018-12-31. This instance is immutable and unaffected by this method call."
},
{
"code": null,
"e": 24370,
"s": 24362,
"text": "Syntax:"
},
{
"code": null,
"e": 24415,
"s": 24370,
"text": "public LocalDate plusWeeks(long weeksToAdd)\n"
},
{
"code": null,
"e": 24529,
"s": 24415,
"text": "Parameters: This method accepts a single parameter weeksToAdd which represents the weeks to add, may be negative."
},
{
"code": null,
"e": 24626,
"s": 24529,
"text": "Return value: This method returns a LocalDate based on this date with the weeks added, not null."
},
{
"code": null,
"e": 24722,
"s": 24626,
"text": "Exception: This method throws DateTimeException if the result exceeds the supported date range."
},
{
"code": null,
"e": 24772,
"s": 24722,
"text": "Below programs illustrate the plusWeeks() method:"
},
{
"code": null,
"e": 24783,
"s": 24772,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// LocalDate.plusWeeks() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-12-26\"); // print instance System.out.println(\"LocalDate before\" + \" adding weeks: \" + date); // add 5 weeks LocalDate returnvalue = date.plusWeeks(5); // print result System.out.println(\"LocalDate after \" + \" adding weeks: \" + returnvalue); }}",
"e": 25387,
"s": 24783,
"text": null
},
{
"code": null,
"e": 25395,
"s": 25387,
"text": "Output:"
},
{
"code": null,
"e": 25480,
"s": 25395,
"text": "LocalDate before adding weeks: 2018-12-26\nLocalDate after adding weeks: 2019-01-30\n"
},
{
"code": null,
"e": 25491,
"s": 25480,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalDate.plusWeeks() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-12-24\"); // print instance System.out.println(\"LocalDate before\" + \" adding weeks: \" + date); // add -3 weeks LocalDate returnvalue = date.plusWeeks(-3); // print result System.out.println(\"LocalDate after \" + \" adding weeks: \" + returnvalue); }}",
"e": 26097,
"s": 25491,
"text": null
},
{
"code": null,
"e": 26182,
"s": 26097,
"text": "LocalDate before adding weeks: 2018-12-24\nLocalDate after adding weeks: 2018-12-03\n"
},
{
"code": null,
"e": 26277,
"s": 26182,
"text": "Reference :https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusWeeks(long)"
},
{
"code": null,
"e": 26288,
"s": 26277,
"text": "nidhi_biet"
},
{
"code": null,
"e": 26303,
"s": 26288,
"text": "Java-Functions"
},
{
"code": null,
"e": 26318,
"s": 26303,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 26336,
"s": 26318,
"text": "Java-time package"
},
{
"code": null,
"e": 26341,
"s": 26336,
"text": "Java"
},
{
"code": null,
"e": 26346,
"s": 26341,
"text": "Java"
},
{
"code": null,
"e": 26444,
"s": 26346,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26459,
"s": 26444,
"text": "Stream In Java"
},
{
"code": null,
"e": 26478,
"s": 26459,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26524,
"s": 26478,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26545,
"s": 26524,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26575,
"s": 26545,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26592,
"s": 26575,
"text": "Generics in Java"
},
{
"code": null,
"e": 26635,
"s": 26592,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26657,
"s": 26635,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 26678,
"s": 26657,
"text": "Introduction to Java"
}
] |
TuriCreate library in Python - GeeksforGeeks | 16 Jul, 2020
TuriCreate(Machine Learning Python Library):Custom Machine Learning models can be made using Turi create very easily. You don’t have to be an expert in Machine Learning to use Turi create and it helps in building an add recommendations, object detection, image classification, image similarity or activity classification systems easily.
Advantages of TuriCreate:
It is easy to use.
Flexible to use.
Ready to deploy model to ios, MacOs, watchOs and tvOs apps.
It one of the crazy features is that it can read the .csv(Comma Separated Values) and use the Machine Learning Model.
Supported Platform for TuriCreate:
macOS 10.12+
Linux (with glibc 2.12+)
Windows 10 (via WSL)=It is little tricky to install it on windows but you can install via WSL(Windows Subsystem Linux) and if does have the same error then you have to upgrade pip by using this command:pip3 install –upgrade pipSystem RequirementsPython 2.7, 3.5 or above (ex. 3.7, 3.8)Python 3.7 macOS only+x86_64 architectureUsing a Conda Environment or virtualenv is highly recommended so that we can have different Python Interpreter on the same Machine.
pip3 install –upgrade pip
System Requirements
Python 2.7, 3.5 or above (ex. 3.7, 3.8)
Python 3.7 macOS only+
x86_64 architecture
Using a Conda Environment or virtualenv is highly recommended so that we can have different Python Interpreter on the same Machine.
Turicreate uses SFrames for data handling:SFrames means scalable data frame. It is a tabular, column-mutable data frame object that can scale to big data. It’s one of the advantages is that is mutable.
Code: How to use SFrame for Loading the data:
import turicreate as tcfrom turicreate import SFrame # Let's declare a variable for loading the datadata = tc.SFrame("data.csv") # Here data.csv is a file stored in your system# with name = data
Data Structure of TuriCreate:
SFrame
SGraph
SArray
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree Introduction with example
Python | Decision tree implementation
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24638,
"s": 24610,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24975,
"s": 24638,
"text": "TuriCreate(Machine Learning Python Library):Custom Machine Learning models can be made using Turi create very easily. You don’t have to be an expert in Machine Learning to use Turi create and it helps in building an add recommendations, object detection, image classification, image similarity or activity classification systems easily."
},
{
"code": null,
"e": 25001,
"s": 24975,
"text": "Advantages of TuriCreate:"
},
{
"code": null,
"e": 25020,
"s": 25001,
"text": "It is easy to use."
},
{
"code": null,
"e": 25037,
"s": 25020,
"text": "Flexible to use."
},
{
"code": null,
"e": 25097,
"s": 25037,
"text": "Ready to deploy model to ios, MacOs, watchOs and tvOs apps."
},
{
"code": null,
"e": 25215,
"s": 25097,
"text": "It one of the crazy features is that it can read the .csv(Comma Separated Values) and use the Machine Learning Model."
},
{
"code": null,
"e": 25250,
"s": 25215,
"text": "Supported Platform for TuriCreate:"
},
{
"code": null,
"e": 25263,
"s": 25250,
"text": "macOS 10.12+"
},
{
"code": null,
"e": 25288,
"s": 25263,
"text": "Linux (with glibc 2.12+)"
},
{
"code": null,
"e": 25746,
"s": 25288,
"text": "Windows 10 (via WSL)=It is little tricky to install it on windows but you can install via WSL(Windows Subsystem Linux) and if does have the same error then you have to upgrade pip by using this command:pip3 install –upgrade pipSystem RequirementsPython 2.7, 3.5 or above (ex. 3.7, 3.8)Python 3.7 macOS only+x86_64 architectureUsing a Conda Environment or virtualenv is highly recommended so that we can have different Python Interpreter on the same Machine."
},
{
"code": null,
"e": 25772,
"s": 25746,
"text": "pip3 install –upgrade pip"
},
{
"code": null,
"e": 25792,
"s": 25772,
"text": "System Requirements"
},
{
"code": null,
"e": 25832,
"s": 25792,
"text": "Python 2.7, 3.5 or above (ex. 3.7, 3.8)"
},
{
"code": null,
"e": 25855,
"s": 25832,
"text": "Python 3.7 macOS only+"
},
{
"code": null,
"e": 25875,
"s": 25855,
"text": "x86_64 architecture"
},
{
"code": null,
"e": 26007,
"s": 25875,
"text": "Using a Conda Environment or virtualenv is highly recommended so that we can have different Python Interpreter on the same Machine."
},
{
"code": null,
"e": 26209,
"s": 26007,
"text": "Turicreate uses SFrames for data handling:SFrames means scalable data frame. It is a tabular, column-mutable data frame object that can scale to big data. It’s one of the advantages is that is mutable."
},
{
"code": null,
"e": 26255,
"s": 26209,
"text": "Code: How to use SFrame for Loading the data:"
},
{
"code": "import turicreate as tcfrom turicreate import SFrame # Let's declare a variable for loading the datadata = tc.SFrame(\"data.csv\") # Here data.csv is a file stored in your system# with name = data",
"e": 26452,
"s": 26255,
"text": null
},
{
"code": null,
"e": 26482,
"s": 26452,
"text": "Data Structure of TuriCreate:"
},
{
"code": null,
"e": 26489,
"s": 26482,
"text": "SFrame"
},
{
"code": null,
"e": 26496,
"s": 26489,
"text": "SGraph"
},
{
"code": null,
"e": 26503,
"s": 26496,
"text": "SArray"
},
{
"code": null,
"e": 26520,
"s": 26503,
"text": "Machine Learning"
},
{
"code": null,
"e": 26527,
"s": 26520,
"text": "Python"
},
{
"code": null,
"e": 26544,
"s": 26527,
"text": "Machine Learning"
},
{
"code": null,
"e": 26642,
"s": 26544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26665,
"s": 26642,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 26705,
"s": 26665,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 26743,
"s": 26705,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 26776,
"s": 26743,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 26810,
"s": 26776,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 26838,
"s": 26810,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26888,
"s": 26838,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26910,
"s": 26888,
"text": "Python map() function"
}
] |
How to detect when the window size is resized using JavaScript ? - GeeksforGeeks | 02 Apr, 2020
The window resize event occurs whenever the size of the browser window gets changed. We can listen to the resize event in two ways:
Using onresize eventUsing Resize Observer API
Using onresize event
Using Resize Observer API
Method 1: Using resize event: We can add an event listener to the body element which fires every time when the window size is resized.
Example:
<!DOCTYPE html><html> <head> <title> How to detect and resize the window size </title> <style> body { text-align: center; } h1 { color:green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> Resizing the screen size and display its <br>corresponding width and height </h3> <div id="height">Height: <span></span></div> <div id="width">Width: <span></span></div> <script> const height = document.querySelector("#height span"); const width = document.querySelector("#width span"); // Insert values on load of page window.onload = function() { height.innerHTML = window.innerHeight; width.innerHTML = window.innerWidth; }; // Change values when window is resized window.onresize = function() { // Setting the current height & width // to the elements height.innerHTML = window.innerHeight; width.innerHTML = window.innerWidth; }; </script></body> </html>
Output:
Method 2: Using ResizeObserver API: We can use the latest ResizeObserver API to listen the window resize event. This API is not fully supported.
Example:
<!DOCTYPE html><html> <head> <title> How to detect and resize the window size </title> <style> body { text-align: center; } h1 { color:green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> Resizing the screen size and display its <br>corresponding width and height </h3> <div id="height">Height: <span></span></div> <div id="width">Width: <span></span></div> <script> const body = document.getElementsByTagName("body")[0]; const height = document.querySelector("#height span"); const width = document.querySelector("#width span"); // Initialize resize observer object let resizeObserver = new ResizeObserver(() => { // Set the current height and width // to the element height.innerHTML = window.innerHeight; width.innerHTML = window.innerWidth; }); // Add a listener to body resizeObserver.observe(body); </script></body> </html>
Output:
References:
MDN
Browser Support
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n02 Apr, 2020"
},
{
"code": null,
"e": 24954,
"s": 24822,
"text": "The window resize event occurs whenever the size of the browser window gets changed. We can listen to the resize event in two ways:"
},
{
"code": null,
"e": 25000,
"s": 24954,
"text": "Using onresize eventUsing Resize Observer API"
},
{
"code": null,
"e": 25021,
"s": 25000,
"text": "Using onresize event"
},
{
"code": null,
"e": 25047,
"s": 25021,
"text": "Using Resize Observer API"
},
{
"code": null,
"e": 25182,
"s": 25047,
"text": "Method 1: Using resize event: We can add an event listener to the body element which fires every time when the window size is resized."
},
{
"code": null,
"e": 25191,
"s": 25182,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to detect and resize the window size </title> <style> body { text-align: center; } h1 { color:green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> Resizing the screen size and display its <br>corresponding width and height </h3> <div id=\"height\">Height: <span></span></div> <div id=\"width\">Width: <span></span></div> <script> const height = document.querySelector(\"#height span\"); const width = document.querySelector(\"#width span\"); // Insert values on load of page window.onload = function() { height.innerHTML = window.innerHeight; width.innerHTML = window.innerWidth; }; // Change values when window is resized window.onresize = function() { // Setting the current height & width // to the elements height.innerHTML = window.innerHeight; width.innerHTML = window.innerWidth; }; </script></body> </html>",
"e": 26339,
"s": 25191,
"text": null
},
{
"code": null,
"e": 26347,
"s": 26339,
"text": "Output:"
},
{
"code": null,
"e": 26492,
"s": 26347,
"text": "Method 2: Using ResizeObserver API: We can use the latest ResizeObserver API to listen the window resize event. This API is not fully supported."
},
{
"code": null,
"e": 26501,
"s": 26492,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to detect and resize the window size </title> <style> body { text-align: center; } h1 { color:green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> Resizing the screen size and display its <br>corresponding width and height </h3> <div id=\"height\">Height: <span></span></div> <div id=\"width\">Width: <span></span></div> <script> const body = document.getElementsByTagName(\"body\")[0]; const height = document.querySelector(\"#height span\"); const width = document.querySelector(\"#width span\"); // Initialize resize observer object let resizeObserver = new ResizeObserver(() => { // Set the current height and width // to the element height.innerHTML = window.innerHeight; width.innerHTML = window.innerWidth; }); // Add a listener to body resizeObserver.observe(body); </script></body> </html>",
"e": 27624,
"s": 26501,
"text": null
},
{
"code": null,
"e": 27632,
"s": 27624,
"text": "Output:"
},
{
"code": null,
"e": 27644,
"s": 27632,
"text": "References:"
},
{
"code": null,
"e": 27648,
"s": 27644,
"text": "MDN"
},
{
"code": null,
"e": 27664,
"s": 27648,
"text": "Browser Support"
},
{
"code": null,
"e": 27680,
"s": 27664,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27687,
"s": 27680,
"text": "Picked"
},
{
"code": null,
"e": 27698,
"s": 27687,
"text": "JavaScript"
},
{
"code": null,
"e": 27715,
"s": 27698,
"text": "Web Technologies"
},
{
"code": null,
"e": 27813,
"s": 27715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27822,
"s": 27813,
"text": "Comments"
},
{
"code": null,
"e": 27835,
"s": 27822,
"text": "Old Comments"
},
{
"code": null,
"e": 27880,
"s": 27835,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27941,
"s": 27880,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28013,
"s": 27941,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28065,
"s": 28013,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28111,
"s": 28065,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28153,
"s": 28111,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28186,
"s": 28153,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28248,
"s": 28186,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28291,
"s": 28248,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to refresh Activity when IntentService is finished in android? | Before getting into the example, we should know what Intent service is in android. Intent Service is going to do background operation asynchronously. When user call startService() from activity, it doesn’t create an instance for each request and it going to stop service after done some action in service class or else we need to stop service using stopSelf().
This example demonstrates How to refresh Activity when IntentService is finished.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Start Service"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken text view, when the user gets the data from intent service it will update.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String someValue = intent.getStringExtra("someName");
text.setText(someValue);
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, service.class));
}
});
}
@Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}
}
Create a class called service.class file and add the following code –
package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
public class service extends IntentService {
public static volatile boolean shouldStop = false;
public service() {
super(service.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent intent1 = new Intent("com.example.andy.myapplication");
intent1.putExtra("someName", "Tutorialspoint.com");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
if(shouldStop){
stopSelf();
return;
}
}
}
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.WAKE_LOCK"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name = ".service"/>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, it has shown a default screen of an application. When user click on “Start Service” it will start service and update the textview as shown below-
Click here to download the project code | [
{
"code": null,
"e": 1423,
"s": 1062,
"text": "Before getting into the example, we should know what Intent service is in android. Intent Service is going to do background operation asynchronously. When user call startService() from activity, it doesn’t create an instance for each request and it going to stop service after done some action in service class or else we need to stop service using stopSelf()."
},
{
"code": null,
"e": 1505,
"s": 1423,
"text": "This example demonstrates How to refresh Activity when IntentService is finished."
},
{
"code": null,
"e": 1634,
"s": 1505,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1699,
"s": 1634,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2542,
"s": 1699,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2650,
"s": 2542,
"text": "In the above code, we have taken text view, when the user gets the data from intent service it will update."
},
{
"code": null,
"e": 2707,
"s": 2650,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4259,
"s": 2707,
"text": "package com.example.andy.myapplication;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Bundle;\nimport android.support.v4.content.LocalBroadcastManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String someValue = intent.getStringExtra(\"someName\");\n text.setText(someValue);\n }\n };\n @Override\n protected void onStart() {\n super.onStart();\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(\"com.example.andy.myapplication\");\n LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter);\n }\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n startService(new Intent(MainActivity.this, service.class));\n }\n });\n }\n @Override\n protected void onStop() {\n super.onStop();\n LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);\n }\n}"
},
{
"code": null,
"e": 4329,
"s": 4259,
"text": "Create a class called service.class file and add the following code –"
},
{
"code": null,
"e": 5104,
"s": 4329,
"text": "package com.example.andy.myapplication;\n\nimport android.app.IntentService;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.support.v4.content.LocalBroadcastManager;\n\npublic class service extends IntentService {\n public static volatile boolean shouldStop = false;\n public service() {\n super(service.class.getSimpleName());\n }\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n protected void onHandleIntent(Intent intent) {\n Intent intent1 = new Intent(\"com.example.andy.myapplication\");\n intent1.putExtra(\"someName\", \"Tutorialspoint.com\");\n LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);\n if(shouldStop){\n stopSelf();\n return;\n }\n }\n}"
},
{
"code": null,
"e": 5152,
"s": 5104,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 5978,
"s": 5152,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WAKE_LOCK\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name = \".service\"/>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6325,
"s": 5978,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 6492,
"s": 6325,
"text": "In the above result, it has shown a default screen of an application. When user click on “Start Service” it will start service and update the textview as shown below-"
},
{
"code": null,
"e": 6532,
"s": 6492,
"text": "Click here to download the project code"
}
] |
Evaluating a string as a mathematical expression in JavaScript | We are required to write a JavaScript function that takes in a stringified mathematical equation. The function should return the result of the equation provided to the function.
For example: If the equation is −
const str = '1+23+4+5-30';
Then the output should be 3
The code for this will be −
const str = '1+23+4+5-30';
const compute = (str = '') => {
let total = 0;
str = str.match(/[+\−]*(\.\d+|\d+(\.\d+)?)/g) || [];
while (str.length) {
total += parseFloat(str.shift());
};
return total;
};
console.log(compute(str));
And the output in the console will be −
3 | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a stringified mathematical equation. The function should return the result of the equation provided to the function."
},
{
"code": null,
"e": 1274,
"s": 1240,
"text": "For example: If the equation is −"
},
{
"code": null,
"e": 1301,
"s": 1274,
"text": "const str = '1+23+4+5-30';"
},
{
"code": null,
"e": 1329,
"s": 1301,
"text": "Then the output should be 3"
},
{
"code": null,
"e": 1357,
"s": 1329,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1607,
"s": 1357,
"text": "const str = '1+23+4+5-30';\nconst compute = (str = '') => {\n let total = 0;\n str = str.match(/[+\\−]*(\\.\\d+|\\d+(\\.\\d+)?)/g) || [];\n while (str.length) {\n total += parseFloat(str.shift());\n };\n return total;\n};\nconsole.log(compute(str));"
},
{
"code": null,
"e": 1647,
"s": 1607,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1649,
"s": 1647,
"text": "3"
}
] |
DateTime.ToShortTimeString() Method in C# | The DateTime.ToShortTimeString() method in C# is used to convert the value of the current DateTime object to its equivalent short time string representation.
Following is the syntax −
public string ToShortTimeString ();
Let us now see an example to implement the DateTime.ToShortTimeString() method −
using System;
using System.Globalization;
public class Demo {
public static void Main() {
DateTime d = DateTime.Now;
Console.WriteLine("Date = {0}", d);
Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name);
var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
string str = d.ToShortTimeString();
Console.WriteLine("Short time string = {0}", pattern.ShortTimePattern);
Console.WriteLine("Short time string representation = {0}", str);
}
}
This will produce the following output −
Date = 10/16/2019 8:59:23 AM
Current culture = en-US
Short time string = h:mm tt
Short time string representation = 8:59 AM
Let us now see another example to implement the DateTime.ToShortTimeString() method −
using System;
public class Demo {
public static void Main() {
DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
Console.WriteLine("Date = {0}", d);
string str = d.ToShortTimeString();
Console.WriteLine("Short time string representation = {0}", str);
}
}
This will produce the following output −
Date = 11/11/2019 7:11:25 AM
Short time string representation = 7:11 AM | [
{
"code": null,
"e": 1220,
"s": 1062,
"text": "The DateTime.ToShortTimeString() method in C# is used to convert the value of the current DateTime object to its equivalent short time string representation."
},
{
"code": null,
"e": 1246,
"s": 1220,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1282,
"s": 1246,
"text": "public string ToShortTimeString ();"
},
{
"code": null,
"e": 1363,
"s": 1282,
"text": "Let us now see an example to implement the DateTime.ToShortTimeString() method −"
},
{
"code": null,
"e": 1872,
"s": 1363,
"text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main() {\n DateTime d = DateTime.Now;\n Console.WriteLine(\"Date = {0}\", d);\n Console.WriteLine(\"Current culture = \"+CultureInfo.CurrentCulture.Name);\n var pattern = CultureInfo.CurrentCulture.DateTimeFormat;\n string str = d.ToShortTimeString();\n Console.WriteLine(\"Short time string = {0}\", pattern.ShortTimePattern);\n Console.WriteLine(\"Short time string representation = {0}\", str);\n }\n}"
},
{
"code": null,
"e": 1913,
"s": 1872,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2037,
"s": 1913,
"text": "Date = 10/16/2019 8:59:23 AM\nCurrent culture = en-US\nShort time string = h:mm tt\nShort time string representation = 8:59 AM"
},
{
"code": null,
"e": 2123,
"s": 2037,
"text": "Let us now see another example to implement the DateTime.ToShortTimeString() method −"
},
{
"code": null,
"e": 2409,
"s": 2123,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);\n Console.WriteLine(\"Date = {0}\", d);\n string str = d.ToShortTimeString();\n Console.WriteLine(\"Short time string representation = {0}\", str);\n }\n}"
},
{
"code": null,
"e": 2450,
"s": 2409,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2522,
"s": 2450,
"text": "Date = 11/11/2019 7:11:25 AM\nShort time string representation = 7:11 AM"
}
] |
Java program to merge two files into a third file | Following is the Java program to merge two files into a third file −
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {
PrintWriter my_pw = new PrintWriter("path to third .txt file");
BufferedReader my_br = new BufferedReader(new FileReader("path to first .txt file"));
String my_line = my_br.readLine();
while (my_line != null) {
my_pw.println(my_line);
my_line = my_br.readLine();
}
my_br = new BufferedReader(new FileReader("path to second .txt file"));
my_line = my_br.readLine();
while(my_line != null) {
my_pw.println(my_line);
my_line = my_br.readLine();
}
my_pw.flush();
my_br.close();
my_pw.close();
System.out.println("The first two files have been merged into the third file successfully.");
}
}
The first two files have been merged into the third file successfully.
A class named Demo contains the main function. Here an instance of the PrintWriter class and BufferedReader is generated. Every line in the two files is read, until it reaches null. It is then added to the third file, and the class instances are flushed and closed. | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Following is the Java program to merge two files into a third file −"
},
{
"code": null,
"e": 1936,
"s": 1131,
"text": "import java.io.*;\npublic class Demo {\n public static void main(String[] args) throws IOException {\n PrintWriter my_pw = new PrintWriter(\"path to third .txt file\");\n BufferedReader my_br = new BufferedReader(new FileReader(\"path to first .txt file\"));\n String my_line = my_br.readLine();\n while (my_line != null) {\n my_pw.println(my_line);\n my_line = my_br.readLine();\n }\n my_br = new BufferedReader(new FileReader(\"path to second .txt file\"));\n my_line = my_br.readLine();\n while(my_line != null) {\n my_pw.println(my_line);\n my_line = my_br.readLine();\n }\n my_pw.flush();\n my_br.close();\n my_pw.close();\n System.out.println(\"The first two files have been merged into the third file successfully.\");\n }\n}"
},
{
"code": null,
"e": 2007,
"s": 1936,
"text": "The first two files have been merged into the third file successfully."
},
{
"code": null,
"e": 2273,
"s": 2007,
"text": "A class named Demo contains the main function. Here an instance of the PrintWriter class and BufferedReader is generated. Every line in the two files is read, until it reaches null. It is then added to the third file, and the class instances are flushed and closed."
}
] |
Check if the given RGB color code is valid or not - GeeksforGeeks | 06 Dec, 2021
Given three numbers R, G and B as the color code for Red, Green and Blue respectively as in the form of RGB color code. The task is to know whether the given color code is valid or not.
RGB Format: The RGB(Red, Green, Blue) format is used to define the color of an HTML element by specifying the R, G, B values range between 0 to 255. For example: RGB value of Red color is (255, 0, 0), Green color is (0, 255, 0), Blue color is (0, 0, 255) etc.
color: rgb(R, G, B);
Note: The color code is valid when all numbers are in the range [0, 255].
Examples:
Input: R=0, G=100, B=255Output: TrueExplanation: Every color is in range [0, 255]
Input: R=0, G=200, B=355Output: FalseExplanation: Blue is not in range [0, 255]
Approach: To check if the color code is valid or not we need to check if each of the color is in the range [0, 255] or not. If any of the color is not in this range, return false, else return true.
Below is the implementation of the approach:
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; // Function to check validity// of the color codebool isValidRGB(int R, int G, int B){ if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true;} // Driver codeint main(){ int R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0, G = 0, B = 0; (isValidRGB(R, G, B)) ? cout << "true\n" : cout << "false\n"; // Check if rgb(0, 100, 255) is valid or not R = 0, G = 100, B = 255; (isValidRGB(R, G, B)) ? cout << "true\n" : cout << "false\n"; // Check if rgb(0, 200, 355) is valid or not R = 0, G = 200, B = 355; (isValidRGB(R, G, B)) ? cout << "true\n" : cout << "false\n"; // Check if rgb(-100, 0, 255) is valid or not R = -100, G = 0, B = 255; (isValidRGB(R, G, B)) ? cout << "true\n" : cout << "false\n"; return 0;}
class GFG { // Function to check validity // of the color code public static boolean isValidRGB(int R, int G, int B) { if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true; } // Driver code public static void main(String args[]) { int R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0; G = 0; B = 0; if (isValidRGB(R, G, B)) System.out.println("true"); else System.out.println("false"); // Check if rgb(0, 100, 255) is valid or not R = 0; G = 100; B = 255; if (isValidRGB(R, G, B)) System.out.println("true"); else System.out.println("false"); // Check if rgb(0, 200, 355) is valid or not R = 0; G = 200; B = 355; if (isValidRGB(R, G, B)) System.out.println("true"); else System.out.println("false"); // Check if rgb(-100, 0, 255) is valid or not R = -100; G = 0; B = 255; if (isValidRGB(R, G, B)) System.out.println("true"); else System.out.println("false"); }} // This code is contributed by saurabh_jaiswal
# Function to check validity# of the color codedef isValidRGB(R, G, B) : if (R < 0 or R > 255) : return False; elif (G < 0 or G > 255) : return False; elif (B < 0 or B > 255) : return False; else : return True; # Driver codeif __name__ == "__main__" : # Check if rgb(0, 0, 0) is valid or not R = 0; G = 0; B = 0; if isValidRGB(R, G, B) : print("true") else : print("false") # Check if rgb(0, 100, 255) is valid or not R = 0; G = 100; B = 255; if isValidRGB(R, G, B) : print("true") else : print("false") # Check if rgb(0, 200, 355) is valid or not R = 0; G = 200; B = 355; if isValidRGB(R, G, B) : print("true") else : print("false") # Check if rgb(-100, 0, 255) is valid or not R = -100; G = 0; B = 255; if isValidRGB(R, G, B) : print("true") else : print("false") # This code is contributed by AnkThon
using System;public class GFG { // Function to check validity // of the color code public static bool isValidRGB(int R, int G, int B) { if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true; } // Driver code public static void Main(string []args) { int R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0; G = 0; B = 0; if (isValidRGB(R, G, B)) Console.WriteLine("true"); else Console.WriteLine("false"); // Check if rgb(0, 100, 255) is valid or not R = 0; G = 100; B = 255; if (isValidRGB(R, G, B)) Console.WriteLine("true"); else Console.WriteLine("false"); // Check if rgb(0, 200, 355) is valid or not R = 0; G = 200; B = 355; if (isValidRGB(R, G, B)) Console.WriteLine("true"); else Console.WriteLine("false"); // Check if rgb(-100, 0, 255) is valid or not R = -100; G = 0; B = 255; if (isValidRGB(R, G, B)) Console.WriteLine("true"); else Console.WriteLine("false"); }} // This code is contributed by AnkThon
<script> // Function to check validity // of the color code const isValidRGB = (R, G, B) => { if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true; } // Driver code let R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0, G = 0, B = 0; (isValidRGB(R, G, B)) ? document.write("true<br/>") : document.write("false<br/>"); // Check if rgb(0, 100, 255) is valid or not R = 0, G = 100, B = 255; (isValidRGB(R, G, B)) ? document.write("true<br/>") : document.write("false<br/>"); // Check if rgb(0, 200, 355) is valid or not R = 0, G = 200, B = 355; (isValidRGB(R, G, B)) ? document.write("true<br/>") : document.write("false<br/>"); // Check if rgb(-100, 0, 255) is valid or not R = -100, G = 0, B = 255; (isValidRGB(R, G, B)) ? document.write("true<br/>") : document.write("false<br/>"); // This code is contributed by rakeshsahni </script>
true
true
false
false
Time Complexity: O(1)Auxiliary Space: O(1)
rakeshsahni
ankthon
samim2000
_saurabh_jaiswal
Mathematical
Pattern Searching
Mathematical
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to convert a given number to words
Count ways to reach the n'th stair
KMP Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 24612,
"s": 24584,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 24798,
"s": 24612,
"text": "Given three numbers R, G and B as the color code for Red, Green and Blue respectively as in the form of RGB color code. The task is to know whether the given color code is valid or not."
},
{
"code": null,
"e": 25058,
"s": 24798,
"text": "RGB Format: The RGB(Red, Green, Blue) format is used to define the color of an HTML element by specifying the R, G, B values range between 0 to 255. For example: RGB value of Red color is (255, 0, 0), Green color is (0, 255, 0), Blue color is (0, 0, 255) etc."
},
{
"code": null,
"e": 25082,
"s": 25058,
"text": " color: rgb(R, G, B);"
},
{
"code": null,
"e": 25156,
"s": 25082,
"text": "Note: The color code is valid when all numbers are in the range [0, 255]."
},
{
"code": null,
"e": 25166,
"s": 25156,
"text": "Examples:"
},
{
"code": null,
"e": 25248,
"s": 25166,
"text": "Input: R=0, G=100, B=255Output: TrueExplanation: Every color is in range [0, 255]"
},
{
"code": null,
"e": 25328,
"s": 25248,
"text": "Input: R=0, G=200, B=355Output: FalseExplanation: Blue is not in range [0, 255]"
},
{
"code": null,
"e": 25526,
"s": 25328,
"text": "Approach: To check if the color code is valid or not we need to check if each of the color is in the range [0, 255] or not. If any of the color is not in this range, return false, else return true."
},
{
"code": null,
"e": 25571,
"s": 25526,
"text": "Below is the implementation of the approach:"
},
{
"code": null,
"e": 25575,
"s": 25571,
"text": "C++"
},
{
"code": null,
"e": 25580,
"s": 25575,
"text": "Java"
},
{
"code": null,
"e": 25588,
"s": 25580,
"text": "Python3"
},
{
"code": null,
"e": 25591,
"s": 25588,
"text": "C#"
},
{
"code": null,
"e": 25602,
"s": 25591,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; // Function to check validity// of the color codebool isValidRGB(int R, int G, int B){ if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true;} // Driver codeint main(){ int R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0, G = 0, B = 0; (isValidRGB(R, G, B)) ? cout << \"true\\n\" : cout << \"false\\n\"; // Check if rgb(0, 100, 255) is valid or not R = 0, G = 100, B = 255; (isValidRGB(R, G, B)) ? cout << \"true\\n\" : cout << \"false\\n\"; // Check if rgb(0, 200, 355) is valid or not R = 0, G = 200, B = 355; (isValidRGB(R, G, B)) ? cout << \"true\\n\" : cout << \"false\\n\"; // Check if rgb(-100, 0, 255) is valid or not R = -100, G = 0, B = 255; (isValidRGB(R, G, B)) ? cout << \"true\\n\" : cout << \"false\\n\"; return 0;}",
"e": 26626,
"s": 25602,
"text": null
},
{
"code": "class GFG { // Function to check validity // of the color code public static boolean isValidRGB(int R, int G, int B) { if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true; } // Driver code public static void main(String args[]) { int R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0; G = 0; B = 0; if (isValidRGB(R, G, B)) System.out.println(\"true\"); else System.out.println(\"false\"); // Check if rgb(0, 100, 255) is valid or not R = 0; G = 100; B = 255; if (isValidRGB(R, G, B)) System.out.println(\"true\"); else System.out.println(\"false\"); // Check if rgb(0, 200, 355) is valid or not R = 0; G = 200; B = 355; if (isValidRGB(R, G, B)) System.out.println(\"true\"); else System.out.println(\"false\"); // Check if rgb(-100, 0, 255) is valid or not R = -100; G = 0; B = 255; if (isValidRGB(R, G, B)) System.out.println(\"true\"); else System.out.println(\"false\"); }} // This code is contributed by saurabh_jaiswal",
"e": 27988,
"s": 26626,
"text": null
},
{
"code": "# Function to check validity# of the color codedef isValidRGB(R, G, B) : if (R < 0 or R > 255) : return False; elif (G < 0 or G > 255) : return False; elif (B < 0 or B > 255) : return False; else : return True; # Driver codeif __name__ == \"__main__\" : # Check if rgb(0, 0, 0) is valid or not R = 0; G = 0; B = 0; if isValidRGB(R, G, B) : print(\"true\") else : print(\"false\") # Check if rgb(0, 100, 255) is valid or not R = 0; G = 100; B = 255; if isValidRGB(R, G, B) : print(\"true\") else : print(\"false\") # Check if rgb(0, 200, 355) is valid or not R = 0; G = 200; B = 355; if isValidRGB(R, G, B) : print(\"true\") else : print(\"false\") # Check if rgb(-100, 0, 255) is valid or not R = -100; G = 0; B = 255; if isValidRGB(R, G, B) : print(\"true\") else : print(\"false\") # This code is contributed by AnkThon",
"e": 29001,
"s": 27988,
"text": null
},
{
"code": "using System;public class GFG { // Function to check validity // of the color code public static bool isValidRGB(int R, int G, int B) { if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true; } // Driver code public static void Main(string []args) { int R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0; G = 0; B = 0; if (isValidRGB(R, G, B)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); // Check if rgb(0, 100, 255) is valid or not R = 0; G = 100; B = 255; if (isValidRGB(R, G, B)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); // Check if rgb(0, 200, 355) is valid or not R = 0; G = 200; B = 355; if (isValidRGB(R, G, B)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); // Check if rgb(-100, 0, 255) is valid or not R = -100; G = 0; B = 255; if (isValidRGB(R, G, B)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); }} // This code is contributed by AnkThon",
"e": 30403,
"s": 29001,
"text": null
},
{
"code": "<script> // Function to check validity // of the color code const isValidRGB = (R, G, B) => { if (R < 0 || R > 255) return false; else if (G < 0 || G > 255) return false; else if (B < 0 || B > 255) return false; else return true; } // Driver code let R, G, B; // Check if rgb(0, 0, 0) is valid or not R = 0, G = 0, B = 0; (isValidRGB(R, G, B)) ? document.write(\"true<br/>\") : document.write(\"false<br/>\"); // Check if rgb(0, 100, 255) is valid or not R = 0, G = 100, B = 255; (isValidRGB(R, G, B)) ? document.write(\"true<br/>\") : document.write(\"false<br/>\"); // Check if rgb(0, 200, 355) is valid or not R = 0, G = 200, B = 355; (isValidRGB(R, G, B)) ? document.write(\"true<br/>\") : document.write(\"false<br/>\"); // Check if rgb(-100, 0, 255) is valid or not R = -100, G = 0, B = 255; (isValidRGB(R, G, B)) ? document.write(\"true<br/>\") : document.write(\"false<br/>\"); // This code is contributed by rakeshsahni </script>",
"e": 31492,
"s": 30403,
"text": null
},
{
"code": null,
"e": 31517,
"s": 31495,
"text": "true\ntrue\nfalse\nfalse"
},
{
"code": null,
"e": 31562,
"s": 31519,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31576,
"s": 31564,
"text": "rakeshsahni"
},
{
"code": null,
"e": 31584,
"s": 31576,
"text": "ankthon"
},
{
"code": null,
"e": 31594,
"s": 31584,
"text": "samim2000"
},
{
"code": null,
"e": 31611,
"s": 31594,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31624,
"s": 31611,
"text": "Mathematical"
},
{
"code": null,
"e": 31642,
"s": 31624,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31655,
"s": 31642,
"text": "Mathematical"
},
{
"code": null,
"e": 31673,
"s": 31655,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31771,
"s": 31673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31780,
"s": 31771,
"text": "Comments"
},
{
"code": null,
"e": 31793,
"s": 31780,
"text": "Old Comments"
},
{
"code": null,
"e": 31825,
"s": 31793,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 31856,
"s": 31825,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31889,
"s": 31856,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31932,
"s": 31889,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 31967,
"s": 31932,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 32003,
"s": 31967,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32041,
"s": 32003,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 32084,
"s": 32041,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32126,
"s": 32084,
"text": "Check if a string is substring of another"
}
] |
Tricks in R to Boost Your Productivity (Part 2) | by Wei Lin | Towards Data Science | I am always keen on tools and tricks that can help me get things done faster. While increasing productivity does not necessarily mean that it can give you good or right results, it can definitely reduce your working hours which means less time to make mistakes. Spending some time learning tricks and tools will pay itself back later in your work and is totally worthwhile. Following my previous article on tricks in R and RStudio, I will continue to share with you in this article some other tricks that I think is useful.
When an R session starts, it first tries to search for a .Rprofile file in your project directory or in your home directory and execute the function .First if it exists. A few things you can use the .Rprofile to execute at the beginning of each session to save your time are
Load packages that you constantly work (such as tidyverse, data.table, ggplot2, etc.).
Set Environmental variables (such as a development environment identifier (“sandbox”, “staging”, “prod”, etc.), AWS credentials, your database connection credentials, .etc.).
Set Java parameters (you definitely need to set this if you need to pull large data from a database through DBI/rJava package).
Set ggplot2 theme and color palette (useful if you need to use a brand-specific color palette).
An example of my .Rprofile is shown below:
If you use R to query the database a lot, you should consider better organizing your file structures and writing wrapper functions to make your life easier. First of all, you should put all your R files into a folder and all SQL files to another one. Some people like to write SQL commands directly into the R functions or scripts, which I don’t think is the best practice and it will make your R code ugly and your SQL code is not reusable by another R code. After the organization, you can write the following wrapper functions:
connect_db is the wrapper function that returns a database connection handler after you call the driver and establish the database connection with the url and credentials.
get_sql is the SQL file parser.
db_query is the function you call to execute your query, where you can send either a SQL file path or a pure sql string. You can pass additional arguments to the function to substitute parameters in the SQL query through DBI::sqlInterpolate function. Most importantly, we need to close the connection after executing the query.
With the above wrapper functions, so you can perform the SQL query by simply calling the following commands for example.
# String based queryaccounts <- db_query('select count(*) from accounts where created_at < ?time', time = '2019-01-01')# File based queryaccounts <- db_query('sql/accounts.sql', time = '2019-01-01')
You can easily extend the above wrapper functions with more functionality such as delete, load, etc. to meet your needs.
If you use the R command-line tool in a terminal for all your work, you will be asked whether to save your workspace data when you want to exit the R session. If you choose to save the workspace data, a hidden “.RData” file will be created in your working directory. It is OK to save the data if your workspace only contains a small amount of data. However, if your workspace contains a large amount of data (512MB or more), the saving process could take a long time to execute because the workspace data needs to be compressed into the file, which is slow for large data. Therefore, my personal suggestion is that you should never save the workspace data store. If you use RStudio, you can set the options like below. If you really want to save the data on some occasions, you can simply call the save command before you exit.
If you are writing an R package and want to reload the whole developing package without restarting the R session and hence losing the data, you can use the function devtools::reload() from devtools package to achieve that. The shortcut for reloading is CMD + SHIFT + L in RStudio.
Inside the function of your package, you can pressCMD + Option + Shift + R to call Roxygen2 to generate a document skeleton for your function as shown below.
I am a heavy user of RStudio and have been using RStudio for over 4 years. Below is my code setting recommendation for RStudio. The purpose is to make the coding experience more pleasant and efficient.
I believe that 99% of R users use RStudio as their primary R programming IDE. There are two major products of RStudio IDE. One is RStudio desktop and the other is RStudio server. Most of the R users start with the desktop version mainly for ad-hoc analysis and model development. If their needs expand to model deployment, task automation, shiny website, dashboard, reports, etc., then the server version becomes a better choice. If you use the server version, you had better create your dev, staging, and production environment on your servers for better software management. For me, I only have one EC2 server and don’t have three dedicated servers to dev, staging, and production environments, respectively. As a workaround, you can create three R projects in three different folders version controlled by git and Github to mimic the dev, staging, and production environments as shown below:
dev: it is my sandbox for modeling and analysis.
stg: it is a testing environment for new features.
prod: it contains code and cron jobs used to generate reports, dashboard, and automated tasks. In the production environment, you should only change the code through git pull but never manually.
If you use the free version of RStudio server, switching between projects will restart your R session and hence lose data. If you use the RStudio Pro version, you can run 3 R sessions side by side in your browser, which is more convenient. | [
{
"code": null,
"e": 696,
"s": 172,
"text": "I am always keen on tools and tricks that can help me get things done faster. While increasing productivity does not necessarily mean that it can give you good or right results, it can definitely reduce your working hours which means less time to make mistakes. Spending some time learning tricks and tools will pay itself back later in your work and is totally worthwhile. Following my previous article on tricks in R and RStudio, I will continue to share with you in this article some other tricks that I think is useful."
},
{
"code": null,
"e": 971,
"s": 696,
"text": "When an R session starts, it first tries to search for a .Rprofile file in your project directory or in your home directory and execute the function .First if it exists. A few things you can use the .Rprofile to execute at the beginning of each session to save your time are"
},
{
"code": null,
"e": 1058,
"s": 971,
"text": "Load packages that you constantly work (such as tidyverse, data.table, ggplot2, etc.)."
},
{
"code": null,
"e": 1233,
"s": 1058,
"text": "Set Environmental variables (such as a development environment identifier (“sandbox”, “staging”, “prod”, etc.), AWS credentials, your database connection credentials, .etc.)."
},
{
"code": null,
"e": 1361,
"s": 1233,
"text": "Set Java parameters (you definitely need to set this if you need to pull large data from a database through DBI/rJava package)."
},
{
"code": null,
"e": 1457,
"s": 1361,
"text": "Set ggplot2 theme and color palette (useful if you need to use a brand-specific color palette)."
},
{
"code": null,
"e": 1500,
"s": 1457,
"text": "An example of my .Rprofile is shown below:"
},
{
"code": null,
"e": 2031,
"s": 1500,
"text": "If you use R to query the database a lot, you should consider better organizing your file structures and writing wrapper functions to make your life easier. First of all, you should put all your R files into a folder and all SQL files to another one. Some people like to write SQL commands directly into the R functions or scripts, which I don’t think is the best practice and it will make your R code ugly and your SQL code is not reusable by another R code. After the organization, you can write the following wrapper functions:"
},
{
"code": null,
"e": 2203,
"s": 2031,
"text": "connect_db is the wrapper function that returns a database connection handler after you call the driver and establish the database connection with the url and credentials."
},
{
"code": null,
"e": 2235,
"s": 2203,
"text": "get_sql is the SQL file parser."
},
{
"code": null,
"e": 2563,
"s": 2235,
"text": "db_query is the function you call to execute your query, where you can send either a SQL file path or a pure sql string. You can pass additional arguments to the function to substitute parameters in the SQL query through DBI::sqlInterpolate function. Most importantly, we need to close the connection after executing the query."
},
{
"code": null,
"e": 2684,
"s": 2563,
"text": "With the above wrapper functions, so you can perform the SQL query by simply calling the following commands for example."
},
{
"code": null,
"e": 2883,
"s": 2684,
"text": "# String based queryaccounts <- db_query('select count(*) from accounts where created_at < ?time', time = '2019-01-01')# File based queryaccounts <- db_query('sql/accounts.sql', time = '2019-01-01')"
},
{
"code": null,
"e": 3004,
"s": 2883,
"text": "You can easily extend the above wrapper functions with more functionality such as delete, load, etc. to meet your needs."
},
{
"code": null,
"e": 3832,
"s": 3004,
"text": "If you use the R command-line tool in a terminal for all your work, you will be asked whether to save your workspace data when you want to exit the R session. If you choose to save the workspace data, a hidden “.RData” file will be created in your working directory. It is OK to save the data if your workspace only contains a small amount of data. However, if your workspace contains a large amount of data (512MB or more), the saving process could take a long time to execute because the workspace data needs to be compressed into the file, which is slow for large data. Therefore, my personal suggestion is that you should never save the workspace data store. If you use RStudio, you can set the options like below. If you really want to save the data on some occasions, you can simply call the save command before you exit."
},
{
"code": null,
"e": 4113,
"s": 3832,
"text": "If you are writing an R package and want to reload the whole developing package without restarting the R session and hence losing the data, you can use the function devtools::reload() from devtools package to achieve that. The shortcut for reloading is CMD + SHIFT + L in RStudio."
},
{
"code": null,
"e": 4271,
"s": 4113,
"text": "Inside the function of your package, you can pressCMD + Option + Shift + R to call Roxygen2 to generate a document skeleton for your function as shown below."
},
{
"code": null,
"e": 4473,
"s": 4271,
"text": "I am a heavy user of RStudio and have been using RStudio for over 4 years. Below is my code setting recommendation for RStudio. The purpose is to make the coding experience more pleasant and efficient."
},
{
"code": null,
"e": 5368,
"s": 4473,
"text": "I believe that 99% of R users use RStudio as their primary R programming IDE. There are two major products of RStudio IDE. One is RStudio desktop and the other is RStudio server. Most of the R users start with the desktop version mainly for ad-hoc analysis and model development. If their needs expand to model deployment, task automation, shiny website, dashboard, reports, etc., then the server version becomes a better choice. If you use the server version, you had better create your dev, staging, and production environment on your servers for better software management. For me, I only have one EC2 server and don’t have three dedicated servers to dev, staging, and production environments, respectively. As a workaround, you can create three R projects in three different folders version controlled by git and Github to mimic the dev, staging, and production environments as shown below:"
},
{
"code": null,
"e": 5417,
"s": 5368,
"text": "dev: it is my sandbox for modeling and analysis."
},
{
"code": null,
"e": 5468,
"s": 5417,
"text": "stg: it is a testing environment for new features."
},
{
"code": null,
"e": 5663,
"s": 5468,
"text": "prod: it contains code and cron jobs used to generate reports, dashboard, and automated tasks. In the production environment, you should only change the code through git pull but never manually."
}
] |
An Introduction to Food Delivery Time Prediction | by Jye Sawtell-Rickson | Towards Data Science | Delivery time prediction has long been a part of city logistics, but refining accuracy has recently become very important for services such as Deliveroo, Foodpanda and Uber Eats which deliver food on-demand.
These services and similar ones must receive an order and have it delivered within ~30 minutes to appease their users. In these situations +/- 5 minutes can make a big difference so it’s very important for customer satisfaction that the initial prediction is highly accurate and that any delays are communicated effectively.
In this article, I’ll discuss my experience building a (real-world) delivery time prediction model for a food delivery startup and how it came to give better predictions than our trained operations team.
This article will touch on the technical topics of machine learning while focusing on the business knowledge required to create a well-functioning predictive model. Links to external resources for further reading will also be included for your reading pleasure.
Our Roadmap:
📝 Problem Statement
🔢 The Data
⚒️ Toolkit
📈 Model Building
🤔 Improving Estimates
To start, let’s formulate a problem statement that we can work with. This will help us to stay focused on the goal.
We’d like to build a model which will take data about a food delivery as input and then output the desired pick-up time to be communicated to drivers.
Some other things to note:
The deliveries are large and can be assumed to require cars.
The suppliers (or suppliers) range from restaurants to caterers and can have very different characteristics.
Drivers can be assumed to arrive at the supplier at exactly the dictated pick-up time. In reality this isn’t always true, but with a sufficient number of drivers this can be kept to a minimal amount.
Food should not be delivered too late as the customer will be left waiting and angry and not too early as it will have to sit out before the customer is ready to eat it.
As an input to our model, we have three categories of data that are typical for this sort of problem:
Orders: what are people ordering? what supplier are they ordering from? what time is the delivery for?
Customers: who is ordering? where are they located?
Delivery Results: for previous deliveries, how did we perform? how long did each step take?
An example of the data available for a delivery is:
Delivery Team : Deliveries 'R' UsOrder_ID : 12345Agent_Name : Bob DriverSupplier : Delicious DonutsCustomer : Big Corporation Inc.Pickup_Address : Shop 1, Busy Street, 23456, Hong KongDelivery_Address : Level 9, Skyscraper, 34567, Hong KongDelivery_Time : 29/05/2016 08:00:00Order_Size : $500
Since we have a lot of text, we’ll need to process the data first to get it in a machine-ready format.
The addresses can be processed using regular expressions to get more structured information. The key points are: floor, building, postcode, area, country.
After the processing above, the building, postcode, areas and postcodes can be combined with the other variables to perform one-hot-encoding. One hot encoding will create many binary variables for each possible text. These numeric variables can then be fed into our models. You can read more of an introduction on one-hot-encoding here.
To train the model we will use data from previous deliveries, this includes the predicted time for delivery and the actual time for delivery (the target variable for our exercise). For the purpose of this article, we will work with around 1000 data points.
Before going any deeper, we should consider what models will be the best to solve the type of problem we have. The below diagram from the Scikit-Learn documentation gives a great way to decide which algorithm you should use.
Let’s have a look at what we know about our problem:
As previously mentioned, we have 1000+ data points for training.
The output of the model should be a numeric value.
Due to the one-hot-encoding, we’re left with a fairly large number of binary variables which means it’s likely that many features are important.
With this in mind, we can follow along the chart above to arrive at Ridge Regression and SVR with a Linear Kernel. For the sake of simplicity, we’ll just work with Ridge Regression as well as add a Random Forest Regressor to see how it performs differently with the data.
If you’re interested in some more background, you can read up on the algorithms on their respective pages in the Scikit-Learn documentation: Ridge Regression, SVR (Support Vector Regression) and Random Forest Regression.
We should also pay attention to the metric that we will use to judge our model’s effectiveness.
A common metric that we can use to get a quick idea of our performance is the Mean Absolute Error (MAE). This tells us the average of the difference between our delivery time estimates and the actual delivery time.
Going further, we can define two more domain-specific metrics:
Basically on-time (< 5 mins late)
OK, we’re a little late (< 10 mins late)
These two metrics tell us how often we’ll upset users. If we’re 15 minutes late or 25 minutes late, it doesn’t really matter to the user, we’re just really late. MAE doesn’t realise this, and will count one worse than the other but in terms of the business, it’s effectively the same thing and it’s important our model understands that.
Note: We’ll actually use the inverse of these metrics (i.e. deliveries over 5 mins late) as they are a little easier to work with.
So a quick recap: we know what we need to do, we know what data we have to do it with and we know they way we’re going to do it — so let’s get doing!
Let’s think about what is involved in food delivery. We can break it down into three principal components:
Pick-up the food from the supplier.Drive from the supplier to the customer.Drop-off the food to the customer.
Pick-up the food from the supplier.
Drive from the supplier to the customer.
Drop-off the food to the customer.
We can predict the time taken for each component and then add these together to get the final delivery time.
Delivery Time = Pick-up Time + Point-to-Point Time + Drop-off Time
Alternatively, we could train a model to predict the entire delivery time. The reason we should break this up is to create specialty models which will have superior ability over one generic model. If we replace the models with people it makes sense. In your business development team you would have a person who knows the suppliers really well and how long they might take for delivery. In your client service team you would have someone who knows each client well and can predict how long the delivery might take based on their location and building. We’re structuring our process with this in mind.
Now that we have three stages, let’s dive into them and build our models.
When a driver arrives at a destination, he is required to find a carpark, pick-up the food and make it back to the car. Let’s explore the potential complications that could occur during this process.
No park: For restaurants located in the city centre this can be significantly more difficult compared to those located in more residential areas. To capture this information we can use the postcode or the latitude/longitude information. I found that postcodes were particularly valuable since they capture high-level generic information due to their specific structure.
Difficult access: Restaurants will tend to be fairly easy to access since they rely on that to serve customers, but caterers can be in industrial areas as well as not having an obvious entrance making it more difficult. Similar to the above we can use location information while adding the category of the supplier.
Food not ready: As the order sizes can be quite large, it’s not uncommon for food to be unprepared. To deal with this the caterer can be contacted on the day of the pick-up to check food will be ready on time. The response to these messages would be a useful flag to understand our timing. Whether or not the particular supplier has a history would also be useful input. Finally, the order size is a good indicator; not much can go wrong when preparing a small amount of food but when it’s for 100 pax there’s a lot more potential for something to go wrong.
Something missing from the order: Driver should check order on arrival and in some cases they may find something missing. This means they must wait for the extra food to be prepared. Again, this probably depends on the supplier and how busy they are at the time of pick-up.
For this part of the problem we’ll use the following data points:
Supplier : Delicious DonutsCustomer : Big Corporation Inc.Pickup_Address : Shop 1, Busy Street, 23456, Hong KongDelivery_Time : 29/05/2016 08:00:00Order_Size : $500
After performing the processing as described above, the data can then be fed into our Scikit-Learn models resulting in the following:
Baseline Results:Mean Absolute Error: 544 secondsGreater than 5 mins late: 55%Greater than 10 mins late: 19%Random Forest Results:Mean Absolute Error: 575 secondsGreater than 5 mins late: 42%Greater than 10 mins late: 22%Linear Regressor Results:Mean Absolute Error: 550 secondsGreater than 5 mins late: 44%Greater than 10 mins late: 17%Ensemble Results:Mean Absolute Error: 549 secondsGreater than 5 mins late: 45%Greater than 10 mins late: 17%
It can be seen that it if we use the basic metric of Mean Absolute Error (MAE) all of the models perform worse than the baseline model. However, if we look at the metrics which are more relevant to the food delivery business we see that each model has its benefits.
The Random Forest model reduces the orders greater than 5 minutes late by almost 25%. The Linear Regressor does best in reducing the orders which are 10 minutes late, by around 10%. Interestingly, the ensemble model does fairly well in both metrics but notably, it has the smallest MAE out of the three models.
When choosing the correct model, the business goals come first, dictating our choice of important metrics and thus, correct model. With this motivation, we’ll stick with the Ensemble model.
Estimating the travel time between destinations is a tricky task for many reasons; there are thousands of routes to choose from, traffic conditions that are constantly changing, road closures and accidents; all of which provide so much unpredictability into any model you could create.
Luckily for us, there are a bunch of people who have thought long and hard about this problem and collect millions of data points to help better understand the environment. In comes Google.
To predict point-to-point travel time we will call the Google Maps API with the known pick-up and drop-off points. The results returned include parameters taking into account traffic and worse-case-scenarios which we can be used as input to the model. A call to the API is quite simple, it looks like this:
gmaps = googlemaps.Client(key='MY_API_KEY')params = {'mode': 'driving', 'alternatives': False, 'avoid': 'tolls', 'language': 'en', 'units': 'metric', 'region': country}directions_result = gmaps.directions(pick_up_location, drop_off_location, arrival_time=arrival_time, **params)
With this, we can get a highly accurate result for a problem that has already been well thought-through. It’s important not to redo work,
Always think if there is already a good enough solution to your problem, don’t reinvent the wheel!
Previous to implementing this model, our organisation was using the public Google Maps interface to predict the delivery times. As such, the performance of our new model for this part of the journey is identical to the baseline. As such, we won’t calculate any comparisons here.
An important side-note is that addresses aren’t always properly formed! When querying Google Maps there’s always a chance that they’ll respond saying “Uh...I don’t know”, to which we must have an answer. This is a great example of how humans and machines must work together. Whenever an address is not properly formed it’s possible for an operator to step in and clarify the address or even call up the customer to clarify the information.
With that, we can move on the third part of our model.
Once the driver arrives at the location they must find a park, get the food to the right person and get a final sign-off. Potential issues along the way include:
Carpark has height restrictions: It’s simple, but many deliveries happen in vans and in this case, there may be height restrictions stopping drivers from using the main entrance.
Building has no carpark: This is an obvious one. No carpark means that the driver has to dedicate time driving around and looking for somewhere to leave his vehicle while doing the delivery.
Building security issue: Most modern office buildings require a security card to gain access. In the best case, drivers can simply be swiped through, but in the worst case, drivers can be required to go to a separate location, sign-up for a card and then use a back entrance.
Customer on a high floor or in a tricky location: It may sound ridiculous but some office buildings are very difficult to navigate with different lifts for different floors and for smaller companies they can be hidden among a maze of hallways.
With all of these, postal code is a great indicator as it tells us if we can expect a business district or a residential area. We can also deep-dive further on the address. For example, if we have Level 40 it’s quite obvious the delivery is in a big tower block and will likely have a complicated security process.
For this part of the problem we’ll use the following data points.
Customer : Big Corporation Inc.Delivery_Address : Level 9, Skyscraper, 34567, Hong KongDelivery_Time : 29/05/2016 08:00:00Order_Size : $500
After performing the typical processing and running our models we see the following:
Baseline Results:Mean Absolute Error: 351 secondsGreater than 5 mins late: 35%Greater than 10 mins late: 0%Random Forest Results:Mean Absolute Error: 296 secondsGreater than 5 mins late: 15%Greater than 10 mins late: 7%Linear Regressor Results:Mean Absolute Error: 300 secondsGreater than 5 mins late: 14%Greater than 10 mins late: 5%Ensemble Results:Mean Absolute Error: 293 secondsGreater than 5 mins late: 13%Greater than 10 mins late: 6%
Here, we’re able to see a reduction in MAE of 17%, — much better than before. Similarly, we see reductions in the orders greater than 5 mins late by a humungous 63%. On the other hand, the model does increase the number of orders late from 0% to 6%. Again, we’re faced with a trade-off between models which both have their merits and we must let our business KPIs be the deciding factors.
We can now combine our models together with the following formula:
Delivery Time = Pick-up Time + Point-to-Point Time + Drop-off Time + Hyperparamater
Note the addition of a hyperparameter this time. We’ll add this in to take into account any other weird effects that we see in the data such as the pick-up time always been set 5 minutes earlier to meet the expectations of drivers. We’ll set this parameter in order to minimise the final error metrics after calculating the combined results.
Putting it all together, we get the final result:
Baseline Results:Mean Absolute Error: 1429 secondsGreater than 5 mins late: 60%Greater than 10 mins late: 19%Ensemble Results:Mean Absolute Error: 1263 secondsGreater than 5 mins late: 41%Greater than 10 mins late: 12%
So our final model has a significant improvement over the baseline model in all metrics — we did it!
Most importantly, we’ve seen a reduction in orders greater than 10 mins late of almost 40%! We were able to achieve this by working on three separate models which were optimised to their own specific business problem. Combining them and fine-tuning at the last stage made sure we produced a model which is on the level of trained professionals.
Having a model which gives even more accuracy would be great, but it would also require a lot more effort due to the law of diminishing returns. Instead, there are other solutions if we think more about the business case and less about machine learning.
As you may recall from the start, this model is for catering delivery, which means we know the delivery time in advance. One simple way to avoid late deliveries is to take whatever value the model outputs and increase it to make sure that we’re early enough.
This is not a great solution because being too early also has a problem in that the food could go bad or be unprepared. However, it does bring up the point that we should consider the distribution of ‘lateness’ and ‘earliness’. Maybe it is better if we’re 10 minutes early than 5 minutes late. With the metrics used up until this point, we didn’t optimise for such scenarios and so we can reconsider this and optimise accordingly.
Another thing to consider is how the model is presented to users. If a user is told you’ll arrive at 2pm and you don’t, they’ll be frustrated. If you tell someone you’ll be there from 1:45pm-2pm then you can aim to deliver at 1:50pm and if you’re a little late you have leeway.
It’s always important to consider machine learning problems as a solution to an actual real-world problem — this context can often lead to ‘improvements’ that would otherwise be impossible from the model itself.
One of the key wins for this model was being able to effectively differentiate between the different preparation times of the suppliers. That tells us that the suppliers must have very different performance.
Digging deeper, it was found that drivers were spending 3x the time at a few suppliers. With this is information, moving back to the business world, it is possible to discuss with the suppliers and identify the problems which can reduce the time spent at these suppliers and by reducing the variation, improve the overall performance of the model.
We started with a problem statement for predicting food delivery timings. We decided what data we would use and what sort of processing we should do. We thought about what would be the best models to solve our particular problem. We then broke our problem down into three components to build targeted models and finally put them together to create a fully-functioning predictive model. We didn’t stop there though, we used our business knowledge to improve the effectiveness of our model.
This resulted in a reduction of 40% in orders that were over 10 minutes late which can be translated directly into dollars saved in refunds. It also helped to lighten the load on the operations team meaning they could focus on more meaningful tasks such as improving supplier efficiencies.
As outlined, this is the general procedure that can be used to apply machine learning to solve business problems. It’s an approach that makes sure to get the basics right before later optimising for the extra few percent points of improvement. It’s one that I’ve used successfully and I hope you can too.
If you enjoyed reading this, please don’t forget to leave a clap or two, or three... 👏👏👏🔄
If you’d like to read about why using high-tech (like in this article) isn’t always the best solution, check this out: | [
{
"code": null,
"e": 380,
"s": 172,
"text": "Delivery time prediction has long been a part of city logistics, but refining accuracy has recently become very important for services such as Deliveroo, Foodpanda and Uber Eats which deliver food on-demand."
},
{
"code": null,
"e": 705,
"s": 380,
"text": "These services and similar ones must receive an order and have it delivered within ~30 minutes to appease their users. In these situations +/- 5 minutes can make a big difference so it’s very important for customer satisfaction that the initial prediction is highly accurate and that any delays are communicated effectively."
},
{
"code": null,
"e": 909,
"s": 705,
"text": "In this article, I’ll discuss my experience building a (real-world) delivery time prediction model for a food delivery startup and how it came to give better predictions than our trained operations team."
},
{
"code": null,
"e": 1171,
"s": 909,
"text": "This article will touch on the technical topics of machine learning while focusing on the business knowledge required to create a well-functioning predictive model. Links to external resources for further reading will also be included for your reading pleasure."
},
{
"code": null,
"e": 1184,
"s": 1171,
"text": "Our Roadmap:"
},
{
"code": null,
"e": 1204,
"s": 1184,
"text": "📝 Problem Statement"
},
{
"code": null,
"e": 1215,
"s": 1204,
"text": "🔢 The Data"
},
{
"code": null,
"e": 1226,
"s": 1215,
"text": "⚒️ Toolkit"
},
{
"code": null,
"e": 1243,
"s": 1226,
"text": "📈 Model Building"
},
{
"code": null,
"e": 1265,
"s": 1243,
"text": "🤔 Improving Estimates"
},
{
"code": null,
"e": 1381,
"s": 1265,
"text": "To start, let’s formulate a problem statement that we can work with. This will help us to stay focused on the goal."
},
{
"code": null,
"e": 1532,
"s": 1381,
"text": "We’d like to build a model which will take data about a food delivery as input and then output the desired pick-up time to be communicated to drivers."
},
{
"code": null,
"e": 1559,
"s": 1532,
"text": "Some other things to note:"
},
{
"code": null,
"e": 1620,
"s": 1559,
"text": "The deliveries are large and can be assumed to require cars."
},
{
"code": null,
"e": 1729,
"s": 1620,
"text": "The suppliers (or suppliers) range from restaurants to caterers and can have very different characteristics."
},
{
"code": null,
"e": 1929,
"s": 1729,
"text": "Drivers can be assumed to arrive at the supplier at exactly the dictated pick-up time. In reality this isn’t always true, but with a sufficient number of drivers this can be kept to a minimal amount."
},
{
"code": null,
"e": 2099,
"s": 1929,
"text": "Food should not be delivered too late as the customer will be left waiting and angry and not too early as it will have to sit out before the customer is ready to eat it."
},
{
"code": null,
"e": 2201,
"s": 2099,
"text": "As an input to our model, we have three categories of data that are typical for this sort of problem:"
},
{
"code": null,
"e": 2304,
"s": 2201,
"text": "Orders: what are people ordering? what supplier are they ordering from? what time is the delivery for?"
},
{
"code": null,
"e": 2356,
"s": 2304,
"text": "Customers: who is ordering? where are they located?"
},
{
"code": null,
"e": 2448,
"s": 2356,
"text": "Delivery Results: for previous deliveries, how did we perform? how long did each step take?"
},
{
"code": null,
"e": 2500,
"s": 2448,
"text": "An example of the data available for a delivery is:"
},
{
"code": null,
"e": 2837,
"s": 2500,
"text": "Delivery Team : Deliveries 'R' UsOrder_ID : 12345Agent_Name : Bob DriverSupplier : Delicious DonutsCustomer : Big Corporation Inc.Pickup_Address : Shop 1, Busy Street, 23456, Hong KongDelivery_Address : Level 9, Skyscraper, 34567, Hong KongDelivery_Time : 29/05/2016 08:00:00Order_Size : $500"
},
{
"code": null,
"e": 2940,
"s": 2837,
"text": "Since we have a lot of text, we’ll need to process the data first to get it in a machine-ready format."
},
{
"code": null,
"e": 3095,
"s": 2940,
"text": "The addresses can be processed using regular expressions to get more structured information. The key points are: floor, building, postcode, area, country."
},
{
"code": null,
"e": 3432,
"s": 3095,
"text": "After the processing above, the building, postcode, areas and postcodes can be combined with the other variables to perform one-hot-encoding. One hot encoding will create many binary variables for each possible text. These numeric variables can then be fed into our models. You can read more of an introduction on one-hot-encoding here."
},
{
"code": null,
"e": 3689,
"s": 3432,
"text": "To train the model we will use data from previous deliveries, this includes the predicted time for delivery and the actual time for delivery (the target variable for our exercise). For the purpose of this article, we will work with around 1000 data points."
},
{
"code": null,
"e": 3914,
"s": 3689,
"text": "Before going any deeper, we should consider what models will be the best to solve the type of problem we have. The below diagram from the Scikit-Learn documentation gives a great way to decide which algorithm you should use."
},
{
"code": null,
"e": 3967,
"s": 3914,
"text": "Let’s have a look at what we know about our problem:"
},
{
"code": null,
"e": 4032,
"s": 3967,
"text": "As previously mentioned, we have 1000+ data points for training."
},
{
"code": null,
"e": 4083,
"s": 4032,
"text": "The output of the model should be a numeric value."
},
{
"code": null,
"e": 4228,
"s": 4083,
"text": "Due to the one-hot-encoding, we’re left with a fairly large number of binary variables which means it’s likely that many features are important."
},
{
"code": null,
"e": 4500,
"s": 4228,
"text": "With this in mind, we can follow along the chart above to arrive at Ridge Regression and SVR with a Linear Kernel. For the sake of simplicity, we’ll just work with Ridge Regression as well as add a Random Forest Regressor to see how it performs differently with the data."
},
{
"code": null,
"e": 4721,
"s": 4500,
"text": "If you’re interested in some more background, you can read up on the algorithms on their respective pages in the Scikit-Learn documentation: Ridge Regression, SVR (Support Vector Regression) and Random Forest Regression."
},
{
"code": null,
"e": 4817,
"s": 4721,
"text": "We should also pay attention to the metric that we will use to judge our model’s effectiveness."
},
{
"code": null,
"e": 5032,
"s": 4817,
"text": "A common metric that we can use to get a quick idea of our performance is the Mean Absolute Error (MAE). This tells us the average of the difference between our delivery time estimates and the actual delivery time."
},
{
"code": null,
"e": 5095,
"s": 5032,
"text": "Going further, we can define two more domain-specific metrics:"
},
{
"code": null,
"e": 5129,
"s": 5095,
"text": "Basically on-time (< 5 mins late)"
},
{
"code": null,
"e": 5170,
"s": 5129,
"text": "OK, we’re a little late (< 10 mins late)"
},
{
"code": null,
"e": 5507,
"s": 5170,
"text": "These two metrics tell us how often we’ll upset users. If we’re 15 minutes late or 25 minutes late, it doesn’t really matter to the user, we’re just really late. MAE doesn’t realise this, and will count one worse than the other but in terms of the business, it’s effectively the same thing and it’s important our model understands that."
},
{
"code": null,
"e": 5638,
"s": 5507,
"text": "Note: We’ll actually use the inverse of these metrics (i.e. deliveries over 5 mins late) as they are a little easier to work with."
},
{
"code": null,
"e": 5788,
"s": 5638,
"text": "So a quick recap: we know what we need to do, we know what data we have to do it with and we know they way we’re going to do it — so let’s get doing!"
},
{
"code": null,
"e": 5895,
"s": 5788,
"text": "Let’s think about what is involved in food delivery. We can break it down into three principal components:"
},
{
"code": null,
"e": 6005,
"s": 5895,
"text": "Pick-up the food from the supplier.Drive from the supplier to the customer.Drop-off the food to the customer."
},
{
"code": null,
"e": 6041,
"s": 6005,
"text": "Pick-up the food from the supplier."
},
{
"code": null,
"e": 6082,
"s": 6041,
"text": "Drive from the supplier to the customer."
},
{
"code": null,
"e": 6117,
"s": 6082,
"text": "Drop-off the food to the customer."
},
{
"code": null,
"e": 6226,
"s": 6117,
"text": "We can predict the time taken for each component and then add these together to get the final delivery time."
},
{
"code": null,
"e": 6293,
"s": 6226,
"text": "Delivery Time = Pick-up Time + Point-to-Point Time + Drop-off Time"
},
{
"code": null,
"e": 6894,
"s": 6293,
"text": "Alternatively, we could train a model to predict the entire delivery time. The reason we should break this up is to create specialty models which will have superior ability over one generic model. If we replace the models with people it makes sense. In your business development team you would have a person who knows the suppliers really well and how long they might take for delivery. In your client service team you would have someone who knows each client well and can predict how long the delivery might take based on their location and building. We’re structuring our process with this in mind."
},
{
"code": null,
"e": 6968,
"s": 6894,
"text": "Now that we have three stages, let’s dive into them and build our models."
},
{
"code": null,
"e": 7168,
"s": 6968,
"text": "When a driver arrives at a destination, he is required to find a carpark, pick-up the food and make it back to the car. Let’s explore the potential complications that could occur during this process."
},
{
"code": null,
"e": 7538,
"s": 7168,
"text": "No park: For restaurants located in the city centre this can be significantly more difficult compared to those located in more residential areas. To capture this information we can use the postcode or the latitude/longitude information. I found that postcodes were particularly valuable since they capture high-level generic information due to their specific structure."
},
{
"code": null,
"e": 7854,
"s": 7538,
"text": "Difficult access: Restaurants will tend to be fairly easy to access since they rely on that to serve customers, but caterers can be in industrial areas as well as not having an obvious entrance making it more difficult. Similar to the above we can use location information while adding the category of the supplier."
},
{
"code": null,
"e": 8412,
"s": 7854,
"text": "Food not ready: As the order sizes can be quite large, it’s not uncommon for food to be unprepared. To deal with this the caterer can be contacted on the day of the pick-up to check food will be ready on time. The response to these messages would be a useful flag to understand our timing. Whether or not the particular supplier has a history would also be useful input. Finally, the order size is a good indicator; not much can go wrong when preparing a small amount of food but when it’s for 100 pax there’s a lot more potential for something to go wrong."
},
{
"code": null,
"e": 8686,
"s": 8412,
"text": "Something missing from the order: Driver should check order on arrival and in some cases they may find something missing. This means they must wait for the extra food to be prepared. Again, this probably depends on the supplier and how busy they are at the time of pick-up."
},
{
"code": null,
"e": 8752,
"s": 8686,
"text": "For this part of the problem we’ll use the following data points:"
},
{
"code": null,
"e": 8944,
"s": 8752,
"text": "Supplier : Delicious DonutsCustomer : Big Corporation Inc.Pickup_Address : Shop 1, Busy Street, 23456, Hong KongDelivery_Time : 29/05/2016 08:00:00Order_Size : $500"
},
{
"code": null,
"e": 9078,
"s": 8944,
"text": "After performing the processing as described above, the data can then be fed into our Scikit-Learn models resulting in the following:"
},
{
"code": null,
"e": 9524,
"s": 9078,
"text": "Baseline Results:Mean Absolute Error: 544 secondsGreater than 5 mins late: 55%Greater than 10 mins late: 19%Random Forest Results:Mean Absolute Error: 575 secondsGreater than 5 mins late: 42%Greater than 10 mins late: 22%Linear Regressor Results:Mean Absolute Error: 550 secondsGreater than 5 mins late: 44%Greater than 10 mins late: 17%Ensemble Results:Mean Absolute Error: 549 secondsGreater than 5 mins late: 45%Greater than 10 mins late: 17%"
},
{
"code": null,
"e": 9790,
"s": 9524,
"text": "It can be seen that it if we use the basic metric of Mean Absolute Error (MAE) all of the models perform worse than the baseline model. However, if we look at the metrics which are more relevant to the food delivery business we see that each model has its benefits."
},
{
"code": null,
"e": 10101,
"s": 9790,
"text": "The Random Forest model reduces the orders greater than 5 minutes late by almost 25%. The Linear Regressor does best in reducing the orders which are 10 minutes late, by around 10%. Interestingly, the ensemble model does fairly well in both metrics but notably, it has the smallest MAE out of the three models."
},
{
"code": null,
"e": 10291,
"s": 10101,
"text": "When choosing the correct model, the business goals come first, dictating our choice of important metrics and thus, correct model. With this motivation, we’ll stick with the Ensemble model."
},
{
"code": null,
"e": 10577,
"s": 10291,
"text": "Estimating the travel time between destinations is a tricky task for many reasons; there are thousands of routes to choose from, traffic conditions that are constantly changing, road closures and accidents; all of which provide so much unpredictability into any model you could create."
},
{
"code": null,
"e": 10767,
"s": 10577,
"text": "Luckily for us, there are a bunch of people who have thought long and hard about this problem and collect millions of data points to help better understand the environment. In comes Google."
},
{
"code": null,
"e": 11074,
"s": 10767,
"text": "To predict point-to-point travel time we will call the Google Maps API with the known pick-up and drop-off points. The results returned include parameters taking into account traffic and worse-case-scenarios which we can be used as input to the model. A call to the API is quite simple, it looks like this:"
},
{
"code": null,
"e": 11506,
"s": 11074,
"text": "gmaps = googlemaps.Client(key='MY_API_KEY')params = {'mode': 'driving', 'alternatives': False, 'avoid': 'tolls', 'language': 'en', 'units': 'metric', 'region': country}directions_result = gmaps.directions(pick_up_location, drop_off_location, arrival_time=arrival_time, **params)"
},
{
"code": null,
"e": 11644,
"s": 11506,
"text": "With this, we can get a highly accurate result for a problem that has already been well thought-through. It’s important not to redo work,"
},
{
"code": null,
"e": 11743,
"s": 11644,
"text": "Always think if there is already a good enough solution to your problem, don’t reinvent the wheel!"
},
{
"code": null,
"e": 12022,
"s": 11743,
"text": "Previous to implementing this model, our organisation was using the public Google Maps interface to predict the delivery times. As such, the performance of our new model for this part of the journey is identical to the baseline. As such, we won’t calculate any comparisons here."
},
{
"code": null,
"e": 12462,
"s": 12022,
"text": "An important side-note is that addresses aren’t always properly formed! When querying Google Maps there’s always a chance that they’ll respond saying “Uh...I don’t know”, to which we must have an answer. This is a great example of how humans and machines must work together. Whenever an address is not properly formed it’s possible for an operator to step in and clarify the address or even call up the customer to clarify the information."
},
{
"code": null,
"e": 12517,
"s": 12462,
"text": "With that, we can move on the third part of our model."
},
{
"code": null,
"e": 12679,
"s": 12517,
"text": "Once the driver arrives at the location they must find a park, get the food to the right person and get a final sign-off. Potential issues along the way include:"
},
{
"code": null,
"e": 12858,
"s": 12679,
"text": "Carpark has height restrictions: It’s simple, but many deliveries happen in vans and in this case, there may be height restrictions stopping drivers from using the main entrance."
},
{
"code": null,
"e": 13049,
"s": 12858,
"text": "Building has no carpark: This is an obvious one. No carpark means that the driver has to dedicate time driving around and looking for somewhere to leave his vehicle while doing the delivery."
},
{
"code": null,
"e": 13325,
"s": 13049,
"text": "Building security issue: Most modern office buildings require a security card to gain access. In the best case, drivers can simply be swiped through, but in the worst case, drivers can be required to go to a separate location, sign-up for a card and then use a back entrance."
},
{
"code": null,
"e": 13569,
"s": 13325,
"text": "Customer on a high floor or in a tricky location: It may sound ridiculous but some office buildings are very difficult to navigate with different lifts for different floors and for smaller companies they can be hidden among a maze of hallways."
},
{
"code": null,
"e": 13884,
"s": 13569,
"text": "With all of these, postal code is a great indicator as it tells us if we can expect a business district or a residential area. We can also deep-dive further on the address. For example, if we have Level 40 it’s quite obvious the delivery is in a big tower block and will likely have a complicated security process."
},
{
"code": null,
"e": 13950,
"s": 13884,
"text": "For this part of the problem we’ll use the following data points."
},
{
"code": null,
"e": 14107,
"s": 13950,
"text": "Customer : Big Corporation Inc.Delivery_Address : Level 9, Skyscraper, 34567, Hong KongDelivery_Time : 29/05/2016 08:00:00Order_Size : $500"
},
{
"code": null,
"e": 14192,
"s": 14107,
"text": "After performing the typical processing and running our models we see the following:"
},
{
"code": null,
"e": 14634,
"s": 14192,
"text": "Baseline Results:Mean Absolute Error: 351 secondsGreater than 5 mins late: 35%Greater than 10 mins late: 0%Random Forest Results:Mean Absolute Error: 296 secondsGreater than 5 mins late: 15%Greater than 10 mins late: 7%Linear Regressor Results:Mean Absolute Error: 300 secondsGreater than 5 mins late: 14%Greater than 10 mins late: 5%Ensemble Results:Mean Absolute Error: 293 secondsGreater than 5 mins late: 13%Greater than 10 mins late: 6%"
},
{
"code": null,
"e": 15023,
"s": 14634,
"text": "Here, we’re able to see a reduction in MAE of 17%, — much better than before. Similarly, we see reductions in the orders greater than 5 mins late by a humungous 63%. On the other hand, the model does increase the number of orders late from 0% to 6%. Again, we’re faced with a trade-off between models which both have their merits and we must let our business KPIs be the deciding factors."
},
{
"code": null,
"e": 15090,
"s": 15023,
"text": "We can now combine our models together with the following formula:"
},
{
"code": null,
"e": 15190,
"s": 15090,
"text": "Delivery Time = Pick-up Time + Point-to-Point Time + Drop-off Time + Hyperparamater"
},
{
"code": null,
"e": 15532,
"s": 15190,
"text": "Note the addition of a hyperparameter this time. We’ll add this in to take into account any other weird effects that we see in the data such as the pick-up time always been set 5 minutes earlier to meet the expectations of drivers. We’ll set this parameter in order to minimise the final error metrics after calculating the combined results."
},
{
"code": null,
"e": 15582,
"s": 15532,
"text": "Putting it all together, we get the final result:"
},
{
"code": null,
"e": 15801,
"s": 15582,
"text": "Baseline Results:Mean Absolute Error: 1429 secondsGreater than 5 mins late: 60%Greater than 10 mins late: 19%Ensemble Results:Mean Absolute Error: 1263 secondsGreater than 5 mins late: 41%Greater than 10 mins late: 12%"
},
{
"code": null,
"e": 15902,
"s": 15801,
"text": "So our final model has a significant improvement over the baseline model in all metrics — we did it!"
},
{
"code": null,
"e": 16247,
"s": 15902,
"text": "Most importantly, we’ve seen a reduction in orders greater than 10 mins late of almost 40%! We were able to achieve this by working on three separate models which were optimised to their own specific business problem. Combining them and fine-tuning at the last stage made sure we produced a model which is on the level of trained professionals."
},
{
"code": null,
"e": 16501,
"s": 16247,
"text": "Having a model which gives even more accuracy would be great, but it would also require a lot more effort due to the law of diminishing returns. Instead, there are other solutions if we think more about the business case and less about machine learning."
},
{
"code": null,
"e": 16760,
"s": 16501,
"text": "As you may recall from the start, this model is for catering delivery, which means we know the delivery time in advance. One simple way to avoid late deliveries is to take whatever value the model outputs and increase it to make sure that we’re early enough."
},
{
"code": null,
"e": 17191,
"s": 16760,
"text": "This is not a great solution because being too early also has a problem in that the food could go bad or be unprepared. However, it does bring up the point that we should consider the distribution of ‘lateness’ and ‘earliness’. Maybe it is better if we’re 10 minutes early than 5 minutes late. With the metrics used up until this point, we didn’t optimise for such scenarios and so we can reconsider this and optimise accordingly."
},
{
"code": null,
"e": 17469,
"s": 17191,
"text": "Another thing to consider is how the model is presented to users. If a user is told you’ll arrive at 2pm and you don’t, they’ll be frustrated. If you tell someone you’ll be there from 1:45pm-2pm then you can aim to deliver at 1:50pm and if you’re a little late you have leeway."
},
{
"code": null,
"e": 17681,
"s": 17469,
"text": "It’s always important to consider machine learning problems as a solution to an actual real-world problem — this context can often lead to ‘improvements’ that would otherwise be impossible from the model itself."
},
{
"code": null,
"e": 17889,
"s": 17681,
"text": "One of the key wins for this model was being able to effectively differentiate between the different preparation times of the suppliers. That tells us that the suppliers must have very different performance."
},
{
"code": null,
"e": 18237,
"s": 17889,
"text": "Digging deeper, it was found that drivers were spending 3x the time at a few suppliers. With this is information, moving back to the business world, it is possible to discuss with the suppliers and identify the problems which can reduce the time spent at these suppliers and by reducing the variation, improve the overall performance of the model."
},
{
"code": null,
"e": 18726,
"s": 18237,
"text": "We started with a problem statement for predicting food delivery timings. We decided what data we would use and what sort of processing we should do. We thought about what would be the best models to solve our particular problem. We then broke our problem down into three components to build targeted models and finally put them together to create a fully-functioning predictive model. We didn’t stop there though, we used our business knowledge to improve the effectiveness of our model."
},
{
"code": null,
"e": 19016,
"s": 18726,
"text": "This resulted in a reduction of 40% in orders that were over 10 minutes late which can be translated directly into dollars saved in refunds. It also helped to lighten the load on the operations team meaning they could focus on more meaningful tasks such as improving supplier efficiencies."
},
{
"code": null,
"e": 19321,
"s": 19016,
"text": "As outlined, this is the general procedure that can be used to apply machine learning to solve business problems. It’s an approach that makes sure to get the basics right before later optimising for the extra few percent points of improvement. It’s one that I’ve used successfully and I hope you can too."
},
{
"code": null,
"e": 19411,
"s": 19321,
"text": "If you enjoyed reading this, please don’t forget to leave a clap or two, or three... 👏👏👏🔄"
}
] |
A Feature Selection Tool for Machine Learning in Python | by Will Koehrsen | Towards Data Science | Feature selection, the process of finding and selecting the most useful features in a dataset, is a crucial step of the machine learning pipeline. Unnecessary features decrease training speed, decrease model interpretability, and, most importantly, decrease generalization performance on the test set.
Frustrated by the ad-hoc feature selection methods I found myself applying over and over again for machine learning problems, I built a class for feature selection in Python available on GitHub. The FeatureSelector includes some of the most common feature selection methods:
Features with a high percentage of missing valuesCollinear (highly correlated) featuresFeatures with zero importance in a tree-based modelFeatures with low importanceFeatures with a single unique value
Features with a high percentage of missing values
Collinear (highly correlated) features
Features with zero importance in a tree-based model
Features with low importance
Features with a single unique value
In this article we will walk through using the FeatureSelector on an example machine learning dataset. We’ll see how it allows us to rapidly implement these methods, allowing for a more efficient workflow.
The complete code is available on GitHub and I encourage any contributions. The Feature Selector is a work in progress and will continue to improve based on the community needs!
For this example, we will use a sample of data from the Home Credit Default Risk machine learning competition on Kaggle. (To get started with the competition, see this article). The entire dataset is available for download and here we will use a sample for illustration purposes.
The competition is a supervised classification problem and this is a good dataset to use because it has many missing values, numerous highly correlated (collinear) features, and a number of irrelevant features that do not help a machine learning model.
To create an instance of the FeatureSelector class, we need to pass in a structured dataset with observations in the rows and features in the columns. We can use some of the methods with only features, but the importance-based methods also require training labels. Since we have a supervised classification task, we will use a set of features and a set of labels.
(Make sure to run this in the same directory as feature_selector.py )
from feature_selector import FeatureSelector# Features are in train and labels are in train_labelsfs = FeatureSelector(data = train, labels = train_labels)
The feature selector has five methods for finding features to remove. We can access any of the identified features and remove them from the data manually, or use the remove function in the Feature Selector.
Here we will go through each of the identification methods and also show how all 5 can be run at once. The FeatureSelector additionally has several plotting capabilities because visually inspecting data is a crucial component of machine learning.
The first method for finding features to remove is straightforward: find features with a fraction of missing values above a specified threshold. The call below identifies features with more than 60% missing values (bold is output).
fs.identify_missing(missing_threshold = 0.6)17 features with greater than 0.60 missing values.
We can see the fraction of missing values in every column in a dataframe:
fs.missing_stats.head()
To see the features identified for removal, we access the ops attribute of the FeatureSelector , a Python dict with features as lists in the values.
missing_features = fs.ops['missing']missing_features[:5]['OWN_CAR_AGE', 'YEARS_BUILD_AVG', 'COMMONAREA_AVG', 'FLOORSMIN_AVG', 'LIVINGAPARTMENTS_AVG']
Finally, we have a plot of the distribution of missing values in all feature:
fs.plot_missing()
Collinear features are features that are highly correlated with one another. In machine learning, these lead to decreased generalization performance on the test set due to high variance and less model interpretability.
The identify_collinear method finds collinear features based on a specified correlation coefficient value. For each pair of correlated features, it identifies one of the features for removal (since we only need to remove one):
fs.identify_collinear(correlation_threshold = 0.98)21 features with a correlation magnitude greater than 0.98.
A neat visualization we can make with correlations is a heatmap. This shows all the features that have at least one correlation above the threshold:
fs.plot_collinear()
As before, we can access the entire list of correlated features that will be removed, or see the highly correlated pairs of features in a dataframe.
# list of collinear features to removecollinear_features = fs.ops['collinear']# dataframe of collinear featuresfs.record_collinear.head()
If we want to investigate our dataset, we can also make a plot of all the correlations in the data by passing in plot_all = True to the call:
The previous two methods can be applied to any structured dataset and are deterministic — the results will be the same every time for a given threshold. The next method is designed only for supervised machine learning problems where we have labels for training a model and is non-deterministic. The identify_zero_importance function finds features that have zero importance according to a gradient boosting machine (GBM) learning model.
With tree-based machine learning models, such as a boosting ensemble, we can find feature importances. The absolute value of the importance is not as important as the relative values, which we can use to determine the most relevant features for a task. We can also use feature importances for feature selection by removing zero importance features. In a tree-based model, the features with zero importance are not used to split any nodes, and so we can remove them without affecting model performance.
The FeatureSelector finds feature importances using the gradient boosting machine from the LightGBM library. The feature importances are averaged over 10 training runs of the GBM in order to reduce variance. Also, the model is trained using early stopping with a validation set (there is an option to turn this off) to prevent overfitting to the training data.
The code below calls the method and extracts the zero importance features:
# Pass in the appropriate parametersfs.identify_zero_importance(task = 'classification', eval_metric = 'auc', n_iterations = 10, early_stopping = True)# list of zero importance featureszero_importance_features = fs.ops['zero_importance']63 features with zero importance after one-hot encoding.
The parameters we pass in are as follows:
task : either “classification” or “regression” corresponding to our problem
eval_metric: metric to use for early stopping (not necessary if early stopping is disabled)
n_iterations : number of training runs to average the feature importances over
early_stopping: whether or not use early stopping for training the model
This time we get two plots with plot_feature_importances:
# plot the feature importancesfs.plot_feature_importances(threshold = 0.99, plot_n = 12)124 features required for 0.99 of cumulative importance
On the left we have the plot_n most important features (plotted in terms of normalized importance where the total sums to 1). On the right we have the cumulative importance versus the number of features. The vertical line is drawn at threshold of the cumulative importance, in this case 99%.
Two notes are good to remember for the importance-based methods:
Training the gradient boosting machine is stochastic meaning the feature importances will change every time the model is run
This should not have a major impact (the most important features will not suddenly become the least) but it will change the ordering of some of the features. It also can affect the number of zero importance features identified. Don’t be surprised if the feature importances change every time!
To train the machine learning model, the features are first one-hot encoded. This means some of the features identified as having 0 importance might be one-hot encoded features added during modeling.
When we get to the feature removal stage, there is an option to remove any added one-hot encoded features. However, if we are doing machine learning after feature selection, we will have to one-hot encode the features anyway!
The next method builds on zero importance function, using the feature importances from the model for further selection. The function identify_low_importance finds the lowest importance features that do not contribute to a specified total importance.
For example, the call below finds the least important features that are not required for achieving 99% of the total importance:
fs.identify_low_importance(cumulative_importance = 0.99)123 features required for cumulative importance of 0.99 after one hot encoding.116 features do not contribute to cumulative importance of 0.99.
Based on the plot of cumulative importance and this information, the gradient boosting machine considers many of the features to be irrelevant for learning. Again, the results of this method will change on each training run.
To view all the feature importances in a dataframe:
fs.feature_importances.head(10)
The low_importance method borrows from one of the methods of using Principal Components Analysis (PCA) where it is common to keep only the PC needed to retain a certain percentage of the variance (such as 95%). The percentage of total importance accounted for is based on the same idea.
The feature importance based methods are really only applicable if we are going to use a tree-based model for making predictions. Besides being stochastic, the importance-based methods are a black-box approach in that we don’t really know why the model considers the features to be irrelevant. If using these methods, run them several times to see how the results change, and perhaps create multiple datasets with different parameters to test!
The final method is fairly basic: find any columns that have a single unique value. A feature with only one unique value cannot be useful for machine learning because this feature has zero variance. For example, a tree-based model can never make a split on a feature with only one value (since there are no groups to divide the observations into).
There are no parameters here to select, unlike the other methods:
fs.identify_single_unique()4 features with a single unique value.
We can plot a histogram of the number of unique values in each category:
fs.plot_unique()
One point to remember is NaNs are dropped before calculating unique values in Pandas by default.
Once we’ve identified the features to discard, we have two options for removing them. All of the features to remove are stored in the ops dict of the FeatureSelector and we can use the lists to remove features manually. Another option is to use the remove built-in function.
For this method, we pass in the methods to use to remove features. If we want to use all the methods implemented, we just pass in methods = 'all'.
# Remove the features from all methods (returns a df)train_removed = fs.remove(methods = 'all')['missing', 'single_unique', 'collinear', 'zero_importance', 'low_importance'] methods have been runRemoved 140 features.
This method returns a dataframe with the features removed. To also remove the one-hot encoded features that are created during machine learning:
train_removed_all = fs.remove(methods = 'all', keep_one_hot=False)Removed 187 features including one-hot features.
It might be a good idea to check the features that will be removed before going ahead with the operation! The original dataset is stored in the data attribute of the FeatureSelector as a back-up!
Rather than using the methods individually, we can use all of them with identify_all. This takes a dictionary of the parameters for each method:
fs.identify_all(selection_params = {'missing_threshold': 0.6, 'correlation_threshold': 0.98, 'task': 'classification', 'eval_metric': 'auc', 'cumulative_importance': 0.99})151 total features out of 255 identified for removal after one-hot encoding.
Notice that the number of total features will change because we re-ran the model. The remove function can then be called to discard these features.
The Feature Selector class implements several common operations for removing features before training a machine learning model. It offers functions for identifying features for removal as well as visualizations. Methods can be run individually or all at once for efficient workflows.
The missing, collinear, and single_unique methods are deterministic while the feature importance-based methods will change with each run. Feature selection, much like the field of machine learning, is largely empirical and requires testing multiple combinations to find the optimal answer. It’s best practice to try several configurations in a pipeline, and the Feature Selector offers a way to rapidly evaluate parameters for feature selection.
As always, I welcome feedback and constructive criticism. I want to emphasis that I’m looking for help on the FeatureSelector. Anyone can contribute on GitHub and I appreciate advice from those who just uses the tool! I can also be reached on Twitter @koehrsen_will. | [
{
"code": null,
"e": 474,
"s": 172,
"text": "Feature selection, the process of finding and selecting the most useful features in a dataset, is a crucial step of the machine learning pipeline. Unnecessary features decrease training speed, decrease model interpretability, and, most importantly, decrease generalization performance on the test set."
},
{
"code": null,
"e": 749,
"s": 474,
"text": "Frustrated by the ad-hoc feature selection methods I found myself applying over and over again for machine learning problems, I built a class for feature selection in Python available on GitHub. The FeatureSelector includes some of the most common feature selection methods:"
},
{
"code": null,
"e": 951,
"s": 749,
"text": "Features with a high percentage of missing valuesCollinear (highly correlated) featuresFeatures with zero importance in a tree-based modelFeatures with low importanceFeatures with a single unique value"
},
{
"code": null,
"e": 1001,
"s": 951,
"text": "Features with a high percentage of missing values"
},
{
"code": null,
"e": 1040,
"s": 1001,
"text": "Collinear (highly correlated) features"
},
{
"code": null,
"e": 1092,
"s": 1040,
"text": "Features with zero importance in a tree-based model"
},
{
"code": null,
"e": 1121,
"s": 1092,
"text": "Features with low importance"
},
{
"code": null,
"e": 1157,
"s": 1121,
"text": "Features with a single unique value"
},
{
"code": null,
"e": 1363,
"s": 1157,
"text": "In this article we will walk through using the FeatureSelector on an example machine learning dataset. We’ll see how it allows us to rapidly implement these methods, allowing for a more efficient workflow."
},
{
"code": null,
"e": 1541,
"s": 1363,
"text": "The complete code is available on GitHub and I encourage any contributions. The Feature Selector is a work in progress and will continue to improve based on the community needs!"
},
{
"code": null,
"e": 1821,
"s": 1541,
"text": "For this example, we will use a sample of data from the Home Credit Default Risk machine learning competition on Kaggle. (To get started with the competition, see this article). The entire dataset is available for download and here we will use a sample for illustration purposes."
},
{
"code": null,
"e": 2074,
"s": 1821,
"text": "The competition is a supervised classification problem and this is a good dataset to use because it has many missing values, numerous highly correlated (collinear) features, and a number of irrelevant features that do not help a machine learning model."
},
{
"code": null,
"e": 2438,
"s": 2074,
"text": "To create an instance of the FeatureSelector class, we need to pass in a structured dataset with observations in the rows and features in the columns. We can use some of the methods with only features, but the importance-based methods also require training labels. Since we have a supervised classification task, we will use a set of features and a set of labels."
},
{
"code": null,
"e": 2508,
"s": 2438,
"text": "(Make sure to run this in the same directory as feature_selector.py )"
},
{
"code": null,
"e": 2664,
"s": 2508,
"text": "from feature_selector import FeatureSelector# Features are in train and labels are in train_labelsfs = FeatureSelector(data = train, labels = train_labels)"
},
{
"code": null,
"e": 2871,
"s": 2664,
"text": "The feature selector has five methods for finding features to remove. We can access any of the identified features and remove them from the data manually, or use the remove function in the Feature Selector."
},
{
"code": null,
"e": 3118,
"s": 2871,
"text": "Here we will go through each of the identification methods and also show how all 5 can be run at once. The FeatureSelector additionally has several plotting capabilities because visually inspecting data is a crucial component of machine learning."
},
{
"code": null,
"e": 3350,
"s": 3118,
"text": "The first method for finding features to remove is straightforward: find features with a fraction of missing values above a specified threshold. The call below identifies features with more than 60% missing values (bold is output)."
},
{
"code": null,
"e": 3445,
"s": 3350,
"text": "fs.identify_missing(missing_threshold = 0.6)17 features with greater than 0.60 missing values."
},
{
"code": null,
"e": 3519,
"s": 3445,
"text": "We can see the fraction of missing values in every column in a dataframe:"
},
{
"code": null,
"e": 3543,
"s": 3519,
"text": "fs.missing_stats.head()"
},
{
"code": null,
"e": 3692,
"s": 3543,
"text": "To see the features identified for removal, we access the ops attribute of the FeatureSelector , a Python dict with features as lists in the values."
},
{
"code": null,
"e": 3842,
"s": 3692,
"text": "missing_features = fs.ops['missing']missing_features[:5]['OWN_CAR_AGE', 'YEARS_BUILD_AVG', 'COMMONAREA_AVG', 'FLOORSMIN_AVG', 'LIVINGAPARTMENTS_AVG']"
},
{
"code": null,
"e": 3920,
"s": 3842,
"text": "Finally, we have a plot of the distribution of missing values in all feature:"
},
{
"code": null,
"e": 3938,
"s": 3920,
"text": "fs.plot_missing()"
},
{
"code": null,
"e": 4157,
"s": 3938,
"text": "Collinear features are features that are highly correlated with one another. In machine learning, these lead to decreased generalization performance on the test set due to high variance and less model interpretability."
},
{
"code": null,
"e": 4384,
"s": 4157,
"text": "The identify_collinear method finds collinear features based on a specified correlation coefficient value. For each pair of correlated features, it identifies one of the features for removal (since we only need to remove one):"
},
{
"code": null,
"e": 4495,
"s": 4384,
"text": "fs.identify_collinear(correlation_threshold = 0.98)21 features with a correlation magnitude greater than 0.98."
},
{
"code": null,
"e": 4644,
"s": 4495,
"text": "A neat visualization we can make with correlations is a heatmap. This shows all the features that have at least one correlation above the threshold:"
},
{
"code": null,
"e": 4664,
"s": 4644,
"text": "fs.plot_collinear()"
},
{
"code": null,
"e": 4813,
"s": 4664,
"text": "As before, we can access the entire list of correlated features that will be removed, or see the highly correlated pairs of features in a dataframe."
},
{
"code": null,
"e": 4951,
"s": 4813,
"text": "# list of collinear features to removecollinear_features = fs.ops['collinear']# dataframe of collinear featuresfs.record_collinear.head()"
},
{
"code": null,
"e": 5093,
"s": 4951,
"text": "If we want to investigate our dataset, we can also make a plot of all the correlations in the data by passing in plot_all = True to the call:"
},
{
"code": null,
"e": 5530,
"s": 5093,
"text": "The previous two methods can be applied to any structured dataset and are deterministic — the results will be the same every time for a given threshold. The next method is designed only for supervised machine learning problems where we have labels for training a model and is non-deterministic. The identify_zero_importance function finds features that have zero importance according to a gradient boosting machine (GBM) learning model."
},
{
"code": null,
"e": 6032,
"s": 5530,
"text": "With tree-based machine learning models, such as a boosting ensemble, we can find feature importances. The absolute value of the importance is not as important as the relative values, which we can use to determine the most relevant features for a task. We can also use feature importances for feature selection by removing zero importance features. In a tree-based model, the features with zero importance are not used to split any nodes, and so we can remove them without affecting model performance."
},
{
"code": null,
"e": 6393,
"s": 6032,
"text": "The FeatureSelector finds feature importances using the gradient boosting machine from the LightGBM library. The feature importances are averaged over 10 training runs of the GBM in order to reduce variance. Also, the model is trained using early stopping with a validation set (there is an option to turn this off) to prevent overfitting to the training data."
},
{
"code": null,
"e": 6468,
"s": 6393,
"text": "The code below calls the method and extracts the zero importance features:"
},
{
"code": null,
"e": 6847,
"s": 6468,
"text": "# Pass in the appropriate parametersfs.identify_zero_importance(task = 'classification', eval_metric = 'auc', n_iterations = 10, early_stopping = True)# list of zero importance featureszero_importance_features = fs.ops['zero_importance']63 features with zero importance after one-hot encoding."
},
{
"code": null,
"e": 6889,
"s": 6847,
"text": "The parameters we pass in are as follows:"
},
{
"code": null,
"e": 6965,
"s": 6889,
"text": "task : either “classification” or “regression” corresponding to our problem"
},
{
"code": null,
"e": 7057,
"s": 6965,
"text": "eval_metric: metric to use for early stopping (not necessary if early stopping is disabled)"
},
{
"code": null,
"e": 7136,
"s": 7057,
"text": "n_iterations : number of training runs to average the feature importances over"
},
{
"code": null,
"e": 7209,
"s": 7136,
"text": "early_stopping: whether or not use early stopping for training the model"
},
{
"code": null,
"e": 7267,
"s": 7209,
"text": "This time we get two plots with plot_feature_importances:"
},
{
"code": null,
"e": 7411,
"s": 7267,
"text": "# plot the feature importancesfs.plot_feature_importances(threshold = 0.99, plot_n = 12)124 features required for 0.99 of cumulative importance"
},
{
"code": null,
"e": 7703,
"s": 7411,
"text": "On the left we have the plot_n most important features (plotted in terms of normalized importance where the total sums to 1). On the right we have the cumulative importance versus the number of features. The vertical line is drawn at threshold of the cumulative importance, in this case 99%."
},
{
"code": null,
"e": 7768,
"s": 7703,
"text": "Two notes are good to remember for the importance-based methods:"
},
{
"code": null,
"e": 7893,
"s": 7768,
"text": "Training the gradient boosting machine is stochastic meaning the feature importances will change every time the model is run"
},
{
"code": null,
"e": 8186,
"s": 7893,
"text": "This should not have a major impact (the most important features will not suddenly become the least) but it will change the ordering of some of the features. It also can affect the number of zero importance features identified. Don’t be surprised if the feature importances change every time!"
},
{
"code": null,
"e": 8386,
"s": 8186,
"text": "To train the machine learning model, the features are first one-hot encoded. This means some of the features identified as having 0 importance might be one-hot encoded features added during modeling."
},
{
"code": null,
"e": 8612,
"s": 8386,
"text": "When we get to the feature removal stage, there is an option to remove any added one-hot encoded features. However, if we are doing machine learning after feature selection, we will have to one-hot encode the features anyway!"
},
{
"code": null,
"e": 8862,
"s": 8612,
"text": "The next method builds on zero importance function, using the feature importances from the model for further selection. The function identify_low_importance finds the lowest importance features that do not contribute to a specified total importance."
},
{
"code": null,
"e": 8990,
"s": 8862,
"text": "For example, the call below finds the least important features that are not required for achieving 99% of the total importance:"
},
{
"code": null,
"e": 9190,
"s": 8990,
"text": "fs.identify_low_importance(cumulative_importance = 0.99)123 features required for cumulative importance of 0.99 after one hot encoding.116 features do not contribute to cumulative importance of 0.99."
},
{
"code": null,
"e": 9415,
"s": 9190,
"text": "Based on the plot of cumulative importance and this information, the gradient boosting machine considers many of the features to be irrelevant for learning. Again, the results of this method will change on each training run."
},
{
"code": null,
"e": 9467,
"s": 9415,
"text": "To view all the feature importances in a dataframe:"
},
{
"code": null,
"e": 9499,
"s": 9467,
"text": "fs.feature_importances.head(10)"
},
{
"code": null,
"e": 9786,
"s": 9499,
"text": "The low_importance method borrows from one of the methods of using Principal Components Analysis (PCA) where it is common to keep only the PC needed to retain a certain percentage of the variance (such as 95%). The percentage of total importance accounted for is based on the same idea."
},
{
"code": null,
"e": 10230,
"s": 9786,
"text": "The feature importance based methods are really only applicable if we are going to use a tree-based model for making predictions. Besides being stochastic, the importance-based methods are a black-box approach in that we don’t really know why the model considers the features to be irrelevant. If using these methods, run them several times to see how the results change, and perhaps create multiple datasets with different parameters to test!"
},
{
"code": null,
"e": 10578,
"s": 10230,
"text": "The final method is fairly basic: find any columns that have a single unique value. A feature with only one unique value cannot be useful for machine learning because this feature has zero variance. For example, a tree-based model can never make a split on a feature with only one value (since there are no groups to divide the observations into)."
},
{
"code": null,
"e": 10644,
"s": 10578,
"text": "There are no parameters here to select, unlike the other methods:"
},
{
"code": null,
"e": 10710,
"s": 10644,
"text": "fs.identify_single_unique()4 features with a single unique value."
},
{
"code": null,
"e": 10783,
"s": 10710,
"text": "We can plot a histogram of the number of unique values in each category:"
},
{
"code": null,
"e": 10800,
"s": 10783,
"text": "fs.plot_unique()"
},
{
"code": null,
"e": 10897,
"s": 10800,
"text": "One point to remember is NaNs are dropped before calculating unique values in Pandas by default."
},
{
"code": null,
"e": 11172,
"s": 10897,
"text": "Once we’ve identified the features to discard, we have two options for removing them. All of the features to remove are stored in the ops dict of the FeatureSelector and we can use the lists to remove features manually. Another option is to use the remove built-in function."
},
{
"code": null,
"e": 11319,
"s": 11172,
"text": "For this method, we pass in the methods to use to remove features. If we want to use all the methods implemented, we just pass in methods = 'all'."
},
{
"code": null,
"e": 11536,
"s": 11319,
"text": "# Remove the features from all methods (returns a df)train_removed = fs.remove(methods = 'all')['missing', 'single_unique', 'collinear', 'zero_importance', 'low_importance'] methods have been runRemoved 140 features."
},
{
"code": null,
"e": 11681,
"s": 11536,
"text": "This method returns a dataframe with the features removed. To also remove the one-hot encoded features that are created during machine learning:"
},
{
"code": null,
"e": 11796,
"s": 11681,
"text": "train_removed_all = fs.remove(methods = 'all', keep_one_hot=False)Removed 187 features including one-hot features."
},
{
"code": null,
"e": 11992,
"s": 11796,
"text": "It might be a good idea to check the features that will be removed before going ahead with the operation! The original dataset is stored in the data attribute of the FeatureSelector as a back-up!"
},
{
"code": null,
"e": 12137,
"s": 11992,
"text": "Rather than using the methods individually, we can use all of them with identify_all. This takes a dictionary of the parameters for each method:"
},
{
"code": null,
"e": 12536,
"s": 12137,
"text": "fs.identify_all(selection_params = {'missing_threshold': 0.6, 'correlation_threshold': 0.98, 'task': 'classification', 'eval_metric': 'auc', 'cumulative_importance': 0.99})151 total features out of 255 identified for removal after one-hot encoding."
},
{
"code": null,
"e": 12684,
"s": 12536,
"text": "Notice that the number of total features will change because we re-ran the model. The remove function can then be called to discard these features."
},
{
"code": null,
"e": 12968,
"s": 12684,
"text": "The Feature Selector class implements several common operations for removing features before training a machine learning model. It offers functions for identifying features for removal as well as visualizations. Methods can be run individually or all at once for efficient workflows."
},
{
"code": null,
"e": 13414,
"s": 12968,
"text": "The missing, collinear, and single_unique methods are deterministic while the feature importance-based methods will change with each run. Feature selection, much like the field of machine learning, is largely empirical and requires testing multiple combinations to find the optimal answer. It’s best practice to try several configurations in a pipeline, and the Feature Selector offers a way to rapidly evaluate parameters for feature selection."
}
] |
The mutable storage class in C++ | The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. You cannot use the mutable specifier with names declared as static or const, or reference members.
In the following example −
class A
{
public:
A() : x(4), y(5) { };
mutable int x;
int y;
};
int main()
{
const A var2;
var2.x = 345;
// var2.y = 2345;
}
the compiler would not allow the assignment var2.y = 2345 because var2 has been declared as const. The compiler will allow the assignment var2.x = 345 because A::x has been declared as mutable. | [
{
"code": null,
"e": 1318,
"s": 1062,
"text": "The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. You cannot use the mutable specifier with names declared as static or const, or reference members."
},
{
"code": null,
"e": 1345,
"s": 1318,
"text": "In the following example −"
},
{
"code": null,
"e": 1493,
"s": 1345,
"text": "class A\n{\n public:\n A() : x(4), y(5) { };\n mutable int x;\n int y;\n};\n\nint main()\n{\n const A var2;\n var2.x = 345;\n // var2.y = 2345;\n}"
},
{
"code": null,
"e": 1687,
"s": 1493,
"text": "the compiler would not allow the assignment var2.y = 2345 because var2 has been declared as const. The compiler will allow the assignment var2.x = 345 because A::x has been declared as mutable."
}
] |
How to perform topic modeling with Top2Vec. | Towards Data Science | Topic modeling is a problem in natural language processing that has many real-world applications. Being able to discover topics within large sections of text helps us understand text data in greater detail.
For many years, Latent Dirichlet Allocation (LDA) has been the most commonly used algorithm for topic modeling. The algorithm was first introduced in 2003 and treats topics as probability distributions for the occurrence of different words. If you want to see an example of LDA in action, you should check out my article below where I performed LDA on a fake news classification dataset.
towardsdatascience.com
However, with the introduction of transformer models and embedding algorithms such as Doc2Vec, we can create much more sophisticated topic models that capture semantic similarities in words. In fact, an algorithm called Top2Vec makes it possible to build topic models using embedding vectors and clustering. In this article, I will demonstrate how you can use Top2Vec to perform unsupervised topic modeling using embedding vectors and clustering techniques.
Top2Vec is an algorithm that detects topics present in the text and generates jointly embedded topic, document, and word vectors. At a high level, the algorithm performs the following steps to discover topics in a list of documents.
Generate embedding vectors for documents and words.Perform dimensionality reduction on the vectors using an algorithm such as UMAP.Cluster the vectors using a clustering algorithm such as HDBSCAN.Assign topics to each cluster.
Generate embedding vectors for documents and words.
Perform dimensionality reduction on the vectors using an algorithm such as UMAP.
Cluster the vectors using a clustering algorithm such as HDBSCAN.
Assign topics to each cluster.
I have explained each step in detail below.
An embedding vector is a vector that allows us to represent a word or text document in multi-dimensional space. The idea behind embedding vectors is that similar words or text documents will have similar vectors.
There are many algorithms for generating embedding vectors. Word2Vec and Doc2Vec are quite popular but in recent years, NLP developers and researchers have started using transformers to generate embedding vectors. If you’re interested in learning more about transformers, check out my article below.
towardsdatascience.com
Creating embedding vectors for each document allows us to treat each document as a point in multi-dimensional space. Top2Vec also creates jointly embedded word vectors, which allows us to determine topic keywords later.
Once we have a set of word and document vectors, we can move on to the next step.
After we have vectors for each document, the next natural step would be to divide them into clusters using a clustering algorithm. However, the vectors generated from the first step can have as many as 512 components depending on the embedding model that was used.
For this reason, it makes sense to perform some kind of dimensionality reduction algorithm to reduce the number of dimensions in the data. Top2Vec uses an algorithm called UMAP (Uniform Manifold Approximation and Projection) to generate lower-dimensional embedding vectors for each document.
Top2Vec uses HDBSCAN, a hierarchical density-based clustering algorithm, to find dense areas of documents. HDBSCAN is basically just an extension of the DBSCAN algorithm that converts it into a hierarchical clustering algorithm. Using HDBSCAN for topic modeling makes sense because larger topics can consist of several subtopics.
Once we have clusters for each document, we can simply treat each cluster of documents as a separate topic in the topic model. Each topic can be represented as a topic vector that is essentially just the centroid (average point) of the original documents belonging to that topic cluster. In order to label the topic using a set of keywords, we can compute the n-closest words to the topic centroid vector.
Once we have keywords for each topic, the algorithm’s job is done, and it's up to us as humans to interpret what these topics really mean. While Top2Vec is much more complex than the standard LDA approach to topic modeling, it may be able to give us better results since the embedding vectors for words and documents can effectively capture the meaning of words and phrases.
You can install Top2Vec using pip with the following command:
pip install top2vec
You can also install Top2Vec with additional options as demonstrated in the README document in the Top2Vec GitHub repository.
In order to get Top2Vec installed with the pre-trained universal sentence encoders required to follow along with this tutorial, you should run the following command.
pip install top2vec[sentence_encoders]
In this tutorial, I will demonstrate how to use Top2Vec to discover topics in the 20 newsgroups text dataset. This dataset contains roughly 18000 newsgroups posts on 20 topics. You can access the full code for this tutorial on GitHub.
import numpy as npimport pandas as pdfrom top2vec import Top2Vec
For this tutorial, I will be using the 20 newsgroups text dataset. This dataset contains roughly 18000 newsgroups posts on 20 topics. We can download the dataset through Scikit-learn as demonstrated below.
from sklearn.datasets import fetch_20newsgroupsnewsgroups = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))
Training a Top2Vec model is very easy and requires only one line of code as demonstrated below.
from top2vec import Top2Vecmodel = Top2Vec(articles_df['content'].values, embedding_model='universal-sentence-encoder')
Note that I used the universal sentence encoder embedding model above. You can use this model if you installed Top2Vec with the sentence encoders option. Otherwise, simply remove this argument and the model will be trained with Doc2Vec embeddings by default.
Once a Top2Vec model has been trained on the data, we can use the model object to get information about the topics that were extracted. For example, we can view the number of topics that were discovered using the get_num_topics function as demonstrated below.
model.get_num_topics()
Running the code above produces the following output.
100
The Top2Vec model has an attribute called topic_words that is basically just a Numpy array with lists of words for each topic.
model.topic_words
Running the code above in a Jupyter notebook cell produces the following output.
array([['recchi', 'potvin', 'nyr', ..., 'pittsburgh', 'binghamton', 'pitt'], ['diagnosed', 'symptoms', 'diagnosis', ..., 'mfm', 'affected', 'admitted'], ['spacecraft', 'jpl', 'orbiter', ..., 'scientist', 'convention', 'comet'], ..., ['liefeld', 'wolverine', 'comics', ..., 'requests', 'tickets', 'lemieux'], ['vice', 'pacific', 'bay', ..., 'projects', 'chapter', 'caps'], ['armenians', 'ankara', 'armenian', ..., 'discussed', 'azerbaijani', 'whom']], dtype='<U15')
If we want to see the words for a specific topic, we can simply index this array as demonstrated below.
model.topic_words[0]
The code above gives us the following list of words for topic 0.
array(['recchi', 'potvin', 'nyr', 'nyi', 'lemieux', 'lindros', 'nhl', 'phillies', 'defenseman', 'mets', 'ahl', 'jagr', 'bruins', 'sabres', 'cubs', 'gretzky', 'alomar', 'pitchers', 'pitching', 'clemens', 'canucks', 'inning', 'henrik', 'innings', 'yankees', 'oilers', 'utica', 'islanders', 'boswell', 'braves', 'hockey', 'rangers', 'leafs', 'flyers', 'sox', 'playoffs', 'wpg', 'baseball', 'dodgers', 'espn', 'goalie', 'fuhr', 'playoff', 'ulf', 'hawks', 'batting', 'tampa', 'pittsburgh', 'binghamton', 'pitt'], dtype='<U15')
As we can see, this topic seems to be mostly about sports, particularly baseball and hockey because we see the names of popular baseball teams along with the last names of hockey players.
We can easily generate word clouds for topics in order to get a better understanding of the frequency of keywords within a topic.
model.generate_topic_wordcloud(0)
Running the code above produces the word cloud below.
The word cloud above is useful because it lets us visually understand the relative frequency of different words with the topic. We can see that words such as “Phillies” and “Lemieux” appear more often than words such as “playoff” or “Tampa”.
The topic_vectors attribute allows us to access the topic vectors for each topic as demonstrated below.
model.topic_vectors
As we can see in the output below, the topic vectors for a Top2Vec model are stored as a two-dimensional Numpy array where each row corresponds to a specific topic vector.
array([[-9.1372393e-03, -8.8540517e-02, -5.1944017e-02, ..., 2.0455582e-02, -1.1964893e-01, -1.1116098e-04], [-4.0708046e-02, -2.6885601e-02, 2.2835255e-02, ..., 7.2831921e-02, -6.1708521e-02, -5.2916467e-02], [-3.2222651e-02, -4.7691587e-02, -2.9298926e-02, ..., 4.8001394e-02, -4.6445496e-02, -3.5007432e-02], ..., [-4.3788709e-02, -6.5007553e-02, 5.3533200e-02, ..., 2.7984662e-02, 6.5978311e-02, -4.4375043e-02], [ 1.2126865e-02, -4.5126071e-03, -4.6988029e-02, ..., 3.7431438e-02, -1.2432544e-02, -5.3018846e-02], [-5.2520853e-02, 4.9585234e-02, 5.9694829e-03, ..., 4.1887209e-02, -2.1055080e-02, -5.4151181e-02]], dtype=float32)
If we want to access the vector for any topic, for example, we can simply index the Numpy array based on the topic number we are looking for.
We can also use the embedding model used by the Top2Vec model to generate document embeddings for any section of text as demonstrated below. Note that this is not possible if you did not specify an embedding model when training the Top2Vec model.
embedding_vector = model.embed(["This is a fake news article."])embedding_vector.shape
Running the function above produces the following output.
TensorShape([1, 512])
Based on the output above, we can see that the embedding model transformed the text into a 512-dimensional vector in the form of a Python Tensor object.
We can search for topics using keywords as demonstrated below. Note that the function returns lists of topic keywords, word scores, topic scores, and topic numbers for each topic that is found from the search.
topic_words, word_scores, topic_scores, topic_nums = model.search_topics(keywords=["politics"], num_topics=3)
We can take a look at the topic words and topic scores to see what topics were returned from the search.
topic_words, topic_scores
The code above produces the following output in Jupyter.
([array(['clinton', 'bush', 'president', 'reagan', 'democratic', 'republicans', 'elected', 'congress', 'wiretap', 'administration', 'election', 'johnson', 'politically', 'politicians', 'politics', 'political', 'executive', 'senate', 'bill', 'constitutional', 'democracy', 'lib', 'government', 'gov', 'iraq', 'corrupt', 'convention', 'rockefeller', 'nist', 'ford', 'grant', 'libertarian', 'nuy', 'govt', 'feds', 'libertarians', 'decades', 'recall', 'ws', 'bureau', 'bullshit', 'nsa', 'stephanopoulos', 'weren', 'liar', 'koresh', 'affairs', 'barry', 'conservative', 'secretary'], dtype='<U15'), array(['um', 'ci', 'oo', 'll', 'ye', 'hmm', 'un', 'uh', 'y_', 'wt', 'on', 'uu', 'actually', 'an', 'eh', 'way', 'des', 'er', 'se', 'not', 'has', 'huh', 'of', 'ya', 'so', 'it', 'in', 'le', 'upon', 'hm', 'one', 'is', 'es', 'ne', 'at', 'what', 'no', 'au', 'est', 'shut', 'mm', 'got', 'dont', 'lo', 'tu', 'en', 'the', 'have', 'am', 'there'], dtype='<U15'), array(['libertarian', 'libertarians', 'govt', 'liberties', 'democracy', 'democratic', 'government', 'conservative', 'gov', 'republicans', 'governments', 'liberty', 'constitutional', 'opposed', 'communist', 'politically', 'advocate', 'citizens', 'premise', 'opposition', 'patents', 'fascist', 'opposing', 'compromise', 'feds', 'liberal', 'politicians', 'independent', 'reform', 'johnson', 'philosophy', 'ron', 'citizen', 'aclu', 'politics', 'frankly', 'xt', 'defend', 'political', 'regulated', 'militia', 'republic', 'radical', 'against', 'amendment', 'unified', 'argument', 'revolution', 'senate', 'obey'], dtype='<U15')], array([0.23019153, 0.21416718, 0.19618901]))
We can see that the topics are also ranked by topic score. The topics with the highest similarity scores are shown first in the first list above.
We can easily find documents that belong to specific topics with the search_documents_by_topic function. This function requires both a topic number and the number of documents that we want to retrieve.
model.search_documents_by_topic(0, num_docs=1)
Running the function above produces the following output.
(array(['\nI think this guy is going to be just a little bit disappointed. Lemieux\ntwo, Tocchet, Mullen, Tippett, and Jagr. I buzzed my friend because I forgot\nwho had scored Mullen\'s goal. I said, "Who scored? Lemieux two, Tocchet,\nTippett, Jagr." The funny part was I said the "Jagr" part non-chalantly as\nhe was in the process of scoring while I was asking this question!!! :-)\n\nAll in all ABC\'s coverage wasn\'t bad. On a scale of 1-10, I give it about\nan 8. How were the games in the Chi/St. Louis/LA area???\n\n\nThat\'s stupid!!! I\'d complain to the television network! If I were to even\nsee a Pirates game on instead of a Penguins game at this time of the year, I\nand many other Pittsburghers would surely raise hell!!!\n\n\nTexas is off to a good start, they may pull it out this year. Whoops! That\nbelongs in rec.sport.baseball!!!'], dtype=object), array([0.75086796], dtype=float32), array([12405]))
We can see that the article above is definitely about baseball, which matches our interpretation of the first topic.
Sometimes the Top2Vec model will discover many small topics and it is difficult to work with so many different topics. Fortunately, Top2Vec allows us to perform hierarchical topic reduction, which iteratively merges similar topics until we have reached the desired number of topics. We can reduce the number of topics in the model from 100 topics to only 20 topics as demonstrated in the code below.
topic_mapping = model.hierarchical_topic_reduction(num_topics=20)
The topic mapping that the function returns is a nested list that explains which topics have been merged together to form the 20 larger topics.
If we want to look at the original topics within topic 1 we can run the following code in Jupyter.
topic_mapping[1]
The code above produces the following list of merged topic numbers.
[52, 61, 75, 13, 37, 72, 14, 21, 19, 74, 65, 15]
Working with this mapping, however, can be a bit tedious so Top2Vec allows us to access information for the new topics with new attributes. For example, we can access the new topic keywords with the topic_words_reduced attribute.
model.topic_words_reduced[1]
Running the code above gives us the following updated list of keywords for topic 1:
array(['irq', 'mhz', 'processor', 'sgi', 'motherboard', 'risc', 'processors', 'ati', 'dma', 'scsi', 'cmos', 'powerbook', 'vms', 'vga', 'cpu', 'packard', 'bsd', 'baud', 'maxtor', 'ansi', 'hardware', 'ieee', 'xt', 'ibm', 'computer', 'workstation', 'vesa', 'printers', 'deskjet', 'msdos', 'modems', 'intel', 'printer', 'linux', 'floppies', 'computing', 'implementations', 'workstations', 'hp', 'macs', 'monitor', 'vram', 'unix', 'telnet', 'bios', 'pcs', 'specs', 'oscillator', 'cdrom', 'pc'], dtype='<U15')
Based on the keywords above, we can see that this topic seems to be mostly about computer hardware.
For more details about the functions that are available in Top2Vec, please check out the Top2Vec GitHub repository. I hope you found this tutorial to be useful.
Top2Vec is a recently developed topic modeling algorithm that may replace LDA in the near future. Unlike LDA, Top2Vec generates jointly embedded word and document vectors and clusters these vectors in order to find topics within text data. The open-source Top2Vec library is also very easy to use and allows developers to train sophisticated topic models in just one line of code.
As usual, you can find the full code for this article on GitHub.
Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?
Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up! You can also follow me on Twitter for content updates.
And while you’re at it, consider joining the Medium community to read articles from thousands of other writers as well.
D. M. Blei, A. Y. Ng, M. I. Jordan, Latent Dirichlet Allocation, (2003), Journal of Machine Learning Research 3.D. Angelov, Top2Vec: Distributed Representations of Topics, (2020), arXiv.org.L. McInnes, J. Healy, and J. Melville, UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, (2020), arXiv.org.C. Malzer and M. Baum, A Hybrid Approach To Hierarchical Density-based Cluster Selection, (2021), arXiv.org.
D. M. Blei, A. Y. Ng, M. I. Jordan, Latent Dirichlet Allocation, (2003), Journal of Machine Learning Research 3.
D. Angelov, Top2Vec: Distributed Representations of Topics, (2020), arXiv.org.
L. McInnes, J. Healy, and J. Melville, UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, (2020), arXiv.org.
C. Malzer and M. Baum, A Hybrid Approach To Hierarchical Density-based Cluster Selection, (2021), arXiv.org. | [
{
"code": null,
"e": 379,
"s": 172,
"text": "Topic modeling is a problem in natural language processing that has many real-world applications. Being able to discover topics within large sections of text helps us understand text data in greater detail."
},
{
"code": null,
"e": 767,
"s": 379,
"text": "For many years, Latent Dirichlet Allocation (LDA) has been the most commonly used algorithm for topic modeling. The algorithm was first introduced in 2003 and treats topics as probability distributions for the occurrence of different words. If you want to see an example of LDA in action, you should check out my article below where I performed LDA on a fake news classification dataset."
},
{
"code": null,
"e": 790,
"s": 767,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1248,
"s": 790,
"text": "However, with the introduction of transformer models and embedding algorithms such as Doc2Vec, we can create much more sophisticated topic models that capture semantic similarities in words. In fact, an algorithm called Top2Vec makes it possible to build topic models using embedding vectors and clustering. In this article, I will demonstrate how you can use Top2Vec to perform unsupervised topic modeling using embedding vectors and clustering techniques."
},
{
"code": null,
"e": 1481,
"s": 1248,
"text": "Top2Vec is an algorithm that detects topics present in the text and generates jointly embedded topic, document, and word vectors. At a high level, the algorithm performs the following steps to discover topics in a list of documents."
},
{
"code": null,
"e": 1708,
"s": 1481,
"text": "Generate embedding vectors for documents and words.Perform dimensionality reduction on the vectors using an algorithm such as UMAP.Cluster the vectors using a clustering algorithm such as HDBSCAN.Assign topics to each cluster."
},
{
"code": null,
"e": 1760,
"s": 1708,
"text": "Generate embedding vectors for documents and words."
},
{
"code": null,
"e": 1841,
"s": 1760,
"text": "Perform dimensionality reduction on the vectors using an algorithm such as UMAP."
},
{
"code": null,
"e": 1907,
"s": 1841,
"text": "Cluster the vectors using a clustering algorithm such as HDBSCAN."
},
{
"code": null,
"e": 1938,
"s": 1907,
"text": "Assign topics to each cluster."
},
{
"code": null,
"e": 1982,
"s": 1938,
"text": "I have explained each step in detail below."
},
{
"code": null,
"e": 2195,
"s": 1982,
"text": "An embedding vector is a vector that allows us to represent a word or text document in multi-dimensional space. The idea behind embedding vectors is that similar words or text documents will have similar vectors."
},
{
"code": null,
"e": 2495,
"s": 2195,
"text": "There are many algorithms for generating embedding vectors. Word2Vec and Doc2Vec are quite popular but in recent years, NLP developers and researchers have started using transformers to generate embedding vectors. If you’re interested in learning more about transformers, check out my article below."
},
{
"code": null,
"e": 2518,
"s": 2495,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2738,
"s": 2518,
"text": "Creating embedding vectors for each document allows us to treat each document as a point in multi-dimensional space. Top2Vec also creates jointly embedded word vectors, which allows us to determine topic keywords later."
},
{
"code": null,
"e": 2820,
"s": 2738,
"text": "Once we have a set of word and document vectors, we can move on to the next step."
},
{
"code": null,
"e": 3085,
"s": 2820,
"text": "After we have vectors for each document, the next natural step would be to divide them into clusters using a clustering algorithm. However, the vectors generated from the first step can have as many as 512 components depending on the embedding model that was used."
},
{
"code": null,
"e": 3377,
"s": 3085,
"text": "For this reason, it makes sense to perform some kind of dimensionality reduction algorithm to reduce the number of dimensions in the data. Top2Vec uses an algorithm called UMAP (Uniform Manifold Approximation and Projection) to generate lower-dimensional embedding vectors for each document."
},
{
"code": null,
"e": 3707,
"s": 3377,
"text": "Top2Vec uses HDBSCAN, a hierarchical density-based clustering algorithm, to find dense areas of documents. HDBSCAN is basically just an extension of the DBSCAN algorithm that converts it into a hierarchical clustering algorithm. Using HDBSCAN for topic modeling makes sense because larger topics can consist of several subtopics."
},
{
"code": null,
"e": 4113,
"s": 3707,
"text": "Once we have clusters for each document, we can simply treat each cluster of documents as a separate topic in the topic model. Each topic can be represented as a topic vector that is essentially just the centroid (average point) of the original documents belonging to that topic cluster. In order to label the topic using a set of keywords, we can compute the n-closest words to the topic centroid vector."
},
{
"code": null,
"e": 4488,
"s": 4113,
"text": "Once we have keywords for each topic, the algorithm’s job is done, and it's up to us as humans to interpret what these topics really mean. While Top2Vec is much more complex than the standard LDA approach to topic modeling, it may be able to give us better results since the embedding vectors for words and documents can effectively capture the meaning of words and phrases."
},
{
"code": null,
"e": 4550,
"s": 4488,
"text": "You can install Top2Vec using pip with the following command:"
},
{
"code": null,
"e": 4570,
"s": 4550,
"text": "pip install top2vec"
},
{
"code": null,
"e": 4696,
"s": 4570,
"text": "You can also install Top2Vec with additional options as demonstrated in the README document in the Top2Vec GitHub repository."
},
{
"code": null,
"e": 4862,
"s": 4696,
"text": "In order to get Top2Vec installed with the pre-trained universal sentence encoders required to follow along with this tutorial, you should run the following command."
},
{
"code": null,
"e": 4901,
"s": 4862,
"text": "pip install top2vec[sentence_encoders]"
},
{
"code": null,
"e": 5136,
"s": 4901,
"text": "In this tutorial, I will demonstrate how to use Top2Vec to discover topics in the 20 newsgroups text dataset. This dataset contains roughly 18000 newsgroups posts on 20 topics. You can access the full code for this tutorial on GitHub."
},
{
"code": null,
"e": 5201,
"s": 5136,
"text": "import numpy as npimport pandas as pdfrom top2vec import Top2Vec"
},
{
"code": null,
"e": 5407,
"s": 5201,
"text": "For this tutorial, I will be using the 20 newsgroups text dataset. This dataset contains roughly 18000 newsgroups posts on 20 topics. We can download the dataset through Scikit-learn as demonstrated below."
},
{
"code": null,
"e": 5541,
"s": 5407,
"text": "from sklearn.datasets import fetch_20newsgroupsnewsgroups = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))"
},
{
"code": null,
"e": 5637,
"s": 5541,
"text": "Training a Top2Vec model is very easy and requires only one line of code as demonstrated below."
},
{
"code": null,
"e": 5757,
"s": 5637,
"text": "from top2vec import Top2Vecmodel = Top2Vec(articles_df['content'].values, embedding_model='universal-sentence-encoder')"
},
{
"code": null,
"e": 6016,
"s": 5757,
"text": "Note that I used the universal sentence encoder embedding model above. You can use this model if you installed Top2Vec with the sentence encoders option. Otherwise, simply remove this argument and the model will be trained with Doc2Vec embeddings by default."
},
{
"code": null,
"e": 6276,
"s": 6016,
"text": "Once a Top2Vec model has been trained on the data, we can use the model object to get information about the topics that were extracted. For example, we can view the number of topics that were discovered using the get_num_topics function as demonstrated below."
},
{
"code": null,
"e": 6299,
"s": 6276,
"text": "model.get_num_topics()"
},
{
"code": null,
"e": 6353,
"s": 6299,
"text": "Running the code above produces the following output."
},
{
"code": null,
"e": 6357,
"s": 6353,
"text": "100"
},
{
"code": null,
"e": 6484,
"s": 6357,
"text": "The Top2Vec model has an attribute called topic_words that is basically just a Numpy array with lists of words for each topic."
},
{
"code": null,
"e": 6502,
"s": 6484,
"text": "model.topic_words"
},
{
"code": null,
"e": 6583,
"s": 6502,
"text": "Running the code above in a Jupyter notebook cell produces the following output."
},
{
"code": null,
"e": 7119,
"s": 6583,
"text": "array([['recchi', 'potvin', 'nyr', ..., 'pittsburgh', 'binghamton', 'pitt'], ['diagnosed', 'symptoms', 'diagnosis', ..., 'mfm', 'affected', 'admitted'], ['spacecraft', 'jpl', 'orbiter', ..., 'scientist', 'convention', 'comet'], ..., ['liefeld', 'wolverine', 'comics', ..., 'requests', 'tickets', 'lemieux'], ['vice', 'pacific', 'bay', ..., 'projects', 'chapter', 'caps'], ['armenians', 'ankara', 'armenian', ..., 'discussed', 'azerbaijani', 'whom']], dtype='<U15')"
},
{
"code": null,
"e": 7223,
"s": 7119,
"text": "If we want to see the words for a specific topic, we can simply index this array as demonstrated below."
},
{
"code": null,
"e": 7244,
"s": 7223,
"text": "model.topic_words[0]"
},
{
"code": null,
"e": 7309,
"s": 7244,
"text": "The code above gives us the following list of words for topic 0."
},
{
"code": null,
"e": 7878,
"s": 7309,
"text": "array(['recchi', 'potvin', 'nyr', 'nyi', 'lemieux', 'lindros', 'nhl', 'phillies', 'defenseman', 'mets', 'ahl', 'jagr', 'bruins', 'sabres', 'cubs', 'gretzky', 'alomar', 'pitchers', 'pitching', 'clemens', 'canucks', 'inning', 'henrik', 'innings', 'yankees', 'oilers', 'utica', 'islanders', 'boswell', 'braves', 'hockey', 'rangers', 'leafs', 'flyers', 'sox', 'playoffs', 'wpg', 'baseball', 'dodgers', 'espn', 'goalie', 'fuhr', 'playoff', 'ulf', 'hawks', 'batting', 'tampa', 'pittsburgh', 'binghamton', 'pitt'], dtype='<U15')"
},
{
"code": null,
"e": 8066,
"s": 7878,
"text": "As we can see, this topic seems to be mostly about sports, particularly baseball and hockey because we see the names of popular baseball teams along with the last names of hockey players."
},
{
"code": null,
"e": 8196,
"s": 8066,
"text": "We can easily generate word clouds for topics in order to get a better understanding of the frequency of keywords within a topic."
},
{
"code": null,
"e": 8230,
"s": 8196,
"text": "model.generate_topic_wordcloud(0)"
},
{
"code": null,
"e": 8284,
"s": 8230,
"text": "Running the code above produces the word cloud below."
},
{
"code": null,
"e": 8526,
"s": 8284,
"text": "The word cloud above is useful because it lets us visually understand the relative frequency of different words with the topic. We can see that words such as “Phillies” and “Lemieux” appear more often than words such as “playoff” or “Tampa”."
},
{
"code": null,
"e": 8630,
"s": 8526,
"text": "The topic_vectors attribute allows us to access the topic vectors for each topic as demonstrated below."
},
{
"code": null,
"e": 8650,
"s": 8630,
"text": "model.topic_vectors"
},
{
"code": null,
"e": 8822,
"s": 8650,
"text": "As we can see in the output below, the topic vectors for a Top2Vec model are stored as a two-dimensional Numpy array where each row corresponds to a specific topic vector."
},
{
"code": null,
"e": 9546,
"s": 8822,
"text": "array([[-9.1372393e-03, -8.8540517e-02, -5.1944017e-02, ..., 2.0455582e-02, -1.1964893e-01, -1.1116098e-04], [-4.0708046e-02, -2.6885601e-02, 2.2835255e-02, ..., 7.2831921e-02, -6.1708521e-02, -5.2916467e-02], [-3.2222651e-02, -4.7691587e-02, -2.9298926e-02, ..., 4.8001394e-02, -4.6445496e-02, -3.5007432e-02], ..., [-4.3788709e-02, -6.5007553e-02, 5.3533200e-02, ..., 2.7984662e-02, 6.5978311e-02, -4.4375043e-02], [ 1.2126865e-02, -4.5126071e-03, -4.6988029e-02, ..., 3.7431438e-02, -1.2432544e-02, -5.3018846e-02], [-5.2520853e-02, 4.9585234e-02, 5.9694829e-03, ..., 4.1887209e-02, -2.1055080e-02, -5.4151181e-02]], dtype=float32)"
},
{
"code": null,
"e": 9688,
"s": 9546,
"text": "If we want to access the vector for any topic, for example, we can simply index the Numpy array based on the topic number we are looking for."
},
{
"code": null,
"e": 9935,
"s": 9688,
"text": "We can also use the embedding model used by the Top2Vec model to generate document embeddings for any section of text as demonstrated below. Note that this is not possible if you did not specify an embedding model when training the Top2Vec model."
},
{
"code": null,
"e": 10022,
"s": 9935,
"text": "embedding_vector = model.embed([\"This is a fake news article.\"])embedding_vector.shape"
},
{
"code": null,
"e": 10080,
"s": 10022,
"text": "Running the function above produces the following output."
},
{
"code": null,
"e": 10102,
"s": 10080,
"text": "TensorShape([1, 512])"
},
{
"code": null,
"e": 10255,
"s": 10102,
"text": "Based on the output above, we can see that the embedding model transformed the text into a 512-dimensional vector in the form of a Python Tensor object."
},
{
"code": null,
"e": 10465,
"s": 10255,
"text": "We can search for topics using keywords as demonstrated below. Note that the function returns lists of topic keywords, word scores, topic scores, and topic numbers for each topic that is found from the search."
},
{
"code": null,
"e": 10575,
"s": 10465,
"text": "topic_words, word_scores, topic_scores, topic_nums = model.search_topics(keywords=[\"politics\"], num_topics=3)"
},
{
"code": null,
"e": 10680,
"s": 10575,
"text": "We can take a look at the topic words and topic scores to see what topics were returned from the search."
},
{
"code": null,
"e": 10706,
"s": 10680,
"text": "topic_words, topic_scores"
},
{
"code": null,
"e": 10763,
"s": 10706,
"text": "The code above produces the following output in Jupyter."
},
{
"code": null,
"e": 12562,
"s": 10763,
"text": "([array(['clinton', 'bush', 'president', 'reagan', 'democratic', 'republicans', 'elected', 'congress', 'wiretap', 'administration', 'election', 'johnson', 'politically', 'politicians', 'politics', 'political', 'executive', 'senate', 'bill', 'constitutional', 'democracy', 'lib', 'government', 'gov', 'iraq', 'corrupt', 'convention', 'rockefeller', 'nist', 'ford', 'grant', 'libertarian', 'nuy', 'govt', 'feds', 'libertarians', 'decades', 'recall', 'ws', 'bureau', 'bullshit', 'nsa', 'stephanopoulos', 'weren', 'liar', 'koresh', 'affairs', 'barry', 'conservative', 'secretary'], dtype='<U15'), array(['um', 'ci', 'oo', 'll', 'ye', 'hmm', 'un', 'uh', 'y_', 'wt', 'on', 'uu', 'actually', 'an', 'eh', 'way', 'des', 'er', 'se', 'not', 'has', 'huh', 'of', 'ya', 'so', 'it', 'in', 'le', 'upon', 'hm', 'one', 'is', 'es', 'ne', 'at', 'what', 'no', 'au', 'est', 'shut', 'mm', 'got', 'dont', 'lo', 'tu', 'en', 'the', 'have', 'am', 'there'], dtype='<U15'), array(['libertarian', 'libertarians', 'govt', 'liberties', 'democracy', 'democratic', 'government', 'conservative', 'gov', 'republicans', 'governments', 'liberty', 'constitutional', 'opposed', 'communist', 'politically', 'advocate', 'citizens', 'premise', 'opposition', 'patents', 'fascist', 'opposing', 'compromise', 'feds', 'liberal', 'politicians', 'independent', 'reform', 'johnson', 'philosophy', 'ron', 'citizen', 'aclu', 'politics', 'frankly', 'xt', 'defend', 'political', 'regulated', 'militia', 'republic', 'radical', 'against', 'amendment', 'unified', 'argument', 'revolution', 'senate', 'obey'], dtype='<U15')], array([0.23019153, 0.21416718, 0.19618901]))"
},
{
"code": null,
"e": 12708,
"s": 12562,
"text": "We can see that the topics are also ranked by topic score. The topics with the highest similarity scores are shown first in the first list above."
},
{
"code": null,
"e": 12910,
"s": 12708,
"text": "We can easily find documents that belong to specific topics with the search_documents_by_topic function. This function requires both a topic number and the number of documents that we want to retrieve."
},
{
"code": null,
"e": 12957,
"s": 12910,
"text": "model.search_documents_by_topic(0, num_docs=1)"
},
{
"code": null,
"e": 13015,
"s": 12957,
"text": "Running the function above produces the following output."
},
{
"code": null,
"e": 13956,
"s": 13015,
"text": "(array(['\\nI think this guy is going to be just a little bit disappointed. Lemieux\\ntwo, Tocchet, Mullen, Tippett, and Jagr. I buzzed my friend because I forgot\\nwho had scored Mullen\\'s goal. I said, \"Who scored? Lemieux two, Tocchet,\\nTippett, Jagr.\" The funny part was I said the \"Jagr\" part non-chalantly as\\nhe was in the process of scoring while I was asking this question!!! :-)\\n\\nAll in all ABC\\'s coverage wasn\\'t bad. On a scale of 1-10, I give it about\\nan 8. How were the games in the Chi/St. Louis/LA area???\\n\\n\\nThat\\'s stupid!!! I\\'d complain to the television network! If I were to even\\nsee a Pirates game on instead of a Penguins game at this time of the year, I\\nand many other Pittsburghers would surely raise hell!!!\\n\\n\\nTexas is off to a good start, they may pull it out this year. Whoops! That\\nbelongs in rec.sport.baseball!!!'], dtype=object), array([0.75086796], dtype=float32), array([12405]))"
},
{
"code": null,
"e": 14073,
"s": 13956,
"text": "We can see that the article above is definitely about baseball, which matches our interpretation of the first topic."
},
{
"code": null,
"e": 14473,
"s": 14073,
"text": "Sometimes the Top2Vec model will discover many small topics and it is difficult to work with so many different topics. Fortunately, Top2Vec allows us to perform hierarchical topic reduction, which iteratively merges similar topics until we have reached the desired number of topics. We can reduce the number of topics in the model from 100 topics to only 20 topics as demonstrated in the code below."
},
{
"code": null,
"e": 14539,
"s": 14473,
"text": "topic_mapping = model.hierarchical_topic_reduction(num_topics=20)"
},
{
"code": null,
"e": 14683,
"s": 14539,
"text": "The topic mapping that the function returns is a nested list that explains which topics have been merged together to form the 20 larger topics."
},
{
"code": null,
"e": 14782,
"s": 14683,
"text": "If we want to look at the original topics within topic 1 we can run the following code in Jupyter."
},
{
"code": null,
"e": 14799,
"s": 14782,
"text": "topic_mapping[1]"
},
{
"code": null,
"e": 14867,
"s": 14799,
"text": "The code above produces the following list of merged topic numbers."
},
{
"code": null,
"e": 14916,
"s": 14867,
"text": "[52, 61, 75, 13, 37, 72, 14, 21, 19, 74, 65, 15]"
},
{
"code": null,
"e": 15146,
"s": 14916,
"text": "Working with this mapping, however, can be a bit tedious so Top2Vec allows us to access information for the new topics with new attributes. For example, we can access the new topic keywords with the topic_words_reduced attribute."
},
{
"code": null,
"e": 15175,
"s": 15146,
"text": "model.topic_words_reduced[1]"
},
{
"code": null,
"e": 15259,
"s": 15175,
"text": "Running the code above gives us the following updated list of keywords for topic 1:"
},
{
"code": null,
"e": 15805,
"s": 15259,
"text": "array(['irq', 'mhz', 'processor', 'sgi', 'motherboard', 'risc', 'processors', 'ati', 'dma', 'scsi', 'cmos', 'powerbook', 'vms', 'vga', 'cpu', 'packard', 'bsd', 'baud', 'maxtor', 'ansi', 'hardware', 'ieee', 'xt', 'ibm', 'computer', 'workstation', 'vesa', 'printers', 'deskjet', 'msdos', 'modems', 'intel', 'printer', 'linux', 'floppies', 'computing', 'implementations', 'workstations', 'hp', 'macs', 'monitor', 'vram', 'unix', 'telnet', 'bios', 'pcs', 'specs', 'oscillator', 'cdrom', 'pc'], dtype='<U15')"
},
{
"code": null,
"e": 15905,
"s": 15805,
"text": "Based on the keywords above, we can see that this topic seems to be mostly about computer hardware."
},
{
"code": null,
"e": 16066,
"s": 15905,
"text": "For more details about the functions that are available in Top2Vec, please check out the Top2Vec GitHub repository. I hope you found this tutorial to be useful."
},
{
"code": null,
"e": 16447,
"s": 16066,
"text": "Top2Vec is a recently developed topic modeling algorithm that may replace LDA in the near future. Unlike LDA, Top2Vec generates jointly embedded word and document vectors and clusters these vectors in order to find topics within text data. The open-source Top2Vec library is also very easy to use and allows developers to train sophisticated topic models in just one line of code."
},
{
"code": null,
"e": 16512,
"s": 16447,
"text": "As usual, you can find the full code for this article on GitHub."
},
{
"code": null,
"e": 16713,
"s": 16512,
"text": "Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?"
},
{
"code": null,
"e": 16930,
"s": 16713,
"text": "Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up! You can also follow me on Twitter for content updates."
},
{
"code": null,
"e": 17050,
"s": 16930,
"text": "And while you’re at it, consider joining the Medium community to read articles from thousands of other writers as well."
},
{
"code": null,
"e": 17483,
"s": 17050,
"text": "D. M. Blei, A. Y. Ng, M. I. Jordan, Latent Dirichlet Allocation, (2003), Journal of Machine Learning Research 3.D. Angelov, Top2Vec: Distributed Representations of Topics, (2020), arXiv.org.L. McInnes, J. Healy, and J. Melville, UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, (2020), arXiv.org.C. Malzer and M. Baum, A Hybrid Approach To Hierarchical Density-based Cluster Selection, (2021), arXiv.org."
},
{
"code": null,
"e": 17596,
"s": 17483,
"text": "D. M. Blei, A. Y. Ng, M. I. Jordan, Latent Dirichlet Allocation, (2003), Journal of Machine Learning Research 3."
},
{
"code": null,
"e": 17675,
"s": 17596,
"text": "D. Angelov, Top2Vec: Distributed Representations of Topics, (2020), arXiv.org."
},
{
"code": null,
"e": 17810,
"s": 17675,
"text": "L. McInnes, J. Healy, and J. Melville, UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, (2020), arXiv.org."
}
] |
XML DOM - Loading | In this chapter, we will study about XML Loading and Parsing.
In order to describe the interfaces provided by the API, the W3C uses an abstract language called the Interface Definition Language (IDL). The advantage of using IDL is that the developer learns how to use the DOM with his or her favorite language and can switch easily to a different language.
The disadvantage is that, since it is abstract, the IDL cannot be used directly by Web developers. Due to the differences between programming languages, they need to have mapping — or binding — between the abstract interfaces and their concrete languages. DOM has been mapped to programming languages such as Javascript, JScript, Java, C, C++, PLSQL, Python, and Perl.
A parser is a software application that is designed to analyze a document, in our case XML document and do something specific with the information. Some of the DOM based parsers are listed in the following table −
JAXP
Sun Microsystem’s Java API for XML Parsing (JAXP)
XML4J
IBM’s XML Parser for Java (XML4J)
msxml
Microsoft’s XML parser (msxml) version 2.0 is built-into Internet Explorer 5.5
4DOM
4DOM is a parser for the Python programming language
XML::DOM
XML::DOM is a Perl module to manipulate XML documents using Perl
Xerces
Apache’s Xerces Java Parser
In a tree-based API like DOM, the parser traverses the XML file and creates the corresponding DOM objects. Then you can traverse the DOM structure back and forth.
While loading an XML document, the XML content can come in two forms −
Directly as XML file
As XML string
Following example demonstrates how to load XML (node.xml) data using Ajax and Javascript when the XML content is received as an XML file. Here, the Ajax function gets the content of an xml file and stores it in XML DOM. Once the DOM object is created, it is then parsed.
<!DOCTYPE html>
<html>
<body>
<div>
<b>FirstName:</b> <span id = "FirstName"></span><br>
<b>LastName:</b> <span id = "LastName"></span><br>
<b>ContactNo:</b> <span id = "ContactNo"></span><br>
<b>Email:</b> <span id = "Email"></span>
</div>
<script>
//if browser supports XMLHttpRequest
if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object.
code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// sets and sends the request for calling "node.xml"
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
// sets and returns the content as XML DOM
xmlDoc = xmlhttp.responseXML;
//parsing the DOM object
document.getElementById("FirstName").innerHTML =
xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue;
document.getElementById("LastName").innerHTML =
xmlDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue;
document.getElementById("ContactNo").innerHTML =
xmlDoc.getElementsByTagName("ContactNo")[0].childNodes[0].nodeValue;
document.getElementById("Email").innerHTML =
xmlDoc.getElementsByTagName("Email")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
<Company>
<Employee category = "Technical" id = "firstelement">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>[email protected]</Email>
</Employee>
<Employee category = "Non-Technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
<Email>[email protected]</Email>
</Employee>
<Employee category = "Management">
<FirstName>Tanisha</FirstName>
<LastName>Sharma</LastName>
<ContactNo>1234562350</ContactNo>
<Email>[email protected]</Email>
</Employee>
</Company>
Most of the details of the code are in the script code.
Internet Explorer uses the ActiveXObject("Microsoft.XMLHTTP") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method.
Internet Explorer uses the ActiveXObject("Microsoft.XMLHTTP") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method.
the responseXML transforms the XML content directly in XML DOM.
the responseXML transforms the XML content directly in XML DOM.
Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name).
Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name).
Save this file as loadingexample.html and open it in your browser. You will receive the following output −
Following example demonstrates how to load XML data using Ajax and Javascript when XML content is received as XML file. Here, the Ajax function, gets the content of an xml file and stores it in XML DOM. Once the DOM object is created it is then parsed.
<!DOCTYPE html>
<html>
<head>
<script>
// loads the xml string in a dom object
function loadXMLString(t) { // for non IE browsers
if (window.DOMParser) {
// create an instance for xml dom object parser = new DOMParser();
xmlDoc = parser.parseFromString(t,"text/xml");
}
// code for IE
else { // create an instance for xml dom object
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(t);
}
return xmlDoc;
}
</script>
</head>
<body>
<script>
// a variable with the string
var text = "<Employee>";
text = text+"<FirstName>Tanmay</FirstName>";
text = text+"<LastName>Patil</LastName>";
text = text+"<ContactNo>1234567890</ContactNo>";
text = text+"<Email>[email protected]</Email>";
text = text+"</Employee>";
// calls the loadXMLString() with "text" function and store the xml dom in a variable
var xmlDoc = loadXMLString(text);
//parsing the DOM object
y = xmlDoc.documentElement.childNodes;
for (i = 0;i<y.length;i++) {
document.write(y[i].childNodes[0].nodeValue);
document.write("<br>");
}
</script>
</body>
</html>
Most of the details of the code are in the script code.
Internet Explorer uses the ActiveXObject("Microsoft.XMLDOM") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method.
Internet Explorer uses the ActiveXObject("Microsoft.XMLDOM") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method.
The variable text shall contain a string with XML content.
The variable text shall contain a string with XML content.
Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue.
Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue.
Save this file as loadingexample.html and open it in your browser. You will see the following output −
Now that we saw how the XML content transforms into JavaScript XML DOM, you can now access any XML element by using the XML DOM methods.
41 Lectures
5 hours
Abhishek And Pukhraj
33 Lectures
3.5 hours
Abhishek And Pukhraj
15 Lectures
1 hours
Zach Miller
15 Lectures
4 hours
Prof. Paul Cline, Ed.D
13 Lectures
4 hours
Prof. Paul Cline, Ed.D
17 Lectures
2 hours
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2350,
"s": 2288,
"text": "In this chapter, we will study about XML Loading and Parsing."
},
{
"code": null,
"e": 2645,
"s": 2350,
"text": "In order to describe the interfaces provided by the API, the W3C uses an abstract language called the Interface Definition Language (IDL). The advantage of using IDL is that the developer learns how to use the DOM with his or her favorite language and can switch easily to a different language."
},
{
"code": null,
"e": 3014,
"s": 2645,
"text": "The disadvantage is that, since it is abstract, the IDL cannot be used directly by Web developers. Due to the differences between programming languages, they need to have mapping — or binding — between the abstract interfaces and their concrete languages. DOM has been mapped to programming languages such as Javascript, JScript, Java, C, C++, PLSQL, Python, and Perl."
},
{
"code": null,
"e": 3228,
"s": 3014,
"text": "A parser is a software application that is designed to analyze a document, in our case XML document and do something specific with the information. Some of the DOM based parsers are listed in the following table −"
},
{
"code": null,
"e": 3233,
"s": 3228,
"text": "JAXP"
},
{
"code": null,
"e": 3283,
"s": 3233,
"text": "Sun Microsystem’s Java API for XML Parsing (JAXP)"
},
{
"code": null,
"e": 3289,
"s": 3283,
"text": "XML4J"
},
{
"code": null,
"e": 3323,
"s": 3289,
"text": "IBM’s XML Parser for Java (XML4J)"
},
{
"code": null,
"e": 3329,
"s": 3323,
"text": "msxml"
},
{
"code": null,
"e": 3408,
"s": 3329,
"text": "Microsoft’s XML parser (msxml) version 2.0 is built-into Internet Explorer 5.5"
},
{
"code": null,
"e": 3413,
"s": 3408,
"text": "4DOM"
},
{
"code": null,
"e": 3466,
"s": 3413,
"text": "4DOM is a parser for the Python programming language"
},
{
"code": null,
"e": 3475,
"s": 3466,
"text": "XML::DOM"
},
{
"code": null,
"e": 3540,
"s": 3475,
"text": "XML::DOM is a Perl module to manipulate XML documents using Perl"
},
{
"code": null,
"e": 3547,
"s": 3540,
"text": "Xerces"
},
{
"code": null,
"e": 3575,
"s": 3547,
"text": "Apache’s Xerces Java Parser"
},
{
"code": null,
"e": 3738,
"s": 3575,
"text": "In a tree-based API like DOM, the parser traverses the XML file and creates the corresponding DOM objects. Then you can traverse the DOM structure back and forth."
},
{
"code": null,
"e": 3809,
"s": 3738,
"text": "While loading an XML document, the XML content can come in two forms −"
},
{
"code": null,
"e": 3830,
"s": 3809,
"text": "Directly as XML file"
},
{
"code": null,
"e": 3844,
"s": 3830,
"text": "As XML string"
},
{
"code": null,
"e": 4115,
"s": 3844,
"text": "Following example demonstrates how to load XML (node.xml) data using Ajax and Javascript when the XML content is received as an XML file. Here, the Ajax function gets the content of an xml file and stores it in XML DOM. Once the DOM object is created, it is then parsed."
},
{
"code": null,
"e": 5678,
"s": 4115,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <div>\n <b>FirstName:</b> <span id = \"FirstName\"></span><br>\n <b>LastName:</b> <span id = \"LastName\"></span><br>\n <b>ContactNo:</b> <span id = \"ContactNo\"></span><br>\n <b>Email:</b> <span id = \"Email\"></span>\n </div>\n <script>\n //if browser supports XMLHttpRequest\n \n if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object. \n code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest();\n } else { // code for IE6, IE5 \n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n \n // sets and sends the request for calling \"node.xml\"\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n\n // sets and returns the content as XML DOM\n xmlDoc = xmlhttp.responseXML;\n\n //parsing the DOM object\n document.getElementById(\"FirstName\").innerHTML = \n xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0].nodeValue;\n document.getElementById(\"LastName\").innerHTML = \n xmlDoc.getElementsByTagName(\"LastName\")[0].childNodes[0].nodeValue;\n document.getElementById(\"ContactNo\").innerHTML = \n xmlDoc.getElementsByTagName(\"ContactNo\")[0].childNodes[0].nodeValue;\n document.getElementById(\"Email\").innerHTML = \n xmlDoc.getElementsByTagName(\"Email\")[0].childNodes[0].nodeValue;\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 6366,
"s": 5678,
"text": "<Company> \n <Employee category = \"Technical\" id = \"firstelement\"> \n <FirstName>Tanmay</FirstName> \n <LastName>Patil</LastName> \n <ContactNo>1234567890</ContactNo> \n <Email>[email protected]</Email> \n </Employee> \n \n <Employee category = \"Non-Technical\"> \n <FirstName>Taniya</FirstName> \n <LastName>Mishra</LastName> \n <ContactNo>1234667898</ContactNo> \n <Email>[email protected]</Email> \n </Employee> \n \n <Employee category = \"Management\"> \n <FirstName>Tanisha</FirstName> \n <LastName>Sharma</LastName> \n <ContactNo>1234562350</ContactNo> \n <Email>[email protected]</Email> \n </Employee> \n</Company> "
},
{
"code": null,
"e": 6422,
"s": 6366,
"text": "Most of the details of the code are in the script code."
},
{
"code": null,
"e": 6580,
"s": 6422,
"text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLHTTP\") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method."
},
{
"code": null,
"e": 6738,
"s": 6580,
"text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLHTTP\") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method."
},
{
"code": null,
"e": 6802,
"s": 6738,
"text": "the responseXML transforms the XML content directly in XML DOM."
},
{
"code": null,
"e": 6866,
"s": 6802,
"text": "the responseXML transforms the XML content directly in XML DOM."
},
{
"code": null,
"e": 7142,
"s": 6866,
"text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name)."
},
{
"code": null,
"e": 7418,
"s": 7142,
"text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name)."
},
{
"code": null,
"e": 7525,
"s": 7418,
"text": "Save this file as loadingexample.html and open it in your browser. You will receive the following output −"
},
{
"code": null,
"e": 7778,
"s": 7525,
"text": "Following example demonstrates how to load XML data using Ajax and Javascript when XML content is received as XML file. Here, the Ajax function, gets the content of an xml file and stores it in XML DOM. Once the DOM object is created it is then parsed."
},
{
"code": null,
"e": 9242,
"s": 7778,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n \n // loads the xml string in a dom object\n function loadXMLString(t) { // for non IE browsers\n if (window.DOMParser) {\n // create an instance for xml dom object parser = new DOMParser();\n xmlDoc = parser.parseFromString(t,\"text/xml\");\n }\n // code for IE\n else { // create an instance for xml dom object\n xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async = false;\n xmlDoc.loadXML(t);\n }\n return xmlDoc;\n }\n </script>\n </head>\n <body>\n <script>\n \n // a variable with the string\n var text = \"<Employee>\";\n text = text+\"<FirstName>Tanmay</FirstName>\";\n text = text+\"<LastName>Patil</LastName>\";\n text = text+\"<ContactNo>1234567890</ContactNo>\";\n text = text+\"<Email>[email protected]</Email>\";\n text = text+\"</Employee>\";\n\n // calls the loadXMLString() with \"text\" function and store the xml dom in a variable\n var xmlDoc = loadXMLString(text);\n\t\n //parsing the DOM object\n y = xmlDoc.documentElement.childNodes;\n for (i = 0;i<y.length;i++) {\n document.write(y[i].childNodes[0].nodeValue);\n document.write(\"<br>\");\n }\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 9298,
"s": 9242,
"text": "Most of the details of the code are in the script code."
},
{
"code": null,
"e": 9485,
"s": 9298,
"text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLDOM\") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method."
},
{
"code": null,
"e": 9672,
"s": 9485,
"text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLDOM\") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method."
},
{
"code": null,
"e": 9731,
"s": 9672,
"text": "The variable text shall contain a string with XML content."
},
{
"code": null,
"e": 9790,
"s": 9731,
"text": "The variable text shall contain a string with XML content."
},
{
"code": null,
"e": 9981,
"s": 9790,
"text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue."
},
{
"code": null,
"e": 10172,
"s": 9981,
"text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue."
},
{
"code": null,
"e": 10275,
"s": 10172,
"text": "Save this file as loadingexample.html and open it in your browser. You will see the following output −"
},
{
"code": null,
"e": 10413,
"s": 10275,
"text": "Now that we saw how the XML content transforms into JavaScript XML DOM, you can now access any XML element by using the XML DOM methods."
},
{
"code": null,
"e": 10446,
"s": 10413,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10468,
"s": 10446,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 10503,
"s": 10468,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10525,
"s": 10503,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 10558,
"s": 10525,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10571,
"s": 10558,
"text": " Zach Miller"
},
{
"code": null,
"e": 10604,
"s": 10571,
"text": "\n 15 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10628,
"s": 10604,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 10661,
"s": 10628,
"text": "\n 13 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10685,
"s": 10661,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 10718,
"s": 10685,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10735,
"s": 10718,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 10742,
"s": 10735,
"text": " Print"
},
{
"code": null,
"e": 10753,
"s": 10742,
"text": " Add Notes"
}
] |
Days of Our Lives | Practice | GeeksforGeeks | Given a month with arbitrary number of days, N, and an integer K representing the day with which it starts. ie- 1 for Monday, 2 for Tuesday and so on. Find the number of times each day (Monday, Tuesday, ..., Sunday) appears in the month.
Example 1:
Input:
N = 31 , K = 1
Output:
5 5 5 4 4 4 4
Explanation: The month starts from Monday.
There will be 4 days of each day
(Sunday , Monday , etc) upto 28th of the
Month. Then, The successive 3 days will
have a extra day each. So, Monday, Tuesday
and Wednesday will have 5 days while the
others will have 4 days each.
Example 2:
Input:
N = 28, K = 5
Output:
5 5 5 4 4 4 4
Explanation: Each day of the month will
have 4 days each and thus the Output.
Your Task:
You don't need to read input or print anything. Your task is to complete the function daysOfWeeks() which takes Integers N and K as input and return a list of 7 integers indicating number of days in each day of the week.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
1 <= K <= 7
0
pawan16085 months ago
vector<int> v={N/7,N/7,N/7,N/7,N/7,N/7,N/7};
N = N%7;
int i = 0;
while(N--)
{
int a = (K-1 + i)%7;
v[a]++;
i++;
}
return v;
0
Nandan9 months ago
Nandan
Wrong output in example-2https://uploads.disquscdn.c...
-1
Kamal Meena2 years ago
Kamal Meena
Python Solution Ex.Time:0.01https://ide.geeksforgeeks.o...
-1
Jaspal Singh2 years ago
Jaspal Singh
#include<bits stdc++.h="">#define int long long int using namespace std; main(){ int t;cin>>t; while(t--){ int n,k;cin>>n>>k;int arr[7]; for(int i=0;i<7;i++) arr[i]=0; int tmp=n/7; for(int i=0;i<7;i++) arr[i]=tmp; n=n-tmp*7; k=k-1; if(n!=0) while(n!=0) { arr[k++]+=1; if(k==7) k=0; n--; } for(int i=0;i<7;i++) cout<<arr[i]<<" ";="" cout<<endl;="" }="" }="">
-1
vinayak lakhotiya4 years ago
vinayak lakhotiya
Simple https://ide.geeksforgeeks.o... https://uploads.disquscdn.c...
-1
juggernaut4 years ago
juggernaut
use long instead
-1
El Mayor Misterio4 years ago
El Mayor Misterio
what's wrong with this code..
https://ide.geeksforgeeks.o...
what does this mean:Runtime Error:Runtime ErrorException in thread "main" java.util.InputMismatchException: For input string: "696407850067"at java.util.Scanner.nextInt(Scanner.java:2123)at java.util.Scanner.nextInt(Scanner.java:2076)at GFG.main(File.java:13)
-1
Vincenzo4 years ago
Vincenzo
Solvable in O(k)
Execution Time:0.03Is there a better way to deal with the remainder?https://ide.geeksforgeeks.o...
-1
Palash Bhatnagar4 years ago
Palash Bhatnagar
https://ide.geeksforgeeks.o... I'm having Time Exceed Error. what's wrong with my code
-1
ad!tya4 years ago
ad!tya
https://ide.geeksforgeeks.o...i have tested this code for every boundary cases and it gave correct answer but submition is giving run time error (Abort signal from abort(3) (SIGABRT)) what is the reason?
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": 466,
"s": 226,
"text": "Given a month with arbitrary number of days, N, and an integer K representing the day with which it starts. ie- 1 for Monday, 2 for Tuesday and so on. Find the number of times each day (Monday, Tuesday, ..., Sunday) appears in the month. "
},
{
"code": null,
"e": 479,
"s": 468,
"text": "Example 1:"
},
{
"code": null,
"e": 795,
"s": 479,
"text": "Input:\nN = 31 , K = 1\nOutput:\n5 5 5 4 4 4 4 \nExplanation: The month starts from Monday.\nThere will be 4 days of each day\n(Sunday , Monday , etc) upto 28th of the\nMonth. Then, The successive 3 days will\nhave a extra day each. So, Monday, Tuesday\nand Wednesday will have 5 days while the\nothers will have 4 days each."
},
{
"code": null,
"e": 807,
"s": 795,
"text": "\nExample 2:"
},
{
"code": null,
"e": 929,
"s": 807,
"text": "Input:\nN = 28, K = 5\nOutput:\n5 5 5 4 4 4 4 \nExplanation: Each day of the month will\nhave 4 days each and thus the Output."
},
{
"code": null,
"e": 1164,
"s": 931,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function daysOfWeeks() which takes Integers N and K as input and return a list of 7 integers indicating number of days in each day of the week."
},
{
"code": null,
"e": 1230,
"s": 1166,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n "
},
{
"code": null,
"e": 1269,
"s": 1230,
"text": "Constraints:\n1 <= N <= 105\n1 <= K <= 7"
},
{
"code": null,
"e": 1271,
"s": 1269,
"text": "0"
},
{
"code": null,
"e": 1293,
"s": 1271,
"text": "pawan16085 months ago"
},
{
"code": null,
"e": 1501,
"s": 1293,
"text": "vector<int> v={N/7,N/7,N/7,N/7,N/7,N/7,N/7};\n N = N%7;\n int i = 0;\n while(N--)\n {\n int a = (K-1 + i)%7;\n v[a]++;\n i++;\n }\n return v;"
},
{
"code": null,
"e": 1503,
"s": 1501,
"text": "0"
},
{
"code": null,
"e": 1522,
"s": 1503,
"text": "Nandan9 months ago"
},
{
"code": null,
"e": 1529,
"s": 1522,
"text": "Nandan"
},
{
"code": null,
"e": 1585,
"s": 1529,
"text": "Wrong output in example-2https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 1588,
"s": 1585,
"text": "-1"
},
{
"code": null,
"e": 1611,
"s": 1588,
"text": "Kamal Meena2 years ago"
},
{
"code": null,
"e": 1623,
"s": 1611,
"text": "Kamal Meena"
},
{
"code": null,
"e": 1682,
"s": 1623,
"text": "Python Solution Ex.Time:0.01https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 1685,
"s": 1682,
"text": "-1"
},
{
"code": null,
"e": 1709,
"s": 1685,
"text": "Jaspal Singh2 years ago"
},
{
"code": null,
"e": 1722,
"s": 1709,
"text": "Jaspal Singh"
},
{
"code": null,
"e": 2188,
"s": 1722,
"text": "#include<bits stdc++.h=\"\">#define int long long int using namespace std; main(){ int t;cin>>t; while(t--){ int n,k;cin>>n>>k;int arr[7]; for(int i=0;i<7;i++) arr[i]=0; int tmp=n/7; for(int i=0;i<7;i++) arr[i]=tmp; n=n-tmp*7; k=k-1; if(n!=0) while(n!=0) { arr[k++]+=1; if(k==7) k=0; n--; } for(int i=0;i<7;i++) cout<<arr[i]<<\" \";=\"\" cout<<endl;=\"\" }=\"\" }=\"\">"
},
{
"code": null,
"e": 2191,
"s": 2188,
"text": "-1"
},
{
"code": null,
"e": 2220,
"s": 2191,
"text": "vinayak lakhotiya4 years ago"
},
{
"code": null,
"e": 2238,
"s": 2220,
"text": "vinayak lakhotiya"
},
{
"code": null,
"e": 2307,
"s": 2238,
"text": "Simple https://ide.geeksforgeeks.o... https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2310,
"s": 2307,
"text": "-1"
},
{
"code": null,
"e": 2332,
"s": 2310,
"text": "juggernaut4 years ago"
},
{
"code": null,
"e": 2343,
"s": 2332,
"text": "juggernaut"
},
{
"code": null,
"e": 2360,
"s": 2343,
"text": "use long instead"
},
{
"code": null,
"e": 2363,
"s": 2360,
"text": "-1"
},
{
"code": null,
"e": 2392,
"s": 2363,
"text": "El Mayor Misterio4 years ago"
},
{
"code": null,
"e": 2410,
"s": 2392,
"text": "El Mayor Misterio"
},
{
"code": null,
"e": 2440,
"s": 2410,
"text": "what's wrong with this code.."
},
{
"code": null,
"e": 2471,
"s": 2440,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2731,
"s": 2471,
"text": "what does this mean:Runtime Error:Runtime ErrorException in thread \"main\" java.util.InputMismatchException: For input string: \"696407850067\"at java.util.Scanner.nextInt(Scanner.java:2123)at java.util.Scanner.nextInt(Scanner.java:2076)at GFG.main(File.java:13)"
},
{
"code": null,
"e": 2734,
"s": 2731,
"text": "-1"
},
{
"code": null,
"e": 2754,
"s": 2734,
"text": "Vincenzo4 years ago"
},
{
"code": null,
"e": 2763,
"s": 2754,
"text": "Vincenzo"
},
{
"code": null,
"e": 2780,
"s": 2763,
"text": "Solvable in O(k)"
},
{
"code": null,
"e": 2879,
"s": 2780,
"text": "Execution Time:0.03Is there a better way to deal with the remainder?https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2882,
"s": 2879,
"text": "-1"
},
{
"code": null,
"e": 2910,
"s": 2882,
"text": "Palash Bhatnagar4 years ago"
},
{
"code": null,
"e": 2927,
"s": 2910,
"text": "Palash Bhatnagar"
},
{
"code": null,
"e": 3014,
"s": 2927,
"text": "https://ide.geeksforgeeks.o... I'm having Time Exceed Error. what's wrong with my code"
},
{
"code": null,
"e": 3017,
"s": 3014,
"text": "-1"
},
{
"code": null,
"e": 3035,
"s": 3017,
"text": "ad!tya4 years ago"
},
{
"code": null,
"e": 3042,
"s": 3035,
"text": "ad!tya"
},
{
"code": null,
"e": 3246,
"s": 3042,
"text": "https://ide.geeksforgeeks.o...i have tested this code for every boundary cases and it gave correct answer but submition is giving run time error (Abort signal from abort(3) (SIGABRT)) what is the reason?"
},
{
"code": null,
"e": 3392,
"s": 3246,
"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": 3428,
"s": 3392,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3438,
"s": 3428,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3448,
"s": 3438,
"text": "\nContest\n"
},
{
"code": null,
"e": 3511,
"s": 3448,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3659,
"s": 3511,
"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": 3867,
"s": 3659,
"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": 3973,
"s": 3867,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Arduino - Trigonometric Functions | You need to use Trigonometry practically like calculating the distance for moving object or angular speed. Arduino provides traditional trigonometric functions (sin, cos, tan, asin, acos, atan) that can be summarized by writing their prototypes. Math.h contains the trigonometry function's prototype.
double sin(double x); //returns sine of x radians
double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x
double sine = sin(2); // approximately 0.90929737091
double cosine = cos(2); // approximately -0.41614685058
double tangent = tan(2); // approximately -2.18503975868
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3171,
"s": 2870,
"text": "You need to use Trigonometry practically like calculating the distance for moving object or angular speed. Arduino provides traditional trigonometric functions (sin, cos, tan, asin, acos, atan) that can be summarized by writing their prototypes. Math.h contains the trigonometry function's prototype."
},
{
"code": null,
"e": 3556,
"s": 3171,
"text": "double sin(double x); //returns sine of x radians\ndouble cos(double y); //returns cosine of y radians\ndouble tan(double x); //returns the tangent of x radians\ndouble acos(double x); //returns A, the angle corresponding to cos (A) = x\ndouble asin(double x); //returns A, the angle corresponding to sin (A) = x\ndouble atan(double x); //returns A, the angle corresponding to tan (A) = x\n"
},
{
"code": null,
"e": 3722,
"s": 3556,
"text": "double sine = sin(2); // approximately 0.90929737091\ndouble cosine = cos(2); // approximately -0.41614685058\ndouble tangent = tan(2); // approximately -2.18503975868"
},
{
"code": null,
"e": 3757,
"s": 3722,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3768,
"s": 3757,
"text": " Amit Rana"
},
{
"code": null,
"e": 3801,
"s": 3768,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3812,
"s": 3801,
"text": " Amit Rana"
},
{
"code": null,
"e": 3845,
"s": 3812,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3858,
"s": 3845,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3893,
"s": 3858,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3906,
"s": 3893,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3938,
"s": 3906,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 3951,
"s": 3938,
"text": " Ashraf Said"
},
{
"code": null,
"e": 3982,
"s": 3951,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 3995,
"s": 3982,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4002,
"s": 3995,
"text": " Print"
},
{
"code": null,
"e": 4013,
"s": 4002,
"text": " Add Notes"
}
] |
Difference between two given times - GeeksforGeeks | 16 Dec, 2021
Given two times in string “HH:MM” format. Here ‘H’ shows hours and ‘M’ shows minutes. You have to find the difference in the same string format between these two strings. But both given strings should follow these cases. 1) Time 1 will be less than or equal to time2 2) Hours will be possible from 0 to 23. 3) Minutes will be possible from 0 to 59Examples:
Input : s1 = "14:00";
s2 = "16:45";
Output : result = "2:45"
Input : s1 = "1:04"
s2 = "13:05"
Output : result = "12:01"
The idea is to first remove colon. After removing colon, hour difference can be computed using simple mathematics.
C++
Python3
Javascript
// C++ program to find difference between two// given times.#include <bits/stdc++.h>using namespace std; // remove ':' and convert it into an integerint removeColon(string s){ if (s.size() == 4) s.replace(1, 1, ""); if (s.size() == 5) s.replace(2, 1, ""); return stoi(s);} // Main function which finds differencestring diff(string s1, string s2){ // change string (eg. 2:21 --> 221, 00:23 --> 23) int time1 = removeColon(s1); int time2 = removeColon(s2); // difference between hours int hourDiff = time2 / 100 - time1 / 100 - 1; // difference between minutes int minDiff = time2 % 100 + (60 - time1 % 100); if (minDiff >= 60) { hourDiff++; minDiff = minDiff - 60; } // convert answer again in string with ':' string res = to_string(hourDiff) + ':' + to_string(minDiff); return res;} // Driver program to test above functionsint main(){ string s1 = "14:00"; string s2 = "16:45"; cout << diff(s1, s2) << endl; return 0;}
# Python 3 program to find difference between two# given times. # Remove ':' and convert it into an integerdef removeColon(s): if (len(s) == 4): s = s[:1] + s[2:] if (len(s) == 5): s = s[:2] + s[3:] return int(s) # Main function which finds differencedef diff(s1, s2): # Change string # (eg. 2:21 --> 221, 00:23 --> 23) time1 = removeColon(s1) time2 = removeColon(s2) # Difference between hours hourDiff = time2 // 100 - time1 // 100 - 1; # Difference between minutes minDiff = time2 % 100 + (60 - time1 % 100) if (minDiff >= 60): hourDiff += 1 minDiff = minDiff - 60 # Convert answer again in string with ':' res = str(hourDiff) + ':' + str(minDiff) return res # Driver codes1 = "14:00"s2 = "16:45" print(diff(s1, s2)) # This code is contributed by ApurvaRaj
<script>// JavaScript program to find difference between two// given times. // remove ':' and convert it into an integerfunction removeColon( s){ if (s.length == 4) s= s.replace(":", ""); if (s.length == 5) s= s.replace(":", ""); return parseInt(s);} // Main function which finds differencefunction diff( s1, s2){ // change string (eg. 2:21 --> 221, 00:23 --> 23) time1 = removeColon(s1); time2 = removeColon(s2); // difference between hours hourDiff = parseInt(time2 / 100 - time1 / 100 - 1); // difference between minutes minDiff = parseInt(time2 % 100 + (60 - time1 % 100)); if (minDiff >= 60) { hourDiff++; minDiff = minDiff - 60; } // convert answer again in string with ':' res = (hourDiff).toString() + ':' + (minDiff).toString(); return res;} // Driver program to test above functions s1 = "14:00"; s2 = "16:45"; console.log(diff(s1, s2)); // This code is contributed by ukasp.</script>
Output:
2:45
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ApurvaRaj
ukasp
date-time-program
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1 | [
{
"code": null,
"e": 24441,
"s": 24413,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 24800,
"s": 24441,
"text": "Given two times in string “HH:MM” format. Here ‘H’ shows hours and ‘M’ shows minutes. You have to find the difference in the same string format between these two strings. But both given strings should follow these cases. 1) Time 1 will be less than or equal to time2 2) Hours will be possible from 0 to 23. 3) Minutes will be possible from 0 to 59Examples: "
},
{
"code": null,
"e": 24937,
"s": 24800,
"text": "Input : s1 = \"14:00\";\n s2 = \"16:45\";\nOutput : result = \"2:45\"\n\nInput : s1 = \"1:04\"\n s2 = \"13:05\"\nOutput : result = \"12:01\""
},
{
"code": null,
"e": 25056,
"s": 24939,
"text": "The idea is to first remove colon. After removing colon, hour difference can be computed using simple mathematics. "
},
{
"code": null,
"e": 25060,
"s": 25056,
"text": "C++"
},
{
"code": null,
"e": 25068,
"s": 25060,
"text": "Python3"
},
{
"code": null,
"e": 25079,
"s": 25068,
"text": "Javascript"
},
{
"code": "// C++ program to find difference between two// given times.#include <bits/stdc++.h>using namespace std; // remove ':' and convert it into an integerint removeColon(string s){ if (s.size() == 4) s.replace(1, 1, \"\"); if (s.size() == 5) s.replace(2, 1, \"\"); return stoi(s);} // Main function which finds differencestring diff(string s1, string s2){ // change string (eg. 2:21 --> 221, 00:23 --> 23) int time1 = removeColon(s1); int time2 = removeColon(s2); // difference between hours int hourDiff = time2 / 100 - time1 / 100 - 1; // difference between minutes int minDiff = time2 % 100 + (60 - time1 % 100); if (minDiff >= 60) { hourDiff++; minDiff = minDiff - 60; } // convert answer again in string with ':' string res = to_string(hourDiff) + ':' + to_string(minDiff); return res;} // Driver program to test above functionsint main(){ string s1 = \"14:00\"; string s2 = \"16:45\"; cout << diff(s1, s2) << endl; return 0;}",
"e": 26101,
"s": 25079,
"text": null
},
{
"code": "# Python 3 program to find difference between two# given times. # Remove ':' and convert it into an integerdef removeColon(s): if (len(s) == 4): s = s[:1] + s[2:] if (len(s) == 5): s = s[:2] + s[3:] return int(s) # Main function which finds differencedef diff(s1, s2): # Change string # (eg. 2:21 --> 221, 00:23 --> 23) time1 = removeColon(s1) time2 = removeColon(s2) # Difference between hours hourDiff = time2 // 100 - time1 // 100 - 1; # Difference between minutes minDiff = time2 % 100 + (60 - time1 % 100) if (minDiff >= 60): hourDiff += 1 minDiff = minDiff - 60 # Convert answer again in string with ':' res = str(hourDiff) + ':' + str(minDiff) return res # Driver codes1 = \"14:00\"s2 = \"16:45\" print(diff(s1, s2)) # This code is contributed by ApurvaRaj",
"e": 26963,
"s": 26101,
"text": null
},
{
"code": "<script>// JavaScript program to find difference between two// given times. // remove ':' and convert it into an integerfunction removeColon( s){ if (s.length == 4) s= s.replace(\":\", \"\"); if (s.length == 5) s= s.replace(\":\", \"\"); return parseInt(s);} // Main function which finds differencefunction diff( s1, s2){ // change string (eg. 2:21 --> 221, 00:23 --> 23) time1 = removeColon(s1); time2 = removeColon(s2); // difference between hours hourDiff = parseInt(time2 / 100 - time1 / 100 - 1); // difference between minutes minDiff = parseInt(time2 % 100 + (60 - time1 % 100)); if (minDiff >= 60) { hourDiff++; minDiff = minDiff - 60; } // convert answer again in string with ':' res = (hourDiff).toString() + ':' + (minDiff).toString(); return res;} // Driver program to test above functions s1 = \"14:00\"; s2 = \"16:45\"; console.log(diff(s1, s2)); // This code is contributed by ukasp.</script>",
"e": 27974,
"s": 26963,
"text": null
},
{
"code": null,
"e": 27984,
"s": 27974,
"text": "Output: "
},
{
"code": null,
"e": 27989,
"s": 27984,
"text": "2:45"
},
{
"code": null,
"e": 28413,
"s": 27989,
"text": "This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28423,
"s": 28413,
"text": "ApurvaRaj"
},
{
"code": null,
"e": 28429,
"s": 28423,
"text": "ukasp"
},
{
"code": null,
"e": 28447,
"s": 28429,
"text": "date-time-program"
},
{
"code": null,
"e": 28460,
"s": 28447,
"text": "Mathematical"
},
{
"code": null,
"e": 28473,
"s": 28460,
"text": "Mathematical"
},
{
"code": null,
"e": 28571,
"s": 28473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28580,
"s": 28571,
"text": "Comments"
},
{
"code": null,
"e": 28593,
"s": 28580,
"text": "Old Comments"
},
{
"code": null,
"e": 28617,
"s": 28593,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 28659,
"s": 28617,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 28673,
"s": 28659,
"text": "Prime Numbers"
},
{
"code": null,
"e": 28716,
"s": 28673,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28738,
"s": 28716,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 28779,
"s": 28738,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 28824,
"s": 28779,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 28873,
"s": 28824,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28900,
"s": 28873,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Relational Operators in C | The following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20 then −
Try the following example to understand all the relational operators available in C −
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b ) {
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}
if ( a > b ) {
printf("Line 3 - a is greater than b\n" );
} else {
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2222,
"s": 2084,
"text": "The following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20 then −"
},
{
"code": null,
"e": 2308,
"s": 2222,
"text": "Try the following example to understand all the relational operators available in C −"
},
{
"code": null,
"e": 3033,
"s": 2308,
"text": "#include <stdio.h>\n\nmain() {\n\n int a = 21;\n int b = 10;\n int c ;\n\n if( a == b ) {\n printf(\"Line 1 - a is equal to b\\n\" );\n } else {\n printf(\"Line 1 - a is not equal to b\\n\" );\n }\n\t\n if ( a < b ) {\n printf(\"Line 2 - a is less than b\\n\" );\n } else {\n printf(\"Line 2 - a is not less than b\\n\" );\n }\n\t\n if ( a > b ) {\n printf(\"Line 3 - a is greater than b\\n\" );\n } else {\n printf(\"Line 3 - a is not greater than b\\n\" );\n }\n \n /* Lets change value of a and b */\n a = 5;\n b = 20;\n\t\n if ( a <= b ) {\n printf(\"Line 4 - a is either less than or equal to b\\n\" );\n }\n\t\n if ( b >= a ) {\n printf(\"Line 5 - b is either greater than or equal to b\\n\" );\n }\n}"
},
{
"code": null,
"e": 3116,
"s": 3033,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 3300,
"s": 3116,
"text": "Line 1 - a is not equal to b\nLine 2 - a is not less than b\nLine 3 - a is greater than b\nLine 4 - a is either less than or equal to b\nLine 5 - b is either greater than or equal to b\n"
},
{
"code": null,
"e": 3307,
"s": 3300,
"text": " Print"
},
{
"code": null,
"e": 3318,
"s": 3307,
"text": " Add Notes"
}
] |
Conditional Independence — The Backbone of Bayesian Networks | by Aerin Kim | Towards Data Science | Sometimes the explanation in Wikipedia is not the easiest to understand.
Let’s say A is the height of a child and B is the number of words that the child knows. It seems when A is high, B is high too.
There is a single piece of information that will make A and B completely independent. What would that be?
The child’s age.
The height and the # of words known by the kid are NOT independent, but they are conditionally independent if you provide the kid’s age.
A: The height of a childB: The # of words that the child knowsC: The child's age
A better way to remember the expression:
Conditional independence is basically the concept of independence P(A ∩ B) = P(A) * P(B) applied to the conditional model.
But I’ve seen the definition of not only P(A ∩ B|C) but also P(A|B ∩ C)!
Why is P(A|B ∩ C) = P(A|C) when (Aᅭ B)|C?
Here goes the proof.
The gist of conditional independence: Knowing C makes A and B independent.
P(A,B|C) = P(A|C) * P(B|C)
Why does the conditional independence even matter?
Because it is a foundation for many statistical models that we use. (e.g., latent class models, factor analysis, graphical models, etc.)
A Bayesian network represents a joint distribution using a graph. Specifically, it is a directed acyclic graph in which each edge is a conditional dependency, and each node is a distinctive random variable. It has many other names: belief network, decision network, causal network, Bayes(ian) model or probabilistic directed acyclic graphical model, etc.
It looks like so:
In order for the Bayesian network to model a probability distribution, it relies on the important assumption: each variable is conditionally independent of its non-descendants, given its parents.
For instance, we can simplify P(Grass Wet|Sprinkler, Rain) into P(Grass Wet|Sprinkler) since Grass Wet is conditionally independent of its non-descendant, Rain, given Sprinkler.
Using this property, we can simplify the whole joint distribution into the formula below:
Conditional independence between variables can greatly reduce the number of parameters.
This reduces so much of the computation since we now only take into account its parent and disregard everything else.
Let’s take a look at the numbers.
Let’s say you have n binary variables (= n nodes).
The unconstrained joint distribution requires O(2^n) probabilities.
For a Bayesian Network, with a maximum of k parents for any node, we need only O(n * 2^k) probabilities. (This can be carried out in linear time for certain numbers of classes.)
n = 30 binary variables, k = 4 maximum parents for nodes• Unconstrained Joint Distribution: needs 2^30 (about 1 million) probabilities -> Intractable!• Bayesian Network: needs only 480 probabilities
We can have an efficient factored representation for a joint distribution using Conditional independence.
Let’s say I’d like to estimate the engagement (clap) rate of my blog. Let p be the proportion of readers who will clap for my articles. We’ll choose n readers randomly from the population. For i = 1, ..., n, let Xi = 1 if the reader claps or Xi = 0 if s/he doesn’t.
In a frequentist approach, we don’t assign the probability distribution to p. p would be simply ‘sum (Xi) / n’. And we would treat X1, ..., Xn as independent random variables.
On the other hand, in Bayesian inference, we assume p follows a distribution, not just a constant. In this model, the random variables X1, ..., Xn are NOT independent, but they are conditionally independent given the distribution of p.
“Correlation is not causation” means that just because two things correlate does not necessarily mean that one causes the other.
Here is a hilarious example of taxi accidents:
A study has shown a positive and significant correlation between the number of accidents and taxi drivers’ wearing coats. They found that coats might hinder the driver’s movements and cause accidents. A new law was ready to ban taxi drivers from wearing coats while driving.
Until another study pointed out that people wear coats when it rains... 😂
P(accidents, coats | rain) = P(accidents | rain) * P(coats | rain)
Correlations between two things can be caused by a third factor that affects both of them. This third factor is called a confounder. The confounder, which is rain, was responsible for the correlation between accident and wearing coats.
P(accidents | coats, rain) = P(accidents | coats)
Note that this does NOT mean accidents are independent of rain. What it means is: given drivers wearing coats, knowing rain doesn’t give any more information about accidents.
Marginal independence is just the same as plain independence,
Sometimes, two random variables might not be marginally independent. However, they can become independent after we observe some third variable.
Amount of speeding fine ᅭ Type of car | Speed
Lung cancer ᅭ Yellow teeth | Smoking
Child’s genes ᅭ Grandparents’ genes | Parents’ genes
Is the car’s starter motor working? ᅭ Is the car’s radio working?| Battery
Future ᅭ Past | Present (This is the Markov assumption!)
They are all in the same form as A ᅭ B | C. A and B look related if we don’t take C into account. However, once we include C in the picture, then the apparent relationship between A and B disappears. As you see, any causal relationship is potentially conditionally independent. We will never know for sure about the relationship between A & B until we test every possible C (confounding variable)! | [
{
"code": null,
"e": 244,
"s": 171,
"text": "Sometimes the explanation in Wikipedia is not the easiest to understand."
},
{
"code": null,
"e": 372,
"s": 244,
"text": "Let’s say A is the height of a child and B is the number of words that the child knows. It seems when A is high, B is high too."
},
{
"code": null,
"e": 478,
"s": 372,
"text": "There is a single piece of information that will make A and B completely independent. What would that be?"
},
{
"code": null,
"e": 495,
"s": 478,
"text": "The child’s age."
},
{
"code": null,
"e": 632,
"s": 495,
"text": "The height and the # of words known by the kid are NOT independent, but they are conditionally independent if you provide the kid’s age."
},
{
"code": null,
"e": 713,
"s": 632,
"text": "A: The height of a childB: The # of words that the child knowsC: The child's age"
},
{
"code": null,
"e": 754,
"s": 713,
"text": "A better way to remember the expression:"
},
{
"code": null,
"e": 877,
"s": 754,
"text": "Conditional independence is basically the concept of independence P(A ∩ B) = P(A) * P(B) applied to the conditional model."
},
{
"code": null,
"e": 950,
"s": 877,
"text": "But I’ve seen the definition of not only P(A ∩ B|C) but also P(A|B ∩ C)!"
},
{
"code": null,
"e": 992,
"s": 950,
"text": "Why is P(A|B ∩ C) = P(A|C) when (Aᅭ B)|C?"
},
{
"code": null,
"e": 1013,
"s": 992,
"text": "Here goes the proof."
},
{
"code": null,
"e": 1088,
"s": 1013,
"text": "The gist of conditional independence: Knowing C makes A and B independent."
},
{
"code": null,
"e": 1115,
"s": 1088,
"text": "P(A,B|C) = P(A|C) * P(B|C)"
},
{
"code": null,
"e": 1166,
"s": 1115,
"text": "Why does the conditional independence even matter?"
},
{
"code": null,
"e": 1303,
"s": 1166,
"text": "Because it is a foundation for many statistical models that we use. (e.g., latent class models, factor analysis, graphical models, etc.)"
},
{
"code": null,
"e": 1658,
"s": 1303,
"text": "A Bayesian network represents a joint distribution using a graph. Specifically, it is a directed acyclic graph in which each edge is a conditional dependency, and each node is a distinctive random variable. It has many other names: belief network, decision network, causal network, Bayes(ian) model or probabilistic directed acyclic graphical model, etc."
},
{
"code": null,
"e": 1676,
"s": 1658,
"text": "It looks like so:"
},
{
"code": null,
"e": 1872,
"s": 1676,
"text": "In order for the Bayesian network to model a probability distribution, it relies on the important assumption: each variable is conditionally independent of its non-descendants, given its parents."
},
{
"code": null,
"e": 2050,
"s": 1872,
"text": "For instance, we can simplify P(Grass Wet|Sprinkler, Rain) into P(Grass Wet|Sprinkler) since Grass Wet is conditionally independent of its non-descendant, Rain, given Sprinkler."
},
{
"code": null,
"e": 2140,
"s": 2050,
"text": "Using this property, we can simplify the whole joint distribution into the formula below:"
},
{
"code": null,
"e": 2228,
"s": 2140,
"text": "Conditional independence between variables can greatly reduce the number of parameters."
},
{
"code": null,
"e": 2346,
"s": 2228,
"text": "This reduces so much of the computation since we now only take into account its parent and disregard everything else."
},
{
"code": null,
"e": 2380,
"s": 2346,
"text": "Let’s take a look at the numbers."
},
{
"code": null,
"e": 2431,
"s": 2380,
"text": "Let’s say you have n binary variables (= n nodes)."
},
{
"code": null,
"e": 2499,
"s": 2431,
"text": "The unconstrained joint distribution requires O(2^n) probabilities."
},
{
"code": null,
"e": 2677,
"s": 2499,
"text": "For a Bayesian Network, with a maximum of k parents for any node, we need only O(n * 2^k) probabilities. (This can be carried out in linear time for certain numbers of classes.)"
},
{
"code": null,
"e": 2877,
"s": 2677,
"text": "n = 30 binary variables, k = 4 maximum parents for nodes• Unconstrained Joint Distribution: needs 2^30 (about 1 million) probabilities -> Intractable!• Bayesian Network: needs only 480 probabilities "
},
{
"code": null,
"e": 2983,
"s": 2877,
"text": "We can have an efficient factored representation for a joint distribution using Conditional independence."
},
{
"code": null,
"e": 3249,
"s": 2983,
"text": "Let’s say I’d like to estimate the engagement (clap) rate of my blog. Let p be the proportion of readers who will clap for my articles. We’ll choose n readers randomly from the population. For i = 1, ..., n, let Xi = 1 if the reader claps or Xi = 0 if s/he doesn’t."
},
{
"code": null,
"e": 3425,
"s": 3249,
"text": "In a frequentist approach, we don’t assign the probability distribution to p. p would be simply ‘sum (Xi) / n’. And we would treat X1, ..., Xn as independent random variables."
},
{
"code": null,
"e": 3661,
"s": 3425,
"text": "On the other hand, in Bayesian inference, we assume p follows a distribution, not just a constant. In this model, the random variables X1, ..., Xn are NOT independent, but they are conditionally independent given the distribution of p."
},
{
"code": null,
"e": 3790,
"s": 3661,
"text": "“Correlation is not causation” means that just because two things correlate does not necessarily mean that one causes the other."
},
{
"code": null,
"e": 3837,
"s": 3790,
"text": "Here is a hilarious example of taxi accidents:"
},
{
"code": null,
"e": 4112,
"s": 3837,
"text": "A study has shown a positive and significant correlation between the number of accidents and taxi drivers’ wearing coats. They found that coats might hinder the driver’s movements and cause accidents. A new law was ready to ban taxi drivers from wearing coats while driving."
},
{
"code": null,
"e": 4186,
"s": 4112,
"text": "Until another study pointed out that people wear coats when it rains... 😂"
},
{
"code": null,
"e": 4253,
"s": 4186,
"text": "P(accidents, coats | rain) = P(accidents | rain) * P(coats | rain)"
},
{
"code": null,
"e": 4489,
"s": 4253,
"text": "Correlations between two things can be caused by a third factor that affects both of them. This third factor is called a confounder. The confounder, which is rain, was responsible for the correlation between accident and wearing coats."
},
{
"code": null,
"e": 4539,
"s": 4489,
"text": "P(accidents | coats, rain) = P(accidents | coats)"
},
{
"code": null,
"e": 4714,
"s": 4539,
"text": "Note that this does NOT mean accidents are independent of rain. What it means is: given drivers wearing coats, knowing rain doesn’t give any more information about accidents."
},
{
"code": null,
"e": 4776,
"s": 4714,
"text": "Marginal independence is just the same as plain independence,"
},
{
"code": null,
"e": 4920,
"s": 4776,
"text": "Sometimes, two random variables might not be marginally independent. However, they can become independent after we observe some third variable."
},
{
"code": null,
"e": 4966,
"s": 4920,
"text": "Amount of speeding fine ᅭ Type of car | Speed"
},
{
"code": null,
"e": 5003,
"s": 4966,
"text": "Lung cancer ᅭ Yellow teeth | Smoking"
},
{
"code": null,
"e": 5056,
"s": 5003,
"text": "Child’s genes ᅭ Grandparents’ genes | Parents’ genes"
},
{
"code": null,
"e": 5131,
"s": 5056,
"text": "Is the car’s starter motor working? ᅭ Is the car’s radio working?| Battery"
},
{
"code": null,
"e": 5188,
"s": 5131,
"text": "Future ᅭ Past | Present (This is the Markov assumption!)"
}
] |
C# - Interview Questions | Dear readers, these C# Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C#. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
C# is a modern, general-purpose, object-oriented programming language developed by Microsoft. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures.
A Jagged array is an array of arrays.
You can initialize a jagged array as −
int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and scores[1] is an array of 4 integers.
There are three ways that parameters can be passed to a method −
Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
Output parameters − This method helps in returning more than one value.
Output parameters − This method helps in returning more than one value.
Yes! Using output parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function.
Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it. Reference parameter copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
using keyword is used to include a namespace in the program. A program generally has multiple using statements.
Value type variables can be assigned a value directly. They are derived from the class System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.
The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing.
When an object type is converted to a value type, it is called unboxing.
You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
Syntax for declaring a dynamic type is −
dynamic <variable_name> = value;
For example,
dynamic d = 20;
Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is −
type* identifier;
For example
char* cptr;
int* iptr;
is operator determines whether an object is of a certain type.
If( Ford is Car) // checks if Ford is an object of the Car class.
as operator casts without raising an exception if the cast fails.
Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;
Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details.
Encapsulation is implemented by using access specifiers.
An access specifier defines the scope and visibility of a class member.
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand.
By using the params keyword, a method parameter can be specified which takes a variable number of arguments or even no argument.
No! additional parameters are not permitted after the params keyword in a method declaration. Only one params keyword is allowed in a method declaration.
The Array class is the base class for all the arrays in C#. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays.
Using Array.sort(array) function. It sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.
First sort the array using Array.sort(array) then reverse the same using Array.reverse(array) method.
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
Classes and Structures have the following basic differences −
classes are reference types and structs are value types.
classes are reference types and structs are value types.
structures do not support inheritance.
structures do not support inheritance.
structures cannot have default constructor.
structures cannot have default constructor.
An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.
C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
Default access specifier for a class type is internal.
Default access for the members is private.
One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.
No! C# does not support multiple inheritance.
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
The syntax used in C# for creating derived classes is as follows −
<acess-specifier> class <base_class>
{
...
}
class <derived_class> : <base_class>
{
...
}
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
C# provides two techniques to implement static polymorphism. They are −
Function overloading
Function overloading
Operator overloading
Operator overloading
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding.
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
When a class is declared sealed, it cannot be inherited.
No! It can not be created as abstract classes cannot be declared sealed.
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list.
n interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.
The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).
You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
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": 2699,
"s": 2270,
"text": "Dear readers, these C# Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C#. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −"
},
{
"code": null,
"e": 3011,
"s": 2699,
"text": "C# is a modern, general-purpose, object-oriented programming language developed by Microsoft. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures."
},
{
"code": null,
"e": 3049,
"s": 3011,
"text": "A Jagged array is an array of arrays."
},
{
"code": null,
"e": 3088,
"s": 3049,
"text": "You can initialize a jagged array as −"
},
{
"code": null,
"e": 3163,
"s": 3088,
"text": "int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};"
},
{
"code": null,
"e": 3294,
"s": 3163,
"text": "Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and scores[1] is an array of 4 integers."
},
{
"code": null,
"e": 3359,
"s": 3294,
"text": "There are three ways that parameters can be passed to a method −"
},
{
"code": null,
"e": 3568,
"s": 3359,
"text": "Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument."
},
{
"code": null,
"e": 3777,
"s": 3568,
"text": "Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument."
},
{
"code": null,
"e": 3965,
"s": 3777,
"text": "Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument."
},
{
"code": null,
"e": 4153,
"s": 3965,
"text": "Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument."
},
{
"code": null,
"e": 4225,
"s": 4153,
"text": "Output parameters − This method helps in returning more than one value."
},
{
"code": null,
"e": 4297,
"s": 4225,
"text": "Output parameters − This method helps in returning more than one value."
},
{
"code": null,
"e": 4481,
"s": 4297,
"text": "Yes! Using output parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function."
},
{
"code": null,
"e": 4779,
"s": 4481,
"text": "Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it. Reference parameter copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument."
},
{
"code": null,
"e": 4978,
"s": 4779,
"text": "A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another."
},
{
"code": null,
"e": 5090,
"s": 4978,
"text": "using keyword is used to include a namespace in the program. A program generally has multiple using statements."
},
{
"code": null,
"e": 5195,
"s": 5090,
"text": "Value type variables can be assigned a value directly. They are derived from the class System.ValueType."
},
{
"code": null,
"e": 5427,
"s": 5195,
"text": "The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value."
},
{
"code": null,
"e": 5547,
"s": 5427,
"text": "The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables."
},
{
"code": null,
"e": 5879,
"s": 5547,
"text": "In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string."
},
{
"code": null,
"e": 6201,
"s": 5879,
"text": "The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion."
},
{
"code": null,
"e": 6269,
"s": 6201,
"text": "When a value type is converted to object type, it is called boxing."
},
{
"code": null,
"e": 6342,
"s": 6269,
"text": "When an object type is converted to a value type, it is called unboxing."
},
{
"code": null,
"e": 6477,
"s": 6342,
"text": "You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time."
},
{
"code": null,
"e": 6518,
"s": 6477,
"text": "Syntax for declaring a dynamic type is −"
},
{
"code": null,
"e": 6551,
"s": 6518,
"text": "dynamic <variable_name> = value;"
},
{
"code": null,
"e": 6564,
"s": 6551,
"text": "For example,"
},
{
"code": null,
"e": 6580,
"s": 6564,
"text": "dynamic d = 20;"
},
{
"code": null,
"e": 6772,
"s": 6580,
"text": "Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time."
},
{
"code": null,
"e": 6908,
"s": 6772,
"text": "Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++."
},
{
"code": null,
"e": 6949,
"s": 6908,
"text": "Syntax for declaring a pointer type is −"
},
{
"code": null,
"e": 6967,
"s": 6949,
"text": "type* identifier;"
},
{
"code": null,
"e": 6979,
"s": 6967,
"text": "For example"
},
{
"code": null,
"e": 7002,
"s": 6979,
"text": "char* cptr;\nint* iptr;"
},
{
"code": null,
"e": 7065,
"s": 7002,
"text": "is operator determines whether an object is of a certain type."
},
{
"code": null,
"e": 7131,
"s": 7065,
"text": "If( Ford is Car) // checks if Ford is an object of the Car class."
},
{
"code": null,
"e": 7197,
"s": 7131,
"text": "as operator casts without raising an exception if the cast fails."
},
{
"code": null,
"e": 7275,
"s": 7197,
"text": "Object obj = new StringReader(\"Hello\");\nStringReader r = obj as StringReader;"
},
{
"code": null,
"e": 7488,
"s": 7275,
"text": "Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details."
},
{
"code": null,
"e": 7545,
"s": 7488,
"text": "Encapsulation is implemented by using access specifiers."
},
{
"code": null,
"e": 7617,
"s": 7545,
"text": "An access specifier defines the scope and visibility of a class member."
},
{
"code": null,
"e": 7798,
"s": 7617,
"text": "Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class."
},
{
"code": null,
"e": 8050,
"s": 7798,
"text": "Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members."
},
{
"code": null,
"e": 8216,
"s": 8050,
"text": "Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance."
},
{
"code": null,
"e": 8527,
"s": 8216,
"text": "Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined."
},
{
"code": null,
"e": 8772,
"s": 8527,
"text": "The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance."
},
{
"code": null,
"e": 8897,
"s": 8772,
"text": "C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values."
},
{
"code": null,
"e": 9087,
"s": 8897,
"text": "For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable."
},
{
"code": null,
"e": 9315,
"s": 9087,
"text": "The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible."
},
{
"code": null,
"e": 9470,
"s": 9315,
"text": "If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand."
},
{
"code": null,
"e": 9599,
"s": 9470,
"text": "By using the params keyword, a method parameter can be specified which takes a variable number of arguments or even no argument."
},
{
"code": null,
"e": 9753,
"s": 9599,
"text": "No! additional parameters are not permitted after the params keyword in a method declaration. Only one params keyword is allowed in a method declaration."
},
{
"code": null,
"e": 9929,
"s": 9753,
"text": "The Array class is the base class for all the arrays in C#. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays."
},
{
"code": null,
"e": 10087,
"s": 9929,
"text": "Using Array.sort(array) function. It sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array."
},
{
"code": null,
"e": 10189,
"s": 10087,
"text": "First sort the array using Array.sort(array) then reverse the same using Array.reverse(array) method."
},
{
"code": null,
"e": 10368,
"s": 10189,
"text": "In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure."
},
{
"code": null,
"e": 10559,
"s": 10368,
"text": "Structures are used to represent a record. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program."
},
{
"code": null,
"e": 10621,
"s": 10559,
"text": "Classes and Structures have the following basic differences −"
},
{
"code": null,
"e": 10678,
"s": 10621,
"text": "classes are reference types and structs are value types."
},
{
"code": null,
"e": 10735,
"s": 10678,
"text": "classes are reference types and structs are value types."
},
{
"code": null,
"e": 10774,
"s": 10735,
"text": "structures do not support inheritance."
},
{
"code": null,
"e": 10813,
"s": 10774,
"text": "structures do not support inheritance."
},
{
"code": null,
"e": 10857,
"s": 10813,
"text": "structures cannot have default constructor."
},
{
"code": null,
"e": 10901,
"s": 10857,
"text": "structures cannot have default constructor."
},
{
"code": null,
"e": 11008,
"s": 10901,
"text": "An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword."
},
{
"code": null,
"e": 11144,
"s": 11008,
"text": "C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance."
},
{
"code": null,
"e": 11199,
"s": 11144,
"text": "Default access specifier for a class type is internal."
},
{
"code": null,
"e": 11242,
"s": 11199,
"text": "Default access for the members is private."
},
{
"code": null,
"e": 11553,
"s": 11242,
"text": "One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time."
},
{
"code": null,
"e": 11843,
"s": 11553,
"text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class."
},
{
"code": null,
"e": 11992,
"s": 11843,
"text": "The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on."
},
{
"code": null,
"e": 12038,
"s": 11992,
"text": "No! C# does not support multiple inheritance."
},
{
"code": null,
"e": 12260,
"s": 12038,
"text": "A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.\nThe syntax used in C# for creating derived classes is as follows −"
},
{
"code": null,
"e": 12356,
"s": 12260,
"text": "<acess-specifier> class <base_class>\n{\n ...\n}\nclass <derived_class> : <base_class>\n{\n ...\n}"
},
{
"code": null,
"e": 12516,
"s": 12356,
"text": "The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'."
},
{
"code": null,
"e": 12693,
"s": 12516,
"text": "Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time."
},
{
"code": null,
"e": 12765,
"s": 12693,
"text": "C# provides two techniques to implement static polymorphism. They are −"
},
{
"code": null,
"e": 12786,
"s": 12765,
"text": "Function overloading"
},
{
"code": null,
"e": 12807,
"s": 12786,
"text": "Function overloading"
},
{
"code": null,
"e": 12828,
"s": 12807,
"text": "Operator overloading"
},
{
"code": null,
"e": 12849,
"s": 12828,
"text": "Operator overloading"
},
{
"code": null,
"e": 12979,
"s": 12849,
"text": "The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding."
},
{
"code": null,
"e": 13259,
"s": 12979,
"text": "You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type."
},
{
"code": null,
"e": 13338,
"s": 13259,
"text": "Dynamic polymorphism is implemented by abstract classes and virtual functions."
},
{
"code": null,
"e": 13395,
"s": 13338,
"text": "When a class is declared sealed, it cannot be inherited."
},
{
"code": null,
"e": 13468,
"s": 13395,
"text": "No! It can not be created as abstract classes cannot be declared sealed."
},
{
"code": null,
"e": 13742,
"s": 13468,
"text": "When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime."
},
{
"code": null,
"e": 13888,
"s": 13742,
"text": "You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well."
},
{
"code": null,
"e": 14112,
"s": 13888,
"text": "Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list."
},
{
"code": null,
"e": 14364,
"s": 14112,
"text": "n interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract."
},
{
"code": null,
"e": 14670,
"s": 14364,
"text": "Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow."
},
{
"code": null,
"e": 14795,
"s": 14670,
"text": "The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts."
},
{
"code": null,
"e": 15008,
"s": 14795,
"text": "All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;)."
},
{
"code": null,
"e": 15279,
"s": 15008,
"text": "You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive."
},
{
"code": null,
"e": 15566,
"s": 15279,
"text": "C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes."
},
{
"code": null,
"e": 15738,
"s": 15566,
"text": "The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class."
},
{
"code": null,
"e": 15826,
"s": 15738,
"text": "The System.SystemException class is the base class for all predefined system exception."
},
{
"code": null,
"e": 16113,
"s": 15826,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 16443,
"s": 16113,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 16480,
"s": 16443,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 16493,
"s": 16480,
"text": " Raja Biswas"
},
{
"code": null,
"e": 16527,
"s": 16493,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 16545,
"s": 16527,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 16578,
"s": 16545,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16592,
"s": 16578,
"text": " Peter Jepson"
},
{
"code": null,
"e": 16629,
"s": 16592,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 16644,
"s": 16629,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 16679,
"s": 16644,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 16694,
"s": 16679,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 16729,
"s": 16694,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 16741,
"s": 16729,
"text": " Eric Frick"
},
{
"code": null,
"e": 16748,
"s": 16741,
"text": " Print"
},
{
"code": null,
"e": 16759,
"s": 16748,
"text": " Add Notes"
}
] |
C++ Program to Implement Expression Tree Algorithm | An expression tree is basically a binary which is used to represent expressions. In expression tree, internal nodes correspond to operators and each leaf node corresponds to an operand. Here is a C++ Program to implement the Expression Tree Algorithm which takes the postfix expression as an input and generates the corresponding expression tree traversed in inorder.
Begin
function construct_expression_tree():
Flag = 1 when it is operand.
Flag = -1 when it is operator.
S = suffix[0] means read the first operand from the expression.
For i = 0 and until s != 0
Check symbol is operand or operator.
Call function void inorder() for inorder traversal.
Print the results.
Increment i
End.
#include <iostream>
using namespace std;
struct n//node declaration {
char d;
n *l;
n *r;
};
char pf[50];
int top = -1;
n *a[50];
int r(char inputch)//check the symbol whether it is an operator or an operand. {
if (inputch == '+' || inputch == '-' || inputch == '*' || inputch == '/')
return (-1);
else if (inputch >= 'A' || inputch <= 'Z')
return (1);
else if (inputch >= 'a' || inputch <= 'z')
return (1);
else
return (-100);
}
void push(n *tree)//push elements in stack {
top++;
a[top] = tree;
}
n *pop() {
top--;
return (a[top + 1]);
}
void construct_expression_tree(char *suffix) {
char s;
n *newl, *p1, *p2;
int flag;
s = suffix[0];
for (int i = 1; s!= 0; i++) {
flag = r(s);
if (flag == 1) {
newl = new n;
newl->d = s;
newl->l = NULL;
newl->r = NULL;
push(newl);
} else {
p1 = pop();
p2 = pop();
newl = new n;
newl->d = s;
newl->l = p2;
newl->r = p1;
push(newl);
}
s = suffix[i];
}
}
void inOrder(n *tree)//perform inorder traversal {
if (tree != NULL) {
inOrder(tree->l);
cout << tree->d;
inOrder(tree->r);
}
}
int main(int argc, char **argv) {
cout << "Enter Postfix Expression : ";
cin >>pf;
construct_expression_tree(pf);
cout << "\nInfix Expression : ";
inOrder(a[0]);
return 0;
}
Enter Postfix Expression : 762*+6+
Infix Expression : 7+6*2+6 | [
{
"code": null,
"e": 1430,
"s": 1062,
"text": "An expression tree is basically a binary which is used to represent expressions. In expression tree, internal nodes correspond to operators and each leaf node corresponds to an operand. Here is a C++ Program to implement the Expression Tree Algorithm which takes the postfix expression as an input and generates the corresponding expression tree traversed in inorder."
},
{
"code": null,
"e": 1798,
"s": 1430,
"text": "Begin\n function construct_expression_tree():\n Flag = 1 when it is operand.\n Flag = -1 when it is operator.\n S = suffix[0] means read the first operand from the expression.\n For i = 0 and until s != 0\n Check symbol is operand or operator.\n Call function void inorder() for inorder traversal.\n Print the results.\n Increment i\nEnd."
},
{
"code": null,
"e": 3249,
"s": 1798,
"text": "#include <iostream>\nusing namespace std;\n\nstruct n//node declaration {\n char d;\n n *l;\n n *r;\n};\nchar pf[50];\nint top = -1;\nn *a[50];\nint r(char inputch)//check the symbol whether it is an operator or an operand. {\n if (inputch == '+' || inputch == '-' || inputch == '*' || inputch == '/')\n return (-1);\n else if (inputch >= 'A' || inputch <= 'Z')\n return (1);\n else if (inputch >= 'a' || inputch <= 'z')\n return (1);\n else\n return (-100);\n}\nvoid push(n *tree)//push elements in stack {\n top++;\n a[top] = tree;\n}\nn *pop() {\n top--;\n return (a[top + 1]);\n}\nvoid construct_expression_tree(char *suffix) {\n char s;\n n *newl, *p1, *p2;\n int flag;\n s = suffix[0];\n for (int i = 1; s!= 0; i++) {\n flag = r(s);\n if (flag == 1) {\n newl = new n;\n newl->d = s;\n newl->l = NULL;\n newl->r = NULL;\n push(newl);\n } else {\n p1 = pop();\n p2 = pop();\n newl = new n;\n newl->d = s;\n newl->l = p2;\n newl->r = p1;\n push(newl);\n }\n s = suffix[i];\n }\n}\n\nvoid inOrder(n *tree)//perform inorder traversal {\n if (tree != NULL) {\n inOrder(tree->l);\n cout << tree->d;\n inOrder(tree->r);\n }\n}\n\nint main(int argc, char **argv) {\n cout << \"Enter Postfix Expression : \";\n cin >>pf;\n construct_expression_tree(pf);\n cout << \"\\nInfix Expression : \";\n inOrder(a[0]);\n return 0;\n}"
},
{
"code": null,
"e": 3311,
"s": 3249,
"text": "Enter Postfix Expression : 762*+6+\nInfix Expression : 7+6*2+6"
}
] |
How to replace characters except last with the specified mask character in JavaScript ? - GeeksforGeeks | 17 Jun, 2021
In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript.
Example: Let’s take a number 12345678 and the masking character is * and the number of the last element that we have to skip is 2 In the below image shows that we skip the last two-element, and we mask another character with ‘*’.
Approach: We will make one function that can mask the character of the string except for the last element we will give our number as a string.
In this function we take three-argument, first one is a string which we want to mask, the second argument will specify mask character, and third is number of character that you want to skip
We use some inbuilt JavaScript function slice to slice our given string here we write slice(0,-n) where -n will skip the last n character of the string.
Then we use replace function to replace the character with a specified mask. Replace all characters we use regex /./g where ‘.’ will match any character and g is tens for globally.
Now we have to add the remaining character into the masking string, so we again use the slice function to get the remaining n character and add it into the masking string.
Example:
Javascript
<script> // Function for masking the character function MaskCharacter(str, mask, n = 1) { // Slice the string and replace with // mask then add remaining string return ('' + str).slice(0, -n) .replace(/./g, mask) + ('' + str).slice(-n); } // Number that we want to mask var num = 12345678; // Convert number into string var str = num.toString(); // Call function without giving value of n console.log(MaskCharacter(str, '#')); // Call function with value of n console.log(MaskCharacter(str, '#', 2));</script>
Output:
javascript-functions
JavaScript-Questions
JavaScript-RegExp
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26655,
"s": 26627,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 26814,
"s": 26655,
"text": "In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript."
},
{
"code": null,
"e": 27045,
"s": 26814,
"text": "Example: Let’s take a number 12345678 and the masking character is * and the number of the last element that we have to skip is 2 In the below image shows that we skip the last two-element, and we mask another character with ‘*’. "
},
{
"code": null,
"e": 27188,
"s": 27045,
"text": "Approach: We will make one function that can mask the character of the string except for the last element we will give our number as a string."
},
{
"code": null,
"e": 27378,
"s": 27188,
"text": "In this function we take three-argument, first one is a string which we want to mask, the second argument will specify mask character, and third is number of character that you want to skip"
},
{
"code": null,
"e": 27531,
"s": 27378,
"text": "We use some inbuilt JavaScript function slice to slice our given string here we write slice(0,-n) where -n will skip the last n character of the string."
},
{
"code": null,
"e": 27712,
"s": 27531,
"text": "Then we use replace function to replace the character with a specified mask. Replace all characters we use regex /./g where ‘.’ will match any character and g is tens for globally."
},
{
"code": null,
"e": 27884,
"s": 27712,
"text": "Now we have to add the remaining character into the masking string, so we again use the slice function to get the remaining n character and add it into the masking string."
},
{
"code": null,
"e": 27895,
"s": 27886,
"text": "Example:"
},
{
"code": null,
"e": 27906,
"s": 27895,
"text": "Javascript"
},
{
"code": "<script> // Function for masking the character function MaskCharacter(str, mask, n = 1) { // Slice the string and replace with // mask then add remaining string return ('' + str).slice(0, -n) .replace(/./g, mask) + ('' + str).slice(-n); } // Number that we want to mask var num = 12345678; // Convert number into string var str = num.toString(); // Call function without giving value of n console.log(MaskCharacter(str, '#')); // Call function with value of n console.log(MaskCharacter(str, '#', 2));</script>",
"e": 28504,
"s": 27906,
"text": null
},
{
"code": null,
"e": 28512,
"s": 28504,
"text": "Output:"
},
{
"code": null,
"e": 28533,
"s": 28512,
"text": "javascript-functions"
},
{
"code": null,
"e": 28554,
"s": 28533,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28572,
"s": 28554,
"text": "JavaScript-RegExp"
},
{
"code": null,
"e": 28590,
"s": 28572,
"text": "javascript-string"
},
{
"code": null,
"e": 28597,
"s": 28590,
"text": "Picked"
},
{
"code": null,
"e": 28608,
"s": 28597,
"text": "JavaScript"
},
{
"code": null,
"e": 28625,
"s": 28608,
"text": "Web Technologies"
},
{
"code": null,
"e": 28723,
"s": 28625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28763,
"s": 28723,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28824,
"s": 28763,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28865,
"s": 28824,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28887,
"s": 28865,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28941,
"s": 28887,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28981,
"s": 28941,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29014,
"s": 28981,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29057,
"s": 29014,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29107,
"s": 29057,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python MongoDB - create_index Query - GeeksforGeeks | 01 Jun, 2020
MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational.
Indexing helps in querying the documents efficiently. It stores the value of a specific field or set of fields which are ordered by the value of the field as specified in the index.
PyMongo contains a function create_index() to explicitly create index. By default _id is the only index present in the document. This function can accept either a key or a list of (key, direction) pairs.
Syntax:
create_index(keys, session=None, **kwargs)
Let’s look at some examples.
Example 1:
Sample Database:
Python3
from pymongo import MongoClient # creation of MongoClient client = MongoClient() # Connect with the portnumber and host client = MongoClient("mongodb://localhost:27017/") # Access database mydatabase = client['GFG'] # Access collection of the database mycollection = mydatabase['College'] # Before Creating indexindex_list = sorted(list(mycollection.index_information()))print("Before Creating index")print(index_list) # Creating indexmycollection.create_index("student_id", unique = True) # After Creating indexindex_list = sorted(list(mycollection.index_information()))print("\nAfter Creating index")print(index_list)
Output:
Before Creating index
['_id_']
After Creating index
['_id_', 'student_id_1']
Here, we create an index named student_id using create_index() method. This results in two indexes in the documents _id and student_id.Using index_information() method, we get all the indexes in the collection,
Here, we create an index named student_id using create_index() method. This results in two indexes in the documents _id and student_id.
Using index_information() method, we get all the indexes in the collection,
Example 2:
Python3
from pymongo import MongoClient # creation of MongoClient client = MongoClient() # Connect with the portnumber and host client = MongoClient("mongodb://localhost:27017/") # Access database mydatabase = client['GFG'] # Access collection of the database mycollection = mydatabase['College'] record = {'_id': 4, "student_id": 873, "name": "John", "section": "A"} mycollection.insert_one(record)
Output:
DuplicateKeyError Traceback (most recent call last)<ipython-input-62-264f0e13db93> in <module> 16 record = {‘_id’: 4, “student_id”: 873, “name”: “John”, “section”: “A”} 17—> 18 mycollection.insert_one(record)
DuplicateKeyError: E11000 duplicate key error collection: GFG.College index: student_id_1 dup key: { : 873 }
It raises the DuplicateKeyError as there is already a document that exists with the student_id 873 and we are trying to insert another document with the same student_id. This error occurs because we created an index on the field student_id and marked it as unique.
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace() | [
{
"code": null,
"e": 41528,
"s": 41500,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 41703,
"s": 41528,
"text": "MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational."
},
{
"code": null,
"e": 41886,
"s": 41703,
"text": "Indexing helps in querying the documents efficiently. It stores the value of a specific field or set of fields which are ordered by the value of the field as specified in the index. "
},
{
"code": null,
"e": 42090,
"s": 41886,
"text": "PyMongo contains a function create_index() to explicitly create index. By default _id is the only index present in the document. This function can accept either a key or a list of (key, direction) pairs."
},
{
"code": null,
"e": 42099,
"s": 42090,
"text": "Syntax: "
},
{
"code": null,
"e": 42142,
"s": 42099,
"text": "create_index(keys, session=None, **kwargs)"
},
{
"code": null,
"e": 42171,
"s": 42142,
"text": "Let’s look at some examples."
},
{
"code": null,
"e": 42182,
"s": 42171,
"text": "Example 1:"
},
{
"code": null,
"e": 42199,
"s": 42182,
"text": "Sample Database:"
},
{
"code": null,
"e": 42207,
"s": 42199,
"text": "Python3"
},
{
"code": "from pymongo import MongoClient # creation of MongoClient client = MongoClient() # Connect with the portnumber and host client = MongoClient(\"mongodb://localhost:27017/\") # Access database mydatabase = client['GFG'] # Access collection of the database mycollection = mydatabase['College'] # Before Creating indexindex_list = sorted(list(mycollection.index_information()))print(\"Before Creating index\")print(index_list) # Creating indexmycollection.create_index(\"student_id\", unique = True) # After Creating indexindex_list = sorted(list(mycollection.index_information()))print(\"\\nAfter Creating index\")print(index_list)",
"e": 42853,
"s": 42207,
"text": null
},
{
"code": null,
"e": 42861,
"s": 42853,
"text": "Output:"
},
{
"code": null,
"e": 42940,
"s": 42861,
"text": "Before Creating index\n['_id_']\n\nAfter Creating index\n['_id_', 'student_id_1']\n"
},
{
"code": null,
"e": 43151,
"s": 42940,
"text": "Here, we create an index named student_id using create_index() method. This results in two indexes in the documents _id and student_id.Using index_information() method, we get all the indexes in the collection,"
},
{
"code": null,
"e": 43287,
"s": 43151,
"text": "Here, we create an index named student_id using create_index() method. This results in two indexes in the documents _id and student_id."
},
{
"code": null,
"e": 43363,
"s": 43287,
"text": "Using index_information() method, we get all the indexes in the collection,"
},
{
"code": null,
"e": 43374,
"s": 43363,
"text": "Example 2:"
},
{
"code": null,
"e": 43382,
"s": 43374,
"text": "Python3"
},
{
"code": "from pymongo import MongoClient # creation of MongoClient client = MongoClient() # Connect with the portnumber and host client = MongoClient(\"mongodb://localhost:27017/\") # Access database mydatabase = client['GFG'] # Access collection of the database mycollection = mydatabase['College'] record = {'_id': 4, \"student_id\": 873, \"name\": \"John\", \"section\": \"A\"} mycollection.insert_one(record)",
"e": 43827,
"s": 43382,
"text": null
},
{
"code": null,
"e": 43835,
"s": 43827,
"text": "Output:"
},
{
"code": null,
"e": 44074,
"s": 43835,
"text": "DuplicateKeyError Traceback (most recent call last)<ipython-input-62-264f0e13db93> in <module> 16 record = {‘_id’: 4, “student_id”: 873, “name”: “John”, “section”: “A”} 17—> 18 mycollection.insert_one(record)"
},
{
"code": null,
"e": 44183,
"s": 44074,
"text": "DuplicateKeyError: E11000 duplicate key error collection: GFG.College index: student_id_1 dup key: { : 873 }"
},
{
"code": null,
"e": 44448,
"s": 44183,
"text": "It raises the DuplicateKeyError as there is already a document that exists with the student_id 873 and we are trying to insert another document with the same student_id. This error occurs because we created an index on the field student_id and marked it as unique."
},
{
"code": null,
"e": 44463,
"s": 44448,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 44470,
"s": 44463,
"text": "Python"
},
{
"code": null,
"e": 44568,
"s": 44470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44577,
"s": 44568,
"text": "Comments"
},
{
"code": null,
"e": 44590,
"s": 44577,
"text": "Old Comments"
},
{
"code": null,
"e": 44618,
"s": 44590,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44668,
"s": 44618,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44690,
"s": 44668,
"text": "Python map() function"
},
{
"code": null,
"e": 44734,
"s": 44690,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44769,
"s": 44734,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44791,
"s": 44769,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44821,
"s": 44791,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 44853,
"s": 44821,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44895,
"s": 44853,
"text": "Different ways to create Pandas Dataframe"
}
] |
Easy MLOps with PyCaret + MLflow. A beginner-friendly, step-by-step... | by Moez Ali | Towards Data Science | PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is known for its ease of use, simplicity, and ability to quickly and efficiently build and deploy end-to-end ML prototypes.
PyCaret is an alternate low-code library that can replace hundreds of code lines with few lines only. This makes the experiment cycle exponentially fast and efficient.
To learn more about PyCaret, you can check out their GitHub.
MLflow is an open-source platform to manage the ML lifecycle, including experimentation, reproducibility, deployment, and a central model registry. MLflow currently offers four components:
To learn more about MLflow, you can check out GitHub.
Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries.
PyCaret’s default installation is a slim version of pycaret that only installs hard dependencies listed here.
# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]
When you install the full version of pycaret, all the optional dependencies as listed here are also installed. MLflow is part of PyCaret’s dependency and hence does not need to be installed separately.
Before I talk about MLOps, let’s talk a little bit about the machine learning lifecycle at a high level:
Business Problem — This is the first step of the machine learning workflow. It may take from few days to a few weeks to complete, depending on the use case and complexity of the problem. It is at this stage, data scientists meet with subject matter experts (SME’s) to gain an understanding of the problem, interview key stakeholders, collect information, and set the overall expectations of the project.
Data Sourcing & ETL — Once the problem understanding is achieved, it then comes to using the information gained during interviews to source the data from the enterprise database.
Exploratory Data Analysis (EDA) — Modeling hasn’t started yet. EDA is where you analyze the raw data. Your goal is to explore the data and assess the quality of the data, missing values, feature distribution, correlation, etc.
Data Preparation — Now it’s time to prepare the data model training. This includes things like dividing data into a train and test set, imputing missing values, one-hot-encoding, target encoding, feature engineering, feature selection, etc.
Model Training & Selection — This is the step everyone is excited about. This involves training a bunch of models, tuning hyperparameters, model ensembling, evaluating performance metrics, model analysis such as AUC, Confusion Matrix, Residuals, etc, and finally selecting one best model to be deployed in production for business use.
Deployment & Monitoring — This is the final step which is mostly about MLOps. This includes things like packaging your final model, creating a docker image, writing the scoring script, and then making it all work together, and finally publish it as an API that can be used to obtain predictions on the new data coming through the pipeline.
The old way of doing all this is pretty cumbersome, long, and requires a lot of technical know-how and I possibly cannot cover it in one tutorial. However, in this tutorial, I will use PyCaret to demonstrate how easy it has become for a data scientist to do all this very efficiently. Before we get to the practical part, let’s talk a little bit more about MLOps.
MLOps is an engineering discipline that aims to combine machine learning development i.e. experimentation (model training, hyperparameter tuning, model ensembling, model selection, etc.), normally performed by Data Scientist with ML engineering and operations in order to standardize and streamline the continuous delivery of machine learning models in production.
If you are an absolute beginner, chances are you have no idea what I am talking about. No worries. Let me give you a simple, non-technical definition:
MLOps are bunch of technical engineering and operational tasks that allows your machine learning model to be used by other users and applications accross the organization. Basically, it’s a way through which your work i.e. machine learning models are published online, so other people can use them and satisfy some business objectives.
This is a very toned-down definition of MLOps. In reality, it involved a little more work and benefits than this but it’s a good start for you if you are new to all this.
Now let’s follow the same workflow as shown in the diagram above to do a practical demo, make sure you have pycaret installed.
For this tutorial, I will be using a very popular case study by Darden School of Business, published in Harvard Business. The case is regarding the story of two people who are going to be married in the future. The guy named Greg wanted to buy a ring to propose to a girl named Sarah. The problem is to find the ring Sarah will like, but after a suggestion from his close friend, Greg decides to buy a diamond stone instead so that Sarah can decide her choice. Greg then collects data of 6000 diamonds with their price and attributes like cut, color, shape, etc.
In this tutorial, I will be using a dataset from a very popular case study by the Darden School of Business, published in Harvard Business. The goal of this tutorial is to predict the diamond price based on its attributes like carat weight, cut, color, etc. You can download the dataset from PyCaret’s repository.
# load the dataset from pycaretfrom pycaret.datasets import get_datadata = get_data('diamond')
Let’s do some quick visualization to assess the relationship of independent features (weight, cut, color, clarity, etc.) with the target variable i.e. Price
# plot scatter carat_weight and Priceimport plotly.express as pxfig = px.scatter(x=data['Carat Weight'], y=data['Price'], facet_col = data['Cut'], opacity = 0.25, template = 'plotly_dark', trendline='ols', trendline_color_override = 'red', title = 'SARAH GETS A DIAMOND - A CASE STUDY')fig.show()
Let’s check the distribution of the target variable.
# plot histogramfig = px.histogram(data, x=["Price"], template = 'plotly_dark', title = 'Histogram of Price')fig.show()
Notice that distribution of Price is right-skewed, we can quickly check to see if log transformation can make Price approximately normal to give fighting chance to algorithms that assume normality.
import numpy as np# create a copy of datadata_copy = data.copy()# create a new feature Log_Pricedata_copy['Log_Price'] = np.log(data['Price'])# plot histogramfig = px.histogram(data_copy, x=["Log_Price"], title = 'Histgram of Log Price', template = 'plotly_dark')fig.show()
This confirms our hypothesis. The transformation will help us to get away with skewness and make the target variable approximately normal. Based on this, we will transform the Price variable before training our models.
Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment using PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link.
# initialize setupfrom pycaret.regression import *s = setup(data, target = 'Price', transform_target = True, log_experiment = True, experiment_name = 'diamond')
When you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. If all data types are correctly inferred, you can press enter to continue.
Notice that:
I have passed log_experiment = True and experiment_name = 'diamond' , this will tell PyCaret to automatically log all the metrics, hyperparameters, and model artifacts behind the scene as you progress through the modeling phase. This is possible due to integration with MLflow.
Also, I have used transform_target = True inside the setup. PyCaret will transform the Price variable behind the scene using box-cox transformation. It affects the distribution of data in a similar way as log transformation (technically different). If you would like to learn more about box-cox transformations, you can refer to this link.
Now that data is ready for modeling, let’s start the training process by using compare_models function. It will train all the algorithms available in the model library and evaluates multiple performance metrics using k-fold cross-validation.
# compare all modelsbest = compare_models()
# check the residuals of trained modelplot_model(best, plot = 'residuals_interactive')
# check feature importanceplot_model(best, plot = 'feature')
Let’s now finalize the best model i.e. train the best model on the entire dataset including the test set and then save the pipeline as a pickle file.
# finalize the modelfinal_best = finalize_model(best)# save model to disksave_model(final_best, 'diamond-pipeline')
save_model function will save the entire pipeline (including the model) as a pickle file on your local disk. By default, it will save the file in the same folder as your Notebook or script is in but you can pass the complete path as well if you would like:
save_model(final_best, 'c:/users/moez/models/diamond-pipeline'
Remember we passed log_experiment = True in the setup function along with experiment_name = 'diamond' . Let’s see the magic PyCaret has done with the help of MLflow behind the scene. To see the magic let’s initiate the MLflow server:
# within notebook (notice ! sign infront)!mlflow ui# on command line in the same foldermlflow ui
Now open your browser and type “localhost:5000”. It will open a UI like this:
Each entry in the table above represents a training run resulting in a trained Pipeline and a bunch of metadata such as DateTime of a run, performance metrics, model hyperparameters, tags, etc. Let’s click on one of the models:
Notice that you have an address path for the logged_model. This is the trained Pipeline with Catboost Regressor. You can read this Pipeline using the load_model function.
# load modelfrom pycaret.regression import load_modelpipeline = load_model('C:/Users/moezs/mlruns/1/b8c10d259b294b28a3e233a9d2c209c0/artifacts/model/model')# print pipelineprint(pipeline)
Let’s now use this Pipeline to generate predictions on the new data
# create a copy of data and drop Pricedata2 = data.copy()data2.drop('Price', axis=1, inplace=True)# generate predictionsfrom pycaret.regression import predict_modelpredictions = predict_model(pipeline, data=data2)predictions.head()
Woohoo! We now have inference from our trained Pipeline. Congrats, if this is your first one. Notice that all the transformations such as target transformation, one-hot-encoding, missing value imputation, etc. happened behind the scene automatically. You get a data frame with prediction in actual scale, and this is what you care about.
What I have shown today is one out of many ways you can serve trained Pipelines from PyCaret in production with the help of MLflow. In the next tutorial, I plan to show how you can using MLflow native serving functionalities to register your models, version them and serve as an API.
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.
Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE
DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret
Click on the links below to see the documentation and working examples.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining | [
{
"code": null,
"e": 456,
"s": 172,
"text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is known for its ease of use, simplicity, and ability to quickly and efficiently build and deploy end-to-end ML prototypes."
},
{
"code": null,
"e": 624,
"s": 456,
"text": "PyCaret is an alternate low-code library that can replace hundreds of code lines with few lines only. This makes the experiment cycle exponentially fast and efficient."
},
{
"code": null,
"e": 685,
"s": 624,
"text": "To learn more about PyCaret, you can check out their GitHub."
},
{
"code": null,
"e": 874,
"s": 685,
"text": "MLflow is an open-source platform to manage the ML lifecycle, including experimentation, reproducibility, deployment, and a central model registry. MLflow currently offers four components:"
},
{
"code": null,
"e": 928,
"s": 874,
"text": "To learn more about MLflow, you can check out GitHub."
},
{
"code": null,
"e": 1091,
"s": 928,
"text": "Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries."
},
{
"code": null,
"e": 1201,
"s": 1091,
"text": "PyCaret’s default installation is a slim version of pycaret that only installs hard dependencies listed here."
},
{
"code": null,
"e": 1304,
"s": 1201,
"text": "# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]"
},
{
"code": null,
"e": 1506,
"s": 1304,
"text": "When you install the full version of pycaret, all the optional dependencies as listed here are also installed. MLflow is part of PyCaret’s dependency and hence does not need to be installed separately."
},
{
"code": null,
"e": 1611,
"s": 1506,
"text": "Before I talk about MLOps, let’s talk a little bit about the machine learning lifecycle at a high level:"
},
{
"code": null,
"e": 2015,
"s": 1611,
"text": "Business Problem — This is the first step of the machine learning workflow. It may take from few days to a few weeks to complete, depending on the use case and complexity of the problem. It is at this stage, data scientists meet with subject matter experts (SME’s) to gain an understanding of the problem, interview key stakeholders, collect information, and set the overall expectations of the project."
},
{
"code": null,
"e": 2194,
"s": 2015,
"text": "Data Sourcing & ETL — Once the problem understanding is achieved, it then comes to using the information gained during interviews to source the data from the enterprise database."
},
{
"code": null,
"e": 2421,
"s": 2194,
"text": "Exploratory Data Analysis (EDA) — Modeling hasn’t started yet. EDA is where you analyze the raw data. Your goal is to explore the data and assess the quality of the data, missing values, feature distribution, correlation, etc."
},
{
"code": null,
"e": 2662,
"s": 2421,
"text": "Data Preparation — Now it’s time to prepare the data model training. This includes things like dividing data into a train and test set, imputing missing values, one-hot-encoding, target encoding, feature engineering, feature selection, etc."
},
{
"code": null,
"e": 2997,
"s": 2662,
"text": "Model Training & Selection — This is the step everyone is excited about. This involves training a bunch of models, tuning hyperparameters, model ensembling, evaluating performance metrics, model analysis such as AUC, Confusion Matrix, Residuals, etc, and finally selecting one best model to be deployed in production for business use."
},
{
"code": null,
"e": 3337,
"s": 2997,
"text": "Deployment & Monitoring — This is the final step which is mostly about MLOps. This includes things like packaging your final model, creating a docker image, writing the scoring script, and then making it all work together, and finally publish it as an API that can be used to obtain predictions on the new data coming through the pipeline."
},
{
"code": null,
"e": 3701,
"s": 3337,
"text": "The old way of doing all this is pretty cumbersome, long, and requires a lot of technical know-how and I possibly cannot cover it in one tutorial. However, in this tutorial, I will use PyCaret to demonstrate how easy it has become for a data scientist to do all this very efficiently. Before we get to the practical part, let’s talk a little bit more about MLOps."
},
{
"code": null,
"e": 4066,
"s": 3701,
"text": "MLOps is an engineering discipline that aims to combine machine learning development i.e. experimentation (model training, hyperparameter tuning, model ensembling, model selection, etc.), normally performed by Data Scientist with ML engineering and operations in order to standardize and streamline the continuous delivery of machine learning models in production."
},
{
"code": null,
"e": 4217,
"s": 4066,
"text": "If you are an absolute beginner, chances are you have no idea what I am talking about. No worries. Let me give you a simple, non-technical definition:"
},
{
"code": null,
"e": 4553,
"s": 4217,
"text": "MLOps are bunch of technical engineering and operational tasks that allows your machine learning model to be used by other users and applications accross the organization. Basically, it’s a way through which your work i.e. machine learning models are published online, so other people can use them and satisfy some business objectives."
},
{
"code": null,
"e": 4724,
"s": 4553,
"text": "This is a very toned-down definition of MLOps. In reality, it involved a little more work and benefits than this but it’s a good start for you if you are new to all this."
},
{
"code": null,
"e": 4851,
"s": 4724,
"text": "Now let’s follow the same workflow as shown in the diagram above to do a practical demo, make sure you have pycaret installed."
},
{
"code": null,
"e": 5414,
"s": 4851,
"text": "For this tutorial, I will be using a very popular case study by Darden School of Business, published in Harvard Business. The case is regarding the story of two people who are going to be married in the future. The guy named Greg wanted to buy a ring to propose to a girl named Sarah. The problem is to find the ring Sarah will like, but after a suggestion from his close friend, Greg decides to buy a diamond stone instead so that Sarah can decide her choice. Greg then collects data of 6000 diamonds with their price and attributes like cut, color, shape, etc."
},
{
"code": null,
"e": 5728,
"s": 5414,
"text": "In this tutorial, I will be using a dataset from a very popular case study by the Darden School of Business, published in Harvard Business. The goal of this tutorial is to predict the diamond price based on its attributes like carat weight, cut, color, etc. You can download the dataset from PyCaret’s repository."
},
{
"code": null,
"e": 5823,
"s": 5728,
"text": "# load the dataset from pycaretfrom pycaret.datasets import get_datadata = get_data('diamond')"
},
{
"code": null,
"e": 5980,
"s": 5823,
"text": "Let’s do some quick visualization to assess the relationship of independent features (weight, cut, color, clarity, etc.) with the target variable i.e. Price"
},
{
"code": null,
"e": 6310,
"s": 5980,
"text": "# plot scatter carat_weight and Priceimport plotly.express as pxfig = px.scatter(x=data['Carat Weight'], y=data['Price'], facet_col = data['Cut'], opacity = 0.25, template = 'plotly_dark', trendline='ols', trendline_color_override = 'red', title = 'SARAH GETS A DIAMOND - A CASE STUDY')fig.show()"
},
{
"code": null,
"e": 6363,
"s": 6310,
"text": "Let’s check the distribution of the target variable."
},
{
"code": null,
"e": 6483,
"s": 6363,
"text": "# plot histogramfig = px.histogram(data, x=[\"Price\"], template = 'plotly_dark', title = 'Histogram of Price')fig.show()"
},
{
"code": null,
"e": 6681,
"s": 6483,
"text": "Notice that distribution of Price is right-skewed, we can quickly check to see if log transformation can make Price approximately normal to give fighting chance to algorithms that assume normality."
},
{
"code": null,
"e": 6955,
"s": 6681,
"text": "import numpy as np# create a copy of datadata_copy = data.copy()# create a new feature Log_Pricedata_copy['Log_Price'] = np.log(data['Price'])# plot histogramfig = px.histogram(data_copy, x=[\"Log_Price\"], title = 'Histgram of Log Price', template = 'plotly_dark')fig.show()"
},
{
"code": null,
"e": 7174,
"s": 6955,
"text": "This confirms our hypothesis. The transformation will help us to get away with skewness and make the target variable approximately normal. Based on this, we will transform the Price variable before training our models."
},
{
"code": null,
"e": 7607,
"s": 7174,
"text": "Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment using PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link."
},
{
"code": null,
"e": 7768,
"s": 7607,
"text": "# initialize setupfrom pycaret.regression import *s = setup(data, target = 'Price', transform_target = True, log_experiment = True, experiment_name = 'diamond')"
},
{
"code": null,
"e": 7968,
"s": 7768,
"text": "When you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. If all data types are correctly inferred, you can press enter to continue."
},
{
"code": null,
"e": 7981,
"s": 7968,
"text": "Notice that:"
},
{
"code": null,
"e": 8259,
"s": 7981,
"text": "I have passed log_experiment = True and experiment_name = 'diamond' , this will tell PyCaret to automatically log all the metrics, hyperparameters, and model artifacts behind the scene as you progress through the modeling phase. This is possible due to integration with MLflow."
},
{
"code": null,
"e": 8599,
"s": 8259,
"text": "Also, I have used transform_target = True inside the setup. PyCaret will transform the Price variable behind the scene using box-cox transformation. It affects the distribution of data in a similar way as log transformation (technically different). If you would like to learn more about box-cox transformations, you can refer to this link."
},
{
"code": null,
"e": 8841,
"s": 8599,
"text": "Now that data is ready for modeling, let’s start the training process by using compare_models function. It will train all the algorithms available in the model library and evaluates multiple performance metrics using k-fold cross-validation."
},
{
"code": null,
"e": 8885,
"s": 8841,
"text": "# compare all modelsbest = compare_models()"
},
{
"code": null,
"e": 8972,
"s": 8885,
"text": "# check the residuals of trained modelplot_model(best, plot = 'residuals_interactive')"
},
{
"code": null,
"e": 9033,
"s": 8972,
"text": "# check feature importanceplot_model(best, plot = 'feature')"
},
{
"code": null,
"e": 9183,
"s": 9033,
"text": "Let’s now finalize the best model i.e. train the best model on the entire dataset including the test set and then save the pipeline as a pickle file."
},
{
"code": null,
"e": 9299,
"s": 9183,
"text": "# finalize the modelfinal_best = finalize_model(best)# save model to disksave_model(final_best, 'diamond-pipeline')"
},
{
"code": null,
"e": 9556,
"s": 9299,
"text": "save_model function will save the entire pipeline (including the model) as a pickle file on your local disk. By default, it will save the file in the same folder as your Notebook or script is in but you can pass the complete path as well if you would like:"
},
{
"code": null,
"e": 9619,
"s": 9556,
"text": "save_model(final_best, 'c:/users/moez/models/diamond-pipeline'"
},
{
"code": null,
"e": 9853,
"s": 9619,
"text": "Remember we passed log_experiment = True in the setup function along with experiment_name = 'diamond' . Let’s see the magic PyCaret has done with the help of MLflow behind the scene. To see the magic let’s initiate the MLflow server:"
},
{
"code": null,
"e": 9950,
"s": 9853,
"text": "# within notebook (notice ! sign infront)!mlflow ui# on command line in the same foldermlflow ui"
},
{
"code": null,
"e": 10028,
"s": 9950,
"text": "Now open your browser and type “localhost:5000”. It will open a UI like this:"
},
{
"code": null,
"e": 10256,
"s": 10028,
"text": "Each entry in the table above represents a training run resulting in a trained Pipeline and a bunch of metadata such as DateTime of a run, performance metrics, model hyperparameters, tags, etc. Let’s click on one of the models:"
},
{
"code": null,
"e": 10427,
"s": 10256,
"text": "Notice that you have an address path for the logged_model. This is the trained Pipeline with Catboost Regressor. You can read this Pipeline using the load_model function."
},
{
"code": null,
"e": 10615,
"s": 10427,
"text": "# load modelfrom pycaret.regression import load_modelpipeline = load_model('C:/Users/moezs/mlruns/1/b8c10d259b294b28a3e233a9d2c209c0/artifacts/model/model')# print pipelineprint(pipeline)"
},
{
"code": null,
"e": 10683,
"s": 10615,
"text": "Let’s now use this Pipeline to generate predictions on the new data"
},
{
"code": null,
"e": 10915,
"s": 10683,
"text": "# create a copy of data and drop Pricedata2 = data.copy()data2.drop('Price', axis=1, inplace=True)# generate predictionsfrom pycaret.regression import predict_modelpredictions = predict_model(pipeline, data=data2)predictions.head()"
},
{
"code": null,
"e": 11253,
"s": 10915,
"text": "Woohoo! We now have inference from our trained Pipeline. Congrats, if this is your first one. Notice that all the transformations such as target transformation, one-hot-encoding, missing value imputation, etc. happened behind the scene automatically. You get a data frame with prediction in actual scale, and this is what you care about."
},
{
"code": null,
"e": 11537,
"s": 11253,
"text": "What I have shown today is one out of many ways you can serve trained Pipelines from PyCaret in production with the help of MLflow. In the next tutorial, I plan to show how you can using MLflow native serving functionalities to register your models, version them and serve as an API."
},
{
"code": null,
"e": 11727,
"s": 11537,
"text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository."
},
{
"code": null,
"e": 11789,
"s": 11727,
"text": "To hear more about PyCaret follow us on LinkedIn and Youtube."
},
{
"code": null,
"e": 11837,
"s": 11789,
"text": "Join us on our slack channel. Invite link here."
},
{
"code": null,
"e": 12300,
"s": 11837,
"text": "Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE"
},
{
"code": null,
"e": 12391,
"s": 12300,
"text": "DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret"
},
{
"code": null,
"e": 12463,
"s": 12391,
"text": "Click on the links below to see the documentation and working examples."
}
] |
Create virtual environment using venv | Python - GeeksforGeeks | 29 Apr, 2022
A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them. This is one of the most important tools that most of the Python developers use.
Imagine a scenario where a web app is hosted on a cloud hosting service provider with a python development environment. The configuration for the web app comes with an option for installing the newest version of the Flask web framework. Suppose, the web app is created on the local system with an older version of the framework and as soon as it is uploaded on the site, there will be a version conflict as some of the modules used are depreciated in the latest versions of Flask.
The above scenario can be solved using virtual environment. Python development environments can be separated by making use of some virtual environment. A virtual environment, here, is an isolated Python installation that allows to manage dependencies and work on separate Python projects without affecting other projects. When a virtual environment is created, it creates a separate folder from the global Python or other virtual environments and copies Python into it along with a site-packages folder among a couple of others. For older versions of Python, virtual machines require installing a third-party tool called virtualenv. It’s been integrated into newer versions of Python3 under the module venv. To know more about virtualenv click here.
First, check whether the pip has the same version of the interpreter as that on the system and where the Python environment currently resides: To check where the python currently resides type the below command in the terminal.
where python
where pip
Output:
C:\Users\GeeksforGeeks\AppData\Local\Programs\Python\Python37\python.exe C:\Users\GeeksforGeeks\AppData\Local\Programs\Python\Python37\Scripts\pip.exe
To create a virtualenv use the following command:
python -m venv ./venv
After running this command, a directory named venv will be created. This is the directory which contains all the necessary executables to use the packages that a Python project would need. This is where Python packages will be installed. To list the files in the folder type below command in the terminal:
dir ./venv
Output: The pip command still points to the global environment. We need to explicitly activate the created virtual environment to configure the current shell session to use pip commands from the virtualenv folder and don’t end up installing packages in the global environment: To activate venv first change the directory to venv\Scripts.
cd venv\Scripts
After changing the directory type the below command.
$ Source venv_name\Scripts> activate
Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active. In the image below, venv named virtual environment is active.
(Note: try “./activate” instead of “activate” if using powershell terminal) The Python interpreter as well would run the version from the virtual environment and not the global one. We can verify where the Python environment currently resides by below command:
where python
Output:
E:\distribution\venv\Scripts\python.exe
C:\Users\GeeksforGeeks\AppData\Local\Programs\Python\Python37\python.exe
The virtual environment is an almost clean Python environment. Run pip list to see a list with packages installed: Output: Now you can install dependencies related to the project in this virtual environment. For example if you are using Django 1.9 for a project, you can install it like you install other packages.
(venv_name)$ pip install Django==1.9
Once you are done with the work, you can deactivate the virtual environment by the following command:
(venv_name)$ deactivate
Now you will be back to system’s default Python installation.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24594,
"s": 24566,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 24837,
"s": 24594,
"text": "A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them. This is one of the most important tools that most of the Python developers use."
},
{
"code": null,
"e": 25318,
"s": 24837,
"text": "Imagine a scenario where a web app is hosted on a cloud hosting service provider with a python development environment. The configuration for the web app comes with an option for installing the newest version of the Flask web framework. Suppose, the web app is created on the local system with an older version of the framework and as soon as it is uploaded on the site, there will be a version conflict as some of the modules used are depreciated in the latest versions of Flask."
},
{
"code": null,
"e": 26068,
"s": 25318,
"text": "The above scenario can be solved using virtual environment. Python development environments can be separated by making use of some virtual environment. A virtual environment, here, is an isolated Python installation that allows to manage dependencies and work on separate Python projects without affecting other projects. When a virtual environment is created, it creates a separate folder from the global Python or other virtual environments and copies Python into it along with a site-packages folder among a couple of others. For older versions of Python, virtual machines require installing a third-party tool called virtualenv. It’s been integrated into newer versions of Python3 under the module venv. To know more about virtualenv click here."
},
{
"code": null,
"e": 26295,
"s": 26068,
"text": "First, check whether the pip has the same version of the interpreter as that on the system and where the Python environment currently resides: To check where the python currently resides type the below command in the terminal."
},
{
"code": null,
"e": 26319,
"s": 26295,
"text": "where python\n\nwhere pip"
},
{
"code": null,
"e": 26327,
"s": 26319,
"text": "Output:"
},
{
"code": null,
"e": 26478,
"s": 26327,
"text": "C:\\Users\\GeeksforGeeks\\AppData\\Local\\Programs\\Python\\Python37\\python.exe C:\\Users\\GeeksforGeeks\\AppData\\Local\\Programs\\Python\\Python37\\Scripts\\pip.exe"
},
{
"code": null,
"e": 26528,
"s": 26478,
"text": "To create a virtualenv use the following command:"
},
{
"code": null,
"e": 26550,
"s": 26528,
"text": "python -m venv ./venv"
},
{
"code": null,
"e": 26856,
"s": 26550,
"text": "After running this command, a directory named venv will be created. This is the directory which contains all the necessary executables to use the packages that a Python project would need. This is where Python packages will be installed. To list the files in the folder type below command in the terminal:"
},
{
"code": null,
"e": 26868,
"s": 26856,
"text": " dir ./venv"
},
{
"code": null,
"e": 27207,
"s": 26868,
"text": "Output: The pip command still points to the global environment. We need to explicitly activate the created virtual environment to configure the current shell session to use pip commands from the virtualenv folder and don’t end up installing packages in the global environment: To activate venv first change the directory to venv\\Scripts."
},
{
"code": null,
"e": 27223,
"s": 27207,
"text": "cd venv\\Scripts"
},
{
"code": null,
"e": 27276,
"s": 27223,
"text": "After changing the directory type the below command."
},
{
"code": null,
"e": 27313,
"s": 27276,
"text": "$ Source venv_name\\Scripts> activate"
},
{
"code": null,
"e": 27567,
"s": 27313,
"text": "Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active. In the image below, venv named virtual environment is active. "
},
{
"code": null,
"e": 27829,
"s": 27567,
"text": "(Note: try “./activate” instead of “activate” if using powershell terminal) The Python interpreter as well would run the version from the virtual environment and not the global one. We can verify where the Python environment currently resides by below command:"
},
{
"code": null,
"e": 27842,
"s": 27829,
"text": "where python"
},
{
"code": null,
"e": 27850,
"s": 27842,
"text": "Output:"
},
{
"code": null,
"e": 27963,
"s": 27850,
"text": "E:\\distribution\\venv\\Scripts\\python.exe\nC:\\Users\\GeeksforGeeks\\AppData\\Local\\Programs\\Python\\Python37\\python.exe"
},
{
"code": null,
"e": 28279,
"s": 27963,
"text": "The virtual environment is an almost clean Python environment. Run pip list to see a list with packages installed: Output: Now you can install dependencies related to the project in this virtual environment. For example if you are using Django 1.9 for a project, you can install it like you install other packages."
},
{
"code": null,
"e": 28316,
"s": 28279,
"text": "(venv_name)$ pip install Django==1.9"
},
{
"code": null,
"e": 28418,
"s": 28316,
"text": "Once you are done with the work, you can deactivate the virtual environment by the following command:"
},
{
"code": null,
"e": 28442,
"s": 28418,
"text": "(venv_name)$ deactivate"
},
{
"code": null,
"e": 28506,
"s": 28444,
"text": "Now you will be back to system’s default Python installation."
},
{
"code": null,
"e": 28521,
"s": 28506,
"text": "python-utility"
},
{
"code": null,
"e": 28528,
"s": 28521,
"text": "Python"
},
{
"code": null,
"e": 28626,
"s": 28528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28644,
"s": 28626,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28679,
"s": 28644,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28701,
"s": 28679,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28733,
"s": 28701,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28763,
"s": 28733,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28805,
"s": 28763,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28831,
"s": 28805,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28874,
"s": 28831,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28911,
"s": 28874,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to generate large random numbers in Java? | For large random numbers, use BigInteger type in Java. At first, create a Random object −
Random randNum = new Random();
Now, declare a byte array and generate random bytes −
byte[] b = new byte[max];
randNum.nextBytes(b);
Now, generate a large random number with BigInteger type −
BigInteger bigInt = new BigInteger(b);
Live Demo
import java.math.BigInteger;
import java.util.Random;
public class Demo {
public static void main(String... a) {
int max = 10;
Random randNum = new Random();
byte[] b = new byte[max];
randNum.nextBytes(b);
// BigInteger type
BigInteger bigInt = new BigInteger(b);
System.out.println("Very large random number = "+bigInt);
}
}
Very large random number = 283258678185163472552410 | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "For large random numbers, use BigInteger type in Java. At first, create a Random object −"
},
{
"code": null,
"e": 1183,
"s": 1152,
"text": "Random randNum = new Random();"
},
{
"code": null,
"e": 1237,
"s": 1183,
"text": "Now, declare a byte array and generate random bytes −"
},
{
"code": null,
"e": 1285,
"s": 1237,
"text": "byte[] b = new byte[max];\nrandNum.nextBytes(b);"
},
{
"code": null,
"e": 1344,
"s": 1285,
"text": "Now, generate a large random number with BigInteger type −"
},
{
"code": null,
"e": 1383,
"s": 1344,
"text": "BigInteger bigInt = new BigInteger(b);"
},
{
"code": null,
"e": 1394,
"s": 1383,
"text": " Live Demo"
},
{
"code": null,
"e": 1768,
"s": 1394,
"text": "import java.math.BigInteger;\nimport java.util.Random;\npublic class Demo {\n public static void main(String... a) {\n int max = 10;\n Random randNum = new Random();\n byte[] b = new byte[max];\n randNum.nextBytes(b);\n // BigInteger type\n BigInteger bigInt = new BigInteger(b);\n System.out.println(\"Very large random number = \"+bigInt);\n }\n}"
},
{
"code": null,
"e": 1820,
"s": 1768,
"text": "Very large random number = 283258678185163472552410"
}
] |
Perl - Formats | Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you have to define a format first and then you can use that format to write formatted data.
Following is the syntax to define a Perl format −
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
Here FormatName represents the name of the format. The fieldline is the specific way, the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period.
Next fieldline can contain any text or fieldholders. The fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format −
@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include −
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
An example format would be −
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
In this example, $name would be written as left justify within 22 character spaces and after that age will be written in two spaces.
In order to invoke this format declaration, we would use the write keyword −
write EMPLOYEE;
The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function.
select(STDOUT);
We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~ or $FORMAT_NAME as follows −
$~ = "EMPLOYEE";
When we now do a write(), the data would be sent to STDOUT. Remember: if you are going to write your report in any other file handle instead of STDOUT then you can use select() function to select that file handle and rest of the logic will remain the same.
Let's take the following example. Here we have hard coded values just for showing the usage. In actual usage you will read values from a file or database to generate actual reports and you may need to write final report again into a file.
#!/usr/bin/perl
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
@n = ("Ali", "Raza", "Jaffer");
@a = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (@n) {
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
When executed, this will produce the following result −
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header and assign it to $^ or $FORMAT_TOP_NAME variable −
#!/usr/bin/perl
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
format EMPLOYEE_TOP =
===================================
Name Age
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;
@n = ("Ali", "Raza", "Jaffer");
@a = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (@n) {
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
Now your report will look like −
===================================
Name Age
===================================
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
What about if your report is taking more than one page? You have a solution for that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with header as follows −
format EMPLOYEE_TOP =
===================================
Name Age Page @<
$%
===================================
.
Now your output will look like as follows −
===================================
Name Age Page 1
===================================
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ), By default $= will be 60.
While $^ or $FORMAT_TOP_NAME contains the name of the current header format, there is no corresponding mechanism to automatically do the same thing for a footer. If you have a fixed-size footer, you can get footers by checking variable $- or $FORMAT_LINES_LEFT before each write() and print the footer yourself if necessary using another format defined as follows −
format EMPLOYEE_BOTTOM =
End of Page @<
$%
.
For a complete set of variables related to formating, please refer to the Perl Special Variables section.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2413,
"s": 2220,
"text": "Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you have to define a format first and then you can use that format to write formatted data."
},
{
"code": null,
"e": 2463,
"s": 2413,
"text": "Following is the syntax to define a Perl format −"
},
{
"code": null,
"e": 2560,
"s": 2463,
"text": "format FormatName =\nfieldline\nvalue_one, value_two, value_three\nfieldline\nvalue_one, value_two\n."
},
{
"code": null,
"e": 2797,
"s": 2560,
"text": "Here FormatName represents the name of the format. The fieldline is the specific way, the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period."
},
{
"code": null,
"e": 2961,
"s": 2797,
"text": "Next fieldline can contain any text or fieldholders. The fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format −"
},
{
"code": null,
"e": 2967,
"s": 2961,
"text": "@<<<<"
},
{
"code": null,
"e": 3143,
"s": 2967,
"text": "This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include −"
},
{
"code": null,
"e": 3236,
"s": 3143,
"text": "@>>>> right-justified\n@|||| centered\n@####.## numeric field holder\n@* multiline field holder"
},
{
"code": null,
"e": 3265,
"s": 3236,
"text": "An example format would be −"
},
{
"code": null,
"e": 3415,
"s": 3265,
"text": "format EMPLOYEE =\n===================================\n@<<<<<<<<<<<<<<<<<<<<<< @<< \n$name $age\n@#####.##\n$salary\n===================================\n."
},
{
"code": null,
"e": 3548,
"s": 3415,
"text": "In this example, $name would be written as left justify within 22 character spaces and after that age will be written in two spaces."
},
{
"code": null,
"e": 3625,
"s": 3548,
"text": "In order to invoke this format declaration, we would use the write keyword −"
},
{
"code": null,
"e": 3641,
"s": 3625,
"text": "write EMPLOYEE;"
},
{
"code": null,
"e": 3991,
"s": 3641,
"text": "The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function."
},
{
"code": null,
"e": 4007,
"s": 3991,
"text": "select(STDOUT);"
},
{
"code": null,
"e": 4155,
"s": 4007,
"text": "We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~ or $FORMAT_NAME as follows −"
},
{
"code": null,
"e": 4172,
"s": 4155,
"text": "$~ = \"EMPLOYEE\";"
},
{
"code": null,
"e": 4429,
"s": 4172,
"text": "When we now do a write(), the data would be sent to STDOUT. Remember: if you are going to write your report in any other file handle instead of STDOUT then you can use select() function to select that file handle and rest of the logic will remain the same."
},
{
"code": null,
"e": 4668,
"s": 4429,
"text": "Let's take the following example. Here we have hard coded values just for showing the usage. In actual usage you will read values from a file or database to generate actual reports and you may need to write final report again into a file."
},
{
"code": null,
"e": 5046,
"s": 4668,
"text": "#!/usr/bin/perl\n\nformat EMPLOYEE =\n===================================\n@<<<<<<<<<<<<<<<<<<<<<< @<< \n$name $age\n@#####.##\n$salary\n===================================\n.\n\nselect(STDOUT);\n$~ = EMPLOYEE;\n\n@n = (\"Ali\", \"Raza\", \"Jaffer\");\n@a = (20,30, 40);\n@s = (2000.00, 2500.00, 4000.000);\n\n$i = 0;\nforeach (@n) {\n $name = $_;\n $age = $a[$i];\n $salary = $s[$i++];\n write;\n}"
},
{
"code": null,
"e": 5102,
"s": 5046,
"text": "When executed, this will produce the following result −"
},
{
"code": null,
"e": 5430,
"s": 5102,
"text": "===================================\nAli 20\n 2000.00\n===================================\n===================================\nRaza 30\n 2500.00\n===================================\n===================================\nJaffer 40\n 4000.00\n===================================\n"
},
{
"code": null,
"e": 5711,
"s": 5430,
"text": "Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header and assign it to $^ or $FORMAT_TOP_NAME variable −"
},
{
"code": null,
"e": 6233,
"s": 5711,
"text": "#!/usr/bin/perl\n\nformat EMPLOYEE =\n===================================\n@<<<<<<<<<<<<<<<<<<<<<< @<< \n$name $age\n@#####.##\n$salary\n===================================\n.\n\nformat EMPLOYEE_TOP =\n===================================\nName Age\n===================================\n.\n\nselect(STDOUT);\n$~ = EMPLOYEE;\n$^ = EMPLOYEE_TOP;\n\n@n = (\"Ali\", \"Raza\", \"Jaffer\");\n@a = (20,30, 40);\n@s = (2000.00, 2500.00, 4000.000);\n\n$i = 0;\nforeach (@n) {\n $name = $_;\n $age = $a[$i];\n $salary = $s[$i++];\n write;\n}"
},
{
"code": null,
"e": 6266,
"s": 6233,
"text": "Now your report will look like −"
},
{
"code": null,
"e": 6694,
"s": 6266,
"text": "===================================\nName Age\n===================================\n===================================\nAli 20\n 2000.00\n===================================\n===================================\nRaza 30\n 2500.00\n===================================\n===================================\nJaffer 40\n 4000.00\n===================================\n"
},
{
"code": null,
"e": 6857,
"s": 6694,
"text": "What about if your report is taking more than one page? You have a solution for that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with header as follows −"
},
{
"code": null,
"e": 7057,
"s": 6857,
"text": "format EMPLOYEE_TOP =\n===================================\nName Age Page @<\n $%\n=================================== \n.\n"
},
{
"code": null,
"e": 7101,
"s": 7057,
"text": "Now your output will look like as follows −"
},
{
"code": null,
"e": 7536,
"s": 7101,
"text": "===================================\nName Age Page 1\n===================================\n===================================\nAli 20\n 2000.00\n===================================\n===================================\nRaza 30\n 2500.00\n===================================\n===================================\nJaffer 40\n 4000.00\n===================================\n"
},
{
"code": null,
"e": 7660,
"s": 7536,
"text": "You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ), By default $= will be 60."
},
{
"code": null,
"e": 8026,
"s": 7660,
"text": "While $^ or $FORMAT_TOP_NAME contains the name of the current header format, there is no corresponding mechanism to automatically do the same thing for a footer. If you have a fixed-size footer, you can get footers by checking variable $- or $FORMAT_LINES_LEFT before each write() and print the footer yourself if necessary using another format defined as follows −"
},
{
"code": null,
"e": 8083,
"s": 8026,
"text": "format EMPLOYEE_BOTTOM =\nEnd of Page @<\n $%\n."
},
{
"code": null,
"e": 8189,
"s": 8083,
"text": "For a complete set of variables related to formating, please refer to the Perl Special Variables section."
},
{
"code": null,
"e": 8224,
"s": 8189,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8238,
"s": 8224,
"text": " Devi Killada"
},
{
"code": null,
"e": 8273,
"s": 8238,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8293,
"s": 8273,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 8326,
"s": 8293,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8342,
"s": 8326,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 8375,
"s": 8342,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8392,
"s": 8375,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8425,
"s": 8392,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8448,
"s": 8425,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 8483,
"s": 8448,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 8506,
"s": 8483,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 8513,
"s": 8506,
"text": " Print"
},
{
"code": null,
"e": 8524,
"s": 8513,
"text": " Add Notes"
}
] |
Remove all duplicates from a given string in Python | To remove all duplicates from a string in python, we need to first split the string by spaces so that we have each word in an array. Then there are multiple ways to remove duplicates.
We can remove duplicates by first converting all words to lowercase, then sorting them and finally picking only the unique ones. For example,
sent = "Hi my name is John Doe John Doe is my name"
# Seperate out each word
words = sent.split(" ")
# Convert all words to lowercase
words = map(lambda x:x.lower(), words)
# Sort the words in order
words.sort()
unique = []
total_words = len(words)
i = 0
while i < (total_words - 1):
while i < total_words and words[i] == words[i + 1]:
i += 1
unique.append(words[i])
i += 1
print(unique)
This will give the output −
['doe', 'hi', 'john', 'is', 'my'] | [
{
"code": null,
"e": 1246,
"s": 1062,
"text": "To remove all duplicates from a string in python, we need to first split the string by spaces so that we have each word in an array. Then there are multiple ways to remove duplicates."
},
{
"code": null,
"e": 1388,
"s": 1246,
"text": "We can remove duplicates by first converting all words to lowercase, then sorting them and finally picking only the unique ones. For example,"
},
{
"code": null,
"e": 1781,
"s": 1388,
"text": "sent = \"Hi my name is John Doe John Doe is my name\"\n\n# Seperate out each word\nwords = sent.split(\" \")\n\n# Convert all words to lowercase\nwords = map(lambda x:x.lower(), words)\n\n# Sort the words in order\nwords.sort()\nunique = []\ntotal_words = len(words)\ni = 0\n\nwhile i < (total_words - 1):\nwhile i < total_words and words[i] == words[i + 1]:\ni += 1\nunique.append(words[i])\ni += 1\n\nprint(unique)"
},
{
"code": null,
"e": 1809,
"s": 1781,
"text": "This will give the output −"
},
{
"code": null,
"e": 1843,
"s": 1809,
"text": "['doe', 'hi', 'john', 'is', 'my']"
}
] |
is_enabled() element method - Selenium Python - GeeksforGeeks | 27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use is_enabled method in Selenium. is_enabled method is used to check if element is enabled or not. It returns a boolean value True or False.
element.is_enabled()
Example –
<a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a>
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_id("link")
Now one can check if this element is being displayed with
text_length = element.is_enabled()
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we gcheck visibility of courses tab in navigation bar at geeksforgeeks.Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # print valueprint(element.is_enabled())
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24540,
"s": 24512,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 25097,
"s": 24540,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies"
},
{
"code": null,
"e": 25275,
"s": 25097,
"text": "This article revolves around how to use is_enabled method in Selenium. is_enabled method is used to check if element is enabled or not. It returns a boolean value True or False."
},
{
"code": null,
"e": 25296,
"s": 25275,
"text": "element.is_enabled()"
},
{
"code": null,
"e": 25306,
"s": 25296,
"text": "Example –"
},
{
"code": "<a href=\"https://www.geeksforgeeks.org/\" id=\"link\" />Text Here</a>",
"e": 25373,
"s": 25306,
"text": null
},
{
"code": null,
"e": 25454,
"s": 25373,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": null,
"e": 25556,
"s": 25454,
"text": "element = driver.find_element_by_id(\"link\")\nelement = driver.find_element_by_xpath(\"//a[@id='link']\")"
},
{
"code": null,
"e": 25602,
"s": 25556,
"text": "Also, to find multiple elements, we can use –"
},
{
"code": null,
"e": 25648,
"s": 25602,
"text": "elements = driver.find_elements_by_id(\"link\")"
},
{
"code": null,
"e": 25706,
"s": 25648,
"text": "Now one can check if this element is being displayed with"
},
{
"code": null,
"e": 25741,
"s": 25706,
"text": "text_length = element.is_enabled()"
},
{
"code": null,
"e": 25915,
"s": 25741,
"text": "Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we gcheck visibility of courses tab in navigation bar at geeksforgeeks.Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # print valueprint(element.is_enabled())",
"e": 26199,
"s": 25915,
"text": null
},
{
"code": null,
"e": 26207,
"s": 26199,
"text": "Output-"
},
{
"code": null,
"e": 26225,
"s": 26207,
"text": "Terminal Output –"
},
{
"code": null,
"e": 26241,
"s": 26225,
"text": "Python-selenium"
},
{
"code": null,
"e": 26250,
"s": 26241,
"text": "selenium"
},
{
"code": null,
"e": 26257,
"s": 26250,
"text": "Python"
},
{
"code": null,
"e": 26355,
"s": 26257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26364,
"s": 26355,
"text": "Comments"
},
{
"code": null,
"e": 26377,
"s": 26364,
"text": "Old Comments"
},
{
"code": null,
"e": 26395,
"s": 26377,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26427,
"s": 26395,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26462,
"s": 26427,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26484,
"s": 26462,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26514,
"s": 26484,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26556,
"s": 26514,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26599,
"s": 26556,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26636,
"s": 26599,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26662,
"s": 26636,
"text": "Python String | replace()"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.