title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
CSS to put icon inside an input element in a form
To show how to put an icon inside an input element in a form using CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome. min.css" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } form { max-width: 450px; margin: auto; } .inputContainer i { position: absolute; } .inputContainer { width: 100%; margin-bottom: 10px; } .icon { padding: 15px; color: rgb(49, 0, 128); width: 70px; text-align: left; } .Field { width: 100%; padding: 10px; text-align: center; font-size: 20px; font-weight: 500; } </style> </head> <body> <h1 style="text-align: center;">Icons inside input element example</h1> <form> <div class="inputContainer"> <i class="fa fa-user icon"> </i> <input class="Field" type="text" placeholder="Username" /> </div> <div class="inputContainer"> <i class="fa fa-envelope icon"> </i> <input class="Field" type="text" placeholder="Email" /> </div> <div class="inputContainer"> <i class="fa fa-key icon"> </i> <input class="Field" type="password" placeholder="Password" /> </div> </form> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1159, "s": 1062, "text": "To show how to put an icon inside an input element in a form using CSS, the code is as follows −" }, { "code": null, "e": 1170, "s": 1159, "text": " Live Demo" }, { "code": null, "e": 2266, "s": 1170, "text": "<!DOCTYPE html>\n<html>\n<head>\n<link\nrel=\"stylesheet\"\nhref=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome.\nmin.css\"\n/>\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\nform {\n max-width: 450px;\n margin: auto;\n}\n.inputContainer i {\n position: absolute;\n}\n.inputContainer {\n width: 100%;\n margin-bottom: 10px;\n}\n.icon {\n padding: 15px;\n color: rgb(49, 0, 128);\n width: 70px;\n text-align: left;\n}\n.Field {\n width: 100%;\n padding: 10px;\n text-align: center;\n font-size: 20px;\n font-weight: 500;\n}\n</style>\n</head>\n<body>\n<h1 style=\"text-align: center;\">Icons inside input element example</h1>\n<form>\n<div class=\"inputContainer\">\n<i class=\"fa fa-user icon\"> </i>\n<input class=\"Field\" type=\"text\" placeholder=\"Username\" />\n</div>\n<div class=\"inputContainer\">\n<i class=\"fa fa-envelope icon\"> </i>\n<input class=\"Field\" type=\"text\" placeholder=\"Email\" />\n</div>\n<div class=\"inputContainer\">\n<i class=\"fa fa-key icon\"> </i>\n<input class=\"Field\" type=\"password\" placeholder=\"Password\" />\n</div>\n</form>\n</body>\n</html>" }, { "code": null, "e": 2317, "s": 2266, "text": "The above code will produce the following output −" } ]
BigDecimal scale() Method in Java - GeeksforGeeks
04 Dec, 2018 The java.math.BigDecimal.scale() is an inbuilt method in java that returns the scale of this BigDecimal. For zero or positive value, the scale is the number of digits to the right of the decimal point. For negative value, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. Syntax: public int scale() Parameters: This method does not accepts any parameter. Return value: This method returns the scale of this BigDecimal object. Below program illustrates the working of the above mentioned method: Program 1: // Java program to demonstrate the// scale() method import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal("456.0"); BigDecimal b2 = new BigDecimal("-1.456"); // Assign the result of scale on // BigDecimal Objects b1, b2 to int objects i1, i2 int i1 = b1.scale(); int i2 = b2.scale(); // Print the values of i1, i2; System.out.println("The scale of " + b1 + " is " + i1); System.out.println("The scale of " + b2 + " is " + i2); }} The scale of 456.0 is 1 The scale of -1.456 is 3 Program 2: // Java program to demonstrate the// scale() method import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal("745"); BigDecimal b2 = new BigDecimal("-174"); // Assign the result of scale on // BigDecimal Objects b1, b2 to int objects i1, i2 int i1 = b1.scale(); int i2 = b2.scale(); // Print the values of i1, i2; System.out.println("The scale of " + b1 + " is " + i1); System.out.println("The scale of " + b2 + " is " + i2); }} The scale of 745 is 0 The scale of -174 is 0 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#scale() Java-BigDecimal Java-Functions java-math Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Initialize an ArrayList in Java 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": 24474, "s": 24446, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24579, "s": 24474, "text": "The java.math.BigDecimal.scale() is an inbuilt method in java that returns the scale of this BigDecimal." }, { "code": null, "e": 24676, "s": 24579, "text": "For zero or positive value, the scale is the number of digits to the right of the decimal point." }, { "code": null, "e": 24793, "s": 24676, "text": "For negative value, the unscaled value of the number is multiplied by ten to the power of the negation of the scale." }, { "code": null, "e": 24801, "s": 24793, "text": "Syntax:" }, { "code": null, "e": 24821, "s": 24801, "text": "public int scale()\n" }, { "code": null, "e": 24877, "s": 24821, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 24948, "s": 24877, "text": "Return value: This method returns the scale of this BigDecimal object." }, { "code": null, "e": 25017, "s": 24948, "text": "Below program illustrates the working of the above mentioned method:" }, { "code": null, "e": 25028, "s": 25017, "text": "Program 1:" }, { "code": "// Java program to demonstrate the// scale() method import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(\"456.0\"); BigDecimal b2 = new BigDecimal(\"-1.456\"); // Assign the result of scale on // BigDecimal Objects b1, b2 to int objects i1, i2 int i1 = b1.scale(); int i2 = b2.scale(); // Print the values of i1, i2; System.out.println(\"The scale of \" + b1 + \" is \" + i1); System.out.println(\"The scale of \" + b2 + \" is \" + i2); }}", "e": 25597, "s": 25028, "text": null }, { "code": null, "e": 25647, "s": 25597, "text": "The scale of 456.0 is 1\nThe scale of -1.456 is 3\n" }, { "code": null, "e": 25658, "s": 25647, "text": "Program 2:" }, { "code": "// Java program to demonstrate the// scale() method import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(\"745\"); BigDecimal b2 = new BigDecimal(\"-174\"); // Assign the result of scale on // BigDecimal Objects b1, b2 to int objects i1, i2 int i1 = b1.scale(); int i2 = b2.scale(); // Print the values of i1, i2; System.out.println(\"The scale of \" + b1 + \" is \" + i1); System.out.println(\"The scale of \" + b2 + \" is \" + i2); }}", "e": 26223, "s": 25658, "text": null }, { "code": null, "e": 26269, "s": 26223, "text": "The scale of 745 is 0\nThe scale of -174 is 0\n" }, { "code": null, "e": 26356, "s": 26269, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#scale()" }, { "code": null, "e": 26372, "s": 26356, "text": "Java-BigDecimal" }, { "code": null, "e": 26387, "s": 26372, "text": "Java-Functions" }, { "code": null, "e": 26397, "s": 26387, "text": "java-math" }, { "code": null, "e": 26415, "s": 26397, "text": "Java-math-package" }, { "code": null, "e": 26420, "s": 26415, "text": "Java" }, { "code": null, "e": 26425, "s": 26420, "text": "Java" }, { "code": null, "e": 26523, "s": 26425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26553, "s": 26523, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26585, "s": 26553, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26604, "s": 26585, "text": "Interfaces in Java" }, { "code": null, "e": 26655, "s": 26604, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26673, "s": 26655, "text": "ArrayList in Java" }, { "code": null, "e": 26704, "s": 26673, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26736, "s": 26704, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26760, "s": 26736, "text": "Singleton Class in Java" }, { "code": null, "e": 26780, "s": 26760, "text": "Stack Class in Java" } ]
Python Program to Determine Whether a Given Number is Even or Odd Recursively
When it is required to check if a given number is an odd number or an even number using recursion, recursion can be used. The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem. Below is a demonstration for the same − Live Demo def check_odd_even(my_num): if (my_num < 2): return (my_num % 2 == 0) return (check_odd_even(my_num - 2)) my_number = int(input("Enter the number that needs to be checked:")) if(check_odd_even(my_number)==True): print("The number is even") else: print("The number is odd!") Enter the number that needs to be checked:48 The number is even A method named ‘check_odd_even’ is defined, that takes a number as parameter. If the number is less than 2, the remainder of the number when divided by 2 is computed, and checked wih 0. The function is called again, and this time, the parameter passed is the number decremented by 2. Outside the function, a number is taken as input by the user. The function is called, and checked to see if it is ‘True’, if yes, it is determined as an even number. Else it is considered an odd number. It is returned as output.
[ { "code": null, "e": 1184, "s": 1062, "text": "When it is required to check if a given number is an odd number or an even number using recursion, recursion can be used." }, { "code": null, "e": 1319, "s": 1184, "text": "The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem." }, { "code": null, "e": 1359, "s": 1319, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1370, "s": 1359, "text": " Live Demo" }, { "code": null, "e": 1662, "s": 1370, "text": "def check_odd_even(my_num):\n if (my_num < 2):\n return (my_num % 2 == 0)\n return (check_odd_even(my_num - 2))\nmy_number = int(input(\"Enter the number that needs to be checked:\"))\nif(check_odd_even(my_number)==True):\n print(\"The number is even\")\nelse:\n print(\"The number is odd!\")" }, { "code": null, "e": 1726, "s": 1662, "text": "Enter the number that needs to be checked:48\nThe number is even" }, { "code": null, "e": 1804, "s": 1726, "text": "A method named ‘check_odd_even’ is defined, that takes a number as parameter." }, { "code": null, "e": 1912, "s": 1804, "text": "If the number is less than 2, the remainder of the number when divided by 2 is computed, and checked wih 0." }, { "code": null, "e": 2010, "s": 1912, "text": "The function is called again, and this time, the parameter passed is the number decremented by 2." }, { "code": null, "e": 2072, "s": 2010, "text": "Outside the function, a number is taken as input by the user." }, { "code": null, "e": 2176, "s": 2072, "text": "The function is called, and checked to see if it is ‘True’, if yes, it is determined as an even number." }, { "code": null, "e": 2213, "s": 2176, "text": "Else it is considered an odd number." }, { "code": null, "e": 2239, "s": 2213, "text": "It is returned as output." } ]
How to get the notification configuration details of a S3 bucket using Boto3 and AWS Client?
Problem Statement − Use boto3 library in Python to get the notification configuration of a S3 bucket. For example, find the notification configuration details of Bucket_1 in S3. Step 1 − Import boto3 and botocore exceptions to handle exceptions. Step 2 − Use bucket_name as the parameter in the function. Step 3 − Create an AWS session using boto3 library. Step 4 − Create an AWS client for S3. Step 5 − Now use the function get_bucket_notification_configuration and pass the bucket name. Step 6 − It returns the dictionary containing the details about S3. If notification is not set, then it returns NONE Step 7 − Handle the generic exception if something went wrong while deleting the file. Use the following code to get the notification configuration details − import boto3 from botocore.exceptions import ClientError def get_bucket_notificationconfiguration_of_s3(bucket_name): session = boto3.session.Session() s3_client = session.client('s3') try: result = s3_client.get_bucket_notification_configuration(Bucket=bucket_name,) except ClientError as e: raise Exception( "boto3 client error in get_bucket_notificationconfiguration_of_s3: " + e.__str__()) except Exception as e: raise Exception( "Unexpected error in get_bucket_notificationconfiguration_of_s3 function: " + e.__str__()) return result print(get_bucket_notificationconfiguration_of_s3("Bucket_1")) { 'TopicConfigurations': [ { 'Id': 'string', 'TopicArn': 'string', 'Events': [ 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated: Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:C ompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|' s3:ObjectRemoved:DeleteMarkerCreated'|'s3:ObjectRestore:*'|'s3:ObjectRes tore:Post'|'s3:ObjectRestore:Completed'|'s3:Replication:*'|'s3:Replicati on:OperationFailedReplication'|'s3:Replication:OperationNotTracked'|'s3: Replication:OperationMissedThreshold'|'s3:Replication:OperationReplicate dAfterThreshold', ], 'Filter': { 'Key': { 'FilterRules': [ { 'Name': 'prefix'|'suffix', 'Value': 'string' }, ] } } }, ], 'QueueConfigurations': [ { 'Id': 'string', 'QueueArn': 'string', 'Events': [ 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated: Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:C ompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|' s3:ObjectRemoved:DeleteMarkerCreated'|'s3:ObjectRestore:*'|'s3:ObjectRes tore:Post'|'s3:ObjectRestore:Completed'|'s3:Replication:*'|'s3:Replicati on:OperationFailedReplication'|'s3:Replication:OperationNotTracked'|'s3: Replication:OperationMissedThreshold'|'s3:Replication:OperationReplicate dAfterThreshold', ], 'Filter': { 'Key': { 'FilterRules': [ { 'Name': 'prefix'|'suffix', 'Value': 'string' }, ] } } }, ], 'LambdaFunctionConfigurations': [ { 'Id': 'string', 'LambdaFunctionArn': 'string', 'Events': [ 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated: Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:C ompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|' s3:ObjectRemoved:DeleteMarkerCreated'|'s3:ObjectRestore:*'|'s3:ObjectRes tore:Post'|'s3:ObjectRestore:Completed'|'s3:Replication:*'|'s3:Replicati on:OperationFailedReplication'|'s3:Replication:OperationNotTracked'|'s3: Replication:OperationMissedThreshold'|'s3:Replication:OperationReplicate dAfterThreshold', ], 'Filter': { 'Key': { 'FilterRules': [ { 'Name': 'prefix'|'suffix', 'Value': 'string' }, ] } } }, ] } Note: This output depends on the settings/permissions of bucket. It omits the result if some settings/permissions are default or not set. Similarly, if notification is not set for bucket then it returns NONE.
[ { "code": null, "e": 1240, "s": 1062, "text": "Problem Statement − Use boto3 library in Python to get the notification configuration of a S3 bucket. For example, find the notification configuration details of Bucket_1 in S3." }, { "code": null, "e": 1308, "s": 1240, "text": "Step 1 − Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1367, "s": 1308, "text": "Step 2 − Use bucket_name as the parameter in the function." }, { "code": null, "e": 1419, "s": 1367, "text": "Step 3 − Create an AWS session using boto3 library." }, { "code": null, "e": 1457, "s": 1419, "text": "Step 4 − Create an AWS client for S3." }, { "code": null, "e": 1551, "s": 1457, "text": "Step 5 − Now use the function get_bucket_notification_configuration and pass the bucket name." }, { "code": null, "e": 1668, "s": 1551, "text": "Step 6 − It returns the dictionary containing the details about S3. If notification is not set, then it returns NONE" }, { "code": null, "e": 1755, "s": 1668, "text": "Step 7 − Handle the generic exception if something went wrong while deleting the file." }, { "code": null, "e": 1826, "s": 1755, "text": "Use the following code to get the notification configuration details −" }, { "code": null, "e": 2462, "s": 1826, "text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_bucket_notificationconfiguration_of_s3(bucket_name):\n session = boto3.session.Session()\n s3_client = session.client('s3')\n try:\n result = s3_client.get_bucket_notification_configuration(Bucket=bucket_name,)\n except ClientError as e:\n raise Exception( \"boto3 client error in get_bucket_notificationconfiguration_of_s3: \" + e.__str__())\n except Exception as e:\n raise Exception( \"Unexpected error in get_bucket_notificationconfiguration_of_s3 function: \" + e.__str__())\nreturn result\n\nprint(get_bucket_notificationconfiguration_of_s3(\"Bucket_1\"))" }, { "code": null, "e": 5685, "s": 2462, "text": "{\n 'TopicConfigurations': [\n {\n 'Id': 'string',\n 'TopicArn': 'string',\n 'Events': [\n\n 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated: Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:C\n ompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'\n s3:ObjectRemoved:DeleteMarkerCreated'|'s3:ObjectRestore:*'|'s3:ObjectRes\n tore:Post'|'s3:ObjectRestore:Completed'|'s3:Replication:*'|'s3:Replicati\n on:OperationFailedReplication'|'s3:Replication:OperationNotTracked'|'s3:\n Replication:OperationMissedThreshold'|'s3:Replication:OperationReplicate\n dAfterThreshold',\n ],\n 'Filter': {\n 'Key': {\n 'FilterRules': [\n {\n 'Name': 'prefix'|'suffix',\n 'Value': 'string'\n },\n ]\n }\n }\n },\n ],\n 'QueueConfigurations': [\n {\n 'Id': 'string',\n 'QueueArn': 'string',\n 'Events': [\n\n 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:\n Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:C\n ompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'\n s3:ObjectRemoved:DeleteMarkerCreated'|'s3:ObjectRestore:*'|'s3:ObjectRes\n tore:Post'|'s3:ObjectRestore:Completed'|'s3:Replication:*'|'s3:Replicati\n on:OperationFailedReplication'|'s3:Replication:OperationNotTracked'|'s3:\n Replication:OperationMissedThreshold'|'s3:Replication:OperationReplicate\n dAfterThreshold',\n ],\n 'Filter': {\n 'Key': {\n 'FilterRules': [\n {\n 'Name': 'prefix'|'suffix',\n 'Value': 'string'\n },\n ]\n }\n }\n },\n ],\n 'LambdaFunctionConfigurations': [\n {\n 'Id': 'string',\n 'LambdaFunctionArn': 'string',\n 'Events': [\n\n 's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:\n Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:C\n ompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'\n s3:ObjectRemoved:DeleteMarkerCreated'|'s3:ObjectRestore:*'|'s3:ObjectRes\n tore:Post'|'s3:ObjectRestore:Completed'|'s3:Replication:*'|'s3:Replicati\n on:OperationFailedReplication'|'s3:Replication:OperationNotTracked'|'s3:\n Replication:OperationMissedThreshold'|'s3:Replication:OperationReplicate\n dAfterThreshold',\n ],\n 'Filter': {\n 'Key': {\n 'FilterRules': [\n {\n 'Name': 'prefix'|'suffix',\n 'Value': 'string'\n },\n ]\n }\n }\n },\n ]\n}" }, { "code": null, "e": 5894, "s": 5685, "text": "Note: This output depends on the settings/permissions of bucket. It omits the result if some settings/permissions are default or not set. Similarly, if notification is not set for bucket then it returns NONE." } ]
What are mixed arrays in C#?
Mixed arrays are a combination of multi-dimension arrays and jagged arrays. Note − The mixed arrays type is obsolete now since .NET 4.0 update removed it. Let us see how you can declare a mixed array − var x = new object[] {89,45,"jacob",9.8} We can also set them as − var x = new object[] {87, 33,"tim",6.7, new List<string>() {"football","tennis","squash",“cricket”} } Since, mixed arrays are obslete now. For the same work, use the List collection. Here, we have set int and string in the list − Tuple<int, string> tuple = new Tuple<int, string>(60, "John"); The same example is displayed below: using System; using System.Collections.Generic; class Program { static void Main() { // Initializing collections Tuple tuple = new Tuple(99, "Jack"); if (t.Item1 == 99) { Console.WriteLine(tuple.Item1); } } }
[ { "code": null, "e": 1138, "s": 1062, "text": "Mixed arrays are a combination of multi-dimension arrays and jagged arrays." }, { "code": null, "e": 1217, "s": 1138, "text": "Note − The mixed arrays type is obsolete now since .NET 4.0 update removed it." }, { "code": null, "e": 1264, "s": 1217, "text": "Let us see how you can declare a mixed array −" }, { "code": null, "e": 1305, "s": 1264, "text": "var x = new object[] {89,45,\"jacob\",9.8}" }, { "code": null, "e": 1331, "s": 1305, "text": "We can also set them as −" }, { "code": null, "e": 1433, "s": 1331, "text": "var x = new object[] {87, 33,\"tim\",6.7, new List<string>() {\"football\",\"tennis\",\"squash\",“cricket”} }" }, { "code": null, "e": 1561, "s": 1433, "text": "Since, mixed arrays are obslete now. For the same work, use the List collection. Here, we have set int and string in the list −" }, { "code": null, "e": 1624, "s": 1561, "text": "Tuple<int, string> tuple = new Tuple<int, string>(60, \"John\");" }, { "code": null, "e": 1661, "s": 1624, "text": "The same example is displayed below:" }, { "code": null, "e": 1910, "s": 1661, "text": "using System;\nusing System.Collections.Generic;\n\nclass Program {\n static void Main() {\n // Initializing collections\n Tuple tuple = new Tuple(99, \"Jack\");\n if (t.Item1 == 99) {\n Console.WriteLine(tuple.Item1);\n }\n }\n}" } ]
Tryit Editor v3.7
HTML Input types Tryit: HTML input button
[ { "code": null, "e": 27, "s": 10, "text": "HTML Input types" } ]
Generating Random String Using PHP - GeeksforGeeks
31 Jul, 2021 Generate a random, unique, alpha-numeric string using PHP. Examples: EA070 aBX32gTf APPROACH 1: Brute ForceThe first approach is the simplest one to understand and thus brute force.It can be achieved as follows: Store all the possible letters into a string. Generate random index from 0 to string length-1. Print the letter at that index. Perform this step n times (where n is the length of string required). Program: <?php$n=10;function getName($n) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $n; $i++) { $index = rand(0, strlen($characters) - 1); $randomString .= $characters[$index]; } return $randomString;} echo getName($n);?> Output 1: 3HDrSOvRIs Output 2: lipHh APPROACH 2: Using Hashing FunctionsPHP has a few functions like md5(), sha1() and hash(), that can be used to hash a string based on certain algorithms like “sha1”, “sha256”, “md5” etc. All these function takes a string as an argument and output an Alpha-Numeric hashed string. To learn more about these functions click here. Once we understand how we utilize these functions, our task becomes pretty simple. Generate a random number using rand() function. Hash it using one of the above functions. Program 1: <?php$str=rand();$result = md5($str);echo $result;?> Output 1: 2e437510c181dd2ae100fc1661a445d4 Output 2: 256394010059991a71ea05e5d859d2be Program 2: <?php$str=rand();$result = sha1($str);echo $result;?> Output 1: 6eadd9b2c4389d9b109b3b869f66aab5d8f9420a Output 2: ca2d3c0993ab87e842d0a7a01f319aca6c587a87 Program 3: <?php$str = rand();$result = hash("sha256", $str);echo $result;?> Output 1: 2a41cbc8cc11f8c8d0eb54210fe524748b4def1c5b04fcf18c2d5972e24d11c2 Output 2: 291144c1cbba4de0bf199d37ee265ac95cc2e44e80fd2642b22a6e8ef2f42a39 NOTE: All the above functions are hashing functions, hence the length of the string generated will always depend on the algorithm used, but for an algorithm it will always remain constant. So if you want to generate string of a fixed length, you can either truncate the generated string or concatenate with another string, based on the requirement. Approach 3:Using uniqid() function.The uniqid( ) function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). By default, it returns a 13 character long unique string. Program: <?php $result = uniqid(); echo $result;?> Output1: 5bdd0b74e9a6c Output2: 5bdd0bbc200c4 NOTE: All the above approaches are built on rand() and uniqid() functions. These functions are not cryptographically secure random generators. So it is advised that if the degree of randomness affect the security of an application, these methods should be avoided. Approach 4: Using random_bytes() function. (Cryptographically Secure)The random_bytes() function generates cryptographically secure pseudo-random bytes, which can later be converted to hexadecimal format using bin2hex() function. Program: <?php $n = 20;$result = bin2hex(random_bytes($n));echo $result;?> Output1: 235aed08a01468f90fa726bd56319fb893967da8 Output2: 508b84494cdf31bec01566d12a924c75d4baed39 PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. PHP-string Hash PHP PHP Programs Randomized Web Technologies Hash PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Most frequent element in an array Counting frequencies of array elements Double Hashing Implementing our Own Hash Table with Separate Chaining in Java Check if two arrays are equal or not How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? PHP in_array() Function How to pop an alert message box using PHP ? How to convert array to string in PHP ?
[ { "code": null, "e": 24796, "s": 24768, "text": "\n31 Jul, 2021" }, { "code": null, "e": 24855, "s": 24796, "text": "Generate a random, unique, alpha-numeric string using PHP." }, { "code": null, "e": 24865, "s": 24855, "text": "Examples:" }, { "code": null, "e": 24881, "s": 24865, "text": "EA070\naBX32gTf\n" }, { "code": null, "e": 25009, "s": 24881, "text": "APPROACH 1: Brute ForceThe first approach is the simplest one to understand and thus brute force.It can be achieved as follows:" }, { "code": null, "e": 25055, "s": 25009, "text": "Store all the possible letters into a string." }, { "code": null, "e": 25104, "s": 25055, "text": "Generate random index from 0 to string length-1." }, { "code": null, "e": 25136, "s": 25104, "text": "Print the letter at that index." }, { "code": null, "e": 25206, "s": 25136, "text": "Perform this step n times (where n is the length of string required)." }, { "code": null, "e": 25215, "s": 25206, "text": "Program:" }, { "code": "<?php$n=10;function getName($n) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $n; $i++) { $index = rand(0, strlen($characters) - 1); $randomString .= $characters[$index]; } return $randomString;} echo getName($n);?>", "e": 25539, "s": 25215, "text": null }, { "code": null, "e": 25549, "s": 25539, "text": "Output 1:" }, { "code": null, "e": 25561, "s": 25549, "text": "3HDrSOvRIs\n" }, { "code": null, "e": 25571, "s": 25561, "text": "Output 2:" }, { "code": null, "e": 25578, "s": 25571, "text": "lipHh\n" }, { "code": null, "e": 25856, "s": 25578, "text": "APPROACH 2: Using Hashing FunctionsPHP has a few functions like md5(), sha1() and hash(), that can be used to hash a string based on certain algorithms like “sha1”, “sha256”, “md5” etc. All these function takes a string as an argument and output an Alpha-Numeric hashed string." }, { "code": null, "e": 25904, "s": 25856, "text": "To learn more about these functions click here." }, { "code": null, "e": 25987, "s": 25904, "text": "Once we understand how we utilize these functions, our task becomes pretty simple." }, { "code": null, "e": 26035, "s": 25987, "text": "Generate a random number using rand() function." }, { "code": null, "e": 26077, "s": 26035, "text": "Hash it using one of the above functions." }, { "code": null, "e": 26088, "s": 26077, "text": "Program 1:" }, { "code": "<?php$str=rand();$result = md5($str);echo $result;?>", "e": 26141, "s": 26088, "text": null }, { "code": null, "e": 26151, "s": 26141, "text": "Output 1:" }, { "code": null, "e": 26185, "s": 26151, "text": "2e437510c181dd2ae100fc1661a445d4\n" }, { "code": null, "e": 26195, "s": 26185, "text": "Output 2:" }, { "code": null, "e": 26229, "s": 26195, "text": "256394010059991a71ea05e5d859d2be\n" }, { "code": null, "e": 26240, "s": 26229, "text": "Program 2:" }, { "code": "<?php$str=rand();$result = sha1($str);echo $result;?>", "e": 26294, "s": 26240, "text": null }, { "code": null, "e": 26304, "s": 26294, "text": "Output 1:" }, { "code": null, "e": 26346, "s": 26304, "text": "6eadd9b2c4389d9b109b3b869f66aab5d8f9420a\n" }, { "code": null, "e": 26356, "s": 26346, "text": "Output 2:" }, { "code": null, "e": 26398, "s": 26356, "text": "ca2d3c0993ab87e842d0a7a01f319aca6c587a87\n" }, { "code": null, "e": 26409, "s": 26398, "text": "Program 3:" }, { "code": "<?php$str = rand();$result = hash(\"sha256\", $str);echo $result;?>", "e": 26475, "s": 26409, "text": null }, { "code": null, "e": 26485, "s": 26475, "text": "Output 1:" }, { "code": null, "e": 26551, "s": 26485, "text": "2a41cbc8cc11f8c8d0eb54210fe524748b4def1c5b04fcf18c2d5972e24d11c2\n" }, { "code": null, "e": 26561, "s": 26551, "text": "Output 2:" }, { "code": null, "e": 26627, "s": 26561, "text": "291144c1cbba4de0bf199d37ee265ac95cc2e44e80fd2642b22a6e8ef2f42a39\n" }, { "code": null, "e": 26976, "s": 26627, "text": "NOTE: All the above functions are hashing functions, hence the length of the string generated will always depend on the algorithm used, but for an algorithm it will always remain constant. So if you want to generate string of a fixed length, you can either truncate the generated string or concatenate with another string, based on the requirement." }, { "code": null, "e": 27216, "s": 26976, "text": "Approach 3:Using uniqid() function.The uniqid( ) function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). By default, it returns a 13 character long unique string." }, { "code": null, "e": 27225, "s": 27216, "text": "Program:" }, { "code": "<?php $result = uniqid(); echo $result;?> ", "e": 27269, "s": 27225, "text": null }, { "code": null, "e": 27278, "s": 27269, "text": "Output1:" }, { "code": null, "e": 27294, "s": 27278, "text": "5bdd0b74e9a6c \n" }, { "code": null, "e": 27303, "s": 27294, "text": "Output2:" }, { "code": null, "e": 27321, "s": 27303, "text": "5bdd0bbc200c4 \n" }, { "code": null, "e": 27586, "s": 27321, "text": "NOTE: All the above approaches are built on rand() and uniqid() functions. These functions are not cryptographically secure random generators. So it is advised that if the degree of randomness affect the security of an application, these methods should be avoided." }, { "code": null, "e": 27816, "s": 27586, "text": "Approach 4: Using random_bytes() function. (Cryptographically Secure)The random_bytes() function generates cryptographically secure pseudo-random bytes, which can later be converted to hexadecimal format using bin2hex() function." }, { "code": null, "e": 27825, "s": 27816, "text": "Program:" }, { "code": "<?php $n = 20;$result = bin2hex(random_bytes($n));echo $result;?> ", "e": 27892, "s": 27825, "text": null }, { "code": null, "e": 27901, "s": 27892, "text": "Output1:" }, { "code": null, "e": 27944, "s": 27901, "text": "235aed08a01468f90fa726bd56319fb893967da8 \n" }, { "code": null, "e": 27953, "s": 27944, "text": "Output2:" }, { "code": null, "e": 27996, "s": 27953, "text": "508b84494cdf31bec01566d12a924c75d4baed39 \n" }, { "code": null, "e": 28165, "s": 27996, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 28176, "s": 28165, "text": "PHP-string" }, { "code": null, "e": 28181, "s": 28176, "text": "Hash" }, { "code": null, "e": 28185, "s": 28181, "text": "PHP" }, { "code": null, "e": 28198, "s": 28185, "text": "PHP Programs" }, { "code": null, "e": 28209, "s": 28198, "text": "Randomized" }, { "code": null, "e": 28226, "s": 28209, "text": "Web Technologies" }, { "code": null, "e": 28231, "s": 28226, "text": "Hash" }, { "code": null, "e": 28235, "s": 28231, "text": "PHP" }, { "code": null, "e": 28333, "s": 28235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28342, "s": 28333, "text": "Comments" }, { "code": null, "e": 28355, "s": 28342, "text": "Old Comments" }, { "code": null, "e": 28389, "s": 28355, "text": "Most frequent element in an array" }, { "code": null, "e": 28428, "s": 28389, "text": "Counting frequencies of array elements" }, { "code": null, "e": 28443, "s": 28428, "text": "Double Hashing" }, { "code": null, "e": 28506, "s": 28443, "text": "Implementing our Own Hash Table with Separate Chaining in Java" }, { "code": null, "e": 28543, "s": 28506, "text": "Check if two arrays are equal or not" }, { "code": null, "e": 28593, "s": 28543, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28638, "s": 28593, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 28662, "s": 28638, "text": "PHP in_array() Function" }, { "code": null, "e": 28706, "s": 28662, "text": "How to pop an alert message box using PHP ?" } ]
Check if a given Graph is 2-edge connected or not - GeeksforGeeks
30 Jun, 2021 Given an undirected graph G, with V vertices and E edges, the task is to check whether the graph is 2-edge connected or not. A graph is said to be 2-edge connected if, on removing any edge of the graph, it still remains connected, i.e. it contains no Bridges. Examples: Input: V = 8, E = 10 Output: Yes Explanation: Given any vertex in the graph, we can reach any other vertex in the graph. Moreover, removing any edge from the graph does not affect its connectivity. So, the graph is said to be 2-edge connected. Input: V = 8, E = 9 Output: No Explanation: On removal of the edge between vertex 3 and vertex 4, the graph is not connected anymore. So, the graph is not 2-edge connected. Naive Approach: The naive approach is to check that on removing any edge X, if the remaining graph G – X is connected or not. If the graph remains connected on removing every edge one by one then it is a 2-edge connected graph. To implement the above idea, remove an edge and perform Depth First Search(DFS) or Breadth-First Search(BFS) from any vertex and check if all vertices are covered or not. Repeat this process for all E edges. If all vertices cannot be traversed for any edge, print No. Otherwise, print Yes. Time Complexity: O(E * ( V + E)) Auxiliary Space: O(1) Efficient Approach: Since the given graph is undirected, the problem can be solved only by counting the number of edges connected to the nodes. If for any of the nodes, the number of edges connected to it is 1 it means on removing this edge the node becomes disconnected and it can’t be reached from any other node. Therefore, the graph is not 2-edge connected. Below are the steps: Create an array noOfEdges[] of size V which will store the number of edges connected to a node.For every edge (u, v) increment the number of edges for nodes u and v.Now iterate over the array noOfEdges[] and check if any of the edges has only 1 edge connected to it. If yes then the graph is not 2-edge connected.Otherwise, the graph is 2-edge connected. Create an array noOfEdges[] of size V which will store the number of edges connected to a node. For every edge (u, v) increment the number of edges for nodes u and v. Now iterate over the array noOfEdges[] and check if any of the edges has only 1 edge connected to it. If yes then the graph is not 2-edge connected. Otherwise, the graph is 2-edge connected. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++14 program for the above approach #include <bits/stdc++.h>using namespace std; // Definition of a graphclass Graph { // No. of vertices int V; // To create adjacency list list<int>* adj; public: // Constructor Graph(int V); // Function to add an edge to graph void addEdge(int v, int w); // Function to check 2-edge // 2-edge connectivity void twoEdge(int v);}; // Initialize the graphGraph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Adding edges to adjacency listvoid Graph::addEdge(int v, int w){ adj[v - 1].push_back(w - 1); adj[w - 1].push_back(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid Graph::twoEdge(int v){ // To store number of edges for // each node int noOfEdges[v]; for (int i = 0; i < v; i++) { noOfEdges[i] = adj[i].size(); } bool flag = true; // Check the number of edges // connected to each node for (int i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) cout << "Yes"; else cout << "No";} // Driver Codeint main(){ // Number of nodes and edges int V = 8; int E = 10; // Given Edges int edges[E][2] = { { 1, 2 }, { 1, 8 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 3, 7 }, { 3, 4 }, { 7, 5 }, { 7, 6 }, { 7, 8 } }; // Initialize the graph Graph g(V); // Adding the edges to graph for (int i = 0; i < E; i++) { g.addEdge(edges[i][0], edges[i][1]); } // Function call g.twoEdge(V); return 0;} // Java program for the above approachimport java.util.*; class Graph{ // No. of vertices private int V; // Array of lists for Adjacency// List Representationprivate LinkedList<Integer> adj[]; // Constructor@SuppressWarnings("unchecked")Graph(int v){ V = v; adj = new LinkedList[v]; for(int i = 0; i < v; ++i) adj[i] = new LinkedList();} // Function to add an edge into the graphvoid addEdge(int v, int w){ adj[v - 1].add(w - 1); // Add w to v's list. adj[w - 1].add(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid twoEdge(int v){ // To store number of edges for // each node int[] noOfEdges = new int[v]; for(int i = 0; i < v; i++) { noOfEdges[i] = adj[i].size(); } boolean flag = true; // Check the number of edges // connected to each node for(int i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) System.out.print("Yes"); else System.out.print("No");} // Driver codepublic static void main (String[] args){ // Number of nodes and edges int V = 8; int E = 10; // Given Edges int edges[][] = { { 1, 2 }, { 1, 8 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 3, 7 }, { 3, 4 }, { 7, 5 }, { 7, 6 }, { 7, 8 } }; Graph g = new Graph(V); // Adding the edges to graph for(int i = 0; i < E; i++) { g.addEdge(edges[i][0], edges[i][1]); } // Function call g.twoEdge(V);}} // This code is contributed by offbeat # Python3 program for the above approach # Definition of a graphclass Graph: # No. of vertices V = 0 # Array of lists for Adjacency # List Representation adj = [[]] # Constructor def __init__(self, v): self.V = v self.adj = [[] for i in range(v)] # Function to add an edge into the graph def addEdge(self, v, w): self.adj[v - 1].append(w - 1) # Add w to v's list. self.adj[w - 1].append(v - 1) # Function to find if the graph is # 2 edge connected or not def twoEdge(self, v): # To store number of edges for # each node noOfEdges = [len(self.adj[i]) for i in range(v)] flag = True # Check the number of edges # connected to each node for i in range(v): if (noOfEdges[i] < 2): flag = False break # Print the result if (flag): print("Yes") else: print("No") # Driver codeif __name__=="__main__": # Number of nodes and edges V = 8 E = 10 # Given Edges edges = [ [ 1, 2 ], [ 1, 8 ], [ 1, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 7 ], [ 3, 4 ], [ 7, 5 ], [ 7, 6 ], [ 7, 8 ] ] g = Graph(V) # Adding the edges to graph for i in range(E): g.addEdge(edges[i][0], edges[i][1]) # Function call g.twoEdge(V) # This code is contributed by rutvik_56 // C# program for the above approachusing System;using System.Collections.Generic; class Graph{ // No. of vertices private int V; // Array of lists for Adjacency// List Representationprivate List<int> []adj; // ConstructorGraph(int v){ V = v; adj = new List<int>[v]; for(int i = 0; i < v; ++i) adj[i] = new List<int>();} // Function to add an edge into the graphvoid addEdge(int v, int w){ // Add w to v's list. adj[v - 1].Add(w - 1); adj[w - 1].Add(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid twoEdge(int v){ // To store number of edges for // each node int[] noOfEdges = new int[v]; for(int i = 0; i < v; i++) { noOfEdges[i] = adj[i].Count; } bool flag = true; // Check the number of edges // connected to each node for(int i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) Console.Write("Yes"); else Console.Write("No");} // Driver codepublic static void Main(String[] args){ // Number of nodes and edges int V = 8; int E = 10; // Given Edges int [,]edges = { { 1, 2 }, { 1, 8 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 3, 7 }, { 3, 4 }, { 7, 5 }, { 7, 6 }, { 7, 8 } }; Graph g = new Graph(V); // Adding the edges to graph for(int i = 0; i < E; i++) { g.addEdge(edges[i, 0], edges[i, 1]); } // Function call g.twoEdge(V);}} // This code is contributed by Amit Katiyar <script>// Javascript program for the above approach // No. of vertices var V; // Array of lists for Adjacency// List Representationvar adj; // Constructorfunction initialize(v){ V = v; adj = Array.from(Array(v), ()=>Array());} // Function to add an edge into the graphfunction addEdge(v, w){ // push w to v's list. adj[v - 1].push(w - 1); adj[w - 1].push(v - 1);} // Function to find if the graph is// 2 edge connected or notfunction twoEdge( v){ // To store number of edges for // each node var noOfEdges = Array(v) for(var i = 0; i < v; i++) { noOfEdges[i] = adj[i].length; } var flag = true; // Check the number of edges // connected to each node for(var i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) document.write("Yes"); else document.write("No");} // Driver code// Number of nodes and edgesvar V = 8;var E = 10; // Given Edgesvar edges = [ [ 1, 2 ], [ 1, 8 ], [ 1, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 7 ], [ 3, 4 ], [ 7, 5 ], [ 7, 6 ], [ 7, 8 ] ]; initialize(V); // Adding the edges to graphfor(var i = 0; i < E; i++){ addEdge(edges[i][0], edges[i][1]);} // Function calltwoEdge(V); </script> No Time Complexity: O(V + E) Auxiliary Space: O(V) offbeat amit143katiyar rutvik_56 rrrtnx BFS DFS Graph Traversals Graph Queue Recursion Searching Searching Recursion DFS Graph Queue BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree, Back, Edge and Cross Edges in DFS of Graph Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm) Comparison between Adjacency List and Adjacency Matrix representation of Graph Eulerian path and circuit for undirected graph Find if there is a path between two vertices in a directed graph Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Queue | Set 1 (Introduction and Array Implementation) Queue - Linked List Implementation
[ { "code": null, "e": 24701, "s": 24673, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24826, "s": 24701, "text": "Given an undirected graph G, with V vertices and E edges, the task is to check whether the graph is 2-edge connected or not." }, { "code": null, "e": 24963, "s": 24826, "text": "A graph is said to be 2-edge connected if, on removing any edge of the graph, it still remains connected, i.e. it contains no Bridges. " }, { "code": null, "e": 24974, "s": 24963, "text": "Examples: " }, { "code": null, "e": 24997, "s": 24974, "text": "Input: V = 8, E = 10 " }, { "code": null, "e": 25220, "s": 24997, "text": "Output: Yes Explanation: Given any vertex in the graph, we can reach any other vertex in the graph. Moreover, removing any edge from the graph does not affect its connectivity. So, the graph is said to be 2-edge connected." }, { "code": null, "e": 25242, "s": 25220, "text": "Input: V = 8, E = 9 " }, { "code": null, "e": 25396, "s": 25242, "text": "Output: No Explanation: On removal of the edge between vertex 3 and vertex 4, the graph is not connected anymore. So, the graph is not 2-edge connected. " }, { "code": null, "e": 25915, "s": 25396, "text": "Naive Approach: The naive approach is to check that on removing any edge X, if the remaining graph G – X is connected or not. If the graph remains connected on removing every edge one by one then it is a 2-edge connected graph. To implement the above idea, remove an edge and perform Depth First Search(DFS) or Breadth-First Search(BFS) from any vertex and check if all vertices are covered or not. Repeat this process for all E edges. If all vertices cannot be traversed for any edge, print No. Otherwise, print Yes. " }, { "code": null, "e": 25971, "s": 25915, "text": "Time Complexity: O(E * ( V + E)) Auxiliary Space: O(1) " }, { "code": null, "e": 26355, "s": 25971, "text": "Efficient Approach: Since the given graph is undirected, the problem can be solved only by counting the number of edges connected to the nodes. If for any of the nodes, the number of edges connected to it is 1 it means on removing this edge the node becomes disconnected and it can’t be reached from any other node. Therefore, the graph is not 2-edge connected. Below are the steps: " }, { "code": null, "e": 26710, "s": 26355, "text": "Create an array noOfEdges[] of size V which will store the number of edges connected to a node.For every edge (u, v) increment the number of edges for nodes u and v.Now iterate over the array noOfEdges[] and check if any of the edges has only 1 edge connected to it. If yes then the graph is not 2-edge connected.Otherwise, the graph is 2-edge connected." }, { "code": null, "e": 26806, "s": 26710, "text": "Create an array noOfEdges[] of size V which will store the number of edges connected to a node." }, { "code": null, "e": 26877, "s": 26806, "text": "For every edge (u, v) increment the number of edges for nodes u and v." }, { "code": null, "e": 27026, "s": 26877, "text": "Now iterate over the array noOfEdges[] and check if any of the edges has only 1 edge connected to it. If yes then the graph is not 2-edge connected." }, { "code": null, "e": 27068, "s": 27026, "text": "Otherwise, the graph is 2-edge connected." }, { "code": null, "e": 27120, "s": 27068, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27126, "s": 27120, "text": "C++14" }, { "code": null, "e": 27131, "s": 27126, "text": "Java" }, { "code": null, "e": 27139, "s": 27131, "text": "Python3" }, { "code": null, "e": 27142, "s": 27139, "text": "C#" }, { "code": null, "e": 27153, "s": 27142, "text": "Javascript" }, { "code": "// C++14 program for the above approach #include <bits/stdc++.h>using namespace std; // Definition of a graphclass Graph { // No. of vertices int V; // To create adjacency list list<int>* adj; public: // Constructor Graph(int V); // Function to add an edge to graph void addEdge(int v, int w); // Function to check 2-edge // 2-edge connectivity void twoEdge(int v);}; // Initialize the graphGraph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Adding edges to adjacency listvoid Graph::addEdge(int v, int w){ adj[v - 1].push_back(w - 1); adj[w - 1].push_back(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid Graph::twoEdge(int v){ // To store number of edges for // each node int noOfEdges[v]; for (int i = 0; i < v; i++) { noOfEdges[i] = adj[i].size(); } bool flag = true; // Check the number of edges // connected to each node for (int i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) cout << \"Yes\"; else cout << \"No\";} // Driver Codeint main(){ // Number of nodes and edges int V = 8; int E = 10; // Given Edges int edges[E][2] = { { 1, 2 }, { 1, 8 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 3, 7 }, { 3, 4 }, { 7, 5 }, { 7, 6 }, { 7, 8 } }; // Initialize the graph Graph g(V); // Adding the edges to graph for (int i = 0; i < E; i++) { g.addEdge(edges[i][0], edges[i][1]); } // Function call g.twoEdge(V); return 0;}", "e": 28822, "s": 27153, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class Graph{ // No. of vertices private int V; // Array of lists for Adjacency// List Representationprivate LinkedList<Integer> adj[]; // Constructor@SuppressWarnings(\"unchecked\")Graph(int v){ V = v; adj = new LinkedList[v]; for(int i = 0; i < v; ++i) adj[i] = new LinkedList();} // Function to add an edge into the graphvoid addEdge(int v, int w){ adj[v - 1].add(w - 1); // Add w to v's list. adj[w - 1].add(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid twoEdge(int v){ // To store number of edges for // each node int[] noOfEdges = new int[v]; for(int i = 0; i < v; i++) { noOfEdges[i] = adj[i].size(); } boolean flag = true; // Check the number of edges // connected to each node for(int i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) System.out.print(\"Yes\"); else System.out.print(\"No\");} // Driver codepublic static void main (String[] args){ // Number of nodes and edges int V = 8; int E = 10; // Given Edges int edges[][] = { { 1, 2 }, { 1, 8 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 3, 7 }, { 3, 4 }, { 7, 5 }, { 7, 6 }, { 7, 8 } }; Graph g = new Graph(V); // Adding the edges to graph for(int i = 0; i < E; i++) { g.addEdge(edges[i][0], edges[i][1]); } // Function call g.twoEdge(V);}} // This code is contributed by offbeat", "e": 30501, "s": 28822, "text": null }, { "code": "# Python3 program for the above approach # Definition of a graphclass Graph: # No. of vertices V = 0 # Array of lists for Adjacency # List Representation adj = [[]] # Constructor def __init__(self, v): self.V = v self.adj = [[] for i in range(v)] # Function to add an edge into the graph def addEdge(self, v, w): self.adj[v - 1].append(w - 1) # Add w to v's list. self.adj[w - 1].append(v - 1) # Function to find if the graph is # 2 edge connected or not def twoEdge(self, v): # To store number of edges for # each node noOfEdges = [len(self.adj[i]) for i in range(v)] flag = True # Check the number of edges # connected to each node for i in range(v): if (noOfEdges[i] < 2): flag = False break # Print the result if (flag): print(\"Yes\") else: print(\"No\") # Driver codeif __name__==\"__main__\": # Number of nodes and edges V = 8 E = 10 # Given Edges edges = [ [ 1, 2 ], [ 1, 8 ], [ 1, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 7 ], [ 3, 4 ], [ 7, 5 ], [ 7, 6 ], [ 7, 8 ] ] g = Graph(V) # Adding the edges to graph for i in range(E): g.addEdge(edges[i][0], edges[i][1]) # Function call g.twoEdge(V) # This code is contributed by rutvik_56", "e": 31993, "s": 30501, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class Graph{ // No. of vertices private int V; // Array of lists for Adjacency// List Representationprivate List<int> []adj; // ConstructorGraph(int v){ V = v; adj = new List<int>[v]; for(int i = 0; i < v; ++i) adj[i] = new List<int>();} // Function to add an edge into the graphvoid addEdge(int v, int w){ // Add w to v's list. adj[v - 1].Add(w - 1); adj[w - 1].Add(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid twoEdge(int v){ // To store number of edges for // each node int[] noOfEdges = new int[v]; for(int i = 0; i < v; i++) { noOfEdges[i] = adj[i].Count; } bool flag = true; // Check the number of edges // connected to each node for(int i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) Console.Write(\"Yes\"); else Console.Write(\"No\");} // Driver codepublic static void Main(String[] args){ // Number of nodes and edges int V = 8; int E = 10; // Given Edges int [,]edges = { { 1, 2 }, { 1, 8 }, { 1, 6 }, { 2, 3 }, { 2, 4 }, { 3, 7 }, { 3, 4 }, { 7, 5 }, { 7, 6 }, { 7, 8 } }; Graph g = new Graph(V); // Adding the edges to graph for(int i = 0; i < E; i++) { g.addEdge(edges[i, 0], edges[i, 1]); } // Function call g.twoEdge(V);}} // This code is contributed by Amit Katiyar", "e": 33652, "s": 31993, "text": null }, { "code": "<script>// Javascript program for the above approach // No. of vertices var V; // Array of lists for Adjacency// List Representationvar adj; // Constructorfunction initialize(v){ V = v; adj = Array.from(Array(v), ()=>Array());} // Function to add an edge into the graphfunction addEdge(v, w){ // push w to v's list. adj[v - 1].push(w - 1); adj[w - 1].push(v - 1);} // Function to find if the graph is// 2 edge connected or notfunction twoEdge( v){ // To store number of edges for // each node var noOfEdges = Array(v) for(var i = 0; i < v; i++) { noOfEdges[i] = adj[i].length; } var flag = true; // Check the number of edges // connected to each node for(var i = 0; i < v; i++) { if (noOfEdges[i] < 2) { flag = false; break; } } // Print the result if (flag) document.write(\"Yes\"); else document.write(\"No\");} // Driver code// Number of nodes and edgesvar V = 8;var E = 10; // Given Edgesvar edges = [ [ 1, 2 ], [ 1, 8 ], [ 1, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 7 ], [ 3, 4 ], [ 7, 5 ], [ 7, 6 ], [ 7, 8 ] ]; initialize(V); // Adding the edges to graphfor(var i = 0; i < E; i++){ addEdge(edges[i][0], edges[i][1]);} // Function calltwoEdge(V); </script>", "e": 35021, "s": 33652, "text": null }, { "code": null, "e": 35024, "s": 35021, "text": "No" }, { "code": null, "e": 35075, "s": 35026, "text": "Time Complexity: O(V + E) Auxiliary Space: O(V) " }, { "code": null, "e": 35083, "s": 35075, "text": "offbeat" }, { "code": null, "e": 35098, "s": 35083, "text": "amit143katiyar" }, { "code": null, "e": 35108, "s": 35098, "text": "rutvik_56" }, { "code": null, "e": 35115, "s": 35108, "text": "rrrtnx" }, { "code": null, "e": 35119, "s": 35115, "text": "BFS" }, { "code": null, "e": 35123, "s": 35119, "text": "DFS" }, { "code": null, "e": 35140, "s": 35123, "text": "Graph Traversals" }, { "code": null, "e": 35146, "s": 35140, "text": "Graph" }, { "code": null, "e": 35152, "s": 35146, "text": "Queue" }, { "code": null, "e": 35162, "s": 35152, "text": "Recursion" }, { "code": null, "e": 35172, "s": 35162, "text": "Searching" }, { "code": null, "e": 35182, "s": 35172, "text": "Searching" }, { "code": null, "e": 35192, "s": 35182, "text": "Recursion" }, { "code": null, "e": 35196, "s": 35192, "text": "DFS" }, { "code": null, "e": 35202, "s": 35196, "text": "Graph" }, { "code": null, "e": 35208, "s": 35202, "text": "Queue" }, { "code": null, "e": 35212, "s": 35208, "text": "BFS" }, { "code": null, "e": 35310, "s": 35212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35319, "s": 35310, "text": "Comments" }, { "code": null, "e": 35332, "s": 35319, "text": "Old Comments" }, { "code": null, "e": 35381, "s": 35332, "text": "Tree, Back, Edge and Cross Edges in DFS of Graph" }, { "code": null, "e": 35451, "s": 35381, "text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)" }, { "code": null, "e": 35530, "s": 35451, "text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph" }, { "code": null, "e": 35577, "s": 35530, "text": "Eulerian path and circuit for undirected graph" }, { "code": null, "e": 35642, "s": 35577, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 35676, "s": 35642, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 35700, "s": 35676, "text": "Queue Interface In Java" }, { "code": null, "e": 35716, "s": 35700, "text": "Queue in Python" }, { "code": null, "e": 35770, "s": 35716, "text": "Queue | Set 1 (Introduction and Array Implementation)" } ]
Representing text in natural language processing | by Michel Kana, Ph.D | Towards Data Science
This article looks at the representation of language for natural language processing (NLP). If you are one of those rare deep learning gurus, you will likely not learn anything new here. If not, dive with me into the fascinating world of turning words into some representations which algorithms can understand. We motivate why we would want to do this, which approaches exist, and how they work on simple examples. We will avoid as much mathematics as possible, and we will use an easy-going writing style in order to increase the chances that you actually read the article till the end. Although the article seems to be relatively long, it is fun to surf. The history of language genesis is repeated every time a baby starts to talk. Indeed, language began when humans started naming objects, actions and phenomena which appeared in real life. When looking at the belief in divine creation, something shared by billions of people, we can think of languages to be as old as human kind. Every time we write a short message, a tweet, a chat, an email, a post or even a web page, an article, a blog or a book, we turn thoughts into words or symbols. Thanks to language, humans are able to turn invisible ideas into visible things. Additionally, human thoughts become accessible to other humans, as well as to ..., guess what? Computers! If humans are able to reconstruct thoughts from words, could computers do this as well? With the recent hype called artificial intelligence, it is quite useful to have computers able to process, understand and generate human language. Google translation is a good example, a useful one. Google started by scanning a lot of books from university libraries and scrapping web pages, including their human translations, and learning from the patterns between source and target (statistical machine translation). Today, thanks to Google Translate and its sequence-to-sequence models (neural machine translation), we can access thoughts encoded in any language we do not speak yet. towardsdatascience.com Another example is text categorization. Humans are very good at grouping things into categories, for example ‘good’ and ‘bad’. They have been doing this for ages. At the same time, humans are also very good at generating and recording information in the form of text. According to Google, there are approximately 129,864,880 books in the entire world. We bet, you don’t want to categorize them by hand, even if you are given the biggest library in the world, with enough space and shelves. At the same time, you really need to have those books categorized at least by genre: comics, cooking, business, biographies, ...etc. That’s where you would embrace a computer program that would read the book’s content and detect its genre automatically. Let’s go away from books for a moment. There is an increasing number of people among us who don’t read books, and who prefer news feeds. They usually receive hundreds of messages, posts, or articles every day. Sorting out spamming messages and fake news from relevant updates e.g. about the industry and the market, has become a very relevant task for them, as long as it is done by a computer program. You are probably reading this article because a recommendation algorithm sorted it out of many other articles and sent it to your inbox or mobile app. That algorithm had to categorize thousands of articles and select this winner article, which you will likely enjoy, based on your reading history and your clever look, of course. Questions-answering bots is another hype nowadays. Imagine how much time you, as customer support specialist, would save if you could have a copy of yourself answering dozen of calls you are receiving every day from your clients asking the same questions over and over. We all heard about Amazon Alexa, Apple Siri or Google Assistant. These systems are automatically answering questions posed by humans in a natural language. Hopefully, the examples above motivate why having computers processing natural language is an engaging topic for you. If not, looking at further examples illustrating speech recognition, speech imitation and speech synthesis would amaze you for sure. Now, why all this talk about language and computers? You type text in your favorite word processor or email software everyday. So, why should it be difficult for a computer to understand your text? Language is ambiguous at all levels: lexical, phrasal, semantic. Language assumes that the listener is aware of the world, the context and the communication techniques. If you type “mouse info” to a search engine, are you looking for a pet or a tool? Representation of text is very important for performance of many real-world applications. Now, how do we turn language into something computer algorithms enjoy? At the base, processors in computers perform simple arithmetic such as adding and multiplying numbers. Is that the reason why computers love numbers? Who knows. Anyway, this problem is solved nicely for images. For example, the area marked with a circle on the picture below is represented by three matrices of numbers, one for each color channel: red, green and blue. Each number tells the level of red, green or blue at the pixel’s location. (0,0,0) is displayed as black, and a pixel whose color components are (255,255,255) is displayed as white. The process of transforming text into numeric stuff, similar to what we did with the image above, is usually performed by building a language model. These models typically assign probabilities, frequencies or some obscure numbers to words, sequences of words, group of words, section of documents or whole documents. The most common techniques are: 1-hot encoding, N-grams, Bag-of-words, vector semantics (tf-idf), distributional semantics (Word2vec, GloVe). Let’s see if we understand what all this means. We should be able to. We are not computers. You, at least. If a document has a vocabulary with 1000 words, we can represent the words with one-hot vectors. In other words, we have 1000-dimensional representation vectors, and we associate each unique word with an index in this vector. To represent a unique word, we set the component of the vector to be 1, and zero out all of the other components. This representation is rather arbitrary. It misses the relationships between words and does not convey information about their surrounding context. This method becomes extremely ineffective for large vocabularies. In the next few sections, we will have a look at a bit more exciting approaches. We start looking at the most basic N-gram model. Let’s consider our most favorite sentence from our childhood: “please eat your food”. A 2-gram (or bigram) is a two-word sequence of words like “please eat”, “eat your”, or ”your food”. A 3-gram (or trigram) will be a three-word sequence of words like “please eat your”, or “eat your food”. N-gram language models estimate the probability of the last word given the previous words. For example, given the sequence of words “please eat your”, the likelihood of the next word is higher for “food” than for “spoon”. In the later case, our mom will be less happy. The best way to compute such likelihood for any pair, triple, quadruplet, ... of words is to use a large body of text. The image below shows few probabilities obtained from a relatively small body of text containing questions and answers related to restaurants and food. “I” is frequently followed by the verb “want”, “eat” or “spend”. Google (again) actually provides a larger set of probabilities for 1-grams, 2-grams, 3-grams, 4-grams, and 5-grams in multiple languages. They calculated them on sources printed between 1500 and 2008! The Google Ngram Viewer allows you to download and use this large collection of n-grams for the purpose of spell checking, auto-completing, language identification, text generation and speech recognition. The longer the context on which we train a N-gram model, the more coherent the sentences we can generate. The image below shows 3 sentences randomly generated from 1-gram, 2-gram and 3-gram models computed from 40 million words of the Wall Street Journal. Even with very large corpus, in general, N-gram is an insufficient model of language because language has long-distance dependencies. For example, in the sentence “The computer which I had just put into the machine room on the fifth floor crashed.”, although the words “computer ” and “crashed ” are 15 positions away one from another, they are related. A 5-gram model will miss that link and our computer administrator might keep thinking that the computer on the fifth floor is running perfect. Now, what about dealing with the longest sentence in German literature which is claimed to have 1077 words! Who wants to train a N-gram language model that understands those usually long interlaced German sentences? Furthermore, the N-gram model is heavily dependent on the training corpus used to calculate the probabilities. One implication of this is that the probabilities often encode specific facts about a given training text, which may not necessarily apply to a new text. These reasons motivate us to look at further language models. When we are interested in categorizing text, classifying it based on sentiment, or verifying whether it is a spam, we often do not want to look at the sequential pattern of words, as suggested by N-gram language models. Rather we would represent the text as a bag of words, as if it were an unordered set of words, while ignoring their original position in the text, keeping only their frequency. Let’s illustrate the bag-of-words representation of text in a simple sentiment analysis example with the two classes positive (+) and negative (-). Below we have 5 sentences (also called documents) with their known categories, as well as 1 sentence with unknown category. The purpose is to classify the last sentence as either positive or negative. This task is solved by a so-called Naive Bayes Classifier, which uses the words frequencies in the bag-of-words of each class to compute the probability of each class c, as well as the conditional probability of each word given a class, as follows. In our example the negative class has the probability 3/5. The positive class will have the probability 2/5. A bit of algebra will show that the probability of the words “predictable”, “with”, “no” and “fun” given the negative class is higher than the sample probability given the positive class. Therefore the sentence “predictable with no fun” will be classified as negative based on the training data. Bag-of-words language models rely on the term frequency TF, defined as the number of times that a word occurs in a given text or document. Bag-of-words helps in sentiment analysis. It is great in detecting the language a text is written in. It is also used to determine authorship attribution such as gender and age. We can also use the term frequency information to engineer additional features such as the number of positive lexicon words (“great”, “nice”, “enjoyable”), or the number of first and second pronouns (“I”, “me”, “you”) and train more complex classifiers based on logistic regression and even neural networks. But, let’s not go that way of headache for now. Despite of the glory, N-gram and Bag-of-words models alone do not allow us to draw useful inferences that will help us solve meaning-related tasks like question-answering, summarization, and dialogue. This is why we will look at semantics in the next section. How should we represent the meaning of a word? The word “mouse” can be found in a lexical dictionary, but its plural form “mice” will be not be described separately. Similarly “sing” as the lemma for “sing”, “sang”, “sung” will be described, but its tense forms will not. How do we tell a computer that all these words mean the same thing? The word “plant” can have a different meaning depending on the context (e.g. “Tesla is building new plants”, “Climate change has a negative effect on plants”). Vector semantics is currently the best approach to building a computational model that successfully deals with the different aspects of word meaning including senses, hyponym, hypernym, antonym, synonym, homonym, similarity, relatedness, lexical fields, lexical frames, connotation. Our apologies for the linguistic jargon. Let’s build up the intuition around vector semantics by looking at the concept of context. In our example sentence “Tesla is building new plants”, if we count words in the context of the word “plant” in a many other sentences writen by humans, we’ll tend to see words like “build”, “machine”, “worker”, and even “Tesla”. The fact that these words and other similar context words also occur around the word “factory” can help us discover the similarity between “plant” and “factory”. In this case we will not tend to attach the meaning “vegetable” to the word “plant” in our sentence “Tesla is building new plants”. We will rather think that Tesla is building new factories. Therefore we can define a word by counting what other words occur in its environment, and we can represent the word by a vector, a list of numbers, a point in N-dimensional space. Such a representation is usually called embedding. Computer can use this cheating trick to understand the meaning of words in its context. In order to have a better grasp of vector semantics, let’s assume that we have a set of texts (documents) and we want to find documents which are similar to each other. This task is relevant in information retrieval, for example in search engines, where documents are web pages. As illustration, each column in the table below represents one of 4 documents with the following titles: “As You Like It”, “Twelfth Night”, “Julius Caesar”, and “Henry V”. Words which appear in the documents are represented as rows. These words build our vocabulary. The table tells us that the word “battle” occurs 7 times in the document “Julius Caesar”. This table is also called term-document matrix, where each row represents a word in the vocabulary and each column represents a document, a section, a paragraph, a tweet, a SMS, an email or whatever. Now we can represent each document by a document vector, e.g. [7 62 1 2] for “Julius Caecar”. We can even draw such vectors in a 2-dimensional vector space for any pair of words. Below we have an example of such a graph. We see a spatial visualization of the document vectors of the space built by the dimensions “fool” and “battle”. We can conclude that the documents “Henry V” and “Julius Caesar” have similar content, which is more related to “battle” than to “fool”. For information retrieval we’ll also represent a query by a document vector, also of length 4 telling how often the words “battle”, “good”, “fool” and “wit” appear in the query. The search results will be obtained by comparing the query vector with all four document vectors to find how similar they are. By looking at the rows of the term-document matrix, we can extract word vectors instead of column vectors. As we saw that similar documents tend to have similar words, similar words have similar vectors because they tend to occur in similar documents. If we now use words as columns of the term-document matrix, instead of documents, we obtain the so-called word-word matrix, term-term matrix, also called term-context matrix. Each cell describes the number of times the row (target) word and the column (context) word co-occur in some context in some training corpus. A simple case is when the context is a document, so the cell will tell how often two words appear in the same document. A more frequent case is to count how often the column word appears within a words-window around the row word. In the example below “data” appears 6 times in the context of “information” when a 7-words-window around “information” is considered. The matrix above suggests that “apricot” and “pineapple” are similar to each other because “pinch” and “sugar” tend to appear in their context. Similarity between two words v and w can be exactly computed using their corresponding word vectors by calculating the so-called cosine-similarity, defined as follows: In the example below, the similarity between “digital” and “information” equals the cosine-similarity between the word vectors [0 1 2] and [1 6 1]. By applying the formula above, we obtain 0.58, which is higher than the cosine-similarity 0.16 between “apricot” and “information”. Word vectors and cosine-similarity are a powerful tool in dealing with natural language contents. However, there are situations where they do not workout so well, as we will see in the next section. Vector semantic models use the raw frequency of the co-occurrence of two words. In natural language, raw frequency is very skewed and not very discriminative. As depicted in the histogram below, the word “the” is simply a frequent word and has roughly equivalent high frequencies in each of the documents or contexts. There are few ways of dealing with this problem. TF-IDF algorithm is by far the dominant way of weighting co-occurrence matrices in natural language processing, especially in information retrieval. The TF-IDF weight is computed as the product of the term frequency and the inverse document frequency. It helps us to assign importance to more discriminative words. The two components used to calculate the TF-IDF weight for each term t in our document d is described below. Term frequency The term or word frequency is calculated as the number of times the word appears in the document. Since a word appearing 100 times in a document doesn’t make that word 100 times more likely to be relevant to the meaning of the document, we use the natural logarithm to downweight the raw frequency a bit. Words which occur 10 times in a document would have a tf=2. Words which occur 100 times in a document means tf=3, 1000 times mean tf=4, etc. Inverse document frequency The document frequency of a given term or word is the number of documents it occurs in. The inverse document frequency is the ratio of the total number of documents over the document frequency. This gives a higher weight to words that occur only in a few documents. Because of the large number of documents in many collections, a natural logarithm is usually applied to the inverse document frequency in order to avoid skewed distribution of IDF. Below on the left side of the image, we see the TF and IDF calculated for words from our example introduced previously. On the right side of the image we show the raw frequency of each word in a given document, as well as its weighted TF-IDF value in the bottom table. Because the word “good” appears with high frequency in all documents, its TF-IDF value turns to zero. This allows more weight on the discriminative word “battle”, which originally has very low frequency. Although Bag-of-words models, augmented with TF-IDF, are great models, there are semantic nuances, they are not able to capture. Let’s show this on the following sentences: “The cat sat on the broken wall”, and, “The dog jumped over the brick structure”. Although both sentences are presenting two separate events, their semantic meanings are similar to one another. A dog is similar to a cat, because they share an entity called animal. A wall could be viewed as similar to a brick structure. Therefore, while the sentences discuss different events, they are semantically related to one another. In the classical bag-of-words model (where words were encoded in their own dimensions), encoding such a semantic similarity is not possible. Additionally such models exhibit few computational issues when a large vocabulary is used and word vectors become larger. We are introducing a better approach in the next section. Representing words or documents by sparse and long vectors is not practically efficient. Those vectors are typically sparse because many positions are filled by zero values. They are long because their dimensionality equals the vocabulary size or the documents collection size. As opposite to sparse vectors, dense vectors may be more successfully included as features in many machine learning systems. Dense vectors also imply less parameters to estimate. In the previous section, we saw how to compute the tf and tf-idf values for any given word in our corpus. If instead of counting how often each word w occurs in the context of another word v, we instead train a classifier on a binary prediction task “Is word w likely to show up near v?”, then we can used the learned classifier weights as the word embeddings. These become continuous vector representations of words. If we want to calculate some semantic similarity between words, we can do it by looking at the angle between two embeddings, i.e their cosine similarity, as we saw previously. Embedding vectors are typically at least around 100-dimensional long to be effective, which means there are more than tens of millions of numbers that the classifier needs to tweak when we have a 100,000 words vocabulary. How do we determine those embeddings for a given corpus? That’s exactly what the word2vec language model is designed to do. Word2vec is available in two flavors: the CBOW model and the skip-gram model (proposed by Mikolov, et. al., 2013, at Google (again!)). In the skip-gram variant, the context words are predicted using the target word, while the variant wherein the target word is predicted using the surrounding words is the CBOW model. Typically people will use the word2vec implementation and pre-trained embeddings on large corpora. We will now develop the intuition behind the skip-gram variant of word2vec model. Let’s assume the sentence below, where “apricot” is the target word and “tablespoon”, “of”, “jam” and “a” are its context words when considering a 2-words window. We can build a binary classifier which takes any pair of words (t, c) as input and predicts True if c is a real context word for t and False elsewhere. For example, the classifier will return True for (apricot, tablespoon) and False for (apricot, pinch). Below we see more examples from the positive and negative classes when considering apricot as target. Taking this a step further, we have to split each (context window, target) pair into (input, output) examples where the input is the target and the output is one of the words from the context. For illustration purpose, the pair ([of, apricot, a, pinch], jam) would produce the positive example (jam, apricot), because apricot is a real context-word of jam. (jam, lemon) would be a negative example. We continue to apply this operation to every (context window, target) pair to build our dataset. Finally, we replace each word with its unique index from the vocabulary in order to work with one-hot vector representations. Given the set of positive and negative training examples, and an initial set ofembeddings W for targets and C for context words, the goal of the classifier is to adjust those embeddings such that we maximize the similarity (dot product) of the positive examples’ embeddings and we minimize the similarity of the negative examples’ embeddings. Typically a logistic regression will solve this task. Alternatively a neural network with softmax is used. Surprisingly, the Word2vec embeddings allow for exploring interesting mathematical relationships between words. For example, if we subtract the vector for word “man” from the vector for word “king” and then add to the resulting vector a vector for work “woman”, we will arrive at the vector for word “queen”. We can also use element-wise addition of embedding vector elements to ask questions such as “German + airlines” and by looking at the closest tokens to the composite vector come up with impressive answers, as shown below. Word2vec vectors should have similar structure when trained on comparable corpora in different languages, allowing us to perform machine translation. Embeddings are also used to find the closest words for a user-specified word. They can also detect the gender relationship and plural-singular relationship between words. The word vectors can be also used for deriving word classes from huge data sets, e.g. by performing K-means clustering on top of the word vectors. In this section, we talked about Word2vec variants CBOW and Skip gram, which are local context window methods. They work well with small amounts of training data and represent even words that are considered rare. However they do not fully exploit the global statistical information regarding word co-occurrences. Therefore, let’s look at another approach that claims to solve this issue. GloVe (Global Vectors) takes a different approach than Word2vec. Instead of extracting the embeddings from a neural network or a logistic regression that is designed to perform a classification task (predicting neighbouring words), GloVe optimizes the embeddings directly so that the dot product of two word vectors equals the log of the number of times the two words will occur near each other (within a 2-words window, for example). This forces the embeddings vectors to encode the frequency distribution of which words occur near them. We thought that some readers might have been missing Python code throughout this article. From now on, we will make them a bit happier. Below we will illustrate how to use words embeddings from a pre-trained GloVe model. We leverage the Python package Gensim. The beauty of embeddings (word vectors) is that, you don’t have to have to implement any Skip gram algorithm nor have to build a large collection of text and calculate the weights yourself. You can use vectors, which generous people have already prepared for the public by using very large corpora and tons of GPUs. We will use the pre-trained word vectors glove.6B, which was trained on a corpus of 6 billion tokens and contains a vocabulary of 400 thousand words, obtained from different massive web datasets (Wikipedia among others). Each word is represented by an embeddings vector of 50, 100, 200 or 300-dimension respectively. We will use 100-dimension vectors, which are stored in a single file. The first step is to convert the GloVe file format to the word2vec file format. The only difference is the addition of a small header line. This can be done by calling the glove2word2vec() function. Each line starts with the word, followed by all the values of the corresponding vector for that word, each separated by a space, as you can see in the image below for the word “the”. As we explained in the previous section, these real-valued word vectors have proven to be useful for all sorts of natural language processing tasks, including parsing, named entity recognition and machine translation. For example, we find that claims like the following hold for the associated word vectors: king − man + woman ≈ queen That is, the word “queen” is the closest word given the subtraction of the notion of “man” from “king” and adding the word “woman” . The “man-ness” in “king” is replaced with “woman-ness” to give us “queen”. Such basic algebra on vectors allows you to do funny semantic reasoning. >>> result = model.most_similar(positive=['woman', 'king'], negative=['man'], topn=1)>>> print(result)[('queen', 0.7698541283607483)] Using the analogy gadget of words embeddings, we can even ask which word is to “russia” as “paris” is to “france”? >>> result = model.most_similar(positive=['russia', 'paris'], negative=['france'], topn=1)>>> print(result)[('moscow', 0.8845715522766113)] Why does this work so nice? Let’s look closer at the embeddings for the four words “russia”, “moscow”, “france”, “paris”. We can project the 100-words vectors into a 2D space using the first 2 components of their PCA transformation. We can also make a similar plot using the t-Distributed Stochastic Neighbor Embedding (t-SNE) method. The PCA plot below shows that a line between “france” and “moscow” would be almost parallel to a line between “france” and “paris”. With t-SNE we obtain lines which are more parallel compared to those obtained with PCA. t-SNE is a technique for dimensionality reduction and is particularly well suited for the visualization of high-dimensional datasets. Contrary to PCA, it is not a mathematical technique but a probabilistic one. The 100-dimension vectors are also very good at answering analogy questions of the form: “a is to b as c is to ?”. For example: what is to russia what paris is to france? what is to woman what king is to man? what is to dog what kitten is to cat? what is to chef what stone is to sculptor? what is to bees what den is to bears? Below we seek answers to these questions and show how a computer can win the next TV show’s quiz challenge using words embeddings. The plot above clearly shows that embeddings vectors are able to find “Moscow” as the capital of “Russia” given that “Paris” is the capital of “France”. Similarly, “hive” is to “bees” what “den” is to “bears”. In this article we motivated why representing text in numerical format is important for natural language processing. We also introduced the most commonly used approaches for doing so, by gently and intuitively covering the key aspects of the underlying algorithms. We covered several language models: one-hot encoding, N-gram, bag-of-words, td-idf, word2vec and glove. There are few popular language models which were not introduced. For example, fastText, an extension of the word2vec model, which instead of learning vectors for words directly, represents each word as an n-gram of characters. This is particularly useful for detecting suffixes and prefixes. Another area not explored in this article is topic modeling. There are various techniques for topic modeling and most of them involve some form of matrix decomposition of the term-document matrix (Latent Semantic Indexing, Latent Dirichlet Allocation). Recently, very powerful language models have been developed such as OpenAI GPT-2 and Google BERT. In my article about Google BERT, I explain how to fine-tune a pre-trained model to leverage powerful vector representations of words for machine learning tasks. towardsdatascience.com Representing text properly can be really helpful in making new friends. In order to be able to properly capitalize our friend’s name in the sentence below, we need to recognize the first “stone” as a person name and the second as an object. This topic is further developed in my article about Truecasing in natural language processing. If you are really interested by the problem of representing natural language text, we would recommend the following book as further reading: Speech and Language Processing, 3rd Ed. by Dan Jurafsky and James Martin, 2018. We assiduously used insights from that book in this article. Thank you for reading. Feel free to check my articles below.
[ { "code": null, "e": 829, "s": 172, "text": "This article looks at the representation of language for natural language processing (NLP). If you are one of those rare deep learning gurus, you will likely not learn anything new here. If not, dive with me into the fascinating world of turning words into some representations which algorithms can understand. We motivate why we would want to do this, which approaches exist, and how they work on simple examples. We will avoid as much mathematics as possible, and we will use an easy-going writing style in order to increase the chances that you actually read the article till the end. Although the article seems to be relatively long, it is fun to surf." }, { "code": null, "e": 1594, "s": 829, "text": "The history of language genesis is repeated every time a baby starts to talk. Indeed, language began when humans started naming objects, actions and phenomena which appeared in real life. When looking at the belief in divine creation, something shared by billions of people, we can think of languages to be as old as human kind. Every time we write a short message, a tweet, a chat, an email, a post or even a web page, an article, a blog or a book, we turn thoughts into words or symbols. Thanks to language, humans are able to turn invisible ideas into visible things. Additionally, human thoughts become accessible to other humans, as well as to ..., guess what? Computers! If humans are able to reconstruct thoughts from words, could computers do this as well?" }, { "code": null, "e": 2182, "s": 1594, "text": "With the recent hype called artificial intelligence, it is quite useful to have computers able to process, understand and generate human language. Google translation is a good example, a useful one. Google started by scanning a lot of books from university libraries and scrapping web pages, including their human translations, and learning from the patterns between source and target (statistical machine translation). Today, thanks to Google Translate and its sequence-to-sequence models (neural machine translation), we can access thoughts encoded in any language we do not speak yet." }, { "code": null, "e": 2205, "s": 2182, "text": "towardsdatascience.com" }, { "code": null, "e": 3682, "s": 2205, "text": "Another example is text categorization. Humans are very good at grouping things into categories, for example ‘good’ and ‘bad’. They have been doing this for ages. At the same time, humans are also very good at generating and recording information in the form of text. According to Google, there are approximately 129,864,880 books in the entire world. We bet, you don’t want to categorize them by hand, even if you are given the biggest library in the world, with enough space and shelves. At the same time, you really need to have those books categorized at least by genre: comics, cooking, business, biographies, ...etc. That’s where you would embrace a computer program that would read the book’s content and detect its genre automatically. Let’s go away from books for a moment. There is an increasing number of people among us who don’t read books, and who prefer news feeds. They usually receive hundreds of messages, posts, or articles every day. Sorting out spamming messages and fake news from relevant updates e.g. about the industry and the market, has become a very relevant task for them, as long as it is done by a computer program. You are probably reading this article because a recommendation algorithm sorted it out of many other articles and sent it to your inbox or mobile app. That algorithm had to categorize thousands of articles and select this winner article, which you will likely enjoy, based on your reading history and your clever look, of course." }, { "code": null, "e": 4108, "s": 3682, "text": "Questions-answering bots is another hype nowadays. Imagine how much time you, as customer support specialist, would save if you could have a copy of yourself answering dozen of calls you are receiving every day from your clients asking the same questions over and over. We all heard about Amazon Alexa, Apple Siri or Google Assistant. These systems are automatically answering questions posed by humans in a natural language." }, { "code": null, "e": 4359, "s": 4108, "text": "Hopefully, the examples above motivate why having computers processing natural language is an engaging topic for you. If not, looking at further examples illustrating speech recognition, speech imitation and speech synthesis would amaze you for sure." }, { "code": null, "e": 4898, "s": 4359, "text": "Now, why all this talk about language and computers? You type text in your favorite word processor or email software everyday. So, why should it be difficult for a computer to understand your text? Language is ambiguous at all levels: lexical, phrasal, semantic. Language assumes that the listener is aware of the world, the context and the communication techniques. If you type “mouse info” to a search engine, are you looking for a pet or a tool? Representation of text is very important for performance of many real-world applications." }, { "code": null, "e": 5520, "s": 4898, "text": "Now, how do we turn language into something computer algorithms enjoy? At the base, processors in computers perform simple arithmetic such as adding and multiplying numbers. Is that the reason why computers love numbers? Who knows. Anyway, this problem is solved nicely for images. For example, the area marked with a circle on the picture below is represented by three matrices of numbers, one for each color channel: red, green and blue. Each number tells the level of red, green or blue at the pixel’s location. (0,0,0) is displayed as black, and a pixel whose color components are (255,255,255) is displayed as white." }, { "code": null, "e": 6086, "s": 5520, "text": "The process of transforming text into numeric stuff, similar to what we did with the image above, is usually performed by building a language model. These models typically assign probabilities, frequencies or some obscure numbers to words, sequences of words, group of words, section of documents or whole documents. The most common techniques are: 1-hot encoding, N-grams, Bag-of-words, vector semantics (tf-idf), distributional semantics (Word2vec, GloVe). Let’s see if we understand what all this means. We should be able to. We are not computers. You, at least." }, { "code": null, "e": 6426, "s": 6086, "text": "If a document has a vocabulary with 1000 words, we can represent the words with one-hot vectors. In other words, we have 1000-dimensional representation vectors, and we associate each unique word with an index in this vector. To represent a unique word, we set the component of the vector to be 1, and zero out all of the other components." }, { "code": null, "e": 6721, "s": 6426, "text": "This representation is rather arbitrary. It misses the relationships between words and does not convey information about their surrounding context. This method becomes extremely ineffective for large vocabularies. In the next few sections, we will have a look at a bit more exciting approaches." }, { "code": null, "e": 7666, "s": 6721, "text": "We start looking at the most basic N-gram model. Let’s consider our most favorite sentence from our childhood: “please eat your food”. A 2-gram (or bigram) is a two-word sequence of words like “please eat”, “eat your”, or ”your food”. A 3-gram (or trigram) will be a three-word sequence of words like “please eat your”, or “eat your food”. N-gram language models estimate the probability of the last word given the previous words. For example, given the sequence of words “please eat your”, the likelihood of the next word is higher for “food” than for “spoon”. In the later case, our mom will be less happy. The best way to compute such likelihood for any pair, triple, quadruplet, ... of words is to use a large body of text. The image below shows few probabilities obtained from a relatively small body of text containing questions and answers related to restaurants and food. “I” is frequently followed by the verb “want”, “eat” or “spend”." }, { "code": null, "e": 8072, "s": 7666, "text": "Google (again) actually provides a larger set of probabilities for 1-grams, 2-grams, 3-grams, 4-grams, and 5-grams in multiple languages. They calculated them on sources printed between 1500 and 2008! The Google Ngram Viewer allows you to download and use this large collection of n-grams for the purpose of spell checking, auto-completing, language identification, text generation and speech recognition." }, { "code": null, "e": 8328, "s": 8072, "text": "The longer the context on which we train a N-gram model, the more coherent the sentences we can generate. The image below shows 3 sentences randomly generated from 1-gram, 2-gram and 3-gram models computed from 40 million words of the Wall Street Journal." }, { "code": null, "e": 9041, "s": 8328, "text": "Even with very large corpus, in general, N-gram is an insufficient model of language because language has long-distance dependencies. For example, in the sentence “The computer which I had just put into the machine room on the fifth floor crashed.”, although the words “computer ” and “crashed ” are 15 positions away one from another, they are related. A 5-gram model will miss that link and our computer administrator might keep thinking that the computer on the fifth floor is running perfect. Now, what about dealing with the longest sentence in German literature which is claimed to have 1077 words! Who wants to train a N-gram language model that understands those usually long interlaced German sentences?" }, { "code": null, "e": 9368, "s": 9041, "text": "Furthermore, the N-gram model is heavily dependent on the training corpus used to calculate the probabilities. One implication of this is that the probabilities often encode specific facts about a given training text, which may not necessarily apply to a new text. These reasons motivate us to look at further language models." }, { "code": null, "e": 9765, "s": 9368, "text": "When we are interested in categorizing text, classifying it based on sentiment, or verifying whether it is a spam, we often do not want to look at the sequential pattern of words, as suggested by N-gram language models. Rather we would represent the text as a bag of words, as if it were an unordered set of words, while ignoring their original position in the text, keeping only their frequency." }, { "code": null, "e": 10114, "s": 9765, "text": "Let’s illustrate the bag-of-words representation of text in a simple sentiment analysis example with the two classes positive (+) and negative (-). Below we have 5 sentences (also called documents) with their known categories, as well as 1 sentence with unknown category. The purpose is to classify the last sentence as either positive or negative." }, { "code": null, "e": 10363, "s": 10114, "text": "This task is solved by a so-called Naive Bayes Classifier, which uses the words frequencies in the bag-of-words of each class to compute the probability of each class c, as well as the conditional probability of each word given a class, as follows." }, { "code": null, "e": 10768, "s": 10363, "text": "In our example the negative class has the probability 3/5. The positive class will have the probability 2/5. A bit of algebra will show that the probability of the words “predictable”, “with”, “no” and “fun” given the negative class is higher than the sample probability given the positive class. Therefore the sentence “predictable with no fun” will be classified as negative based on the training data." }, { "code": null, "e": 11441, "s": 10768, "text": "Bag-of-words language models rely on the term frequency TF, defined as the number of times that a word occurs in a given text or document. Bag-of-words helps in sentiment analysis. It is great in detecting the language a text is written in. It is also used to determine authorship attribution such as gender and age. We can also use the term frequency information to engineer additional features such as the number of positive lexicon words (“great”, “nice”, “enjoyable”), or the number of first and second pronouns (“I”, “me”, “you”) and train more complex classifiers based on logistic regression and even neural networks. But, let’s not go that way of headache for now." }, { "code": null, "e": 11701, "s": 11441, "text": "Despite of the glory, N-gram and Bag-of-words models alone do not allow us to draw useful inferences that will help us solve meaning-related tasks like question-answering, summarization, and dialogue. This is why we will look at semantics in the next section." }, { "code": null, "e": 12616, "s": 11701, "text": "How should we represent the meaning of a word? The word “mouse” can be found in a lexical dictionary, but its plural form “mice” will be not be described separately. Similarly “sing” as the lemma for “sing”, “sang”, “sung” will be described, but its tense forms will not. How do we tell a computer that all these words mean the same thing? The word “plant” can have a different meaning depending on the context (e.g. “Tesla is building new plants”, “Climate change has a negative effect on plants”). Vector semantics is currently the best approach to building a computational model that successfully deals with the different aspects of word meaning including senses, hyponym, hypernym, antonym, synonym, homonym, similarity, relatedness, lexical fields, lexical frames, connotation. Our apologies for the linguistic jargon. Let’s build up the intuition around vector semantics by looking at the concept of context." }, { "code": null, "e": 13199, "s": 12616, "text": "In our example sentence “Tesla is building new plants”, if we count words in the context of the word “plant” in a many other sentences writen by humans, we’ll tend to see words like “build”, “machine”, “worker”, and even “Tesla”. The fact that these words and other similar context words also occur around the word “factory” can help us discover the similarity between “plant” and “factory”. In this case we will not tend to attach the meaning “vegetable” to the word “plant” in our sentence “Tesla is building new plants”. We will rather think that Tesla is building new factories." }, { "code": null, "e": 13518, "s": 13199, "text": "Therefore we can define a word by counting what other words occur in its environment, and we can represent the word by a vector, a list of numbers, a point in N-dimensional space. Such a representation is usually called embedding. Computer can use this cheating trick to understand the meaning of words in its context." }, { "code": null, "e": 14354, "s": 13518, "text": "In order to have a better grasp of vector semantics, let’s assume that we have a set of texts (documents) and we want to find documents which are similar to each other. This task is relevant in information retrieval, for example in search engines, where documents are web pages. As illustration, each column in the table below represents one of 4 documents with the following titles: “As You Like It”, “Twelfth Night”, “Julius Caesar”, and “Henry V”. Words which appear in the documents are represented as rows. These words build our vocabulary. The table tells us that the word “battle” occurs 7 times in the document “Julius Caesar”. This table is also called term-document matrix, where each row represents a word in the vocabulary and each column represents a document, a section, a paragraph, a tweet, a SMS, an email or whatever." }, { "code": null, "e": 15130, "s": 14354, "text": "Now we can represent each document by a document vector, e.g. [7 62 1 2] for “Julius Caecar”. We can even draw such vectors in a 2-dimensional vector space for any pair of words. Below we have an example of such a graph. We see a spatial visualization of the document vectors of the space built by the dimensions “fool” and “battle”. We can conclude that the documents “Henry V” and “Julius Caesar” have similar content, which is more related to “battle” than to “fool”. For information retrieval we’ll also represent a query by a document vector, also of length 4 telling how often the words “battle”, “good”, “fool” and “wit” appear in the query. The search results will be obtained by comparing the query vector with all four document vectors to find how similar they are." }, { "code": null, "e": 16063, "s": 15130, "text": "By looking at the rows of the term-document matrix, we can extract word vectors instead of column vectors. As we saw that similar documents tend to have similar words, similar words have similar vectors because they tend to occur in similar documents. If we now use words as columns of the term-document matrix, instead of documents, we obtain the so-called word-word matrix, term-term matrix, also called term-context matrix. Each cell describes the number of times the row (target) word and the column (context) word co-occur in some context in some training corpus. A simple case is when the context is a document, so the cell will tell how often two words appear in the same document. A more frequent case is to count how often the column word appears within a words-window around the row word. In the example below “data” appears 6 times in the context of “information” when a 7-words-window around “information” is considered." }, { "code": null, "e": 16375, "s": 16063, "text": "The matrix above suggests that “apricot” and “pineapple” are similar to each other because “pinch” and “sugar” tend to appear in their context. Similarity between two words v and w can be exactly computed using their corresponding word vectors by calculating the so-called cosine-similarity, defined as follows:" }, { "code": null, "e": 16655, "s": 16375, "text": "In the example below, the similarity between “digital” and “information” equals the cosine-similarity between the word vectors [0 1 2] and [1 6 1]. By applying the formula above, we obtain 0.58, which is higher than the cosine-similarity 0.16 between “apricot” and “information”." }, { "code": null, "e": 16854, "s": 16655, "text": "Word vectors and cosine-similarity are a powerful tool in dealing with natural language contents. However, there are situations where they do not workout so well, as we will see in the next section." }, { "code": null, "e": 17172, "s": 16854, "text": "Vector semantic models use the raw frequency of the co-occurrence of two words. In natural language, raw frequency is very skewed and not very discriminative. As depicted in the histogram below, the word “the” is simply a frequent word and has roughly equivalent high frequencies in each of the documents or contexts." }, { "code": null, "e": 17645, "s": 17172, "text": "There are few ways of dealing with this problem. TF-IDF algorithm is by far the dominant way of weighting co-occurrence matrices in natural language processing, especially in information retrieval. The TF-IDF weight is computed as the product of the term frequency and the inverse document frequency. It helps us to assign importance to more discriminative words. The two components used to calculate the TF-IDF weight for each term t in our document d is described below." }, { "code": null, "e": 17660, "s": 17645, "text": "Term frequency" }, { "code": null, "e": 18106, "s": 17660, "text": "The term or word frequency is calculated as the number of times the word appears in the document. Since a word appearing 100 times in a document doesn’t make that word 100 times more likely to be relevant to the meaning of the document, we use the natural logarithm to downweight the raw frequency a bit. Words which occur 10 times in a document would have a tf=2. Words which occur 100 times in a document means tf=3, 1000 times mean tf=4, etc." }, { "code": null, "e": 18133, "s": 18106, "text": "Inverse document frequency" }, { "code": null, "e": 18580, "s": 18133, "text": "The document frequency of a given term or word is the number of documents it occurs in. The inverse document frequency is the ratio of the total number of documents over the document frequency. This gives a higher weight to words that occur only in a few documents. Because of the large number of documents in many collections, a natural logarithm is usually applied to the inverse document frequency in order to avoid skewed distribution of IDF." }, { "code": null, "e": 19053, "s": 18580, "text": "Below on the left side of the image, we see the TF and IDF calculated for words from our example introduced previously. On the right side of the image we show the raw frequency of each word in a given document, as well as its weighted TF-IDF value in the bottom table. Because the word “good” appears with high frequency in all documents, its TF-IDF value turns to zero. This allows more weight on the discriminative word “battle”, which originally has very low frequency." }, { "code": null, "e": 19971, "s": 19053, "text": "Although Bag-of-words models, augmented with TF-IDF, are great models, there are semantic nuances, they are not able to capture. Let’s show this on the following sentences: “The cat sat on the broken wall”, and, “The dog jumped over the brick structure”. Although both sentences are presenting two separate events, their semantic meanings are similar to one another. A dog is similar to a cat, because they share an entity called animal. A wall could be viewed as similar to a brick structure. Therefore, while the sentences discuss different events, they are semantically related to one another. In the classical bag-of-words model (where words were encoded in their own dimensions), encoding such a semantic similarity is not possible. Additionally such models exhibit few computational issues when a large vocabulary is used and word vectors become larger. We are introducing a better approach in the next section." }, { "code": null, "e": 20249, "s": 19971, "text": "Representing words or documents by sparse and long vectors is not practically efficient. Those vectors are typically sparse because many positions are filled by zero values. They are long because their dimensionality equals the vocabulary size or the documents collection size." }, { "code": null, "e": 21022, "s": 20249, "text": "As opposite to sparse vectors, dense vectors may be more successfully included as features in many machine learning systems. Dense vectors also imply less parameters to estimate. In the previous section, we saw how to compute the tf and tf-idf values for any given word in our corpus. If instead of counting how often each word w occurs in the context of another word v, we instead train a classifier on a binary prediction task “Is word w likely to show up near v?”, then we can used the learned classifier weights as the word embeddings. These become continuous vector representations of words. If we want to calculate some semantic similarity between words, we can do it by looking at the angle between two embeddings, i.e their cosine similarity, as we saw previously." }, { "code": null, "e": 21368, "s": 21022, "text": "Embedding vectors are typically at least around 100-dimensional long to be effective, which means there are more than tens of millions of numbers that the classifier needs to tweak when we have a 100,000 words vocabulary. How do we determine those embeddings for a given corpus? That’s exactly what the word2vec language model is designed to do." }, { "code": null, "e": 21785, "s": 21368, "text": "Word2vec is available in two flavors: the CBOW model and the skip-gram model (proposed by Mikolov, et. al., 2013, at Google (again!)). In the skip-gram variant, the context words are predicted using the target word, while the variant wherein the target word is predicted using the surrounding words is the CBOW model. Typically people will use the word2vec implementation and pre-trained embeddings on large corpora." }, { "code": null, "e": 22030, "s": 21785, "text": "We will now develop the intuition behind the skip-gram variant of word2vec model. Let’s assume the sentence below, where “apricot” is the target word and “tablespoon”, “of”, “jam” and “a” are its context words when considering a 2-words window." }, { "code": null, "e": 22387, "s": 22030, "text": "We can build a binary classifier which takes any pair of words (t, c) as input and predicts True if c is a real context word for t and False elsewhere. For example, the classifier will return True for (apricot, tablespoon) and False for (apricot, pinch). Below we see more examples from the positive and negative classes when considering apricot as target." }, { "code": null, "e": 23009, "s": 22387, "text": "Taking this a step further, we have to split each (context window, target) pair into (input, output) examples where the input is the target and the output is one of the words from the context. For illustration purpose, the pair ([of, apricot, a, pinch], jam) would produce the positive example (jam, apricot), because apricot is a real context-word of jam. (jam, lemon) would be a negative example. We continue to apply this operation to every (context window, target) pair to build our dataset. Finally, we replace each word with its unique index from the vocabulary in order to work with one-hot vector representations." }, { "code": null, "e": 23459, "s": 23009, "text": "Given the set of positive and negative training examples, and an initial set ofembeddings W for targets and C for context words, the goal of the classifier is to adjust those embeddings such that we maximize the similarity (dot product) of the positive examples’ embeddings and we minimize the similarity of the negative examples’ embeddings. Typically a logistic regression will solve this task. Alternatively a neural network with softmax is used." }, { "code": null, "e": 23768, "s": 23459, "text": "Surprisingly, the Word2vec embeddings allow for exploring interesting mathematical relationships between words. For example, if we subtract the vector for word “man” from the vector for word “king” and then add to the resulting vector a vector for work “woman”, we will arrive at the vector for word “queen”." }, { "code": null, "e": 23990, "s": 23768, "text": "We can also use element-wise addition of embedding vector elements to ask questions such as “German + airlines” and by looking at the closest tokens to the composite vector come up with impressive answers, as shown below." }, { "code": null, "e": 24140, "s": 23990, "text": "Word2vec vectors should have similar structure when trained on comparable corpora in different languages, allowing us to perform machine translation." }, { "code": null, "e": 24458, "s": 24140, "text": "Embeddings are also used to find the closest words for a user-specified word. They can also detect the gender relationship and plural-singular relationship between words. The word vectors can be also used for deriving word classes from huge data sets, e.g. by performing K-means clustering on top of the word vectors." }, { "code": null, "e": 24846, "s": 24458, "text": "In this section, we talked about Word2vec variants CBOW and Skip gram, which are local context window methods. They work well with small amounts of training data and represent even words that are considered rare. However they do not fully exploit the global statistical information regarding word co-occurrences. Therefore, let’s look at another approach that claims to solve this issue." }, { "code": null, "e": 25521, "s": 24846, "text": "GloVe (Global Vectors) takes a different approach than Word2vec. Instead of extracting the embeddings from a neural network or a logistic regression that is designed to perform a classification task (predicting neighbouring words), GloVe optimizes the embeddings directly so that the dot product of two word vectors equals the log of the number of times the two words will occur near each other (within a 2-words window, for example). This forces the embeddings vectors to encode the frequency distribution of which words occur near them. We thought that some readers might have been missing Python code throughout this article. From now on, we will make them a bit happier." }, { "code": null, "e": 25645, "s": 25521, "text": "Below we will illustrate how to use words embeddings from a pre-trained GloVe model. We leverage the Python package Gensim." }, { "code": null, "e": 26730, "s": 25645, "text": "The beauty of embeddings (word vectors) is that, you don’t have to have to implement any Skip gram algorithm nor have to build a large collection of text and calculate the weights yourself. You can use vectors, which generous people have already prepared for the public by using very large corpora and tons of GPUs. We will use the pre-trained word vectors glove.6B, which was trained on a corpus of 6 billion tokens and contains a vocabulary of 400 thousand words, obtained from different massive web datasets (Wikipedia among others). Each word is represented by an embeddings vector of 50, 100, 200 or 300-dimension respectively. We will use 100-dimension vectors, which are stored in a single file. The first step is to convert the GloVe file format to the word2vec file format. The only difference is the addition of a small header line. This can be done by calling the glove2word2vec() function. Each line starts with the word, followed by all the values of the corresponding vector for that word, each separated by a space, as you can see in the image below for the word “the”." }, { "code": null, "e": 27038, "s": 26730, "text": "As we explained in the previous section, these real-valued word vectors have proven to be useful for all sorts of natural language processing tasks, including parsing, named entity recognition and machine translation. For example, we find that claims like the following hold for the associated word vectors:" }, { "code": null, "e": 27065, "s": 27038, "text": "king − man + woman ≈ queen" }, { "code": null, "e": 27346, "s": 27065, "text": "That is, the word “queen” is the closest word given the subtraction of the notion of “man” from “king” and adding the word “woman” . The “man-ness” in “king” is replaced with “woman-ness” to give us “queen”. Such basic algebra on vectors allows you to do funny semantic reasoning." }, { "code": null, "e": 27544, "s": 27346, "text": ">>> result = model.most_similar(positive=['woman', 'king'], negative=['man'], topn=1)>>> print(result)[('queen', 0.7698541283607483)]" }, { "code": null, "e": 27659, "s": 27544, "text": "Using the analogy gadget of words embeddings, we can even ask which word is to “russia” as “paris” is to “france”?" }, { "code": null, "e": 27863, "s": 27659, "text": ">>> result = model.most_similar(positive=['russia', 'paris'], negative=['france'], topn=1)>>> print(result)[('moscow', 0.8845715522766113)]" }, { "code": null, "e": 28629, "s": 27863, "text": "Why does this work so nice? Let’s look closer at the embeddings for the four words “russia”, “moscow”, “france”, “paris”. We can project the 100-words vectors into a 2D space using the first 2 components of their PCA transformation. We can also make a similar plot using the t-Distributed Stochastic Neighbor Embedding (t-SNE) method. The PCA plot below shows that a line between “france” and “moscow” would be almost parallel to a line between “france” and “paris”. With t-SNE we obtain lines which are more parallel compared to those obtained with PCA. t-SNE is a technique for dimensionality reduction and is particularly well suited for the visualization of high-dimensional datasets. Contrary to PCA, it is not a mathematical technique but a probabilistic one." }, { "code": null, "e": 28757, "s": 28629, "text": "The 100-dimension vectors are also very good at answering analogy questions of the form: “a is to b as c is to ?”. For example:" }, { "code": null, "e": 28800, "s": 28757, "text": "what is to russia what paris is to france?" }, { "code": null, "e": 28838, "s": 28800, "text": "what is to woman what king is to man?" }, { "code": null, "e": 28876, "s": 28838, "text": "what is to dog what kitten is to cat?" }, { "code": null, "e": 28919, "s": 28876, "text": "what is to chef what stone is to sculptor?" }, { "code": null, "e": 28957, "s": 28919, "text": "what is to bees what den is to bears?" }, { "code": null, "e": 29088, "s": 28957, "text": "Below we seek answers to these questions and show how a computer can win the next TV show’s quiz challenge using words embeddings." }, { "code": null, "e": 29298, "s": 29088, "text": "The plot above clearly shows that embeddings vectors are able to find “Moscow” as the capital of “Russia” given that “Paris” is the capital of “France”. Similarly, “hive” is to “bees” what “den” is to “bears”." }, { "code": null, "e": 30212, "s": 29298, "text": "In this article we motivated why representing text in numerical format is important for natural language processing. We also introduced the most commonly used approaches for doing so, by gently and intuitively covering the key aspects of the underlying algorithms. We covered several language models: one-hot encoding, N-gram, bag-of-words, td-idf, word2vec and glove. There are few popular language models which were not introduced. For example, fastText, an extension of the word2vec model, which instead of learning vectors for words directly, represents each word as an n-gram of characters. This is particularly useful for detecting suffixes and prefixes. Another area not explored in this article is topic modeling. There are various techniques for topic modeling and most of them involve some form of matrix decomposition of the term-document matrix (Latent Semantic Indexing, Latent Dirichlet Allocation)." }, { "code": null, "e": 30471, "s": 30212, "text": "Recently, very powerful language models have been developed such as OpenAI GPT-2 and Google BERT. In my article about Google BERT, I explain how to fine-tune a pre-trained model to leverage powerful vector representations of words for machine learning tasks." }, { "code": null, "e": 30494, "s": 30471, "text": "towardsdatascience.com" }, { "code": null, "e": 30830, "s": 30494, "text": "Representing text properly can be really helpful in making new friends. In order to be able to properly capitalize our friend’s name in the sentence below, we need to recognize the first “stone” as a person name and the second as an object. This topic is further developed in my article about Truecasing in natural language processing." }, { "code": null, "e": 31112, "s": 30830, "text": "If you are really interested by the problem of representing natural language text, we would recommend the following book as further reading: Speech and Language Processing, 3rd Ed. by Dan Jurafsky and James Martin, 2018. We assiduously used insights from that book in this article." } ]
Report is too long to read? Use NLP to create a summary | by Louis Teo | Towards Data Science
Have you ever had one too many reports to read and you just want a quick summary of each report? Were you ever in a situation where everybody just wanted to read a summary instead of a full-blown report? Summarization has become a very helpful way of tackling the issue of data overburden in the 21st century. In this story, I will show you how you can create your personal text summarizer using Natural Language Processing (NLP) in Python. Foreword: Personal text summarizer is not hard to create — a beginner can easily do it! It’s basically a task to generate an accurate summary while maintaining key information and not losing overall meaning. There are two general types of summarization: Abstractive summary >> generate new sentences from original text. Extractive summary >> recognize important sentences and create a summary using those sentences. I use extractive summary because I can apply this method to many documents without having to do a lot of (daunting) machine learning model training tasks. Besides that, extractive summarization gives better summary outcome than abstractive summary, because abstractive summarization has to generate new sentences from the original text, which is a more difficult method than a data-driven approach to extract important sentences. We will use word histogram to rank the importance of sentences and, subsequently, create a summary. The benefit of doing this is that you don’t need to train your model to use it for your document. Below is the workflow that we will be following... import text>> >> clean text and split into sentences >> remove stop words >> build word histogram>> rank sentences>> select top N sentences for summary (1) Sample Text I used the text from a news article entitled Apple Acquires AI Startup For $50 Million To Advance Its Apps. You can find the original news article here. You can also download the text document from my Github. (2) Import libraries # Natural Language Tool Kit (NLTK)import nltknltk.download('stopwords')nltk.download('punkt')# Regular Expression for text preprocessingimport re# Heap (priority) queue algorithm to get the top sentencesimport heapq# NumPy for numerical computingimport numpy as np# pandas for creating DataFramesimport pandas as pd# matplotlib for plotfrom matplotlib import pyplot as plt%matplotlib inline (3) Import text and perform preprocessing There are many ways to do this. The goal here is to have a clean text that we can feed into our model. # load text filewith open('Apple_Acquires_AI_Startup.txt', 'r') as f: file_data = f.read() Here, we use regular expression to do text preprocessing. We will (A) replace reference number, i.e. [1], [10], [20], with empty space (if any...), (B) replace one or more spaces with single space. text = file_data# replace reference number with empty space, if any..text = re.sub(r'\[[0-9]*\]',' ',text) # replace one or more spaces with single spacetext = re.sub(r'\s+',' ',text) Next, we form a clean text with lower case (without special characters, digits and extra spaces) and split it into individual word, for word score computation and formation of the word histogram. The reason to form a clean text is so that the algorithm won’t treat, e.g. “understanding” and understanding, as two different words. # convert all uppercase characters into lowercase charactersclean_text = text.lower()# replace characters other than [a-zA-Z0-9], digits & one or more spaces with single spaceregex_patterns = [r'\W',r'\d',r'\s+']for regex in regex_patterns: clean_text = re.sub(regex,' ',clean_text) (4) Split (tokenize) text into sentences We split the text into sentences using NLTK sent_tokenize() method. We will evaluate the importance of each of the sentences, then decide if we should include each in our summary. sentences = nltk.sent_tokenize(text) (5) Remove stop words Stop words are English words which do not add much meaning to a sentence. They can be safely ignored without sacrificing the meaning of the sentence. We already downloaded a file with English stop words in ‘(2) Import libraries’ section. Here, we will get the list of stop words and store them in stop_word variable. # get stop words liststop_words = nltk.corpus.stopwords.words('english') (6) Build word histogram Let’s evaluate the importance of each word based on how many times it appears in the entire text. We will do so by (1) splitting the words in clean_text, (2) removing the stop words, and then (3) checking the frequency of each word as it appears in the text. # create an empty dictionary to house the word countword_count = {}# loop through tokenized words, remove stop words and save word count to dictionaryfor word in nltk.word_tokenize(clean_text): # remove stop words if word not in stop_words: # save word count to dictionary if word not in word_count.keys(): word_count[word] = 1 else: word_count[word] += 1 Let’s plot the word histogram and see the results. plt.figure(figsize=(16,10))plt.xticks(rotation = 90)plt.bar(word_count.keys(), word_count.values())plt.show() Ahhh... it’s a bit difficult to read the plot. Let’s convert it to horizontal bar plot and display only the top 20 words with a helper function below. # helper function for plotting the top words.def plot_top_words(word_count_dict, show_top_n=20): word_count_table = pd.DataFrame.from_dict(word_count_dict, orient = 'index').rename(columns={0: 'score'}) word_count_table.sort_values(by='score').tail(show_top_n).plot(kind='barh', figsize=(10,10)) plt.show() Let’s display the top 20 words. plot_top_words(word_count, 20) From the plot above, we can see the words ‘ai’ and ‘apple’ appear on the top. This makes sense because the article is about Apple acquiring an AI startup. (6) Rank sentences based on scores Now, we are going to rank the importance of each sentence based on sentence score. We will: remove sentences that have more than 30 words, recognizing that long sentences may not always be meaningful**; then, add score (count) from each word that forms the sentence to form the sentence score. Sentences that have high scores will form our top sentences. The top sentences will form our summary later. **Note: In my experience, any word count between 25 and 30 should give you a good summary. # create empty dictionary to house sentence score sentence_score = {}# loop through tokenized sentence, only take sentences that have less than 30 words, then add word score to form sentence scorefor sentence in sentences: # check if word in sentence is in word_count dictionary for word in nltk.word_tokenize(sentence.lower()): if word in word_count.keys(): # only take sentence that has less than 30 words if len(sentence.split(' ')) < 30: # add word score to sentence score if sentence not in sentence_score.keys(): sentence_score[sentence] = word_count[word] else: sentence_score[sentence] += word_count[word] We convert the sentence_score dictionary to a DataFrame and display the sentences and scores. Note: dictionary doesn’t allow you to sort the sentences based on scores, so you need to convert the data stored in dictionary to DataFrame. df_sentence_score = pd.DataFrame.from_dict(sentence_score, orient = 'index').rename(columns={0: 'score'})df_sentence_score.sort_values(by='score', ascending = False) (7) Select top sentences for summary We use heap queue algorithm to select the top 3 sentences and store them in best_sentences variable. Usually 3–5 sentences will be enough. Depending on the length of your document, feel free to change the number of top sentences to be displayed. In this case, I chose 3 because our text is a relatively short article. # display the best 3 sentences for summary best_sentences = heapq.nlargest(3, sentence_score, key=sentence_score.get) Let’s display our summarized text using print() and for loop functions. print('SUMMARY')print('------------------------')# display top sentences based on their sentence sequence in the original textfor sentence in sentences: if sentence in best_sentences: print (sentence) Here is the link to my Github to get the Jupyter notebook for this. Below is the complete Python script that you can use right away to summarize your text. Below is the original text from a news article entitled Apple Acquires AI Startup For $50 Million To Advance Its Apps (the original news article can be found here): In an attempt to scale up its AI portfolio, Apple has acquired Spain-based AI video startup — Vilynx for approximately $50 million.Reported by Bloomberg, the AI startup — Vilynx is headquartered in Barcelona, which is known to build software using computer vision to analyse a video’s visual, text, and audio content with the goal of “understanding” what’s in the video. This helps it categorising and tagging metadata to the videos, as well as generate automated video previews, and recommend related content to users, according to the company website.Apple told the media that the company typically acquires smaller technology companies from time to time, and with the recent buy, the company could potentially use Vilynx’s technology to help improve a variety of apps. According to the media, Siri, search, Photos, and other apps that rely on Apple are possible candidates as are Apple TV, Music, News, to name a few that are going to be revolutionised with Vilynx’s technology.With CEO Tim Cook’s vision of the potential of augmented reality, the company could also make use of AI-based tools like Vilynx.The purchase will also advance Apple’s AI expertise, adding up to 50 engineers and data scientists joining from Vilynx, and the startup is going to become one of Apple’s key AI research hubs in Europe, according to the news.Apple has made significant progress in the space of artificial intelligence over the past few months, with this purchase of UK-based Spectral Edge last December, Seattle-based Xnor.ai for $200 million and Voysis and Inductiv to help it improve Siri. With its habit of quietly purchasing smaller companies, Apple is making a mark in the AI space. In 2018, CEO Tim Cook said in an interview that the company had bought 20 companies over six months, while only six were public knowledge. ... and the summarized text is as follows: In an attempt to scale up its AI portfolio, Apple has acquired Spain-based AI video startup — Vilynx for approximately $50 million.With CEO Tim Cook’s vision of the potential of augmented reality, the company could also make use of AI-based tools like Vilynx.With its habit of quietly purchasing smaller companies, Apple is making a mark in the AI space. Congratulations! You have created your personal text summarizer in Python. The summary, I should hope, looks pretty decent. It is important to note that we used word frequency in a document to rank the sentences. The advantage of using this method is that it does not require any prior training and can work on any piece of text. As another tip, you can further tweak the summarizer to your liking based on: (1) The number of top sentences: The simple rule-of-thumb here is that the length of a summary should not be more than 1⁄4 of the original text — it can be one sentence, one paragraph or multiple paragraphs depending on the length of the original text and your purpose of getting the summary. If the text you want to summarize is long, then you can increase the number of top sentences; or (2) Sentence length: On average, a sentence length today ranges between 15 and 20 words. Therefore, limiting your summarizer to take only the sentences of length than 25–30 words is enough; however, feel free to increase and decrease the word count. Thank you for reading this story. Follow me on medium for more of my sharing on data science and machine learning.
[ { "code": null, "e": 251, "s": 47, "text": "Have you ever had one too many reports to read and you just want a quick summary of each report? Were you ever in a situation where everybody just wanted to read a summary instead of a full-blown report?" }, { "code": null, "e": 488, "s": 251, "text": "Summarization has become a very helpful way of tackling the issue of data overburden in the 21st century. In this story, I will show you how you can create your personal text summarizer using Natural Language Processing (NLP) in Python." }, { "code": null, "e": 576, "s": 488, "text": "Foreword: Personal text summarizer is not hard to create — a beginner can easily do it!" }, { "code": null, "e": 696, "s": 576, "text": "It’s basically a task to generate an accurate summary while maintaining key information and not losing overall meaning." }, { "code": null, "e": 742, "s": 696, "text": "There are two general types of summarization:" }, { "code": null, "e": 808, "s": 742, "text": "Abstractive summary >> generate new sentences from original text." }, { "code": null, "e": 904, "s": 808, "text": "Extractive summary >> recognize important sentences and create a summary using those sentences." }, { "code": null, "e": 1059, "s": 904, "text": "I use extractive summary because I can apply this method to many documents without having to do a lot of (daunting) machine learning model training tasks." }, { "code": null, "e": 1334, "s": 1059, "text": "Besides that, extractive summarization gives better summary outcome than abstractive summary, because abstractive summarization has to generate new sentences from the original text, which is a more difficult method than a data-driven approach to extract important sentences." }, { "code": null, "e": 1532, "s": 1334, "text": "We will use word histogram to rank the importance of sentences and, subsequently, create a summary. The benefit of doing this is that you don’t need to train your model to use it for your document." }, { "code": null, "e": 1583, "s": 1532, "text": "Below is the workflow that we will be following..." }, { "code": null, "e": 1735, "s": 1583, "text": "import text>> >> clean text and split into sentences >> remove stop words >> build word histogram>> rank sentences>> select top N sentences for summary" }, { "code": null, "e": 1751, "s": 1735, "text": "(1) Sample Text" }, { "code": null, "e": 1904, "s": 1751, "text": "I used the text from a news article entitled Apple Acquires AI Startup For $50 Million To Advance Its Apps. You can find the original news article here." }, { "code": null, "e": 1960, "s": 1904, "text": "You can also download the text document from my Github." }, { "code": null, "e": 1981, "s": 1960, "text": "(2) Import libraries" }, { "code": null, "e": 2372, "s": 1981, "text": "# Natural Language Tool Kit (NLTK)import nltknltk.download('stopwords')nltk.download('punkt')# Regular Expression for text preprocessingimport re# Heap (priority) queue algorithm to get the top sentencesimport heapq# NumPy for numerical computingimport numpy as np# pandas for creating DataFramesimport pandas as pd# matplotlib for plotfrom matplotlib import pyplot as plt%matplotlib inline" }, { "code": null, "e": 2414, "s": 2372, "text": "(3) Import text and perform preprocessing" }, { "code": null, "e": 2517, "s": 2414, "text": "There are many ways to do this. The goal here is to have a clean text that we can feed into our model." }, { "code": null, "e": 2611, "s": 2517, "text": "# load text filewith open('Apple_Acquires_AI_Startup.txt', 'r') as f: file_data = f.read()" }, { "code": null, "e": 2809, "s": 2611, "text": "Here, we use regular expression to do text preprocessing. We will (A) replace reference number, i.e. [1], [10], [20], with empty space (if any...), (B) replace one or more spaces with single space." }, { "code": null, "e": 2993, "s": 2809, "text": "text = file_data# replace reference number with empty space, if any..text = re.sub(r'\\[[0-9]*\\]',' ',text) # replace one or more spaces with single spacetext = re.sub(r'\\s+',' ',text)" }, { "code": null, "e": 3189, "s": 2993, "text": "Next, we form a clean text with lower case (without special characters, digits and extra spaces) and split it into individual word, for word score computation and formation of the word histogram." }, { "code": null, "e": 3323, "s": 3189, "text": "The reason to form a clean text is so that the algorithm won’t treat, e.g. “understanding” and understanding, as two different words." }, { "code": null, "e": 3609, "s": 3323, "text": "# convert all uppercase characters into lowercase charactersclean_text = text.lower()# replace characters other than [a-zA-Z0-9], digits & one or more spaces with single spaceregex_patterns = [r'\\W',r'\\d',r'\\s+']for regex in regex_patterns: clean_text = re.sub(regex,' ',clean_text)" }, { "code": null, "e": 3650, "s": 3609, "text": "(4) Split (tokenize) text into sentences" }, { "code": null, "e": 3830, "s": 3650, "text": "We split the text into sentences using NLTK sent_tokenize() method. We will evaluate the importance of each of the sentences, then decide if we should include each in our summary." }, { "code": null, "e": 3867, "s": 3830, "text": "sentences = nltk.sent_tokenize(text)" }, { "code": null, "e": 3889, "s": 3867, "text": "(5) Remove stop words" }, { "code": null, "e": 4127, "s": 3889, "text": "Stop words are English words which do not add much meaning to a sentence. They can be safely ignored without sacrificing the meaning of the sentence. We already downloaded a file with English stop words in ‘(2) Import libraries’ section." }, { "code": null, "e": 4206, "s": 4127, "text": "Here, we will get the list of stop words and store them in stop_word variable." }, { "code": null, "e": 4279, "s": 4206, "text": "# get stop words liststop_words = nltk.corpus.stopwords.words('english')" }, { "code": null, "e": 4304, "s": 4279, "text": "(6) Build word histogram" }, { "code": null, "e": 4402, "s": 4304, "text": "Let’s evaluate the importance of each word based on how many times it appears in the entire text." }, { "code": null, "e": 4563, "s": 4402, "text": "We will do so by (1) splitting the words in clean_text, (2) removing the stop words, and then (3) checking the frequency of each word as it appears in the text." }, { "code": null, "e": 4968, "s": 4563, "text": "# create an empty dictionary to house the word countword_count = {}# loop through tokenized words, remove stop words and save word count to dictionaryfor word in nltk.word_tokenize(clean_text): # remove stop words if word not in stop_words: # save word count to dictionary if word not in word_count.keys(): word_count[word] = 1 else: word_count[word] += 1" }, { "code": null, "e": 5019, "s": 4968, "text": "Let’s plot the word histogram and see the results." }, { "code": null, "e": 5129, "s": 5019, "text": "plt.figure(figsize=(16,10))plt.xticks(rotation = 90)plt.bar(word_count.keys(), word_count.values())plt.show()" }, { "code": null, "e": 5280, "s": 5129, "text": "Ahhh... it’s a bit difficult to read the plot. Let’s convert it to horizontal bar plot and display only the top 20 words with a helper function below." }, { "code": null, "e": 5596, "s": 5280, "text": "# helper function for plotting the top words.def plot_top_words(word_count_dict, show_top_n=20): word_count_table = pd.DataFrame.from_dict(word_count_dict, orient = 'index').rename(columns={0: 'score'}) word_count_table.sort_values(by='score').tail(show_top_n).plot(kind='barh', figsize=(10,10)) plt.show()" }, { "code": null, "e": 5628, "s": 5596, "text": "Let’s display the top 20 words." }, { "code": null, "e": 5659, "s": 5628, "text": "plot_top_words(word_count, 20)" }, { "code": null, "e": 5814, "s": 5659, "text": "From the plot above, we can see the words ‘ai’ and ‘apple’ appear on the top. This makes sense because the article is about Apple acquiring an AI startup." }, { "code": null, "e": 5849, "s": 5814, "text": "(6) Rank sentences based on scores" }, { "code": null, "e": 5941, "s": 5849, "text": "Now, we are going to rank the importance of each sentence based on sentence score. We will:" }, { "code": null, "e": 6052, "s": 5941, "text": "remove sentences that have more than 30 words, recognizing that long sentences may not always be meaningful**;" }, { "code": null, "e": 6143, "s": 6052, "text": "then, add score (count) from each word that forms the sentence to form the sentence score." }, { "code": null, "e": 6251, "s": 6143, "text": "Sentences that have high scores will form our top sentences. The top sentences will form our summary later." }, { "code": null, "e": 6342, "s": 6251, "text": "**Note: In my experience, any word count between 25 and 30 should give you a good summary." }, { "code": null, "e": 7077, "s": 6342, "text": "# create empty dictionary to house sentence score sentence_score = {}# loop through tokenized sentence, only take sentences that have less than 30 words, then add word score to form sentence scorefor sentence in sentences: # check if word in sentence is in word_count dictionary for word in nltk.word_tokenize(sentence.lower()): if word in word_count.keys(): # only take sentence that has less than 30 words if len(sentence.split(' ')) < 30: # add word score to sentence score if sentence not in sentence_score.keys(): sentence_score[sentence] = word_count[word] else: sentence_score[sentence] += word_count[word]" }, { "code": null, "e": 7171, "s": 7077, "text": "We convert the sentence_score dictionary to a DataFrame and display the sentences and scores." }, { "code": null, "e": 7312, "s": 7171, "text": "Note: dictionary doesn’t allow you to sort the sentences based on scores, so you need to convert the data stored in dictionary to DataFrame." }, { "code": null, "e": 7478, "s": 7312, "text": "df_sentence_score = pd.DataFrame.from_dict(sentence_score, orient = 'index').rename(columns={0: 'score'})df_sentence_score.sort_values(by='score', ascending = False)" }, { "code": null, "e": 7515, "s": 7478, "text": "(7) Select top sentences for summary" }, { "code": null, "e": 7616, "s": 7515, "text": "We use heap queue algorithm to select the top 3 sentences and store them in best_sentences variable." }, { "code": null, "e": 7761, "s": 7616, "text": "Usually 3–5 sentences will be enough. Depending on the length of your document, feel free to change the number of top sentences to be displayed." }, { "code": null, "e": 7833, "s": 7761, "text": "In this case, I chose 3 because our text is a relatively short article." }, { "code": null, "e": 7963, "s": 7833, "text": "# display the best 3 sentences for summary best_sentences = heapq.nlargest(3, sentence_score, key=sentence_score.get)" }, { "code": null, "e": 8035, "s": 7963, "text": "Let’s display our summarized text using print() and for loop functions." }, { "code": null, "e": 8246, "s": 8035, "text": "print('SUMMARY')print('------------------------')# display top sentences based on their sentence sequence in the original textfor sentence in sentences: if sentence in best_sentences: print (sentence)" }, { "code": null, "e": 8314, "s": 8246, "text": "Here is the link to my Github to get the Jupyter notebook for this." }, { "code": null, "e": 8402, "s": 8314, "text": "Below is the complete Python script that you can use right away to summarize your text." }, { "code": null, "e": 8567, "s": 8402, "text": "Below is the original text from a news article entitled Apple Acquires AI Startup For $50 Million To Advance Its Apps (the original news article can be found here):" }, { "code": null, "e": 10385, "s": 8567, "text": "In an attempt to scale up its AI portfolio, Apple has acquired Spain-based AI video startup — Vilynx for approximately $50 million.Reported by Bloomberg, the AI startup — Vilynx is headquartered in Barcelona, which is known to build software using computer vision to analyse a video’s visual, text, and audio content with the goal of “understanding” what’s in the video. This helps it categorising and tagging metadata to the videos, as well as generate automated video previews, and recommend related content to users, according to the company website.Apple told the media that the company typically acquires smaller technology companies from time to time, and with the recent buy, the company could potentially use Vilynx’s technology to help improve a variety of apps. According to the media, Siri, search, Photos, and other apps that rely on Apple are possible candidates as are Apple TV, Music, News, to name a few that are going to be revolutionised with Vilynx’s technology.With CEO Tim Cook’s vision of the potential of augmented reality, the company could also make use of AI-based tools like Vilynx.The purchase will also advance Apple’s AI expertise, adding up to 50 engineers and data scientists joining from Vilynx, and the startup is going to become one of Apple’s key AI research hubs in Europe, according to the news.Apple has made significant progress in the space of artificial intelligence over the past few months, with this purchase of UK-based Spectral Edge last December, Seattle-based Xnor.ai for $200 million and Voysis and Inductiv to help it improve Siri. With its habit of quietly purchasing smaller companies, Apple is making a mark in the AI space. In 2018, CEO Tim Cook said in an interview that the company had bought 20 companies over six months, while only six were public knowledge." }, { "code": null, "e": 10428, "s": 10385, "text": "... and the summarized text is as follows:" }, { "code": null, "e": 10783, "s": 10428, "text": "In an attempt to scale up its AI portfolio, Apple has acquired Spain-based AI video startup — Vilynx for approximately $50 million.With CEO Tim Cook’s vision of the potential of augmented reality, the company could also make use of AI-based tools like Vilynx.With its habit of quietly purchasing smaller companies, Apple is making a mark in the AI space." }, { "code": null, "e": 10800, "s": 10783, "text": "Congratulations!" }, { "code": null, "e": 10907, "s": 10800, "text": "You have created your personal text summarizer in Python. The summary, I should hope, looks pretty decent." }, { "code": null, "e": 11191, "s": 10907, "text": "It is important to note that we used word frequency in a document to rank the sentences. The advantage of using this method is that it does not require any prior training and can work on any piece of text. As another tip, you can further tweak the summarizer to your liking based on:" }, { "code": null, "e": 11581, "s": 11191, "text": "(1) The number of top sentences: The simple rule-of-thumb here is that the length of a summary should not be more than 1⁄4 of the original text — it can be one sentence, one paragraph or multiple paragraphs depending on the length of the original text and your purpose of getting the summary. If the text you want to summarize is long, then you can increase the number of top sentences; or" }, { "code": null, "e": 11831, "s": 11581, "text": "(2) Sentence length: On average, a sentence length today ranges between 15 and 20 words. Therefore, limiting your summarizer to take only the sentences of length than 25–30 words is enough; however, feel free to increase and decrease the word count." } ]
MySQL query to check if a string contains a word?
For this, you can use the LIKE operator along with CONCAT() function. Let us first create a table − mysql> create table DemoTable ( Value text ); Query OK, 0 rows affected (0.63 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('MySQL'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Is'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Relational'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Database'); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------------+ | Value | +------------+ | MySQL | | Is | | Relational | | Database | +------------+ 4 rows in set (0.00 sec) Following is the query to check if a string contains a word in a column − Note − Below displays for a single word as a column value. The same works for an entire line or string, wherein you need to find only a word − mysql> select Value from DemoTable where 'Relational' LIKE concat('%',Value,'%'); This will produce the following output − +------------+ | Value | +------------+ | Relational | +------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1162, "s": 1062, "text": "For this, you can use the LIKE operator along with CONCAT() function. Let us first create a table −" }, { "code": null, "e": 1248, "s": 1162, "text": "mysql> create table DemoTable\n(\n Value text\n);\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1304, "s": 1248, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1637, "s": 1304, "text": "mysql> insert into DemoTable values('MySQL');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('Is');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('Relational');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('Database');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 1697, "s": 1637, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1728, "s": 1697, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1769, "s": 1728, "text": "This will produce the following output −" }, { "code": null, "e": 1915, "s": 1769, "text": "+------------+\n| Value | \n+------------+\n| MySQL |\n| Is |\n| Relational |\n| Database |\n+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1989, "s": 1915, "text": "Following is the query to check if a string contains a word in a column −" }, { "code": null, "e": 2132, "s": 1989, "text": "Note − Below displays for a single word as a column value. The same works for an entire line or string, wherein you need to find only a word −" }, { "code": null, "e": 2214, "s": 2132, "text": "mysql> select Value from DemoTable where 'Relational' LIKE concat('%',Value,'%');" }, { "code": null, "e": 2255, "s": 2214, "text": "This will produce the following output −" }, { "code": null, "e": 2354, "s": 2255, "text": "+------------+\n| Value |\n+------------+\n| Relational |\n+------------+\n1 row in set (0.00 sec)" } ]
Functional Interfaces in Java - GeeksforGeeks
16 Jan, 2022 Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. There are no solely functions present in a programming language called Java. Functions in the Java programming language are part of a class, and if someone wants to use them, they have to use the class or object of the class to call any function. A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces. Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM interfaces. Functional interfaces in Java are the new feature that provides users with the approach of fundamental programming. Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. Functional interfaces are interfaces that ensure that they include precisely only one abstract method. Functional interfaces are used and executed by representing the interface with an annotation called @FunctionalInterface. As described earlier, functional interfaces can contain only one abstract method. However, they can include any quantity of default and static methods. In Functional interfaces, there is no need to use the abstract keyword as it is optional to use the abstract keyword because, by default, the method defined inside the interface is abstract only. We can also call Lambda expressions as the instance of functional interface. Before Java 8, we had to create anonymous inner class objects or implement these interfaces. Java // Java program to demonstrate functional interface class Test { public static void main(String args[]) { // create anonymous inner class object new Thread(new Runnable() { @Override public void run() { System.out.println("New thread created"); } }).start(); }} New thread created Java 8 onwards, we can assign lambda expression to its functional interface object like this: Java // Java program to demonstrate Implementation of// functional interface using lambda expressions class Test { public static void main(String args[]) { // lambda expression to create the object new Thread(() -> { System.out.println("New thread created"); }).start(); }} New thread created @FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation. Java // Java program to demonstrate lambda expressions to// implement a user defined functional interface. @FunctionalInterface interface Square { int calculate(int x);} class Test { public static void main(String args[]) { int a = 5; // lambda expression to define the calculate method Square s = (int x) -> x * x; // parameter passed and return type must be // same as defined in the prototype int ans = s.calculate(a); System.out.println(ans); }} 25 Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows – Runnable –> This interface only contains the run() method. Comparable –> This interface only contains the compareTo() method. ActionListener –> This interface only contains the actionPerformed() method. Callable –> This interface only contains the call() method. Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations. These are: ConsumerPredicateFunction Supplier Consumer Predicate Function Supplier Amidst the previous four interfaces, the first three interfaces,i.e., Consumer, Predicate, and Function, likewise have additions that are provided beneath – Consumer -> Bi-ConsumerPredicate -> Bi-PredicateFunction -> Bi-Function, Unary Operator, Binary Operator Consumer -> Bi-Consumer Predicate -> Bi-Predicate Function -> Bi-Function, Unary Operator, Binary Operator The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing. There are also functional variants of the Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These variants accept primitive values as arguments. Other than these variants, there is also one more variant of the Consumer interface known as Bi-Consumer. Bi-Consumer – Bi-Consumer is the most exciting variant of the Consumer interface. The consumer interface takes only one argument, but on the other side, the Bi-Consumer interface takes two arguments. Both, Consumer and Bi-Consumer have no return value. It also returns noting just like the Consumer interface. It is used in iterating through the entries of the map. Syntax / Prototype of Consumer Functional Interface – Consumer<Integer> consumer = (value) -> System.out.println(value); This implementation of the Java Consumer functional interface prints the value passed as a parameter to the print statement. This implementation uses the Lambda function of Java. In scientific logic, a function that accepts an argument and, in return, generates a boolean value as an answer is known as a predicate. Similarly, in the java programming language, a predicate functional interface of java is a type of function which accepts a single value or argument and does some sort of processing on it, and returns a boolean (True/ False) answer. The implementation of the Predicate functional interface also encapsulates the logic of filtering (a process that is used to filter stream components on the base of a provided predicate) in Java. Just like the Consumer functional interface, Predicate functional interface also has some extensions. These are IntPredicate, DoublePredicate, and LongPredicate. These types of predicate functional interfaces accept only primitive data types or values as arguments. Bi-Predicate – Bi-Predicate is also an extension of the Predicate functional interface, which, instead of one, takes two arguments, does some processing, and returns the boolean value. Syntax of Predicate Functional Interface – public interface Predicate<T> { boolean test(T t); } The predicate functional interface can also be implemented using a class. The syntax for the implementation of predicate functional interface using a class is given below – public class CheckForNull implements Predicate { @Override public boolean test(Object o) { return o != null; } } The Java predicate functional interface can also be implemented using Lambda expressions. The example of implementation of Predicate functional interface is given below – Predicate predicate = (value) -> value != null; This implementation of functional interfaces in Java using Java Lambda expressions is more manageable and effective than the one implemented using a class as both the implementations are doing the same work, i.e., returning the same output. A function is a type of functional interface in Java that receives only a single argument and returns a value after the required processing. There are many versions of Function interfaces because a primitive type can’t imply a general type argument, so we need these versions of function interfaces. Many different versions of the function interfaces are instrumental and are commonly used in primitive types like double, int, long. The different sequences of these primitive types are also used in the argument. These versions are: Bi-Function – The Bi-Function is substantially related to a Function. Besides, it takes two arguments, whereas Function accepts one argument. The prototype and syntax of Bi-Function is given below – @FunctionalInterface public interface BiFunction<T, U, R> { R apply(T t, U u); ....... } In the above code of interface, T, U are the inputs, and there is only one output that is R. Unary Operator and Binary Operator – There are also two other functional interfaces which are named as Unary Operator and Binary Operator. They both extend the Function and Bi-Function, respectively. In simple words, Unary Operator extends Function, and Binary Operator extends Bi-Function. The prototype of the Unary Operator and Binary Operator is given below – 1. Unary Operator @FunctionalInterface public interface UnaryOperator<T> extends Function<T, U> { ......... } 2. Binary Operator @FunctionalInterface public interface BinaryOperator<T> extends BiFunction<T, U, R> { ......... } We can understand front the above example that the Unary Operator accepts only one argument and returns a single argument only. Still, in Unary Operator both the input and output values must be identical and of the same type. On the other way, Binary Operator takes two values and returns one value comparable to Bi- Function but similarly like Unary Operator, the input and output value type must be identical and of the same type. The Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output. This type of functional interface is generally used in the lazy generation of values. Supplier functional interfaces are also used for defining the logic for the generation of any sequence. For example – The logic behind the Fibonacci Series can be generated with the help of the Stream.generate method, which is implemented by the Supplier functional Interface. The different extensions of the Supplier functional interface hold many other supplier functions like BooleanSupplier, DoubleSupplier, LongSupplier, and IntSupplier. The return type of all these further specializations is their corresponding primitives only. Syntax / Prototype of Supplier Functional Interface is – @FunctionalInterface public interface Supplier<T>{ // gets a result ............. // returns the specific result ............ T.get(); } Java // A simple program to demonstrate the use// of predicate interface import java.util.*;import java.util.function.Predicate; class Test { public static void main(String args[]) { // create a list of strings List<String> names = Arrays.asList( "Geek", "GeeksQuiz", "g1", "QA", "Geek2"); // declare the predicate type as string and use // lambda expression to create object Predicate<String> p = (s) -> s.startsWith("G"); // Iterate through the list for (String st : names) { // call the test method if (p.test(st)) System.out.println(st); } }} Geek GeeksQuiz Geek2 Here are some significant points regarding Functional interfaces in Java: In functional interfaces, there is only one abstract method supported. If the annotation of a functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functional interface, that interface will not be called a functional interface. It is called a non-functional interface.There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional.An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods.Overriding methods from the parent class do not violate the rules of a functional interface in Java.The java.util.function package contains many built-in functional interfaces in Java 8. In functional interfaces, there is only one abstract method supported. If the annotation of a functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functional interface, that interface will not be called a functional interface. It is called a non-functional interface. There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional. An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods. Overriding methods from the parent class do not violate the rules of a functional interface in Java. The java.util.function package contains many built-in functional interfaces in Java 8. This article is contributed by Akash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. moshetrenk simmytarika5 nishkarshgandhi java-interfaces Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Singleton Class in Java Stream In Java Initializing a List in Java Different ways of Reading a text file in Java How to add an element to an Array in Java?
[ { "code": null, "e": 28950, "s": 28922, "text": "\n16 Jan, 2022" }, { "code": null, "e": 29505, "s": 28950, "text": "Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. There are no solely functions present in a programming language called Java. Functions in the Java programming language are part of a class, and if someone wants to use them, they have to use the class or object of the class to call any function." }, { "code": null, "e": 29890, "s": 29505, "text": "A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces. " }, { "code": null, "e": 30142, "s": 29890, "text": "Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM interfaces. Functional interfaces in Java are the new feature that provides users with the approach of fundamental programming. " }, { "code": null, "e": 30679, "s": 30142, "text": "Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. Functional interfaces are interfaces that ensure that they include precisely only one abstract method. Functional interfaces are used and executed by representing the interface with an annotation called @FunctionalInterface. As described earlier, functional interfaces can contain only one abstract method. However, they can include any quantity of default and static methods. " }, { "code": null, "e": 30952, "s": 30679, "text": "In Functional interfaces, there is no need to use the abstract keyword as it is optional to use the abstract keyword because, by default, the method defined inside the interface is abstract only. We can also call Lambda expressions as the instance of functional interface." }, { "code": null, "e": 31045, "s": 30952, "text": "Before Java 8, we had to create anonymous inner class objects or implement these interfaces." }, { "code": null, "e": 31050, "s": 31045, "text": "Java" }, { "code": "// Java program to demonstrate functional interface class Test { public static void main(String args[]) { // create anonymous inner class object new Thread(new Runnable() { @Override public void run() { System.out.println(\"New thread created\"); } }).start(); }}", "e": 31391, "s": 31050, "text": null }, { "code": null, "e": 31410, "s": 31391, "text": "New thread created" }, { "code": null, "e": 31505, "s": 31410, "text": "Java 8 onwards, we can assign lambda expression to its functional interface object like this: " }, { "code": null, "e": 31510, "s": 31505, "text": "Java" }, { "code": "// Java program to demonstrate Implementation of// functional interface using lambda expressions class Test { public static void main(String args[]) { // lambda expression to create the object new Thread(() -> { System.out.println(\"New thread created\"); }).start(); }}", "e": 31823, "s": 31510, "text": null }, { "code": null, "e": 31842, "s": 31823, "text": "New thread created" }, { "code": null, "e": 32145, "s": 31842, "text": "@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation." }, { "code": null, "e": 32150, "s": 32145, "text": "Java" }, { "code": "// Java program to demonstrate lambda expressions to// implement a user defined functional interface. @FunctionalInterface interface Square { int calculate(int x);} class Test { public static void main(String args[]) { int a = 5; // lambda expression to define the calculate method Square s = (int x) -> x * x; // parameter passed and return type must be // same as defined in the prototype int ans = s.calculate(a); System.out.println(ans); }}", "e": 32663, "s": 32150, "text": null }, { "code": null, "e": 32666, "s": 32663, "text": "25" }, { "code": null, "e": 32862, "s": 32666, "text": "Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows – " }, { "code": null, "e": 32921, "s": 32862, "text": "Runnable –> This interface only contains the run() method." }, { "code": null, "e": 32988, "s": 32921, "text": "Comparable –> This interface only contains the compareTo() method." }, { "code": null, "e": 33065, "s": 32988, "text": "ActionListener –> This interface only contains the actionPerformed() method." }, { "code": null, "e": 33125, "s": 33065, "text": "Callable –> This interface only contains the call() method." }, { "code": null, "e": 33241, "s": 33125, "text": "Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations. These are:" }, { "code": null, "e": 33276, "s": 33241, "text": "ConsumerPredicateFunction Supplier" }, { "code": null, "e": 33285, "s": 33276, "text": "Consumer" }, { "code": null, "e": 33295, "s": 33285, "text": "Predicate" }, { "code": null, "e": 33305, "s": 33295, "text": "Function " }, { "code": null, "e": 33314, "s": 33305, "text": "Supplier" }, { "code": null, "e": 33472, "s": 33314, "text": "Amidst the previous four interfaces, the first three interfaces,i.e., Consumer, Predicate, and Function, likewise have additions that are provided beneath – " }, { "code": null, "e": 33578, "s": 33472, "text": "Consumer -> Bi-ConsumerPredicate -> Bi-PredicateFunction -> Bi-Function, Unary Operator, Binary Operator " }, { "code": null, "e": 33602, "s": 33578, "text": "Consumer -> Bi-Consumer" }, { "code": null, "e": 33628, "s": 33602, "text": "Predicate -> Bi-Predicate" }, { "code": null, "e": 33686, "s": 33628, "text": "Function -> Bi-Function, Unary Operator, Binary Operator " }, { "code": null, "e": 34023, "s": 33686, "text": "The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing. There are also functional variants of the Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These variants accept primitive values as arguments. " }, { "code": null, "e": 34130, "s": 34023, "text": "Other than these variants, there is also one more variant of the Consumer interface known as Bi-Consumer. " }, { "code": null, "e": 34497, "s": 34130, "text": "Bi-Consumer – Bi-Consumer is the most exciting variant of the Consumer interface. The consumer interface takes only one argument, but on the other side, the Bi-Consumer interface takes two arguments. Both, Consumer and Bi-Consumer have no return value. It also returns noting just like the Consumer interface. It is used in iterating through the entries of the map. " }, { "code": null, "e": 34552, "s": 34497, "text": "Syntax / Prototype of Consumer Functional Interface – " }, { "code": null, "e": 34619, "s": 34552, "text": "Consumer<Integer> consumer = (value) -> System.out.println(value);" }, { "code": null, "e": 34798, "s": 34619, "text": "This implementation of the Java Consumer functional interface prints the value passed as a parameter to the print statement. This implementation uses the Lambda function of Java." }, { "code": null, "e": 35364, "s": 34798, "text": "In scientific logic, a function that accepts an argument and, in return, generates a boolean value as an answer is known as a predicate. Similarly, in the java programming language, a predicate functional interface of java is a type of function which accepts a single value or argument and does some sort of processing on it, and returns a boolean (True/ False) answer. The implementation of the Predicate functional interface also encapsulates the logic of filtering (a process that is used to filter stream components on the base of a provided predicate) in Java." }, { "code": null, "e": 35632, "s": 35364, "text": "Just like the Consumer functional interface, Predicate functional interface also has some extensions. These are IntPredicate, DoublePredicate, and LongPredicate. These types of predicate functional interfaces accept only primitive data types or values as arguments. " }, { "code": null, "e": 35817, "s": 35632, "text": "Bi-Predicate – Bi-Predicate is also an extension of the Predicate functional interface, which, instead of one, takes two arguments, does some processing, and returns the boolean value." }, { "code": null, "e": 35861, "s": 35817, "text": "Syntax of Predicate Functional Interface – " }, { "code": null, "e": 35922, "s": 35861, "text": "public interface Predicate<T> {\n \n boolean test(T t);\n \n}" }, { "code": null, "e": 36096, "s": 35922, "text": "The predicate functional interface can also be implemented using a class. The syntax for the implementation of predicate functional interface using a class is given below – " }, { "code": null, "e": 36235, "s": 36096, "text": "public class CheckForNull implements Predicate {\n \n @Override\n public boolean test(Object o) {\n \n return o != null;\n \n }\n}" }, { "code": null, "e": 36407, "s": 36235, "text": "The Java predicate functional interface can also be implemented using Lambda expressions. The example of implementation of Predicate functional interface is given below – " }, { "code": null, "e": 36455, "s": 36407, "text": "Predicate predicate = (value) -> value != null;" }, { "code": null, "e": 36696, "s": 36455, "text": "This implementation of functional interfaces in Java using Java Lambda expressions is more manageable and effective than the one implemented using a class as both the implementations are doing the same work, i.e., returning the same output." }, { "code": null, "e": 37209, "s": 36696, "text": "A function is a type of functional interface in Java that receives only a single argument and returns a value after the required processing. There are many versions of Function interfaces because a primitive type can’t imply a general type argument, so we need these versions of function interfaces. Many different versions of the function interfaces are instrumental and are commonly used in primitive types like double, int, long. The different sequences of these primitive types are also used in the argument." }, { "code": null, "e": 37229, "s": 37209, "text": "These versions are:" }, { "code": null, "e": 37372, "s": 37229, "text": "Bi-Function – The Bi-Function is substantially related to a Function. Besides, it takes two arguments, whereas Function accepts one argument. " }, { "code": null, "e": 37429, "s": 37372, "text": "The prototype and syntax of Bi-Function is given below –" }, { "code": null, "e": 37530, "s": 37429, "text": "@FunctionalInterface\npublic interface BiFunction<T, U, R> \n{\n \n R apply(T t, U u);\n .......\n \n}" }, { "code": null, "e": 37624, "s": 37530, "text": "In the above code of interface, T, U are the inputs, and there is only one output that is R. " }, { "code": null, "e": 37916, "s": 37624, "text": "Unary Operator and Binary Operator – There are also two other functional interfaces which are named as Unary Operator and Binary Operator. They both extend the Function and Bi-Function, respectively. In simple words, Unary Operator extends Function, and Binary Operator extends Bi-Function. " }, { "code": null, "e": 37989, "s": 37916, "text": "The prototype of the Unary Operator and Binary Operator is given below –" }, { "code": null, "e": 38007, "s": 37989, "text": "1. Unary Operator" }, { "code": null, "e": 38104, "s": 38007, "text": "@FunctionalInterface\npublic interface UnaryOperator<T> extends Function<T, U> \n{\n .........\n}" }, { "code": null, "e": 38124, "s": 38104, "text": " 2. Binary Operator" }, { "code": null, "e": 38227, "s": 38124, "text": "@FunctionalInterface\npublic interface BinaryOperator<T> extends BiFunction<T, U, R> \n{\n .........\n}" }, { "code": null, "e": 38454, "s": 38227, "text": "We can understand front the above example that the Unary Operator accepts only one argument and returns a single argument only. Still, in Unary Operator both the input and output values must be identical and of the same type. " }, { "code": null, "e": 38661, "s": 38454, "text": "On the other way, Binary Operator takes two values and returns one value comparable to Bi- Function but similarly like Unary Operator, the input and output value type must be identical and of the same type." }, { "code": null, "e": 39172, "s": 38661, "text": "The Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output. This type of functional interface is generally used in the lazy generation of values. Supplier functional interfaces are also used for defining the logic for the generation of any sequence. For example – The logic behind the Fibonacci Series can be generated with the help of the Stream.generate method, which is implemented by the Supplier functional Interface. " }, { "code": null, "e": 39432, "s": 39172, "text": "The different extensions of the Supplier functional interface hold many other supplier functions like BooleanSupplier, DoubleSupplier, LongSupplier, and IntSupplier. The return type of all these further specializations is their corresponding primitives only. " }, { "code": null, "e": 39489, "s": 39432, "text": "Syntax / Prototype of Supplier Functional Interface is –" }, { "code": null, "e": 39634, "s": 39489, "text": "@FunctionalInterface\npublic interface Supplier<T>{\n \n// gets a result\n.............\n \n// returns the specific result\n............\n \nT.get();\n \n}" }, { "code": null, "e": 39639, "s": 39634, "text": "Java" }, { "code": "// A simple program to demonstrate the use// of predicate interface import java.util.*;import java.util.function.Predicate; class Test { public static void main(String args[]) { // create a list of strings List<String> names = Arrays.asList( \"Geek\", \"GeeksQuiz\", \"g1\", \"QA\", \"Geek2\"); // declare the predicate type as string and use // lambda expression to create object Predicate<String> p = (s) -> s.startsWith(\"G\"); // Iterate through the list for (String st : names) { // call the test method if (p.test(st)) System.out.println(st); } }}", "e": 40302, "s": 39639, "text": null }, { "code": null, "e": 40323, "s": 40302, "text": "Geek\nGeeksQuiz\nGeek2" }, { "code": null, "e": 40397, "s": 40323, "text": "Here are some significant points regarding Functional interfaces in Java:" }, { "code": null, "e": 41387, "s": 40397, "text": "In functional interfaces, there is only one abstract method supported. If the annotation of a functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functional interface, that interface will not be called a functional interface. It is called a non-functional interface.There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional.An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods.Overriding methods from the parent class do not violate the rules of a functional interface in Java.The java.util.function package contains many built-in functional interfaces in Java 8." }, { "code": null, "e": 41811, "s": 41387, "text": "In functional interfaces, there is only one abstract method supported. If the annotation of a functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functional interface, that interface will not be called a functional interface. It is called a non-functional interface." }, { "code": null, "e": 41993, "s": 41811, "text": "There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional." }, { "code": null, "e": 42193, "s": 41993, "text": "An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods." }, { "code": null, "e": 42294, "s": 42193, "text": "Overriding methods from the parent class do not violate the rules of a functional interface in Java." }, { "code": null, "e": 42381, "s": 42294, "text": "The java.util.function package contains many built-in functional interfaces in Java 8." }, { "code": null, "e": 42800, "s": 42381, "text": "This article is contributed by Akash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 42811, "s": 42800, "text": "moshetrenk" }, { "code": null, "e": 42824, "s": 42811, "text": "simmytarika5" }, { "code": null, "e": 42840, "s": 42824, "text": "nishkarshgandhi" }, { "code": null, "e": 42856, "s": 42840, "text": "java-interfaces" }, { "code": null, "e": 42861, "s": 42856, "text": "Java" }, { "code": null, "e": 42866, "s": 42861, "text": "Java" }, { "code": null, "e": 42964, "s": 42866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43008, "s": 42964, "text": "Split() String method in Java with examples" }, { "code": null, "e": 43044, "s": 43008, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 43069, "s": 43044, "text": "Reverse a string in Java" }, { "code": null, "e": 43101, "s": 43069, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 43132, "s": 43101, "text": "How to iterate any Map in Java" }, { "code": null, "e": 43156, "s": 43132, "text": "Singleton Class in Java" }, { "code": null, "e": 43171, "s": 43156, "text": "Stream In Java" }, { "code": null, "e": 43199, "s": 43171, "text": "Initializing a List in Java" }, { "code": null, "e": 43245, "s": 43199, "text": "Different ways of Reading a text file in Java" } ]
Firebase - Environment Setup
In this chapter, we will show you how to add Firebase to the existing application. We will need NodeJS. Check the link from the following table, if you do not have it already. NodeJS and NPM NodeJS is the platform needed for Firebase development. Checkout our NodeJS Environment Setup. You can create a Firebase account here. You can create new app from the dashboard page. The following image shows the app we created. We can click the Manage App button to enter the app. You just need to create a folder where your app will be placed. Inside that folder, we will need index.html and index.js files. We will add Firebase to the header of our app. <html> <head> <script src = "https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script type = "text/javascript" src = "index.js"></script> </head> <body> </body> </html> If you want to use your existing app, you can use Firebase NPM or Bowers packages. Run one of the following command from your apps root folder. npm install firebase --save bower install firebase 60 Lectures 5 hours University Code 28 Lectures 2.5 hours Appeteria 85 Lectures 14.5 hours Appeteria 46 Lectures 2.5 hours Gautham Vijayan 13 Lectures 1.5 hours Nishant Kumar 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2342, "s": 2166, "text": "In this chapter, we will show you how to add Firebase to the existing application. We will need NodeJS. Check the link from the following table, if you do not have it already." }, { "code": null, "e": 2357, "s": 2342, "text": "NodeJS and NPM" }, { "code": null, "e": 2452, "s": 2357, "text": "NodeJS is the platform needed for Firebase development. Checkout our NodeJS Environment Setup." }, { "code": null, "e": 2492, "s": 2452, "text": "You can create a Firebase account here." }, { "code": null, "e": 2639, "s": 2492, "text": "You can create new app from the dashboard page. The following image shows the app we created. We can click the Manage App button to enter the app." }, { "code": null, "e": 2814, "s": 2639, "text": "You just need to create a folder where your app will be placed. Inside that folder, we will need index.html and index.js files. We will add Firebase to the header of our app." }, { "code": null, "e": 3025, "s": 2814, "text": "<html>\n <head>\n <script src = \"https://cdn.firebase.com/js/client/2.4.2/firebase.js\"></script>\n <script type = \"text/javascript\" src = \"index.js\"></script>\n </head>\n\t\n <body>\n\n </body>\n</html>" }, { "code": null, "e": 3169, "s": 3025, "text": "If you want to use your existing app, you can use Firebase NPM or Bowers packages. Run one of the following command from your apps root folder." }, { "code": null, "e": 3198, "s": 3169, "text": "npm install firebase --save\n" }, { "code": null, "e": 3222, "s": 3198, "text": "bower install firebase\n" }, { "code": null, "e": 3255, "s": 3222, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 3272, "s": 3255, "text": " University Code" }, { "code": null, "e": 3307, "s": 3272, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3318, "s": 3307, "text": " Appeteria" }, { "code": null, "e": 3354, "s": 3318, "text": "\n 85 Lectures \n 14.5 hours \n" }, { "code": null, "e": 3365, "s": 3354, "text": " Appeteria" }, { "code": null, "e": 3400, "s": 3365, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3417, "s": 3400, "text": " Gautham Vijayan" }, { "code": null, "e": 3452, "s": 3417, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3467, "s": 3452, "text": " Nishant Kumar" }, { "code": null, "e": 3503, "s": 3467, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 3518, "s": 3503, "text": " Rahul Agarwal" }, { "code": null, "e": 3525, "s": 3518, "text": " Print" }, { "code": null, "e": 3536, "s": 3525, "text": " Add Notes" } ]
SQLite - DELETE Query
SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows, otherwise all the records would be deleted. Following is the basic syntax of DELETE query with WHERE clause. DELETE FROM table_name WHERE [condition]; You can combine N number of conditions using AND or OR operators. Consider COMPANY table with the following records. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Following is an example, which will DELETE a customer whose ID is 7. sqlite> DELETE FROM COMPANY WHERE ID = 7; Now COMPANY table will have the following records. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE query, which will be as follows − sqlite> DELETE FROM COMPANY; Now, COMPANY table does not have any record as all the records have been deleted by DELETE statement. 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2827, "s": 2638, "text": "SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows, otherwise all the records would be deleted." }, { "code": null, "e": 2892, "s": 2827, "text": "Following is the basic syntax of DELETE query with WHERE clause." }, { "code": null, "e": 2935, "s": 2892, "text": "DELETE FROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 3001, "s": 2935, "text": "You can combine N number of conditions using AND or OR operators." }, { "code": null, "e": 3052, "s": 3001, "text": "Consider COMPANY table with the following records." }, { "code": null, "e": 3558, "s": 3052, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 3627, "s": 3558, "text": "Following is an example, which will DELETE a customer whose ID is 7." }, { "code": null, "e": 3669, "s": 3627, "text": "sqlite> DELETE FROM COMPANY WHERE ID = 7;" }, { "code": null, "e": 3720, "s": 3669, "text": "Now COMPANY table will have the following records." }, { "code": null, "e": 4170, "s": 3720, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0" }, { "code": null, "e": 4310, "s": 4170, "text": "If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE query, which will be as follows −" }, { "code": null, "e": 4339, "s": 4310, "text": "sqlite> DELETE FROM COMPANY;" }, { "code": null, "e": 4441, "s": 4339, "text": "Now, COMPANY table does not have any record as all the records have been deleted by DELETE statement." }, { "code": null, "e": 4476, "s": 4441, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4497, "s": 4476, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4530, "s": 4497, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4547, "s": 4530, "text": " Laurence Svekis" }, { "code": null, "e": 4578, "s": 4547, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 4591, "s": 4578, "text": " Vinay Kumar" }, { "code": null, "e": 4598, "s": 4591, "text": " Print" }, { "code": null, "e": 4609, "s": 4598, "text": " Add Notes" } ]
Push Down Automata
Theory of Computation The Pushdown Automata is investigated by Sheila Greibach. It is a part in theoretical computer science which employs a stack. It is called "pushed-down" as it works on the principal of stack i.e., Last In First Out. Always the operation is first performed on the top most element. The push down automata is less capable than a Turning Machine and more capable than a Finite State Machine. Pushdown automata machine recognizes best for a wider class of language. The context free language is language recognized by pushdown automata. This also plays an important role in determining the organization of computer programs being processed by a compiler. These are the following components of Pushdown automata - Input tape: The input tape is divided in many cells. The input head is read-only and may only move from left to right, each cell in turn. Finite control: The finite control has some pointer which focuses the current symbol which is to be read. Stack: In stack, elements are inserted and removed from only one end. In PDA, the stack is utilized to store the items temporarily. The formal definition of a Pushdown Automata is defined as - (Q,Σ,Γ,δ,q0,Z0,F) Q- It is the finite set of states, Σ - finite set of input alphabet, Γ - finite set of stack alphabet, δ - transition function, Q x (Σ ∪ ∈) x Γ x Q x Γ* q0 - start state, Z0 - initial pushdown symbol, F - the set of finite state. These are the some symbols used for connecting pairs of ID's. The Instantaneous description is called as an informal notation, and clarifies how a Push down automata (PDA) computes a given input string and makes a decision whether that string is accepted or rejected. The instantaneous description of Pushdown Automata is represented by - (q,w,s) q - current state, w - unconsumed part or remaining input, s - stack contents, top at the left. Here is the example of Pushdown Automata - where δu000e contains the following transitions -
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 501, "s": 112, "text": "The Pushdown Automata is investigated by Sheila Greibach. It is a part in theoretical computer science which employs a stack. It is called \"pushed-down\" as it works on the principal of stack i.e., Last In First Out. Always the operation is first performed on the top most element. The push down automata is less capable than a Turning Machine and more capable than a Finite State Machine." }, { "code": null, "e": 763, "s": 501, "text": "Pushdown automata machine recognizes best for a wider class of language. The context free language is language recognized by pushdown automata. This also plays an important role in determining the organization of computer programs being processed by a compiler." }, { "code": null, "e": 821, "s": 763, "text": "These are the following components of Pushdown automata -" }, { "code": null, "e": 959, "s": 821, "text": "Input tape: The input tape is divided in many cells. The input head is read-only and may only move from left to right, each cell in turn." }, { "code": null, "e": 1065, "s": 959, "text": "Finite control: The finite control has some pointer which focuses the current symbol which is to be read." }, { "code": null, "e": 1197, "s": 1065, "text": "Stack: In stack, elements are inserted and removed from only one end. In PDA, the stack is utilized to store the items temporarily." }, { "code": null, "e": 1258, "s": 1197, "text": "The formal definition of a Pushdown Automata is defined as -" }, { "code": null, "e": 1276, "s": 1258, "text": "(Q,Σ,Γ,δ,q0,Z0,F)" }, { "code": null, "e": 1506, "s": 1276, "text": "Q- It is the finite set of states, Σ - finite set of input alphabet, Γ - finite set of stack alphabet, δ - transition function, Q x (Σ ∪ ∈) x Γ x Q x Γ* q0 - start state, Z0 - initial pushdown symbol, F - the set of finite state." }, { "code": null, "e": 1568, "s": 1506, "text": "These are the some symbols used for connecting pairs of ID's." }, { "code": null, "e": 1845, "s": 1568, "text": "The Instantaneous description is called as an informal notation, and clarifies how a Push down automata (PDA) computes a given input string and makes a decision whether that string is accepted or rejected. The instantaneous description of Pushdown Automata is represented by -" }, { "code": null, "e": 1853, "s": 1845, "text": "(q,w,s)" }, { "code": null, "e": 1950, "s": 1853, "text": "q - current state, w - unconsumed part or remaining input, s - stack contents, top at the left. " }, { "code": null, "e": 1993, "s": 1950, "text": "Here is the example of Pushdown Automata -" } ]
MySQL - WHERE Clause
We have seen the SQL SELECT command to fetch data from a MySQL table. We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table. The following code block has a generic SQL syntax of the SELECT command with the WHERE clause to fetch data from the MySQL table − SELECT field1, field2,...fieldN table_name1, table_name2... [WHERE condition1 [AND [OR]] condition2..... You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command. You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command. You can specify any condition using the WHERE clause. You can specify any condition using the WHERE clause. You can specify more than one condition using the AND or the OR operators. You can specify more than one condition using the AND or the OR operators. A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition. A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition. The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row. Here is the list of operators, which can be used with the WHERE clause. Assume field A holds 10 and field B holds 20, then − The WHERE clause is very useful when you want to fetch the selected rows from a table, especially when you use the MySQL Join. Joins are discussed in another chapter. It is a common practice to search for records using the Primary Key to make the search faster. If the given condition does not match any record in the table, then the query would not return any row. This will use the SQL SELECT command with the WHERE clause to fetch the selected data from the MySQL table – tutorials_tbl. The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay. root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl WHERE tutorial_author = 'Sanjay'; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 1 rows in set (0.01 sec) mysql> Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl \ WHERE BINARY tutorial_author = 'sanjay'; Empty set (0.02 sec) mysql> PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using where clause. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli->query($sql,$resultmode) $sql Required - SQL query to select records in a MySQL table using Where Clause. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. Try the following example to select a record using where clause in a table − Copy and paste the following example as mysql_example.php − <html> <head> <title>Using Where Clause</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s<br />", $mysqli->connect_error); exit(); } printf('Connected successfully.<br />'); $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author = "Mahesh"'; $result = $mysqli->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli->close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script. Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2592, "s": 2333, "text": "We have seen the SQL SELECT command to fetch data from a MySQL table. We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table." }, { "code": null, "e": 2723, "s": 2592, "text": "The following code block has a generic SQL syntax of the SELECT command with the WHERE clause to fetch data from the MySQL table −" }, { "code": null, "e": 2829, "s": 2723, "text": "SELECT field1, field2,...fieldN table_name1, table_name2...\n[WHERE condition1 [AND [OR]] condition2.....\n" }, { "code": null, "e": 2997, "s": 2829, "text": "You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command." }, { "code": null, "e": 3165, "s": 2997, "text": "You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command." }, { "code": null, "e": 3219, "s": 3165, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3273, "s": 3219, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3348, "s": 3273, "text": "You can specify more than one condition using the AND or the OR operators." }, { "code": null, "e": 3423, "s": 3348, "text": "You can specify more than one condition using the AND or the OR operators." }, { "code": null, "e": 3519, "s": 3423, "text": "A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition." }, { "code": null, "e": 3615, "s": 3519, "text": "A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition." }, { "code": null, "e": 3900, "s": 3615, "text": "The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row." }, { "code": null, "e": 3972, "s": 3900, "text": "Here is the list of operators, which can be used with the WHERE clause." }, { "code": null, "e": 4025, "s": 3972, "text": "Assume field A holds 10 and field B holds 20, then −" }, { "code": null, "e": 4192, "s": 4025, "text": "The WHERE clause is very useful when you want to fetch the selected rows from a table, especially when you use the MySQL Join. Joins are discussed in another chapter." }, { "code": null, "e": 4287, "s": 4192, "text": "It is a common practice to search for records using the Primary Key to make the search faster." }, { "code": null, "e": 4391, "s": 4287, "text": "If the given condition does not match any record in the table, then the query would not return any row." }, { "code": null, "e": 4515, "s": 4391, "text": "This will use the SQL SELECT command with the WHERE clause to fetch the selected data from the MySQL table – tutorials_tbl." }, { "code": null, "e": 4631, "s": 4515, "text": "The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay." }, { "code": null, "e": 5184, "s": 4631, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl WHERE tutorial_author = 'Sanjay';\n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 3 | JAVA Tutorial | Sanjay | 2007-05-21 | \n+-------------+----------------+-----------------+-----------------+\n1 rows in set (0.01 sec)\n\nmysql>" }, { "code": null, "e": 5352, "s": 5184, "text": "Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows −" }, { "code": null, "e": 5562, "s": 5352, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl \\\n WHERE BINARY tutorial_author = 'sanjay';\nEmpty set (0.02 sec)\n\nmysql>" }, { "code": null, "e": 5751, "s": 5562, "text": "PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using where clause. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 5785, "s": 5751, "text": "$mysqli->query($sql,$resultmode)\n" }, { "code": null, "e": 5790, "s": 5785, "text": "$sql" }, { "code": null, "e": 5866, "s": 5790, "text": "Required - SQL query to select records in a MySQL table using Where Clause." }, { "code": null, "e": 5878, "s": 5866, "text": "$resultmode" }, { "code": null, "e": 6026, "s": 5878, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 6103, "s": 6026, "text": "Try the following example to select a record using where clause in a table −" }, { "code": null, "e": 6163, "s": 6103, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 7387, "s": 6163, "text": "<html>\n <head>\n <title>Using Where Clause</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date \n FROM tutorials_tbl where tutorial_author = \"Mahesh\"';\n\t\t \n $result = $mysqli->query($sql);\n \n if ($result->num_rows > 0) {\n while($row = $result->fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli->close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 7552, "s": 7387, "text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script." }, { "code": null, "e": 7745, "s": 7552, "text": "Connected successfully.\nId: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021\nId: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021\nId: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021\n" }, { "code": null, "e": 7778, "s": 7745, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 7806, "s": 7778, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7841, "s": 7806, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7858, "s": 7841, "text": " Frahaan Hussain" }, { "code": null, "e": 7892, "s": 7858, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7927, "s": 7892, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 7961, "s": 7927, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 7989, "s": 7961, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8022, "s": 7989, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8042, "s": 8022, "text": " Harshit Srivastava" }, { "code": null, "e": 8075, "s": 8042, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 8093, "s": 8075, "text": " Trevoir Williams" }, { "code": null, "e": 8100, "s": 8093, "text": " Print" }, { "code": null, "e": 8111, "s": 8100, "text": " Add Notes" } ]
C# program to sort an array in descending order
Initialize the array. int[] myArr = new int[5] {98, 76, 99, 32, 77}; Compare the first element in the array with the next element to find the largest element, then the second largest, etc. if(myArr[i] < myArr[j]) { temp = myArr[i]; myArr[i] = myArr[j]; myArr[j] = temp; } Above, i and j are initially set to. i=0; j=i+1; Try to run the following code to sort an array in descending order. Live Demo using System; public class Demo { public static void Main() { int[] myArr = new int[5] {98, 76, 99, 32, 77}; int i, j, temp; Console.Write("Elements: \n"); for(i=0;i<5;i++) { Console.Write("{0} ",myArr[i]); } for(i=0; i<5; i++) { for(j=i+1; j<5; j++) { if(myArr[i] < myArr[j]) { temp = myArr[i]; myArr[i] = myArr[j]; myArr[j] = temp; } } } Console.Write("\nDescending order:\n"); for(i=0; i<5; i++) { Console.Write("{0} ", myArr[i]); } Console.Write("\n\n"); } } Elements: 98 76 99 32 77 Descending order: 99 98 77 76 32
[ { "code": null, "e": 1084, "s": 1062, "text": "Initialize the array." }, { "code": null, "e": 1131, "s": 1084, "text": "int[] myArr = new int[5] {98, 76, 99, 32, 77};" }, { "code": null, "e": 1251, "s": 1131, "text": "Compare the first element in the array with the next element to find the largest element, then the second largest, etc." }, { "code": null, "e": 1343, "s": 1251, "text": "if(myArr[i] < myArr[j]) {\n temp = myArr[i];\n myArr[i] = myArr[j];\n myArr[j] = temp;\n}" }, { "code": null, "e": 1380, "s": 1343, "text": "Above, i and j are initially set to." }, { "code": null, "e": 1392, "s": 1380, "text": "i=0;\nj=i+1;" }, { "code": null, "e": 1460, "s": 1392, "text": "Try to run the following code to sort an array in descending order." }, { "code": null, "e": 1471, "s": 1460, "text": " Live Demo" }, { "code": null, "e": 2111, "s": 1471, "text": "using System;\npublic class Demo {\n public static void Main() {\n int[] myArr = new int[5] {98, 76, 99, 32, 77};\n int i, j, temp;\n Console.Write(\"Elements: \\n\");\n for(i=0;i<5;i++) {\n Console.Write(\"{0} \",myArr[i]);\n }\n for(i=0; i<5; i++) {\n for(j=i+1; j<5; j++) {\n if(myArr[i] < myArr[j]) {\n temp = myArr[i];\n myArr[i] = myArr[j];\n myArr[j] = temp;\n }\n }\n }\n Console.Write(\"\\nDescending order:\\n\");\n for(i=0; i<5; i++) {\n Console.Write(\"{0} \", myArr[i]);\n }\n Console.Write(\"\\n\\n\");\n }\n}" }, { "code": null, "e": 2169, "s": 2111, "text": "Elements:\n98 76 99 32 77\nDescending order:\n99 98 77 76 32" } ]
StyleGAN v2: notes on training and latent space exploration | by 5agado | Towards Data Science
What: in this entry I’m going to present notes, thoughts and experimental results I collected while training multiple StyleGAN models and exploring the learned latent space. Why: this is a dump of ideas/considerations that can range from the obvious to the “ holy moly”, meant to possibly provide insight — or starting point for discussions — for other people out there with similar interests and intents. As such it can be skimmed through to see if anything is of interest. I’m also here heavily leveraging Cunningham’s Law. Who: many considerations apply to both StyleGAN v1 and v2, but all generated results are from v2 models, unless explicitly specified. In term of code resources: StyleGAN v1 and v2 official repos Encoder for v1 (+ directions learning) and encoder for v2 All of the content here has been generated on top of such repos via my customized Jupyter notebooks. Worth mentioning people who diligently shared code, experiments and valuable suggestions: Gwern (TWDNE), pbaylies, gpt2ent, xsteenbrugge, Veqtor, Norod78, roadrunner01. All more than worth following. For a custom dataset, a set of images needs to be created beforehand making sure that all entries have the same square-shape and color space. You can then generate the tf-records as explained here. As it has been pointed out many times, the model is very data-hungry. Dataset size requirements vary greatly based on image content, but in general aim at 4 to 5 orders of magnitude, say around 50k with mirroring and double without. This applies to training from scratch, while in case of fine-tuning there have been many experiments done on very small datasets, providing interesting results. I experimented mainly with two “fashion” datasets dresses (~30k packshot images) footwear (~140k packshot images) But will also showcase some experiments on manually curated artistic dataset (~1k images each). Notice the higher content consistency of the fashion datasets (in terms of location, background, etc.). compared to the artistic entries. As such, irregardless of dataset size, we expect to be able to reach higher generation accuracy for the former. Dresses images are a case where mirror augment should be enabled, as we can double our training set for free, learning the semantic invariant property of dresses for horizontal mirroring. Footwear is instead a case where mirroring should be disabled, as all images in the dataset are aligned, and learning mirrored versions would just be an unnecessary burden for the network. Regarding size, I opted for 512 to first validate the results. From previous experiments with other networks I believe this is a good resolution for capturing patterns, material texture and small details like buttons and zippers. I also plan a future iteration on 256, and validate the quality of the learned representations and comparison with the training regime. I suggest moving to full 1024 resolution (or above) just if you have the proper hardware resources and have validated your dataset already against smaller resolutions. One can train a model from scratch, or piggyback on previous trained results, fine-tuning the learned representation to a new dataset. Training from scratch is as simple as running the following python run_training.py -num-gpus=2 -data-dir=<your_data_dir> -config=config-f -dataset=<your_dataset_name> -mirror-augment=True -result-dir=<your_results_dir> We already talked about the mirror-augment and the number of GPUs simply depends on your setup. Configurations are used to control the architecture and properties of the model, starting from config-a (the original SyleGAN v1), and incrementally adding/changing components (weight demodulation, lazy regularization, path length regularization) to config-e (the full updated setup for v2), plus config-f, a larger network version of config-e and the default used in the paper.I opted on config-e for my 512 size datasets. The complexity added in config-f was mostly motivated by the information bottleneck noticed while exploring the implicit focus of the network on higher resolutions while training, so my rationale was that the added complexity would just be more detrimental in terms of training stability. Fine-tuning is used to save time, relying on the structure already learned by a previous model, and trying to adapt such structure to a new target dataset. I have also seen people fine-tuning using images not entirely related to the original dataset, so that’s a lot up to your goals. Fine-tuning gives quicker visual feedback on training quality, so it is easier to run multiple iterations and experiments, making it a great way to initially learn more about model behavior and hyperparameters. To fine-tune an existing network one needs to specify the snapshot to restart from. For v2 this is done in run_training.py, by adding and adapting the following train.resume_pkl = "your_network_snapshot.pkl" # Network pickle to resume training from, None = train from scratch.train.resume_kimg = 0.0 # Assumed training progress at the beginning. Affects reporting and training schedule.train.resume_time = 0.0 # Assumed wallclock time at the beginning. Affects reporting. Notice how it is important to specify also the resume_kimg in accordance with your snapshot, as this is used to control the training schedule (e.g. learning rate decay). While training the primary metric I am looking at is the Frechet Inception Distance (FID), which by default is computed every 50 training ticks on 50k images. Other metrics can be called as described in the repo README. Notice that Tensorflow logs are generated in the target destination dir and can be accessed by running tensorboard tensorboard --logdir <LOGS_TARGET_DIR> Apart from FID you can here inspect scores/fake and scores/real, which is the discriminator prediction for fake and real images respectively. As the label can be misleading at first, it is worth pointing out again that these are not loss values, but the pure prediction output of the discriminator. I try to gain some guidance from such graphs, but find it often hard to extract precise insight on how the network is doing. Ideally one would like the discriminator to be unable to distinguish fake from real, and as such tending toward zero, as it is just random guessing.Other secondary metrics are present, also based on the loss choice. For example, by default the discriminator uses logistic loss with R1 regularizer, providing a plot for the gradient penalty. For my datasets, FID nicely mapped to personal perceived image quality, but as the metric is computed based on summary statistics comparison between features extracted from an inception v3 model, it might be uninformative for other types of datasets, especially the more the metric value tends to zero.I still suggest to avoid visual comparison across short training periods, as our subjective approximate judgment can often be biased by the specific examples we look at or even by the noise contribution alone, and the network might be improving despite no discernible change in the fake samples. On the other hand, via visual inspection, one can easily spot issues like mode collapse, as illustrated in the following fake samples generated for the Mucha dataset. This an example of partial mode collapse, where the generator is reduced to generate just a few examples, losing in terms of variety. A prominent cause for this might have been the small size of the dataset, plus common duplicates entries. See instead the following sample for Franzetta art, especially in relation to the training curves. While some entries might give the impression of mode collapse, it is instead more likely just the fault of way too many duplicates in the training dataset for that specific example. A decent dataset should generally provide a nice training curve following a Pareto distribution. The official README specifies training times for different configurations, but as said you will obtain most of the improvements during the very first part of your training; the tricky and tedious part is trying to reach the finer quality details. Plateau is a common situation, where the model is subject to little or no improvement. Another possible but less common behavior is divergence or explosion, where after an initial step improvement the model starts deteriorating and exponentially degenerated to pure noise results. The action to take for such situations is to retrain from a previous checkpoint (as explained in the previous fine-tuning section), reasonably tweaking the hyperparameters according to the recognized problem. As often mentioned, this is an art by itself, and strongly based on intuition, experience and luck.Many possibilities are available, depending on goals, model status, etc.. Here some of the most common suggestions, accompanied by some empirical notes. dataset, as usual if your dataset has clear deficits in terms of size or noise, put some effort into fixing those instead of risking to waste time on model tuning learning-rate (lr), here you can decrease lr for potential more stable (but slow) training progress. You can also tweak the lr of discriminator and generator individually, based on the unbalance that might be present in your architecture between the two components. In this regard, Shawn Presser pointed out on Twitter that v2 has actually a bug, for which the generator lr value is incorrectly used as the discriminator lr. Be sure to patch this part before experimenting with G/D lr balance.I tried to increase lr, just for the laughs, and it always ended up with quick and abrupt divergence. batch size, increasing batch size can also provide a more stable training or breakthrough from a local minimum. This is based on the idea that as more predictions are used to compute the gradient, the more accurate the weights update and training direction will be. Multiple experiments I run with bigger minibatch forced a good point percentage increase in FID50k, but some of these became soon unstable and exploded. Also, be aware of memory constraints for your setup, v2 is more expensive, and training on 1024 resolution requires a GPU with at least 16 GB of memory.It is worth pointing out that StyleGAN has two different parameters for batch size, minibatch_size_base and minibatch_gpu_base . The former is the actual maximum minibatch size to use, while the latter is the size as processed at a time by a single GPU. This implies that the two parameters need to be adjusted according to the number of GPUs of your setup, as gradients are accumulated until the base minibatch size is reached. Regarding these aspects, I want to suggest again Gwern StyleGAN v1 post, as it provides in-depth details and references, and three additional excellent papers if you want to explore GAN-training further: Stabilizing Generative Adversarial Network Training: A Survey (2019), Which Training Methods for GANs do actually Converge? (2018), Improved Techniques for Training GANs (2016). Some behaviors still puzzle me, like what causes this change in loss scores after I restart training from a previous checkpoint (same config). Above some examples of latent space exploration for my dresses and footwear models. The idea is just to generate N sample vectors (drawn from a Gaussian distribution) and transition between them sequentially using whatever preferred transition function. In my case here this function is just a linear interpolation done on a fixed frames number (equivalent to morphing). Notice that we are relying on the very initial latent vector z. This means that we are using the StyleGAN mapping network to first generate the latent vector w, and then using w to synthesize a new image. For this reason, we can rely on the truncation trick, and discard areas of the latent space poorly represented. We want to specify how much the generated intermediate vector w has to stay close to the average (computed based on random inputs to the mapping network). ψ (psi) value scales the deviation of w from the average, and as such can be tweaked for quality/variety trade-offs. ψ=1 is equivalent to no truncation (original w), while values towards 0 gets us closer to the average, with quality improvement but a reduction in terms of variety. We often want to be able to obtain the code/latent-vector/embedding of real images with regards to a target model, in other words: what is the input value I should feed to my model to generate the best approximation of my image. In general, there are two methods for this: pass image through the encoder component of the network optimize latent (using gradient descent) The former provides a fast solution but has problems generalizing outside of the training dataset, and unfortunately for us, it doesn’t come out of the box with a vanilla StyleGAN. The architecture simply doesn’t learn an explicit encoding function. We are left with latent optimization option using perceptual loss. We extract high-level features (e.g. from a pre-trained model like VGG) for the reference and generated images, compute the distance between them and optimize on the latent representation (our target code). The initialization of this target code is a very important aspect for efficiency and effectiveness. The easiest way is simple random initialization, but a lot can be done to improve on this, for example by learning an explicit encoding function from images to latent. The idea is to randomly generate a set of N examples and store both the resulting image and the code that generated it. We can then train a model (e.g. ResNet) on this data, and use it to initialize our latent before the actual StyleGAN encoding process. See this rich discussion regarding improved initialization. Encoder for v1 and Encoder for v2 provide code and step-by-step guide for this operation. I also suggest the following two papers: Image2StyleGAN and Image2StyleGAN++, which give a good overview of encoding images for Stylegan, with considerations about initialization options and latent space quality, plus an analysis of image editing operations like morphing and style mixing. StyleGAN uses a mapping network (eight fully connected layers) to convert the input noise (z) to an intermediate latent vector (w). Both are of size 512, but the intermediate vector is replicated for each style layer. For a network trained on 1024 size images, this intermediate vector will then be of shape (512, 18), for 512 size it will be (512, 16). The encoding process is generally done on this intermediate vector, and as such one can decide whether to optimize for w(1) (meaning only one 512 layers, which is then tiled as necessary to each style layer) or the whole w(N). The official projector operated the former, while adaptations often rely on optimizing all w entries individually, for visual fidelity. Regarding this topic see also this Twitter thread. Even more noticeable and goliardic when projecting reference not proper of the model training distribution, like in the following example projecting a dress image for the FFHQ model. In general, one can always notice that for high resolutions the projector seems to fail to match fine details of the reference picture, but this is most likely a consequence of using a resolution of 256x256 for the perceptual loss, as demonstrated in this thread. The StyleGAN improvements on latent space disentanglement allow to explore single attributes of the dataset in a pleasing, orthogonal way (meaning without affecting other attributes).While discriminative models learn boundaries to separate target attributes (e.g. male/female, smile/not-smile, cat/dog) what we are interested here is to cross those boundaries, moving perpendicularly to them. For example, if I start from a sad face I can slowly but steadily move to a smiling version of the same face. This should already provide a hint on how to learn new directions. We first collect multiple samples (image + latent) from our model and manually classify the images for our target attribute (e.g. smiling VS not smiling), trying to guarantee proper class representation balance. We then train a model to classify or regress on our latents and manual labels. At this point we can use the learned functions of these support models as transition directions. Robert Luxemburg shared the learned direction for the official FFHQ model. StyleGAN2 Distillation for Feed-forward Image Manipulation is a very recent paper exploring direction manipulation via a “student” image-to-image network trained on unpaired dataset generated via StyleGAN. The paper aims to overcome the encoding performance-bottleneck and learn a transformation function than can be efficiently applied to real-world images. A lot of my experiments have initially been motivated by evaluating how good is the latent space learned by a StyleGAN model (representation learning), and how performant the obtained embedding can be for downstream tasks (e.g. image classification via linear models). From one side I will keep working on this kind of evaluation, trying to cover also other generative models types, like autoregressive and flow-based models. I’m also interested in pursuing the exploration of such models for the pure image-synthesis capabilities, and the increasing potential for effective semantic mixing and editing, especially in relation to my passion for drawing, digital painting and animation. Automated lineart colorization, animating paintings, frames interpolation are some awesome free utils already out there, but there is so much more that can be done for assisted drawing, especially from a more semantic point of view. There is also plenty of room for practical improvements: generalization capabilities, speeding up inference time, training optimization and transfer learning. Down the line, I also want to go beyond the pure 2-dimensional canvas, and learn more about the amazing things already achieved in the 3D graphics realm. Denoising is something I now frequently rely on, differentiable rendering just blew my mind and to close the loop, back again to GAN for continuous 3D shape generation. Quoting research scientist Károly Zsolnai-Fehér “What a time to be alive” You can check out my code on Github, follow more of my experiments and explanations on Twitter and see my graphics results on Instagram. Disclaimer: at the moment I cannot share datasets and trained models. Apologies.
[ { "code": null, "e": 346, "s": 172, "text": "What: in this entry I’m going to present notes, thoughts and experimental results I collected while training multiple StyleGAN models and exploring the learned latent space." }, { "code": null, "e": 647, "s": 346, "text": "Why: this is a dump of ideas/considerations that can range from the obvious to the “ holy moly”, meant to possibly provide insight — or starting point for discussions — for other people out there with similar interests and intents. As such it can be skimmed through to see if anything is of interest." }, { "code": null, "e": 698, "s": 647, "text": "I’m also here heavily leveraging Cunningham’s Law." }, { "code": null, "e": 832, "s": 698, "text": "Who: many considerations apply to both StyleGAN v1 and v2, but all generated results are from v2 models, unless explicitly specified." }, { "code": null, "e": 859, "s": 832, "text": "In term of code resources:" }, { "code": null, "e": 893, "s": 859, "text": "StyleGAN v1 and v2 official repos" }, { "code": null, "e": 951, "s": 893, "text": "Encoder for v1 (+ directions learning) and encoder for v2" }, { "code": null, "e": 1052, "s": 951, "text": "All of the content here has been generated on top of such repos via my customized Jupyter notebooks." }, { "code": null, "e": 1252, "s": 1052, "text": "Worth mentioning people who diligently shared code, experiments and valuable suggestions: Gwern (TWDNE), pbaylies, gpt2ent, xsteenbrugge, Veqtor, Norod78, roadrunner01. All more than worth following." }, { "code": null, "e": 1844, "s": 1252, "text": "For a custom dataset, a set of images needs to be created beforehand making sure that all entries have the same square-shape and color space. You can then generate the tf-records as explained here. As it has been pointed out many times, the model is very data-hungry. Dataset size requirements vary greatly based on image content, but in general aim at 4 to 5 orders of magnitude, say around 50k with mirroring and double without. This applies to training from scratch, while in case of fine-tuning there have been many experiments done on very small datasets, providing interesting results." }, { "code": null, "e": 1894, "s": 1844, "text": "I experimented mainly with two “fashion” datasets" }, { "code": null, "e": 1925, "s": 1894, "text": "dresses (~30k packshot images)" }, { "code": null, "e": 1958, "s": 1925, "text": "footwear (~140k packshot images)" }, { "code": null, "e": 2054, "s": 1958, "text": "But will also showcase some experiments on manually curated artistic dataset (~1k images each)." }, { "code": null, "e": 2304, "s": 2054, "text": "Notice the higher content consistency of the fashion datasets (in terms of location, background, etc.). compared to the artistic entries. As such, irregardless of dataset size, we expect to be able to reach higher generation accuracy for the former." }, { "code": null, "e": 2492, "s": 2304, "text": "Dresses images are a case where mirror augment should be enabled, as we can double our training set for free, learning the semantic invariant property of dresses for horizontal mirroring." }, { "code": null, "e": 2681, "s": 2492, "text": "Footwear is instead a case where mirroring should be disabled, as all images in the dataset are aligned, and learning mirrored versions would just be an unnecessary burden for the network." }, { "code": null, "e": 3215, "s": 2681, "text": "Regarding size, I opted for 512 to first validate the results. From previous experiments with other networks I believe this is a good resolution for capturing patterns, material texture and small details like buttons and zippers. I also plan a future iteration on 256, and validate the quality of the learned representations and comparison with the training regime. I suggest moving to full 1024 resolution (or above) just if you have the proper hardware resources and have validated your dataset already against smaller resolutions." }, { "code": null, "e": 3350, "s": 3215, "text": "One can train a model from scratch, or piggyback on previous trained results, fine-tuning the learned representation to a new dataset." }, { "code": null, "e": 3410, "s": 3350, "text": "Training from scratch is as simple as running the following" }, { "code": null, "e": 3569, "s": 3410, "text": "python run_training.py -num-gpus=2 -data-dir=<your_data_dir> -config=config-f -dataset=<your_dataset_name> -mirror-augment=True -result-dir=<your_results_dir>" }, { "code": null, "e": 3665, "s": 3569, "text": "We already talked about the mirror-augment and the number of GPUs simply depends on your setup." }, { "code": null, "e": 4378, "s": 3665, "text": "Configurations are used to control the architecture and properties of the model, starting from config-a (the original SyleGAN v1), and incrementally adding/changing components (weight demodulation, lazy regularization, path length regularization) to config-e (the full updated setup for v2), plus config-f, a larger network version of config-e and the default used in the paper.I opted on config-e for my 512 size datasets. The complexity added in config-f was mostly motivated by the information bottleneck noticed while exploring the implicit focus of the network on higher resolutions while training, so my rationale was that the added complexity would just be more detrimental in terms of training stability." }, { "code": null, "e": 4874, "s": 4378, "text": "Fine-tuning is used to save time, relying on the structure already learned by a previous model, and trying to adapt such structure to a new target dataset. I have also seen people fine-tuning using images not entirely related to the original dataset, so that’s a lot up to your goals. Fine-tuning gives quicker visual feedback on training quality, so it is easier to run multiple iterations and experiments, making it a great way to initially learn more about model behavior and hyperparameters." }, { "code": null, "e": 5035, "s": 4874, "text": "To fine-tune an existing network one needs to specify the snapshot to restart from. For v2 this is done in run_training.py, by adding and adapting the following" }, { "code": null, "e": 5349, "s": 5035, "text": "train.resume_pkl = \"your_network_snapshot.pkl\" # Network pickle to resume training from, None = train from scratch.train.resume_kimg = 0.0 # Assumed training progress at the beginning. Affects reporting and training schedule.train.resume_time = 0.0 # Assumed wallclock time at the beginning. Affects reporting." }, { "code": null, "e": 5519, "s": 5349, "text": "Notice how it is important to specify also the resume_kimg in accordance with your snapshot, as this is used to control the training schedule (e.g. learning rate decay)." }, { "code": null, "e": 5854, "s": 5519, "text": "While training the primary metric I am looking at is the Frechet Inception Distance (FID), which by default is computed every 50 training ticks on 50k images. Other metrics can be called as described in the repo README. Notice that Tensorflow logs are generated in the target destination dir and can be accessed by running tensorboard" }, { "code": null, "e": 5893, "s": 5854, "text": "tensorboard --logdir <LOGS_TARGET_DIR>" }, { "code": null, "e": 6192, "s": 5893, "text": "Apart from FID you can here inspect scores/fake and scores/real, which is the discriminator prediction for fake and real images respectively. As the label can be misleading at first, it is worth pointing out again that these are not loss values, but the pure prediction output of the discriminator." }, { "code": null, "e": 6658, "s": 6192, "text": "I try to gain some guidance from such graphs, but find it often hard to extract precise insight on how the network is doing. Ideally one would like the discriminator to be unable to distinguish fake from real, and as such tending toward zero, as it is just random guessing.Other secondary metrics are present, also based on the loss choice. For example, by default the discriminator uses logistic loss with R1 regularizer, providing a plot for the gradient penalty." }, { "code": null, "e": 7256, "s": 6658, "text": "For my datasets, FID nicely mapped to personal perceived image quality, but as the metric is computed based on summary statistics comparison between features extracted from an inception v3 model, it might be uninformative for other types of datasets, especially the more the metric value tends to zero.I still suggest to avoid visual comparison across short training periods, as our subjective approximate judgment can often be biased by the specific examples we look at or even by the noise contribution alone, and the network might be improving despite no discernible change in the fake samples." }, { "code": null, "e": 7423, "s": 7256, "text": "On the other hand, via visual inspection, one can easily spot issues like mode collapse, as illustrated in the following fake samples generated for the Mucha dataset." }, { "code": null, "e": 7663, "s": 7423, "text": "This an example of partial mode collapse, where the generator is reduced to generate just a few examples, losing in terms of variety. A prominent cause for this might have been the small size of the dataset, plus common duplicates entries." }, { "code": null, "e": 7944, "s": 7663, "text": "See instead the following sample for Franzetta art, especially in relation to the training curves. While some entries might give the impression of mode collapse, it is instead more likely just the fault of way too many duplicates in the training dataset for that specific example." }, { "code": null, "e": 8288, "s": 7944, "text": "A decent dataset should generally provide a nice training curve following a Pareto distribution. The official README specifies training times for different configurations, but as said you will obtain most of the improvements during the very first part of your training; the tricky and tedious part is trying to reach the finer quality details." }, { "code": null, "e": 8569, "s": 8288, "text": "Plateau is a common situation, where the model is subject to little or no improvement. Another possible but less common behavior is divergence or explosion, where after an initial step improvement the model starts deteriorating and exponentially degenerated to pure noise results." }, { "code": null, "e": 9030, "s": 8569, "text": "The action to take for such situations is to retrain from a previous checkpoint (as explained in the previous fine-tuning section), reasonably tweaking the hyperparameters according to the recognized problem. As often mentioned, this is an art by itself, and strongly based on intuition, experience and luck.Many possibilities are available, depending on goals, model status, etc.. Here some of the most common suggestions, accompanied by some empirical notes." }, { "code": null, "e": 9193, "s": 9030, "text": "dataset, as usual if your dataset has clear deficits in terms of size or noise, put some effort into fixing those instead of risking to waste time on model tuning" }, { "code": null, "e": 9788, "s": 9193, "text": "learning-rate (lr), here you can decrease lr for potential more stable (but slow) training progress. You can also tweak the lr of discriminator and generator individually, based on the unbalance that might be present in your architecture between the two components. In this regard, Shawn Presser pointed out on Twitter that v2 has actually a bug, for which the generator lr value is incorrectly used as the discriminator lr. Be sure to patch this part before experimenting with G/D lr balance.I tried to increase lr, just for the laughs, and it always ended up with quick and abrupt divergence." }, { "code": null, "e": 10788, "s": 9788, "text": "batch size, increasing batch size can also provide a more stable training or breakthrough from a local minimum. This is based on the idea that as more predictions are used to compute the gradient, the more accurate the weights update and training direction will be. Multiple experiments I run with bigger minibatch forced a good point percentage increase in FID50k, but some of these became soon unstable and exploded. Also, be aware of memory constraints for your setup, v2 is more expensive, and training on 1024 resolution requires a GPU with at least 16 GB of memory.It is worth pointing out that StyleGAN has two different parameters for batch size, minibatch_size_base and minibatch_gpu_base . The former is the actual maximum minibatch size to use, while the latter is the size as processed at a time by a single GPU. This implies that the two parameters need to be adjusted according to the number of GPUs of your setup, as gradients are accumulated until the base minibatch size is reached." }, { "code": null, "e": 11170, "s": 10788, "text": "Regarding these aspects, I want to suggest again Gwern StyleGAN v1 post, as it provides in-depth details and references, and three additional excellent papers if you want to explore GAN-training further: Stabilizing Generative Adversarial Network Training: A Survey (2019), Which Training Methods for GANs do actually Converge? (2018), Improved Techniques for Training GANs (2016)." }, { "code": null, "e": 11313, "s": 11170, "text": "Some behaviors still puzzle me, like what causes this change in loss scores after I restart training from a previous checkpoint (same config)." }, { "code": null, "e": 11684, "s": 11313, "text": "Above some examples of latent space exploration for my dresses and footwear models. The idea is just to generate N sample vectors (drawn from a Gaussian distribution) and transition between them sequentially using whatever preferred transition function. In my case here this function is just a linear interpolation done on a fixed frames number (equivalent to morphing)." }, { "code": null, "e": 12438, "s": 11684, "text": "Notice that we are relying on the very initial latent vector z. This means that we are using the StyleGAN mapping network to first generate the latent vector w, and then using w to synthesize a new image. For this reason, we can rely on the truncation trick, and discard areas of the latent space poorly represented. We want to specify how much the generated intermediate vector w has to stay close to the average (computed based on random inputs to the mapping network). ψ (psi) value scales the deviation of w from the average, and as such can be tweaked for quality/variety trade-offs. ψ=1 is equivalent to no truncation (original w), while values towards 0 gets us closer to the average, with quality improvement but a reduction in terms of variety." }, { "code": null, "e": 12667, "s": 12438, "text": "We often want to be able to obtain the code/latent-vector/embedding of real images with regards to a target model, in other words: what is the input value I should feed to my model to generate the best approximation of my image." }, { "code": null, "e": 12711, "s": 12667, "text": "In general, there are two methods for this:" }, { "code": null, "e": 12767, "s": 12711, "text": "pass image through the encoder component of the network" }, { "code": null, "e": 12808, "s": 12767, "text": "optimize latent (using gradient descent)" }, { "code": null, "e": 13058, "s": 12808, "text": "The former provides a fast solution but has problems generalizing outside of the training dataset, and unfortunately for us, it doesn’t come out of the box with a vanilla StyleGAN. The architecture simply doesn’t learn an explicit encoding function." }, { "code": null, "e": 13915, "s": 13058, "text": "We are left with latent optimization option using perceptual loss. We extract high-level features (e.g. from a pre-trained model like VGG) for the reference and generated images, compute the distance between them and optimize on the latent representation (our target code). The initialization of this target code is a very important aspect for efficiency and effectiveness. The easiest way is simple random initialization, but a lot can be done to improve on this, for example by learning an explicit encoding function from images to latent. The idea is to randomly generate a set of N examples and store both the resulting image and the code that generated it. We can then train a model (e.g. ResNet) on this data, and use it to initialize our latent before the actual StyleGAN encoding process. See this rich discussion regarding improved initialization." }, { "code": null, "e": 14295, "s": 13915, "text": "Encoder for v1 and Encoder for v2 provide code and step-by-step guide for this operation. I also suggest the following two papers: Image2StyleGAN and Image2StyleGAN++, which give a good overview of encoding images for Stylegan, with considerations about initialization options and latent space quality, plus an analysis of image editing operations like morphing and style mixing." }, { "code": null, "e": 14649, "s": 14295, "text": "StyleGAN uses a mapping network (eight fully connected layers) to convert the input noise (z) to an intermediate latent vector (w). Both are of size 512, but the intermediate vector is replicated for each style layer. For a network trained on 1024 size images, this intermediate vector will then be of shape (512, 18), for 512 size it will be (512, 16)." }, { "code": null, "e": 15063, "s": 14649, "text": "The encoding process is generally done on this intermediate vector, and as such one can decide whether to optimize for w(1) (meaning only one 512 layers, which is then tiled as necessary to each style layer) or the whole w(N). The official projector operated the former, while adaptations often rely on optimizing all w entries individually, for visual fidelity. Regarding this topic see also this Twitter thread." }, { "code": null, "e": 15246, "s": 15063, "text": "Even more noticeable and goliardic when projecting reference not proper of the model training distribution, like in the following example projecting a dress image for the FFHQ model." }, { "code": null, "e": 15510, "s": 15246, "text": "In general, one can always notice that for high resolutions the projector seems to fail to match fine details of the reference picture, but this is most likely a consequence of using a resolution of 256x256 for the perceptual loss, as demonstrated in this thread." }, { "code": null, "e": 16013, "s": 15510, "text": "The StyleGAN improvements on latent space disentanglement allow to explore single attributes of the dataset in a pleasing, orthogonal way (meaning without affecting other attributes).While discriminative models learn boundaries to separate target attributes (e.g. male/female, smile/not-smile, cat/dog) what we are interested here is to cross those boundaries, moving perpendicularly to them. For example, if I start from a sad face I can slowly but steadily move to a smiling version of the same face." }, { "code": null, "e": 16468, "s": 16013, "text": "This should already provide a hint on how to learn new directions. We first collect multiple samples (image + latent) from our model and manually classify the images for our target attribute (e.g. smiling VS not smiling), trying to guarantee proper class representation balance. We then train a model to classify or regress on our latents and manual labels. At this point we can use the learned functions of these support models as transition directions." }, { "code": null, "e": 16543, "s": 16468, "text": "Robert Luxemburg shared the learned direction for the official FFHQ model." }, { "code": null, "e": 16902, "s": 16543, "text": "StyleGAN2 Distillation for Feed-forward Image Manipulation is a very recent paper exploring direction manipulation via a “student” image-to-image network trained on unpaired dataset generated via StyleGAN. The paper aims to overcome the encoding performance-bottleneck and learn a transformation function than can be efficiently applied to real-world images." }, { "code": null, "e": 17328, "s": 16902, "text": "A lot of my experiments have initially been motivated by evaluating how good is the latent space learned by a StyleGAN model (representation learning), and how performant the obtained embedding can be for downstream tasks (e.g. image classification via linear models). From one side I will keep working on this kind of evaluation, trying to cover also other generative models types, like autoregressive and flow-based models." }, { "code": null, "e": 17980, "s": 17328, "text": "I’m also interested in pursuing the exploration of such models for the pure image-synthesis capabilities, and the increasing potential for effective semantic mixing and editing, especially in relation to my passion for drawing, digital painting and animation. Automated lineart colorization, animating paintings, frames interpolation are some awesome free utils already out there, but there is so much more that can be done for assisted drawing, especially from a more semantic point of view. There is also plenty of room for practical improvements: generalization capabilities, speeding up inference time, training optimization and transfer learning." }, { "code": null, "e": 18303, "s": 17980, "text": "Down the line, I also want to go beyond the pure 2-dimensional canvas, and learn more about the amazing things already achieved in the 3D graphics realm. Denoising is something I now frequently rely on, differentiable rendering just blew my mind and to close the loop, back again to GAN for continuous 3D shape generation." }, { "code": null, "e": 18353, "s": 18303, "text": "Quoting research scientist Károly Zsolnai-Fehér" }, { "code": null, "e": 18379, "s": 18353, "text": "“What a time to be alive”" }, { "code": null, "e": 18516, "s": 18379, "text": "You can check out my code on Github, follow more of my experiments and explanations on Twitter and see my graphics results on Instagram." } ]
Python - Convert Binary tuple to Integer - GeeksforGeeks
02 Sep, 2020 Given Binary Tuple representing binary representation of number, convert to integer. Input : test_tup = (1, 1, 0)Output : 6Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1)Output : 7Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate the binary tuples in string format using join() and str(), then convert to integer by mentioning base as 2. Python3 # Python3 code to demonstrate working of # Convert Binary tuple to Integer# Using join() + list comprehension + int() # initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tupleprint("The original tuple is : " + str(test_tup)) # using int() with base to get actual numberres = int("".join(str(ele) for ele in test_tup), 2) # printing result print("Decimal number is : " + str(res)) The original tuple is : (1, 1, 0, 1, 0, 0, 1) Decimal number is : 105 Method #2 : Using bit shift and | operator In this we perform left bit shift and use or operator to get binary addition and hence compute the result. Python3 # Python3 code to demonstrate working of # Convert Binary tuple to Integer# Using bit shift and | operator # initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tupleprint("The original tuple is : " + str(test_tup)) res = 0for ele in test_tup: # left bit shift and or operator # for intermediate addition res = (res << 1) | ele # printing result print("Decimal number is : " + str(res)) The original tuple is : (1, 1, 0, 1, 0, 0, 1) Decimal number is : 105 Python tuple-programs Python Python Programs 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 ? Enumerate() in Python Different ways to create Pandas Dataframe Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24404, "s": 24376, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24490, "s": 24404, "text": "Given Binary Tuple representing binary representation of number, convert to integer." }, { "code": null, "e": 24553, "s": 24490, "text": "Input : test_tup = (1, 1, 0)Output : 6Explanation : 4 + 2 = 6." }, { "code": null, "e": 24620, "s": 24553, "text": "Input : test_tup = (1, 1, 1)Output : 7Explanation : 4 + 2 + 1 = 7." }, { "code": null, "e": 24674, "s": 24620, "text": "Method #1 : Using join() + list comprehension + int()" }, { "code": null, "e": 24806, "s": 24674, "text": "In this, we concatenate the binary tuples in string format using join() and str(), then convert to integer by mentioning base as 2." }, { "code": null, "e": 24814, "s": 24806, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert Binary tuple to Integer# Using join() + list comprehension + int() # initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # using int() with base to get actual numberres = int(\"\".join(str(ele) for ele in test_tup), 2) # printing result print(\"Decimal number is : \" + str(res)) ", "e": 25221, "s": 24814, "text": null }, { "code": null, "e": 25292, "s": 25221, "text": "The original tuple is : (1, 1, 0, 1, 0, 0, 1)\nDecimal number is : 105\n" }, { "code": null, "e": 25335, "s": 25292, "text": "Method #2 : Using bit shift and | operator" }, { "code": null, "e": 25442, "s": 25335, "text": "In this we perform left bit shift and use or operator to get binary addition and hence compute the result." }, { "code": null, "e": 25450, "s": 25442, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert Binary tuple to Integer# Using bit shift and | operator # initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) res = 0for ele in test_tup: # left bit shift and or operator # for intermediate addition res = (res << 1) | ele # printing result print(\"Decimal number is : \" + str(res)) ", "e": 25881, "s": 25450, "text": null }, { "code": null, "e": 25952, "s": 25881, "text": "The original tuple is : (1, 1, 0, 1, 0, 0, 1)\nDecimal number is : 105\n" }, { "code": null, "e": 25974, "s": 25952, "text": "Python tuple-programs" }, { "code": null, "e": 25981, "s": 25974, "text": "Python" }, { "code": null, "e": 25997, "s": 25981, "text": "Python Programs" }, { "code": null, "e": 26095, "s": 25997, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26104, "s": 26095, "text": "Comments" }, { "code": null, "e": 26117, "s": 26104, "text": "Old Comments" }, { "code": null, "e": 26135, "s": 26117, "text": "Python Dictionary" }, { "code": null, "e": 26167, "s": 26135, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26189, "s": 26167, "text": "Enumerate() in Python" }, { "code": null, "e": 26231, "s": 26189, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26252, "s": 26231, "text": "Python OOPs Concepts" }, { "code": null, "e": 26274, "s": 26252, "text": "Defaultdict in Python" }, { "code": null, "e": 26313, "s": 26274, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26359, "s": 26313, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26397, "s": 26359, "text": "Python | Convert a list to dictionary" } ]
C++ Program to Compute Cross Product of Two Vectors
This is a C++ program to compute Cross Product of Two Vectors. Let us suppose, M = m1 * i + m2 * j + m3 * k N = n1 * i + n2 * j + n3 * k. So, cross product = (m2 * n3 – m3 * n2) * i + (m1 * n3 – m3 * n1) * j + (m1 * n1 – m2 * n1) * k where m2 * n3 – m3 * n2, m1 * n3 – m3 * n1 and m1 * n1 – m2 * n1 are the coefficients of unit vector along i, j and k directions. Begin Declare a function cProduct(). Declare three vectors v_A[], v_B[], c_P[] of the integer datatype. c_P[0] = v_A[1] * v_B[2] - v_A[2] * v_B[1]. c_P[1] = -(v_A[0] * v_B[2] - v_A[2] * v_B[0]). c_P[2] = v_A[0] * v_B[1] - v_A[1] * v_B[0]. Initialize values in v_A[] vector. Initialize values in v_B[] vector. Initialize c_P[] vector with an integer variable n. Print “Cross product:”. Call the function cProduct() to perform cross product within v_A[] and v_B[]. for (int i = 0; i < n; i++) print the value of c_P[] vector. End. #include #define n 3 using namespace std; void crossProduct(int v_A[], int v_B[], int c_P[]) { c_P[0] = v_A[1] * v_B[2] - v_A[2] * v_B[1]; c_P[1] = -(v_A[0] * v_B[2] - v_A[2] * v_B[0]); c_P[2] = v_A[0] * v_B[1] - v_A[1] * v_B[0]; } int main() { int v_A[] = { 7, 6, 4 }; int v_B[] = { 2, 1, 3 }; int c_P[n]; cout << "Cross product:"; crossProduct(v_A, v_B, c_P); for (int i = 0; i < n; i++) cout << c_P[i] << " "; return 0; } Cross product: 14 13 -5
[ { "code": null, "e": 1125, "s": 1062, "text": "This is a C++ program to compute Cross Product of Two Vectors." }, { "code": null, "e": 1141, "s": 1125, "text": "Let us suppose," }, { "code": null, "e": 1170, "s": 1141, "text": "M = m1 * i + m2 * j + m3 * k" }, { "code": null, "e": 1200, "s": 1170, "text": "N = n1 * i + n2 * j + n3 * k." }, { "code": null, "e": 1296, "s": 1200, "text": "So, cross product = (m2 * n3 – m3 * n2) * i + (m1 * n3 – m3 * n1) * j + (m1 * n1 – m2 * n1) * k" }, { "code": null, "e": 1426, "s": 1296, "text": "where m2 * n3 – m3 * n2, m1 * n3 – m3 * n1 and m1 * n1 – m2 * n1 are the coefficients of unit vector along i, j and k directions." }, { "code": null, "e": 2012, "s": 1426, "text": "Begin\n Declare a function cProduct().\n Declare three vectors v_A[], v_B[], c_P[] of the integer\n datatype.\n c_P[0] = v_A[1] * v_B[2] - v_A[2] * v_B[1].\n c_P[1] = -(v_A[0] * v_B[2] - v_A[2] * v_B[0]).\n c_P[2] = v_A[0] * v_B[1] - v_A[1] * v_B[0].\n Initialize values in v_A[] vector.\n Initialize values in v_B[] vector.\n Initialize c_P[] vector with an integer variable n.\n Print “Cross product:”.\n Call the function cProduct() to perform cross product within v_A[] and\nv_B[].\n for (int i = 0; i < n; i++)\n print the value of c_P[] vector.\nEnd." }, { "code": null, "e": 2473, "s": 2012, "text": "#include\n#define n 3\nusing namespace std;\nvoid crossProduct(int v_A[], int v_B[], int c_P[]) {\n c_P[0] = v_A[1] * v_B[2] - v_A[2] * v_B[1];\n c_P[1] = -(v_A[0] * v_B[2] - v_A[2] * v_B[0]);\n c_P[2] = v_A[0] * v_B[1] - v_A[1] * v_B[0];\n}\nint main() {\n int v_A[] = { 7, 6, 4 };\n int v_B[] = { 2, 1, 3 };\n int c_P[n];\n cout << \"Cross product:\";\n crossProduct(v_A, v_B, c_P);\n for (int i = 0; i < n; i++)\n cout << c_P[i] << \" \";\n return 0;\n}" }, { "code": null, "e": 2497, "s": 2473, "text": "Cross product: 14 13 -5" } ]
Fuzzy Inference System implementation in Python | by Carmel Gafa | Towards Data Science
In a previous article, we discussed the basics of fuzzy sets and fuzzy inferencing. The report also illustrated the construction of a possible control application using a fuzzy inferencing method. In this article, we will build a multi-input/multi-output fuzzy inference system using the Python programming language. It is assumed that the reader has a clear understanding of fuzzy inferencing and has read the article mentioned previously. All the code listed in this article is available on Github. The diagram below illustrates the structure of the application. The design is based on several considerations on Fuzzy Inference Systems, some being: A Fuzzy Inference System will require input and output variables and a collection of fuzzy rules. Both input and output variables will contain a collection of fuzzy sets if the Fuzzy Inference System is of Mamdani type. Input and output variables are very similar, but they are used differently by fuzzy rules. During execution, input variables use the input values to the system to fuzzify their sets, that is they determine the degree of belonging of that input value to all of the fuzzy sets of the variable. Each rule contributes to some extent to the output variables; the totality of this contribution will determine the output of the system. Fuzzy rules have the structure of the form; if {antecedent clauses} then {consequent clauses} Therefore a rule will contain several clauses of antecedent type and some clauses of consequent type. Clauses will be of the form: {variable name} is {set name} We will discuss some implementation details of the classes developed for this system in the following sections: A FuzzySet requires the following parameters so that it can be initiated: name — the name of the set minimum value — the minimum value of the set maximum value — the maximum value of the set resolution — the number of steps between the minimum and maximum value It is, therefore, possible to represent a fuzzy set by using two numpy arrays; one that will hold the domain values and one that will hold the degree-of-membership values. Initially, all degree-of-membership values will be all set to zero. It can be argued that if the minimum and maximum values are available together with the resolution of the set, the domain numpy array is not required as the respective values can be calculated. While this is perfectly true, a domain array was preferred in this example project so that the code is more readable and simple. In the context of a fuzzy variable, all the sets will have the same minimum, maximum and resolution values. As we are dealing with a discretized domain, it will be necessary to adjust any value used to set or retrieve the degree-of-membership to the closest value in the domain array. The class contains methods whereby a set of a given shape can be constructed given a corresponding number of parameters. In the case of a triangular set, for example, three parameters are provided, two that define the extents of the sets and one for the apex. It is possible to construct a triangular set by using these three parameters as can be seen in the figure below. Since the sets are based on numpy arrays, the equation above can be translated directly to code, as can be seen below. Sets having different shapes can be constructed using a similar method. The FuzzySet class also contains union, intersection and negation operators that are necessary so that inferencing can take place. All operator methods return a new fuzzy set with the result of the operation that took place. Finally, we implemented the ability to obtain a crisp result from a fuzzy set using the centre-of-gravity method that is referred to in some detail in the previous article. It is important to mention that there is a large number of defuzzification methods are available in the literature. Still, as the centre-of-gravity method is overwhelmingly popular, it is used in this implementation. As discussed previously, variables can be of input or output in type, with the difference affecting the fuzzy inference calculation. A FuzzyVariable is a collection of sets that are held in a python dictionary having the set name as the key. Methods are available to add FuzzySets to the variable, where such sets will take the variable’s limits and resolution. For input variables, fuzzification is carried out by retrieving the degree-of-membership of all the sets in the variable for a given domain value. The degree-of-membership is stored in the set as it will be required by the rules when they are evaluated. Output variables will ultimately produce the result of a fuzzy inference iteration. This means that for Mamdani-type systems, as we are building here, output variables will hold the union of the fuzzy contributions from all the rules, and will subsequently defuzzify this result to obtain a crisp value that can be used in real-life applications. Therefore, output variables will require an additional FuzzySet attribute that will hold the output distribution for that variable, where the contribution that was resulting from each rule and added using the set union operator. The defuzzification result can then be obtained by calling the centre-of-gravity method for output distribution set. The FuzzyClause class requires two attributes; a fuzzy variable and a fuzzy set so that the statement variable is set can be created. Clauses are used to implement statements that can be chained together to form the antecedent and consequent parts of the rule. When used as an antecedent clause, the FuzzyClause returns the last degree-of-membership value of the set, that is calculated during the fuzzification stage as we have seen previously. The rule will combine the degree-of-membership values from the various antecedent clauses using the min operator, obtaining the rule activation that is then used in conjunction with the consequent clauses to obtain the contribution of the rule to the output variables. This operation is a two-step process: The activation value is combined with the consequent FuzzySet using the min operator, that will act as a threshold to the degree-of-membership values of the FuzzySet. The resultant FuzzySet is combined with the FuzzySets obtained from the other rules using the union operator, obtaining the output distribution for that variable. The FuzzyRule class will, therefore, require two attributes: a list containing the antecedent clauses and a list containing the consequent clauses During the execution of the FuzzyRule, the procedure explained above is carried out. The FuzzyRule coordinates all the tasks by utilizing all the various FuzzyClauses as appropriate. At the topmost level of this architecture, we have the FuzzySystem that coordinates all activities between the FuzzyVariables and FuzzyRules. Hence the system contains the input and output variables, that are stored in python dictionaries using variable-names as keys and a list of the rules. One of the challenges presented at this stage is the method that the end-user will use to add rules, that should ideally abstract the implementation detail of the FuzzyClause classes. The method that was implemented consists of providing two python dictionaries that will contain the antecedent and consequent clauses of the rule in the following format; variable name : set name A more user-friendly method is to provide the rule as a string and then parse that string to create the rule, but this seemed an unnecessary overhead for a demonstration application. Addition of a new rule to the FuzzySystem The execution of the inference process can be achieved with a few lines of code given this structure, where the following steps are carried out; The output distribution sets of all the output variables are cleared.The input values to the system are passed to the corresponding input variables so that each set in the variable can determine its degree-of-membership for that input value.Execution of the Fuzzy Rules takes place, meaning that the output distribution sets of all the output variables will now contain the union of the contributions from each rule.The output distribution sets are defuzzified using a centre-of-gravity defuzzifier to obtain the crisp result. The output distribution sets of all the output variables are cleared. The input values to the system are passed to the corresponding input variables so that each set in the variable can determine its degree-of-membership for that input value. Execution of the Fuzzy Rules takes place, meaning that the output distribution sets of all the output variables will now contain the union of the contributions from each rule. The output distribution sets are defuzzified using a centre-of-gravity defuzzifier to obtain the crisp result. As a final note, the Fuzzy Inferencing System implemented here contains additional functions to plot fuzzy sets and variables and to obtain information about an inference step execution. In this section, we will discuss the use of the fuzzy inference system. In particular, we will implement the fan speed case study that was designed in the previous article in this series. A fuzzy system begins with the consideration of the input and output variables, and the design of the fuzzy sets to explain that variable. The variables will require a lower and upper limit and, as we will be dealing with discrete fuzzy sets, the resolution of the system. Therefore a variable definition will look as follows temp = FuzzyInputVariable('Temperature', 10, 40, 100) where the variable ‘Temperature’ ranges between 10 and 40 degrees and is discretized in 100 bins. The fuzzy sets define for the variable will require different parameters depending on their shape. In the case of triangular sets, for example, three parameters are needed, two for the lower and upper extremes having a degree of membership of 0 and one for the apex which has a degree-of-membership of 1. A triangular set definition for variable ‘Temperature’ can, therefore, look as follows; temp.add_triangular('Cold', 10, 10, 25) where the set called ‘Cold’ has extremes at 10 and 25 and apex at 10 degrees. In our system, we considered two input variables, ‘Temperature’ and ‘Humidity’ and a single output variable ‘Speed’. Each variable us described by three fuzzy sets. The definition of the output variable ‘Speed’ looks as follows: motor_speed = FuzzyOutputVariable('Speed', 0, 100, 100) motor_speed.add_triangular('Slow', 0, 0, 50) motor_speed.add_triangular('Moderate', 10, 50, 90) motor_speed.add_triangular('Fast', 50, 100, 100) As we have seen before, the fuzzy system is the entity that will contain these variables and fuzzy rules. Hence the variables will have to be added to a system as follows: system = FuzzySystem() system.add_input_variable(temp) system.add_input_variable(humidity)system.add_output_variable(motor_speed) A fuzzy system executes fuzzy rules to operate of the form If x1 is S and x2 is M then y is S where the If part of the rule contains several antecedent clauses and the then section will include several consequent clauses. To keep things simple, we will assume rules that require an antecedent clause from each input variable and are only linked together with an ‘and’ statement. It is possible to have statements linked by ‘or’ and statements can also contain operators on the sets like ‘not’. The simplest way to add a fuzzy rule to our system is to provide a list of the antecedent clauses and consequent clauses. One method of doing so is by using a python dictionary that contains Variable:Set entries for the clause sets. Hence the above rule can be implemented as follows: system.add_rule( { 'Temperature':'Cold', 'Humidity':'Wet' },{ 'Speed':'Slow'}) Execution of the system involves inputting values for all the input variables and getting the values for the output values in return. Again this is achieved through the use of dictionaries that us the name of the variables as keys. output = system.evaluate_output({ 'Temperature':18, 'Humidity':60 }) The system will return a dictionary containing the name of the output variables as keys, and the defuzzified result as values. In this article, we have looked at the practical implementation of a fuzzy inference system. Whilst the library presented here will require some further work so that it can be used in real projects, including validation and exception handling, it can serve as the basis for projects that require Fuzzy Inferencing. It is also recommended to look at some open-source projects that are available, in particular skfuzzy, a fuzzy logic toolbox for SciPy. In the next article, we will examine ways whereby a fuzzy system can be created from a dataset so that that fuzzy logic can be used in machine learning scenarios. Similarly to this introduction to Fuzzy Logic concepts, a practical article will follow.
[ { "code": null, "e": 613, "s": 172, "text": "In a previous article, we discussed the basics of fuzzy sets and fuzzy inferencing. The report also illustrated the construction of a possible control application using a fuzzy inferencing method. In this article, we will build a multi-input/multi-output fuzzy inference system using the Python programming language. It is assumed that the reader has a clear understanding of fuzzy inferencing and has read the article mentioned previously." }, { "code": null, "e": 673, "s": 613, "text": "All the code listed in this article is available on Github." }, { "code": null, "e": 823, "s": 673, "text": "The diagram below illustrates the structure of the application. The design is based on several considerations on Fuzzy Inference Systems, some being:" }, { "code": null, "e": 921, "s": 823, "text": "A Fuzzy Inference System will require input and output variables and a collection of fuzzy rules." }, { "code": null, "e": 1043, "s": 921, "text": "Both input and output variables will contain a collection of fuzzy sets if the Fuzzy Inference System is of Mamdani type." }, { "code": null, "e": 1472, "s": 1043, "text": "Input and output variables are very similar, but they are used differently by fuzzy rules. During execution, input variables use the input values to the system to fuzzify their sets, that is they determine the degree of belonging of that input value to all of the fuzzy sets of the variable. Each rule contributes to some extent to the output variables; the totality of this contribution will determine the output of the system." }, { "code": null, "e": 1516, "s": 1472, "text": "Fuzzy rules have the structure of the form;" }, { "code": null, "e": 1566, "s": 1516, "text": "if {antecedent clauses} then {consequent clauses}" }, { "code": null, "e": 1697, "s": 1566, "text": "Therefore a rule will contain several clauses of antecedent type and some clauses of consequent type. Clauses will be of the form:" }, { "code": null, "e": 1727, "s": 1697, "text": "{variable name} is {set name}" }, { "code": null, "e": 1839, "s": 1727, "text": "We will discuss some implementation details of the classes developed for this system in the following sections:" }, { "code": null, "e": 1913, "s": 1839, "text": "A FuzzySet requires the following parameters so that it can be initiated:" }, { "code": null, "e": 1940, "s": 1913, "text": "name — the name of the set" }, { "code": null, "e": 1985, "s": 1940, "text": "minimum value — the minimum value of the set" }, { "code": null, "e": 2030, "s": 1985, "text": "maximum value — the maximum value of the set" }, { "code": null, "e": 2101, "s": 2030, "text": "resolution — the number of steps between the minimum and maximum value" }, { "code": null, "e": 2664, "s": 2101, "text": "It is, therefore, possible to represent a fuzzy set by using two numpy arrays; one that will hold the domain values and one that will hold the degree-of-membership values. Initially, all degree-of-membership values will be all set to zero. It can be argued that if the minimum and maximum values are available together with the resolution of the set, the domain numpy array is not required as the respective values can be calculated. While this is perfectly true, a domain array was preferred in this example project so that the code is more readable and simple." }, { "code": null, "e": 2772, "s": 2664, "text": "In the context of a fuzzy variable, all the sets will have the same minimum, maximum and resolution values." }, { "code": null, "e": 2949, "s": 2772, "text": "As we are dealing with a discretized domain, it will be necessary to adjust any value used to set or retrieve the degree-of-membership to the closest value in the domain array." }, { "code": null, "e": 3322, "s": 2949, "text": "The class contains methods whereby a set of a given shape can be constructed given a corresponding number of parameters. In the case of a triangular set, for example, three parameters are provided, two that define the extents of the sets and one for the apex. It is possible to construct a triangular set by using these three parameters as can be seen in the figure below." }, { "code": null, "e": 3513, "s": 3322, "text": "Since the sets are based on numpy arrays, the equation above can be translated directly to code, as can be seen below. Sets having different shapes can be constructed using a similar method." }, { "code": null, "e": 3738, "s": 3513, "text": "The FuzzySet class also contains union, intersection and negation operators that are necessary so that inferencing can take place. All operator methods return a new fuzzy set with the result of the operation that took place." }, { "code": null, "e": 4128, "s": 3738, "text": "Finally, we implemented the ability to obtain a crisp result from a fuzzy set using the centre-of-gravity method that is referred to in some detail in the previous article. It is important to mention that there is a large number of defuzzification methods are available in the literature. Still, as the centre-of-gravity method is overwhelmingly popular, it is used in this implementation." }, { "code": null, "e": 4490, "s": 4128, "text": "As discussed previously, variables can be of input or output in type, with the difference affecting the fuzzy inference calculation. A FuzzyVariable is a collection of sets that are held in a python dictionary having the set name as the key. Methods are available to add FuzzySets to the variable, where such sets will take the variable’s limits and resolution." }, { "code": null, "e": 4744, "s": 4490, "text": "For input variables, fuzzification is carried out by retrieving the degree-of-membership of all the sets in the variable for a given domain value. The degree-of-membership is stored in the set as it will be required by the rules when they are evaluated." }, { "code": null, "e": 5091, "s": 4744, "text": "Output variables will ultimately produce the result of a fuzzy inference iteration. This means that for Mamdani-type systems, as we are building here, output variables will hold the union of the fuzzy contributions from all the rules, and will subsequently defuzzify this result to obtain a crisp value that can be used in real-life applications." }, { "code": null, "e": 5437, "s": 5091, "text": "Therefore, output variables will require an additional FuzzySet attribute that will hold the output distribution for that variable, where the contribution that was resulting from each rule and added using the set union operator. The defuzzification result can then be obtained by calling the centre-of-gravity method for output distribution set." }, { "code": null, "e": 5539, "s": 5437, "text": "The FuzzyClause class requires two attributes; a fuzzy variable and a fuzzy set so that the statement" }, { "code": null, "e": 5555, "s": 5539, "text": "variable is set" }, { "code": null, "e": 5698, "s": 5555, "text": "can be created. Clauses are used to implement statements that can be chained together to form the antecedent and consequent parts of the rule." }, { "code": null, "e": 5883, "s": 5698, "text": "When used as an antecedent clause, the FuzzyClause returns the last degree-of-membership value of the set, that is calculated during the fuzzification stage as we have seen previously." }, { "code": null, "e": 6190, "s": 5883, "text": "The rule will combine the degree-of-membership values from the various antecedent clauses using the min operator, obtaining the rule activation that is then used in conjunction with the consequent clauses to obtain the contribution of the rule to the output variables. This operation is a two-step process:" }, { "code": null, "e": 6357, "s": 6190, "text": "The activation value is combined with the consequent FuzzySet using the min operator, that will act as a threshold to the degree-of-membership values of the FuzzySet." }, { "code": null, "e": 6520, "s": 6357, "text": "The resultant FuzzySet is combined with the FuzzySets obtained from the other rules using the union operator, obtaining the output distribution for that variable." }, { "code": null, "e": 6581, "s": 6520, "text": "The FuzzyRule class will, therefore, require two attributes:" }, { "code": null, "e": 6626, "s": 6581, "text": "a list containing the antecedent clauses and" }, { "code": null, "e": 6667, "s": 6626, "text": "a list containing the consequent clauses" }, { "code": null, "e": 6850, "s": 6667, "text": "During the execution of the FuzzyRule, the procedure explained above is carried out. The FuzzyRule coordinates all the tasks by utilizing all the various FuzzyClauses as appropriate." }, { "code": null, "e": 7143, "s": 6850, "text": "At the topmost level of this architecture, we have the FuzzySystem that coordinates all activities between the FuzzyVariables and FuzzyRules. Hence the system contains the input and output variables, that are stored in python dictionaries using variable-names as keys and a list of the rules." }, { "code": null, "e": 7498, "s": 7143, "text": "One of the challenges presented at this stage is the method that the end-user will use to add rules, that should ideally abstract the implementation detail of the FuzzyClause classes. The method that was implemented consists of providing two python dictionaries that will contain the antecedent and consequent clauses of the rule in the following format;" }, { "code": null, "e": 7523, "s": 7498, "text": "variable name : set name" }, { "code": null, "e": 7706, "s": 7523, "text": "A more user-friendly method is to provide the rule as a string and then parse that string to create the rule, but this seemed an unnecessary overhead for a demonstration application." }, { "code": null, "e": 7748, "s": 7706, "text": "Addition of a new rule to the FuzzySystem" }, { "code": null, "e": 7893, "s": 7748, "text": "The execution of the inference process can be achieved with a few lines of code given this structure, where the following steps are carried out;" }, { "code": null, "e": 8420, "s": 7893, "text": "The output distribution sets of all the output variables are cleared.The input values to the system are passed to the corresponding input variables so that each set in the variable can determine its degree-of-membership for that input value.Execution of the Fuzzy Rules takes place, meaning that the output distribution sets of all the output variables will now contain the union of the contributions from each rule.The output distribution sets are defuzzified using a centre-of-gravity defuzzifier to obtain the crisp result." }, { "code": null, "e": 8490, "s": 8420, "text": "The output distribution sets of all the output variables are cleared." }, { "code": null, "e": 8663, "s": 8490, "text": "The input values to the system are passed to the corresponding input variables so that each set in the variable can determine its degree-of-membership for that input value." }, { "code": null, "e": 8839, "s": 8663, "text": "Execution of the Fuzzy Rules takes place, meaning that the output distribution sets of all the output variables will now contain the union of the contributions from each rule." }, { "code": null, "e": 8950, "s": 8839, "text": "The output distribution sets are defuzzified using a centre-of-gravity defuzzifier to obtain the crisp result." }, { "code": null, "e": 9137, "s": 8950, "text": "As a final note, the Fuzzy Inferencing System implemented here contains additional functions to plot fuzzy sets and variables and to obtain information about an inference step execution." }, { "code": null, "e": 9325, "s": 9137, "text": "In this section, we will discuss the use of the fuzzy inference system. In particular, we will implement the fan speed case study that was designed in the previous article in this series." }, { "code": null, "e": 9464, "s": 9325, "text": "A fuzzy system begins with the consideration of the input and output variables, and the design of the fuzzy sets to explain that variable." }, { "code": null, "e": 9651, "s": 9464, "text": "The variables will require a lower and upper limit and, as we will be dealing with discrete fuzzy sets, the resolution of the system. Therefore a variable definition will look as follows" }, { "code": null, "e": 9705, "s": 9651, "text": "temp = FuzzyInputVariable('Temperature', 10, 40, 100)" }, { "code": null, "e": 9803, "s": 9705, "text": "where the variable ‘Temperature’ ranges between 10 and 40 degrees and is discretized in 100 bins." }, { "code": null, "e": 10196, "s": 9803, "text": "The fuzzy sets define for the variable will require different parameters depending on their shape. In the case of triangular sets, for example, three parameters are needed, two for the lower and upper extremes having a degree of membership of 0 and one for the apex which has a degree-of-membership of 1. A triangular set definition for variable ‘Temperature’ can, therefore, look as follows;" }, { "code": null, "e": 10236, "s": 10196, "text": "temp.add_triangular('Cold', 10, 10, 25)" }, { "code": null, "e": 10543, "s": 10236, "text": "where the set called ‘Cold’ has extremes at 10 and 25 and apex at 10 degrees. In our system, we considered two input variables, ‘Temperature’ and ‘Humidity’ and a single output variable ‘Speed’. Each variable us described by three fuzzy sets. The definition of the output variable ‘Speed’ looks as follows:" }, { "code": null, "e": 10744, "s": 10543, "text": "motor_speed = FuzzyOutputVariable('Speed', 0, 100, 100) motor_speed.add_triangular('Slow', 0, 0, 50) motor_speed.add_triangular('Moderate', 10, 50, 90) motor_speed.add_triangular('Fast', 50, 100, 100)" }, { "code": null, "e": 10916, "s": 10744, "text": "As we have seen before, the fuzzy system is the entity that will contain these variables and fuzzy rules. Hence the variables will have to be added to a system as follows:" }, { "code": null, "e": 11046, "s": 10916, "text": "system = FuzzySystem() system.add_input_variable(temp) system.add_input_variable(humidity)system.add_output_variable(motor_speed)" }, { "code": null, "e": 11105, "s": 11046, "text": "A fuzzy system executes fuzzy rules to operate of the form" }, { "code": null, "e": 11140, "s": 11105, "text": "If x1 is S and x2 is M then y is S" }, { "code": null, "e": 11540, "s": 11140, "text": "where the If part of the rule contains several antecedent clauses and the then section will include several consequent clauses. To keep things simple, we will assume rules that require an antecedent clause from each input variable and are only linked together with an ‘and’ statement. It is possible to have statements linked by ‘or’ and statements can also contain operators on the sets like ‘not’." }, { "code": null, "e": 11731, "s": 11540, "text": "The simplest way to add a fuzzy rule to our system is to provide a list of the antecedent clauses and consequent clauses. One method of doing so is by using a python dictionary that contains" }, { "code": null, "e": 11744, "s": 11731, "text": "Variable:Set" }, { "code": null, "e": 11825, "s": 11744, "text": "entries for the clause sets. Hence the above rule can be implemented as follows:" }, { "code": null, "e": 11907, "s": 11825, "text": "system.add_rule( { 'Temperature':'Cold', 'Humidity':'Wet' },{ 'Speed':'Slow'})" }, { "code": null, "e": 12139, "s": 11907, "text": "Execution of the system involves inputting values for all the input variables and getting the values for the output values in return. Again this is achieved through the use of dictionaries that us the name of the variables as keys." }, { "code": null, "e": 12215, "s": 12139, "text": "output = system.evaluate_output({ 'Temperature':18, 'Humidity':60 })" }, { "code": null, "e": 12342, "s": 12215, "text": "The system will return a dictionary containing the name of the output variables as keys, and the defuzzified result as values." }, { "code": null, "e": 12793, "s": 12342, "text": "In this article, we have looked at the practical implementation of a fuzzy inference system. Whilst the library presented here will require some further work so that it can be used in real projects, including validation and exception handling, it can serve as the basis for projects that require Fuzzy Inferencing. It is also recommended to look at some open-source projects that are available, in particular skfuzzy, a fuzzy logic toolbox for SciPy." } ]
How to Deploy Models at Scale with AI Platform | by Elsa Scola | Towards Data Science
Usually, when we all start learning Machine Learning, we find a ton of information about how to build models, which of course is the core of the topic. But there’s an equally important aspect of ML that is rarely taught in the academic world of Data Science, and that is how to deploy these models. How can I share this useful thing that I’ve done with the rest of world? Because, at the end of the day...that’s the purpose of our job right? Making people’s lives easier 😊. In this post, we’ll learn how to deploy a machine learning model to the cloud and make it available to the rest of the world as an API. We’re going to first store the model in Firebase Storage to deploy it to AI Platform where we can version it and analyse it in production. Finally, we’re going to make our model available through an API with Firebase Cloud Functions. AI Platform is a service of Google Cloud Platform (GCP) that makes it easy to manage the whole production and deployment process by not having to worry about maintaining your own infrastructure and making you pay only for usage. This will enable you to scale your product massively for fast growing projects. You can try this and many more experiments on your own FOR FREE by making use of GCP’s 12 month, $300 free trial to get you started. Essentially, for the purpose of this post, the cloud function will work as an API. We will make the predictions of our model available through a link that any person can make requests to, and receive the response of our model in real time. A model ready to share ✔ A Google account ✔ yep, that’s all Just for the sake of simplicity, I’m going to assume the model was developed in Python and lives in a Jupyter Notebook. But of course, these steps can be adapted to any other environment. First, sign in to the Firebase Console with your Google account and create a new project. Now you’re inside the Firebase Dashboard, go to the project settings > Service accounts > Firebase Admin SDK, (in this case) you select the Python option and click on Generate new private key. This will give the JSON file of your service account that you can save in your notebook’s directory. Then, install the Firebase Admin SDK package: pip install firebase-admin Once you’ve trained and tested your model it’s ready to upload to AI Platform. But before that, we need to first export and store the model in Firebase Storage, so it can be accessed by AI Platform. If you’re using a notebook, create a new cell at the end and add the following script. This will enable the usage of your firebase account: import firebase_adminfrom firebase_admin import credentialsfrom firebase_admin import firestore# Use a service accountif (not len(firebase_admin._apps)): cred = credentials.Certificate(r'service_account.json') firebase_admin.initialize_app(cred)db = firestore.client() Now, to run the following code you’ll need to get the Project ID, which you can find again in your Firebase project settings. Once we have our Project ID we upload the model by running the following code (you should first change it with your Project ID). from sklearn.externals import joblibfrom firebase_admin import storagejoblib.dump(clf, 'model.joblib')bucket = storage.bucket(name='[YOUR PROJECT ID HERE].appspot.com')b = bucket.blob('model-v1/model.joblib')b.upload_from_filename('model.joblib')print('model uploaded!') Now we can verify that the model has been correctly uploaded by checking in Firebase Storage inside the specified directory (which in our case is model-v1/). Now that the model has been stored, it can be connected to AI Platform. We need to enable a couple of APIs in Google Cloud Platform. On the left panel, inside the Library section, we look for the APIs “AI Platform Training & Prediction API” and “Cloud Build API” and enable them. Now, on the left panel we click on AI Platform > models and we Create new model and input the corresponding information. Once we’ve created the model it’s time to create a version of it, which will point to the .joblib file that we previously stored. We click on the model > new version and fill the information. It’s important that we choose the same Python version that we used for training the model. We choose scikit-learn as the framework. When specifying its version, we can get it by running the following code in our notebook. import sklearnprint('The scikit-learn version is {}.'.format(sklearn.__version__)) When choosing the ML Runtime version, you should select the recommended one. The machine type can be left by default for now. Finally, we specify the folder in which our .joblib file is located. It’s important to select the folder, not the file! The rest of the fields can be left by default and save. At that moment, an instance of our model will be deployed in AI Platform. Now, we’ll be able to make predictions from the command line or from other Google APIs, such as Cloud Function, as we’ll see next. Additionally, we’ll be able to get some performance metrics on our model. Let’s see how to implement the function! We’re going to run some commands on the terminal, but for that, you’ll need to ensure you have Node.js installed in your computer. The following commands are specific for Windows but you should be able to use them in Unix and Mac OS devices by adding sudo at the beginning of each of the commands. Let’s start by installing the Firebase client: $ npm install -g firebase-tools We access the Google account: $ firebase login Initialize a new project directory (make sure you’re in the directory you want to initialize it in):$ firebase init When running this last command you’ll be asked several questions. When asked about the Firebase project that you want in the directory, you have to choose the one that contains the ML model that we previously exported. Select JavaScript as programming language. We don’t use ESLint, so answer no. And finally, answer yes to the installation of dependencies with npm. Once the project has been created, the directory will have the following structure: Inside this directory, we’ll only modify the index.js and the package.json files. We install the packages of the Google API: $ npm i googleapis Now we check the packages have been installed correctly by opening the package.json file. In case you want to use any other external package in your code you should also add it in this file with its corresponding version. For now, it should have a structure similar to this: "dependencies"​: { ​"firebase-admin"​: ​"~7.0.0"​,​ "firebase-functions"​: ​"^2.3.0"​,​ "googleapis"​: ​"^39.2.0"​} I’ll briefly explain what they do: firebase-admin​: It’s the Admin SDK, which allows to interact with Firebase from privileged environments. firebase-functions​: It’s an SDK for the definition of Cloud Functions in Firebase. googleapis: It’s the client library Node.js for the usage of Google APIs. Now let’s see the implementation of the function (we are editing the index.js file), which you can also find in this GitHub repository. As an example, I’ll be using the code to access a simple fake-account detection model. We start by loading the firebase-functions​ and ​firebase-admin modules. const​​ functions ​​= ​​require​(​'firebase-functions'​);const ​​admin​​ =​​ require​(​'firebase-admin'​); We load the googleapis module and add the reference to the version 1 of ml. admin​.​initializeApp​(​functions​.​config​().​firebase​);const​​ googleapis_1​​ =​​ require​(​"googleapis"​);const​​ ml​​ = ​​googleapis_1​.​google​.​ml​(​'v1'​); The requests are going to be sent to an http function. exports​.​predictSPAM​​ = ​​functions​.​https​.​onRequest​(​async​​(request,​​response)​​=>{ We specify the input values of the function. In this example, I’m getting some data about the social media account that my model will use to classify as fake or not. You should specify the fields that you plan to input afterwards to your model. const ​​account_days_old​​ = ​​request​.​body​.​account_days_old​;​const​​ followers_count​​ =​​ request​.​body​.​followers_count​;​const ​​following_count ​​= ​​request​.​body​.​following_count​;​const​​ publications_count​​ =​​ request​.​body​.​publications_count​; After that, we build the input of the model, that is, the input parameters that we’ll send to the model to get the prediction. Note that these inputs should follow the same structure (order of features) with which the model was trained. const​​ instance ​​= [[account_days_old,followers_count,following_count,publications_count]] Now, let’s make the request to the Google API, this request needs authentication, which will connect our Firebase credentials with Google API. const ​​model​​ =​​ "[HERE THE NAME OF YOUR MODEL]"​;​const​ { ​credential​ } ​=​​ awaitgoogleapis_1​.​google​.​auth​.​getApplicationDefault​(); After storing the name of our model in a variable (the name should be the same you gave it in the AI Platform console), we make a prediction call to AI Platform by sending our credentials, the name of the model and the instance that we want the prediction for. const ​​modelName​​ =​​ `projects/[YOUR PROJECT ID HERE]/models/​${​model​}​`​;const​​ preds ​​= ​​await ​​ml​.​projects​.​predict​({ auth​:​​ credential, name​:​​ modelName, requestBody​:​​ { ​instance ​}​ });​ response​.​send​(​preds​.​data​[​'predictions'​][​0​]);}); Once we’ve created the cloud function that accesses the model, we just need to upload it to Firebase to deploy it as an API. To upload the Firebase function we run the following command in the terminal: $ firebase deploy --only functions Once it has finished loading, a URL is obtained through which the function will be accessible, which can be found by logging into Firestore, in the Functions section, under Request in smaller print. And that’s all, now your model is up and running, ready to share! 🎉🎉🎉 You can make requests to this API from a mobile app, a website...it could be integrated anywhere! This is, of course, an optional step, if you followed the previous guidelines, your model should be ready to receive requests. However, as a programmer, I like to test things to check everything works fine. My favourite way to test APIs is by using Insomnia. Insomnia is a REST API client that lets you test your APIs easily. This free desktop app is available for Windows, MacOS and Ubuntu. Let’s check if our newly made API works properly! Once we’ve installed the desktop app we can create a new request. We’ll write the request name and choose POST as a method and JSON for its structure. Once we’ve created the request, we copy the URL of the cloud function and we paste it in the top bar. We will now write the request following the format that we specified in the function, in my case, it’d be like this: { "account_days_old": 32, "followers_count": 162, "following_count": 152, "publications_count": 45,} We now hit SEND and we’ll get the response, as well as the response time and its size. If there were any errors you should also receive the error code instead of the 200 OK message. The response that you get will, of course, vary depending on your model. But if everything works fine, then congrats! You’re ready to share your model with the rest of the world! 🌍 If you made it this far, thank you for your time and I hope you got some value from this post😊 See you in the next one! 🚀
[ { "code": null, "e": 652, "s": 178, "text": "Usually, when we all start learning Machine Learning, we find a ton of information about how to build models, which of course is the core of the topic. But there’s an equally important aspect of ML that is rarely taught in the academic world of Data Science, and that is how to deploy these models. How can I share this useful thing that I’ve done with the rest of world? Because, at the end of the day...that’s the purpose of our job right? Making people’s lives easier 😊." }, { "code": null, "e": 788, "s": 652, "text": "In this post, we’ll learn how to deploy a machine learning model to the cloud and make it available to the rest of the world as an API." }, { "code": null, "e": 1022, "s": 788, "text": "We’re going to first store the model in Firebase Storage to deploy it to AI Platform where we can version it and analyse it in production. Finally, we’re going to make our model available through an API with Firebase Cloud Functions." }, { "code": null, "e": 1331, "s": 1022, "text": "AI Platform is a service of Google Cloud Platform (GCP) that makes it easy to manage the whole production and deployment process by not having to worry about maintaining your own infrastructure and making you pay only for usage. This will enable you to scale your product massively for fast growing projects." }, { "code": null, "e": 1464, "s": 1331, "text": "You can try this and many more experiments on your own FOR FREE by making use of GCP’s 12 month, $300 free trial to get you started." }, { "code": null, "e": 1704, "s": 1464, "text": "Essentially, for the purpose of this post, the cloud function will work as an API. We will make the predictions of our model available through a link that any person can make requests to, and receive the response of our model in real time." }, { "code": null, "e": 1729, "s": 1704, "text": "A model ready to share ✔" }, { "code": null, "e": 1748, "s": 1729, "text": "A Google account ✔" }, { "code": null, "e": 1764, "s": 1748, "text": "yep, that’s all" }, { "code": null, "e": 1952, "s": 1764, "text": "Just for the sake of simplicity, I’m going to assume the model was developed in Python and lives in a Jupyter Notebook. But of course, these steps can be adapted to any other environment." }, { "code": null, "e": 2336, "s": 1952, "text": "First, sign in to the Firebase Console with your Google account and create a new project. Now you’re inside the Firebase Dashboard, go to the project settings > Service accounts > Firebase Admin SDK, (in this case) you select the Python option and click on Generate new private key. This will give the JSON file of your service account that you can save in your notebook’s directory." }, { "code": null, "e": 2409, "s": 2336, "text": "Then, install the Firebase Admin SDK package: pip install firebase-admin" }, { "code": null, "e": 2608, "s": 2409, "text": "Once you’ve trained and tested your model it’s ready to upload to AI Platform. But before that, we need to first export and store the model in Firebase Storage, so it can be accessed by AI Platform." }, { "code": null, "e": 2748, "s": 2608, "text": "If you’re using a notebook, create a new cell at the end and add the following script. This will enable the usage of your firebase account:" }, { "code": null, "e": 3017, "s": 2748, "text": "import firebase_adminfrom firebase_admin import credentialsfrom firebase_admin import firestore# Use a service accountif (not len(firebase_admin._apps)):\tcred = credentials.Certificate(r'service_account.json')\tfirebase_admin.initialize_app(cred)db = firestore.client()" }, { "code": null, "e": 3143, "s": 3017, "text": "Now, to run the following code you’ll need to get the Project ID, which you can find again in your Firebase project settings." }, { "code": null, "e": 3272, "s": 3143, "text": "Once we have our Project ID we upload the model by running the following code (you should first change it with your Project ID)." }, { "code": null, "e": 3543, "s": 3272, "text": "from sklearn.externals import joblibfrom firebase_admin import storagejoblib.dump(clf, 'model.joblib')bucket = storage.bucket(name='[YOUR PROJECT ID HERE].appspot.com')b = bucket.blob('model-v1/model.joblib')b.upload_from_filename('model.joblib')print('model uploaded!')" }, { "code": null, "e": 3701, "s": 3543, "text": "Now we can verify that the model has been correctly uploaded by checking in Firebase Storage inside the specified directory (which in our case is model-v1/)." }, { "code": null, "e": 3773, "s": 3701, "text": "Now that the model has been stored, it can be connected to AI Platform." }, { "code": null, "e": 3981, "s": 3773, "text": "We need to enable a couple of APIs in Google Cloud Platform. On the left panel, inside the Library section, we look for the APIs “AI Platform Training & Prediction API” and “Cloud Build API” and enable them." }, { "code": null, "e": 4102, "s": 3981, "text": "Now, on the left panel we click on AI Platform > models and we Create new model and input the corresponding information." }, { "code": null, "e": 4516, "s": 4102, "text": "Once we’ve created the model it’s time to create a version of it, which will point to the .joblib file that we previously stored. We click on the model > new version and fill the information. It’s important that we choose the same Python version that we used for training the model. We choose scikit-learn as the framework. When specifying its version, we can get it by running the following code in our notebook." }, { "code": null, "e": 4599, "s": 4516, "text": "import sklearnprint('The scikit-learn version is {}.'.format(sklearn.__version__))" }, { "code": null, "e": 4725, "s": 4599, "text": "When choosing the ML Runtime version, you should select the recommended one. The machine type can be left by default for now." }, { "code": null, "e": 4975, "s": 4725, "text": "Finally, we specify the folder in which our .joblib file is located. It’s important to select the folder, not the file! The rest of the fields can be left by default and save. At that moment, an instance of our model will be deployed in AI Platform." }, { "code": null, "e": 5180, "s": 4975, "text": "Now, we’ll be able to make predictions from the command line or from other Google APIs, such as Cloud Function, as we’ll see next. Additionally, we’ll be able to get some performance metrics on our model." }, { "code": null, "e": 5221, "s": 5180, "text": "Let’s see how to implement the function!" }, { "code": null, "e": 5519, "s": 5221, "text": "We’re going to run some commands on the terminal, but for that, you’ll need to ensure you have Node.js installed in your computer. The following commands are specific for Windows but you should be able to use them in Unix and Mac OS devices by adding sudo at the beginning of each of the commands." }, { "code": null, "e": 5598, "s": 5519, "text": "Let’s start by installing the Firebase client: $ npm install -g firebase-tools" }, { "code": null, "e": 5645, "s": 5598, "text": "We access the Google account: $ firebase login" }, { "code": null, "e": 5761, "s": 5645, "text": "Initialize a new project directory (make sure you’re in the directory you want to initialize it in):$ firebase init" }, { "code": null, "e": 6128, "s": 5761, "text": "When running this last command you’ll be asked several questions. When asked about the Firebase project that you want in the directory, you have to choose the one that contains the ML model that we previously exported. Select JavaScript as programming language. We don’t use ESLint, so answer no. And finally, answer yes to the installation of dependencies with npm." }, { "code": null, "e": 6212, "s": 6128, "text": "Once the project has been created, the directory will have the following structure:" }, { "code": null, "e": 6294, "s": 6212, "text": "Inside this directory, we’ll only modify the index.js and the package.json files." }, { "code": null, "e": 6356, "s": 6294, "text": "We install the packages of the Google API: $ npm i googleapis" }, { "code": null, "e": 6578, "s": 6356, "text": "Now we check the packages have been installed correctly by opening the package.json file. In case you want to use any other external package in your code you should also add it in this file with its corresponding version." }, { "code": null, "e": 6631, "s": 6578, "text": "For now, it should have a structure similar to this:" }, { "code": null, "e": 6747, "s": 6631, "text": "\"dependencies\"​: {\t​\"firebase-admin\"​: ​\"~7.0.0\"​,​\t\"firebase-functions\"​: ​\"^2.3.0\"​,​\t\"googleapis\"​: ​\"^39.2.0\"​}" }, { "code": null, "e": 6782, "s": 6747, "text": "I’ll briefly explain what they do:" }, { "code": null, "e": 6888, "s": 6782, "text": "firebase-admin​: It’s the Admin SDK, which allows to interact with Firebase from privileged environments." }, { "code": null, "e": 6972, "s": 6888, "text": "firebase-functions​: It’s an SDK for the definition of Cloud Functions in Firebase." }, { "code": null, "e": 7046, "s": 6972, "text": "googleapis: It’s the client library Node.js for the usage of Google APIs." }, { "code": null, "e": 7269, "s": 7046, "text": "Now let’s see the implementation of the function (we are editing the index.js file), which you can also find in this GitHub repository. As an example, I’ll be using the code to access a simple fake-account detection model." }, { "code": null, "e": 7342, "s": 7269, "text": "We start by loading the firebase-functions​ and ​firebase-admin modules." }, { "code": null, "e": 7449, "s": 7342, "text": "const​​ functions ​​= ​​require​(​'firebase-functions'​);const ​​admin​​ =​​ require​(​'firebase-admin'​);" }, { "code": null, "e": 7525, "s": 7449, "text": "We load the googleapis module and add the reference to the version 1 of ml." }, { "code": null, "e": 7689, "s": 7525, "text": "admin​.​initializeApp​(​functions​.​config​().​firebase​);const​​ googleapis_1​​ =​​ require​(​\"googleapis\"​);const​​ ml​​ = ​​googleapis_1​.​google​.​ml​(​'v1'​);" }, { "code": null, "e": 7744, "s": 7689, "text": "The requests are going to be sent to an http function." }, { "code": null, "e": 7837, "s": 7744, "text": "exports​.​predictSPAM​​ = ​​functions​.​https​.​onRequest​(​async​​(request,​​response)​​=>{" }, { "code": null, "e": 8082, "s": 7837, "text": "We specify the input values of the function. In this example, I’m getting some data about the social media account that my model will use to classify as fake or not. You should specify the fields that you plan to input afterwards to your model." }, { "code": null, "e": 8350, "s": 8082, "text": "const ​​account_days_old​​ = ​​request​.​body​.​account_days_old​;​const​​ followers_count​​ =​​ request​.​body​.​followers_count​;​const ​​following_count ​​= ​​request​.​body​.​following_count​;​const​​ publications_count​​ =​​ request​.​body​.​publications_count​;" }, { "code": null, "e": 8587, "s": 8350, "text": "After that, we build the input of the model, that is, the input parameters that we’ll send to the model to get the prediction. Note that these inputs should follow the same structure (order of features) with which the model was trained." }, { "code": null, "e": 8680, "s": 8587, "text": "const​​ instance ​​= [[account_days_old,followers_count,following_count,publications_count]]" }, { "code": null, "e": 8823, "s": 8680, "text": "Now, let’s make the request to the Google API, this request needs authentication, which will connect our Firebase credentials with Google API." }, { "code": null, "e": 8968, "s": 8823, "text": "const ​​model​​ =​​ \"[HERE THE NAME OF YOUR MODEL]\"​;​const​ { ​credential​ } ​=​​ awaitgoogleapis_1​.​google​.​auth​.​getApplicationDefault​();" }, { "code": null, "e": 9229, "s": 8968, "text": "After storing the name of our model in a variable (the name should be the same you gave it in the AI Platform console), we make a prediction call to AI Platform by sending our credentials, the name of the model and the instance that we want the prediction for." }, { "code": null, "e": 9509, "s": 9229, "text": "const ​​modelName​​ =​​ `projects/[YOUR PROJECT ID HERE]/models/​${​model​}​`​;const​​ preds ​​= ​​await ​​ml​.​projects​.​predict​({\t\tauth​:​​ credential, \t\tname​:​​ modelName, \t\trequestBody​:​​ {\t\t\t​instance\t\t​}​\t});​\tresponse​.​send​(​preds​.​data​[​'predictions'​][​0​]);});" }, { "code": null, "e": 9634, "s": 9509, "text": "Once we’ve created the cloud function that accesses the model, we just need to upload it to Firebase to deploy it as an API." }, { "code": null, "e": 9747, "s": 9634, "text": "To upload the Firebase function we run the following command in the terminal: $ firebase deploy --only functions" }, { "code": null, "e": 9946, "s": 9747, "text": "Once it has finished loading, a URL is obtained through which the function will be accessible, which can be found by logging into Firestore, in the Functions section, under Request in smaller print." }, { "code": null, "e": 10016, "s": 9946, "text": "And that’s all, now your model is up and running, ready to share! 🎉🎉🎉" }, { "code": null, "e": 10114, "s": 10016, "text": "You can make requests to this API from a mobile app, a website...it could be integrated anywhere!" }, { "code": null, "e": 10321, "s": 10114, "text": "This is, of course, an optional step, if you followed the previous guidelines, your model should be ready to receive requests. However, as a programmer, I like to test things to check everything works fine." }, { "code": null, "e": 10556, "s": 10321, "text": "My favourite way to test APIs is by using Insomnia. Insomnia is a REST API client that lets you test your APIs easily. This free desktop app is available for Windows, MacOS and Ubuntu. Let’s check if our newly made API works properly!" }, { "code": null, "e": 10622, "s": 10556, "text": "Once we’ve installed the desktop app we can create a new request." }, { "code": null, "e": 10707, "s": 10622, "text": "We’ll write the request name and choose POST as a method and JSON for its structure." }, { "code": null, "e": 10809, "s": 10707, "text": "Once we’ve created the request, we copy the URL of the cloud function and we paste it in the top bar." }, { "code": null, "e": 10926, "s": 10809, "text": "We will now write the request following the format that we specified in the function, in my case, it’d be like this:" }, { "code": null, "e": 11033, "s": 10926, "text": "{ \"account_days_old\": 32, \"followers_count\": 162, \"following_count\": 152, \"publications_count\": 45,}" }, { "code": null, "e": 11215, "s": 11033, "text": "We now hit SEND and we’ll get the response, as well as the response time and its size. If there were any errors you should also receive the error code instead of the 200 OK message." }, { "code": null, "e": 11396, "s": 11215, "text": "The response that you get will, of course, vary depending on your model. But if everything works fine, then congrats! You’re ready to share your model with the rest of the world! 🌍" }, { "code": null, "e": 11491, "s": 11396, "text": "If you made it this far, thank you for your time and I hope you got some value from this post😊" } ]
Difference between Write-Output and Write-Host command in PowerShell?
Have we ever wondered, Write-Output and Write-Host both are used to print the strings or the output of the command then what is the difference between them? PS C:\> Write-Output "Test String" Test String PS C:\> Write-Host "Test String" Test String The output remains the same. The first major difference is storing the output using the Pipeline structure. Write-Output and Write-Host both support the pipeline structure for example, "Test String" | Write-Output Test String "Test String" | Write-Host Test String The output remains the same. The first major difference is storing the output using the Pipeline structure. Write-Output and Write-Host both support the pipeline structure for example, "Test String" | Write-Output Test String "Test String" | Write-Host Test String But when we store the output then it shows the difference between two commands. $a = "Test String" | Write-Output Get-Variable a Name Value ---- ----- a Test String $b = "Test String" | Write-Host Test String Get-Variable b Name Value ---- ----- b In the above example, when the string output is stored into a variable, Write-Output can store it while Write-Host displays the output in the console and the output is not assigned to a variable because Write-Host produces output directly to the console while Write-Output produces and store the output inside the variable. That is the reason it is not recommended to use the Write-Host for the PowerShell remoting if scripter is not aware of the remote host having the console working properly or not. Another difference is, with the Write-Host cmdlet, you can decorate the output with background and foreground (text) color and this is not possible in Write-Output command. Write-Host "Dark green backgound with White text" -BackgroundColor DarkGreen -ForegroundColor White Dark green backgound with White text
[ { "code": null, "e": 1219, "s": 1062, "text": "Have we ever wondered, Write-Output and Write-Host both are used to print the strings or the output of the command then what is the difference between them?" }, { "code": null, "e": 1311, "s": 1219, "text": "PS C:\\> Write-Output \"Test String\"\nTest String\nPS C:\\> Write-Host \"Test String\"\nTest String" }, { "code": null, "e": 1340, "s": 1311, "text": "The output remains the same." }, { "code": null, "e": 1496, "s": 1340, "text": "The first major difference is storing the output using the Pipeline structure. Write-Output and Write-Host both support the pipeline structure for example," }, { "code": null, "e": 1577, "s": 1496, "text": "\"Test String\" | Write-Output\nTest String\n\n\"Test String\" | Write-Host\nTest String" }, { "code": null, "e": 1606, "s": 1577, "text": "The output remains the same." }, { "code": null, "e": 1762, "s": 1606, "text": "The first major difference is storing the output using the Pipeline structure. Write-Output and Write-Host both support the pipeline structure for example," }, { "code": null, "e": 1843, "s": 1762, "text": "\"Test String\" | Write-Output\nTest String\n\n\"Test String\" | Write-Host\nTest String" }, { "code": null, "e": 1923, "s": 1843, "text": "But when we store the output then it shows the difference between two commands." }, { "code": null, "e": 2097, "s": 1923, "text": "$a = \"Test String\" | Write-Output\n\nGet-Variable a\n\nName Value\n---- -----\na Test String\n\n\n$b = \"Test String\" | Write-Host\nTest String\n\nGet-Variable b\n\nName Value\n---- -----\nb" }, { "code": null, "e": 2600, "s": 2097, "text": "In the above example, when the string output is stored into a variable, Write-Output can store it while Write-Host displays the output in the console and the output is not assigned to a variable because Write-Host produces output directly to the console while Write-Output produces and store the output inside the variable. That is the reason it is not recommended to use the Write-Host for the PowerShell remoting if scripter is not aware of the remote host having the console working properly or not." }, { "code": null, "e": 2773, "s": 2600, "text": "Another difference is, with the Write-Host cmdlet, you can decorate the output with background and foreground (text) color and this is not possible in Write-Output command." }, { "code": null, "e": 2911, "s": 2773, "text": "Write-Host \"Dark green backgound with White text\" -BackgroundColor DarkGreen -ForegroundColor White\n\nDark green backgound with White text" } ]
Difference between %p and %x in C/C++
Here we will see what are the differences between %p and %x in C or C++. The %p is used to print the pointer value, and %x is used to print hexadecimal values. Though pointers can also be displayed using %u, or %x. If we want to print some value using %p and %x then we will not feel any major differences. The only difference that can be noticed is that the %p will print some leading zeros, but %x doesn’t. #include<stdio.h> main() { int x = 59; printf("Value using %%p: %p\n", x); printf("Value using %%x: %x\n", x); } Value using %p: 000000000000003B Value using %x: 3b
[ { "code": null, "e": 1471, "s": 1062, "text": "Here we will see what are the differences between %p and %x in C or C++. The %p is used to print the pointer value, and %x is used to print hexadecimal values. Though pointers can also be displayed using %u, or %x. If we want to print some value using %p and %x then we will not feel any major differences. The only difference that can be noticed is that the %p will print some leading zeros, but %x doesn’t." }, { "code": null, "e": 1593, "s": 1471, "text": "#include<stdio.h>\nmain() {\n int x = 59;\n printf(\"Value using %%p: %p\\n\", x);\n printf(\"Value using %%x: %x\\n\", x);\n}" }, { "code": null, "e": 1645, "s": 1593, "text": "Value using %p: 000000000000003B\nValue using %x: 3b" } ]
Tryit Editor v3.7
Tryit: Different text transformations
[]
Swarm intelligence: Inside the ant colony | by Fabrizio Brioccia | Towards Data Science
“The whole is greater than the sum of its parts” is a well-known quote that according to the Gestalt psychology sums up the idea that a system — the whole — is something more complex and different from the aggregation of its basic elements. In other words, the attempt to understand a complex system trying to dissect it into its basic parts would inevitably fail, leaving out something that the single parts cannot express by their own. Leaving aside the Gestalt psychology, the opening quote will be useful to understand the topic of this dissertation: the ant colony optimization algorithm (ACO). The ant society is a well-organized and hierarchical structure with specific roles and codified behavior. Even though there are many species of ants and each of these has their own features, we can identify a common organization structure: the queen and the workers. The workers carry out the various tasks of the colony: foraging, nest maintenance, larvae care, defense, etc. It is by the observation of the foraging behavior of ants that in 1992 Marco Dorigo proposed the Ant colony optimization algorithm, contributing to the metaheuristic studies and to what later will be defined Swarm Intelligence. The idea arose from the observation of the foraging ant behavior: when an ant leaves the nest in search of food, she would lay down a pheromone trail that the other ants are able to follow; if she reaches some food, she will return to the nest — using the same path — leaving even more pheromone on her way back. If she does not find any food, she will not lay down any pheromone in the way back to the nest and the previous trail will evaporate away. In the case that other foraging ants would chase upon those trails, most of them will follow the trails and find the food adding their pheromone to the path. Another group will not find any trace or decide to follow other paths and other ants will diverge before reaching the end of the trail. If we apply this kind of behavior on a large colony, we would see that strong pheromone trails emerge linking the nest to the food sources. This indirect communication mechanism based on pheromone is at the basis of the knowledge sharing within the colony and allows the ants to find better paths towards food. It is from the early 90s that the biological example of the ant colonies was for the first time translated into a real method for combinatorial optimization problems. This kind of problem consists of finding the global maximum of a given function within a framework of constraints. Combinatorial optimization problems can be described by the model: P=(S, Ω, ƒ) Where S is a finite set of variables with a specific finite domain, Ω is a set of constraints among the variables and ƒ is the objective function: to be minimize\maximize. A feasible solution is simply the collection of all decision variables with an assigned value from their domain in such a way that none of the omega constraints are violated. The solution algorithm will assign to each variable a specific value called solution component;a single solution is the set of all the solution components. The search of the optimal solution and the large number of constraints make those kinds of problems hard to solve, also because the exhaustive search is often not possible. Let us consider for example the traveling salesman problem (TSP). The problem is the following:“Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?”. This is a clear example of combinatorial optimization that often cannot be resolved with an exhaustive search and mathematical exact methods fail to converge in an acceptable amount of time due to a large number of constraints that the mathematical model has to generate and handle. Throughout the years, many heuristic algorithms have been developed and applied to this kind of NP-hard problems. Going back to the ACO, we can formalize the TSP problem using the P model introduced before: First, we associate to each of the nodes representing the n cities a variable X(i) whose domain has n-1 values: j = {1, ... , n} where j != i. On each edge between a pair of cities, we associate a numerical value τ representing the pheromone value. A set of all X(i) with an assigned domain value is a solution if and only if the set of edges corresponding to those values forms a Hamiltonian cycle (this constraint can be introduced in the ant selection behavior). Finally, the function (minimize) ƒ computes for each solution the sum of the lengths of the edges. Since its introduction the ACO algorithm has been proposed in many different versions; the following is the general algorithmic idea of the ACO: begin initialization(); while (termination condition not met) do ConstructAntSolutions(); LocalSearch(); GlobalPheromoneUpdate(); endend Initially, we start with a series of solution components that will allow us to build up the construction graph, a list of constraints to take into account and some parameters that will be used in the algorithm. In the initialization step, all the parameters are set and the construction graph is laid out, and an initial pheromone value is assigned to each variable (edge). In the ConstructAntSolutions phase, a set of m ants start one after the other, to construct a solution by traversing the graph. Each ant stores its own solution and updates it while traveling along the graph. In the beginning, all the ants start with an empty solution, and on each construction step, the current solution is extended by choosing one of the nodes representing a feasible component. Ideally, this process of choosing components and update the partial solution is carried out maintaining solution feasibility, if this is not possible or too hard to maintain, the partial solution can be dropped or penalized, depending on the degree of constraints violation, once it has been completed. The selection process is implemented computing for each solution component its possibility to be chosen: Where τ is the pheromone on the arc, η is the heuristic information, for now, we can define it as a special value of each component solution. (It will be described few lines below). N(s(p)) is the solution components set that can be added maintaining feasibility. α and ß are parameters with a value fixed in the initialization step that determines the relative importance of the pheromone value and the heuristic information. Once p has been computed we can apply the so-called pseudorandom proportional rule: Where r is a random number between 0 and 1 and q0 is a fixed parameter also between 0 and 1 that works as a threshold on r, which allows us to give more emphasis on exploration or exploitation. In fact, if r is greater or equal q0 the ant will choose randomly between the solution components according to the probability distribution of p (exploration). The heuristic information is a numerical value computed on the component solution (node) that represents the quality or the importance of that component in terms of the problem specific knowledge. The heuristic information can be computed a priori in the initialization step or it can be computed at run-time. For most of the NP-hard problems, the heuristic information is known a priori and it does not change throughout the algorithm execution. In other cases, the heuristic information depends on the partial solution constructed so far and therefore computed on each step. In the TSP, for example, η is defined by the length of the edge: d(ij) to the power of minus one. The LocalSearch step is optional; the purpose of this phase is to improve the solutions obtained by the ants by exploiting the problem knowledge i.e. moving and replacing some solution components with others. Finally, in the GlobalPheromoneUpdate the pheromone deposit and evaporation process are applied to the graph. The goal of this phase is to make good solutions more desirable for the next iterations. This is achieved in two ways, first by increasing the pheromone value on the edges belonging to the best solution or to a list of good solutions, then by simulating the pheromone evaporation. At this point of the process, we already have a list of complete solutions produced by the ants; moreover, we can evaluate such solutions by the so-called evaluation function or objective function that determines the quality of a given complete solution (the sum of the distances in the case of the TSP). Also for this phase, there exist many pheromone update approaches, for example, we can decide to strengthen the pheromone of the single best solution so far. The common approach is more general, for each complete solution of the current iteration; we update each pheromone variable using the following formula: Where 1 is the fraction of the old pheromone that persists on the edge(0 < ρ< 1) and 2 is the sum of all the evaluation functions that contain that particular component. Therefore, if the current edge i-j is not contemplated by any solution then the second term of the formula is zero and the pheromone is updated using the simple evaporation mechanism (1). After the update of the pheromone, the termination condition is checked to see if the results are good enough, for example, if there is no improvement of the best solution in 100 consecutive iterations we may decide to stop. Now that I know what Ant Colony optimization is, what do I get out of it? The applications of ACO are many and related to different fields, here some examples: - Routing problems - Assignment and Scheduling problems - Classification Rules - Protein Folding - DNA sequencing - Bayesian Network ... and many others Its wide potential application derived from the flexibility of the whole method to introduce, alongside the pheromone mechanism, a specific problem knowledge in the pheromone distribution and in the evaluation phase. Before concluding this glimpse on the ACO metaheuristic is worth to show an example of its application on a common research area in data science: feature selection. The problem of high-dimensional spaces is a common issue that affects many datasets used for numerical analysis, machine learning, data mining, etc. Leaving aside the problems that a high-dimensional space can entail (learn more about it), is interesting how ACO can be used as feature reduction method. Starting with a list of n features, we want to reduce the entire set, searching for a subset that contains the most important and representative features. First, since the ACO is a graph based metaheuristic we need to lay out the entire graph. Each node of the graph represents a feature of the initial n feature set, and each edge represents a choice from the actual feature to the other. Each ant will start with an empty set of feature and travel through the graph visiting a minimum number of nodes that can satisfy the traversal-stopping criterion, and finally output a candidate subset. As shown in the figure, an ant started on node A performed a route up to node F and then stop having built the following subset {A, B, C, D, F} that satisfy the traversal stopping criterion (e.g. suitably high classification accuracy). The heuristic information can be computed by any appropriate metric function, for example, an entropy-based measure can be very effective. The ant selection process and the pheromone update is performed with the same approach described. The whole process follows these steps: m ants are generated and placed randomly across the graph.From these random positions, each ant starts to construct a path by traversing the edges until the traversing stop criterion is satisfied. All the subset are collected and evaluated; if one of these subsets is good enough or the iterations have been executed a certain number of times, the process stops and the best subset found is returned. If none of these stopping conditions holds, then the pheromone is updated and a new group of ants is generated and a new iteration starts. As described the ACO is born from the observation of the animal world, in particular from the observation of large groups of single simple organisms such as the ants. This kind of intuitions derived directly from nature is the evidence that the animal world can be a source of inspiration and knowledge. The ACO metaheuristic represents nowadays a well-known and solid approach to a multiplicity of problems; it exists in a variety of flavors with simple or very complex formalizations. One of the strongest points of the ACO is its ability to discover rapidly good solution; this advantage is counterbalanced sometimes by its premature convergence. Even though is not applicable to continuous problems the ACO is surely an effective solution for many optimization/discrete problems that deserve to be included in a data scientist toolbox.
[ { "code": null, "e": 413, "s": 172, "text": "“The whole is greater than the sum of its parts” is a well-known quote that according to the Gestalt psychology sums up the idea that a system — the whole — is something more complex and different from the aggregation of its basic elements." }, { "code": null, "e": 610, "s": 413, "text": "In other words, the attempt to understand a complex system trying to dissect it into its basic parts would inevitably fail, leaving out something that the single parts cannot express by their own." }, { "code": null, "e": 772, "s": 610, "text": "Leaving aside the Gestalt psychology, the opening quote will be useful to understand the topic of this dissertation: the ant colony optimization algorithm (ACO)." }, { "code": null, "e": 878, "s": 772, "text": "The ant society is a well-organized and hierarchical structure with specific roles and codified behavior." }, { "code": null, "e": 1039, "s": 878, "text": "Even though there are many species of ants and each of these has their own features, we can identify a common organization structure: the queen and the workers." }, { "code": null, "e": 1149, "s": 1039, "text": "The workers carry out the various tasks of the colony: foraging, nest maintenance, larvae care, defense, etc." }, { "code": null, "e": 1377, "s": 1149, "text": "It is by the observation of the foraging behavior of ants that in 1992 Marco Dorigo proposed the Ant colony optimization algorithm, contributing to the metaheuristic studies and to what later will be defined Swarm Intelligence." }, { "code": null, "e": 1690, "s": 1377, "text": "The idea arose from the observation of the foraging ant behavior: when an ant leaves the nest in search of food, she would lay down a pheromone trail that the other ants are able to follow; if she reaches some food, she will return to the nest — using the same path — leaving even more pheromone on her way back." }, { "code": null, "e": 1829, "s": 1690, "text": "If she does not find any food, she will not lay down any pheromone in the way back to the nest and the previous trail will evaporate away." }, { "code": null, "e": 1987, "s": 1829, "text": "In the case that other foraging ants would chase upon those trails, most of them will follow the trails and find the food adding their pheromone to the path." }, { "code": null, "e": 2123, "s": 1987, "text": "Another group will not find any trace or decide to follow other paths and other ants will diverge before reaching the end of the trail." }, { "code": null, "e": 2263, "s": 2123, "text": "If we apply this kind of behavior on a large colony, we would see that strong pheromone trails emerge linking the nest to the food sources." }, { "code": null, "e": 2434, "s": 2263, "text": "This indirect communication mechanism based on pheromone is at the basis of the knowledge sharing within the colony and allows the ants to find better paths towards food." }, { "code": null, "e": 2601, "s": 2434, "text": "It is from the early 90s that the biological example of the ant colonies was for the first time translated into a real method for combinatorial optimization problems." }, { "code": null, "e": 2716, "s": 2601, "text": "This kind of problem consists of finding the global maximum of a given function within a framework of constraints." }, { "code": null, "e": 2783, "s": 2716, "text": "Combinatorial optimization problems can be described by the model:" }, { "code": null, "e": 2795, "s": 2783, "text": "P=(S, Ω, ƒ)" }, { "code": null, "e": 2967, "s": 2795, "text": "Where S is a finite set of variables with a specific finite domain, Ω is a set of constraints among the variables and ƒ is the objective function: to be minimize\\maximize." }, { "code": null, "e": 3142, "s": 2967, "text": "A feasible solution is simply the collection of all decision variables with an assigned value from their domain in such a way that none of the omega constraints are violated." }, { "code": null, "e": 3298, "s": 3142, "text": "The solution algorithm will assign to each variable a specific value called solution component;a single solution is the set of all the solution components." }, { "code": null, "e": 3471, "s": 3298, "text": "The search of the optimal solution and the large number of constraints make those kinds of problems hard to solve, also because the exhaustive search is often not possible." }, { "code": null, "e": 3537, "s": 3471, "text": "Let us consider for example the traveling salesman problem (TSP)." }, { "code": null, "e": 3729, "s": 3537, "text": "The problem is the following:“Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?”." }, { "code": null, "e": 4012, "s": 3729, "text": "This is a clear example of combinatorial optimization that often cannot be resolved with an exhaustive search and mathematical exact methods fail to converge in an acceptable amount of time due to a large number of constraints that the mathematical model has to generate and handle." }, { "code": null, "e": 4126, "s": 4012, "text": "Throughout the years, many heuristic algorithms have been developed and applied to this kind of NP-hard problems." }, { "code": null, "e": 4219, "s": 4126, "text": "Going back to the ACO, we can formalize the TSP problem using the P model introduced before:" }, { "code": null, "e": 4362, "s": 4219, "text": "First, we associate to each of the nodes representing the n cities a variable X(i) whose domain has n-1 values: j = {1, ... , n} where j != i." }, { "code": null, "e": 4468, "s": 4362, "text": "On each edge between a pair of cities, we associate a numerical value τ representing the pheromone value." }, { "code": null, "e": 4685, "s": 4468, "text": "A set of all X(i) with an assigned domain value is a solution if and only if the set of edges corresponding to those values forms a Hamiltonian cycle (this constraint can be introduced in the ant selection behavior)." }, { "code": null, "e": 4784, "s": 4685, "text": "Finally, the function (minimize) ƒ computes for each solution the sum of the lengths of the edges." }, { "code": null, "e": 4929, "s": 4784, "text": "Since its introduction the ACO algorithm has been proposed in many different versions; the following is the general algorithmic idea of the ACO:" }, { "code": null, "e": 5090, "s": 4929, "text": "begin initialization(); while (termination condition not met) do ConstructAntSolutions(); LocalSearch(); GlobalPheromoneUpdate(); endend" }, { "code": null, "e": 5301, "s": 5090, "text": "Initially, we start with a series of solution components that will allow us to build up the construction graph, a list of constraints to take into account and some parameters that will be used in the algorithm." }, { "code": null, "e": 5464, "s": 5301, "text": "In the initialization step, all the parameters are set and the construction graph is laid out, and an initial pheromone value is assigned to each variable (edge)." }, { "code": null, "e": 5592, "s": 5464, "text": "In the ConstructAntSolutions phase, a set of m ants start one after the other, to construct a solution by traversing the graph." }, { "code": null, "e": 5673, "s": 5592, "text": "Each ant stores its own solution and updates it while traveling along the graph." }, { "code": null, "e": 5862, "s": 5673, "text": "In the beginning, all the ants start with an empty solution, and on each construction step, the current solution is extended by choosing one of the nodes representing a feasible component." }, { "code": null, "e": 6165, "s": 5862, "text": "Ideally, this process of choosing components and update the partial solution is carried out maintaining solution feasibility, if this is not possible or too hard to maintain, the partial solution can be dropped or penalized, depending on the degree of constraints violation, once it has been completed." }, { "code": null, "e": 6270, "s": 6165, "text": "The selection process is implemented computing for each solution component its possibility to be chosen:" }, { "code": null, "e": 6452, "s": 6270, "text": "Where τ is the pheromone on the arc, η is the heuristic information, for now, we can define it as a special value of each component solution. (It will be described few lines below)." }, { "code": null, "e": 6534, "s": 6452, "text": "N(s(p)) is the solution components set that can be added maintaining feasibility." }, { "code": null, "e": 6697, "s": 6534, "text": "α and ß are parameters with a value fixed in the initialization step that determines the relative importance of the pheromone value and the heuristic information." }, { "code": null, "e": 6781, "s": 6697, "text": "Once p has been computed we can apply the so-called pseudorandom proportional rule:" }, { "code": null, "e": 6975, "s": 6781, "text": "Where r is a random number between 0 and 1 and q0 is a fixed parameter also between 0 and 1 that works as a threshold on r, which allows us to give more emphasis on exploration or exploitation." }, { "code": null, "e": 7135, "s": 6975, "text": "In fact, if r is greater or equal q0 the ant will choose randomly between the solution components according to the probability distribution of p (exploration)." }, { "code": null, "e": 7332, "s": 7135, "text": "The heuristic information is a numerical value computed on the component solution (node) that represents the quality or the importance of that component in terms of the problem specific knowledge." }, { "code": null, "e": 7445, "s": 7332, "text": "The heuristic information can be computed a priori in the initialization step or it can be computed at run-time." }, { "code": null, "e": 7582, "s": 7445, "text": "For most of the NP-hard problems, the heuristic information is known a priori and it does not change throughout the algorithm execution." }, { "code": null, "e": 7712, "s": 7582, "text": "In other cases, the heuristic information depends on the partial solution constructed so far and therefore computed on each step." }, { "code": null, "e": 7810, "s": 7712, "text": "In the TSP, for example, η is defined by the length of the edge: d(ij) to the power of minus one." }, { "code": null, "e": 8019, "s": 7810, "text": "The LocalSearch step is optional; the purpose of this phase is to improve the solutions obtained by the ants by exploiting the problem knowledge i.e. moving and replacing some solution components with others." }, { "code": null, "e": 8129, "s": 8019, "text": "Finally, in the GlobalPheromoneUpdate the pheromone deposit and evaporation process are applied to the graph." }, { "code": null, "e": 8218, "s": 8129, "text": "The goal of this phase is to make good solutions more desirable for the next iterations." }, { "code": null, "e": 8410, "s": 8218, "text": "This is achieved in two ways, first by increasing the pheromone value on the edges belonging to the best solution or to a list of good solutions, then by simulating the pheromone evaporation." }, { "code": null, "e": 8715, "s": 8410, "text": "At this point of the process, we already have a list of complete solutions produced by the ants; moreover, we can evaluate such solutions by the so-called evaluation function or objective function that determines the quality of a given complete solution (the sum of the distances in the case of the TSP)." }, { "code": null, "e": 8873, "s": 8715, "text": "Also for this phase, there exist many pheromone update approaches, for example, we can decide to strengthen the pheromone of the single best solution so far." }, { "code": null, "e": 9026, "s": 8873, "text": "The common approach is more general, for each complete solution of the current iteration; we update each pheromone variable using the following formula:" }, { "code": null, "e": 9196, "s": 9026, "text": "Where 1 is the fraction of the old pheromone that persists on the edge(0 < ρ< 1) and 2 is the sum of all the evaluation functions that contain that particular component." }, { "code": null, "e": 9384, "s": 9196, "text": "Therefore, if the current edge i-j is not contemplated by any solution then the second term of the formula is zero and the pheromone is updated using the simple evaporation mechanism (1)." }, { "code": null, "e": 9609, "s": 9384, "text": "After the update of the pheromone, the termination condition is checked to see if the results are good enough, for example, if there is no improvement of the best solution in 100 consecutive iterations we may decide to stop." }, { "code": null, "e": 9683, "s": 9609, "text": "Now that I know what Ant Colony optimization is, what do I get out of it?" }, { "code": null, "e": 9769, "s": 9683, "text": "The applications of ACO are many and related to different fields, here some examples:" }, { "code": null, "e": 9788, "s": 9769, "text": "- Routing problems" }, { "code": null, "e": 9825, "s": 9788, "text": "- Assignment and Scheduling problems" }, { "code": null, "e": 9848, "s": 9825, "text": "- Classification Rules" }, { "code": null, "e": 9866, "s": 9848, "text": "- Protein Folding" }, { "code": null, "e": 9883, "s": 9866, "text": "- DNA sequencing" }, { "code": null, "e": 9902, "s": 9883, "text": "- Bayesian Network" }, { "code": null, "e": 9922, "s": 9902, "text": "... and many others" }, { "code": null, "e": 10139, "s": 9922, "text": "Its wide potential application derived from the flexibility of the whole method to introduce, alongside the pheromone mechanism, a specific problem knowledge in the pheromone distribution and in the evaluation phase." }, { "code": null, "e": 10304, "s": 10139, "text": "Before concluding this glimpse on the ACO metaheuristic is worth to show an example of its application on a common research area in data science: feature selection." }, { "code": null, "e": 10453, "s": 10304, "text": "The problem of high-dimensional spaces is a common issue that affects many datasets used for numerical analysis, machine learning, data mining, etc." }, { "code": null, "e": 10608, "s": 10453, "text": "Leaving aside the problems that a high-dimensional space can entail (learn more about it), is interesting how ACO can be used as feature reduction method." }, { "code": null, "e": 10763, "s": 10608, "text": "Starting with a list of n features, we want to reduce the entire set, searching for a subset that contains the most important and representative features." }, { "code": null, "e": 10852, "s": 10763, "text": "First, since the ACO is a graph based metaheuristic we need to lay out the entire graph." }, { "code": null, "e": 10998, "s": 10852, "text": "Each node of the graph represents a feature of the initial n feature set, and each edge represents a choice from the actual feature to the other." }, { "code": null, "e": 11201, "s": 10998, "text": "Each ant will start with an empty set of feature and travel through the graph visiting a minimum number of nodes that can satisfy the traversal-stopping criterion, and finally output a candidate subset." }, { "code": null, "e": 11437, "s": 11201, "text": "As shown in the figure, an ant started on node A performed a route up to node F and then stop having built the following subset {A, B, C, D, F} that satisfy the traversal stopping criterion (e.g. suitably high classification accuracy)." }, { "code": null, "e": 11576, "s": 11437, "text": "The heuristic information can be computed by any appropriate metric function, for example, an entropy-based measure can be very effective." }, { "code": null, "e": 11674, "s": 11576, "text": "The ant selection process and the pheromone update is performed with the same approach described." }, { "code": null, "e": 11910, "s": 11674, "text": "The whole process follows these steps: m ants are generated and placed randomly across the graph.From these random positions, each ant starts to construct a path by traversing the edges until the traversing stop criterion is satisfied." }, { "code": null, "e": 12114, "s": 11910, "text": "All the subset are collected and evaluated; if one of these subsets is good enough or the iterations have been executed a certain number of times, the process stops and the best subset found is returned." }, { "code": null, "e": 12253, "s": 12114, "text": "If none of these stopping conditions holds, then the pheromone is updated and a new group of ants is generated and a new iteration starts." }, { "code": null, "e": 12420, "s": 12253, "text": "As described the ACO is born from the observation of the animal world, in particular from the observation of large groups of single simple organisms such as the ants." }, { "code": null, "e": 12557, "s": 12420, "text": "This kind of intuitions derived directly from nature is the evidence that the animal world can be a source of inspiration and knowledge." }, { "code": null, "e": 12740, "s": 12557, "text": "The ACO metaheuristic represents nowadays a well-known and solid approach to a multiplicity of problems; it exists in a variety of flavors with simple or very complex formalizations." }, { "code": null, "e": 12903, "s": 12740, "text": "One of the strongest points of the ACO is its ability to discover rapidly good solution; this advantage is counterbalanced sometimes by its premature convergence." } ]
How to add rounded corners to a button with CSS?
To add rounded corners to a button, use the border-radius property. You can try to run the following code to add rounded corners − Live Demo <!DOCTYPE html> <html> <head> <style> .button { background-color: yellow; color: black; text-align: center; font-size: 15px; padding: 20px; border-radius: 15px; } </style> </head> <body> <h2>Result</h2> <p>Click below for result:</p> <button class = "button">Result</button> </body> </html>
[ { "code": null, "e": 1130, "s": 1062, "text": "To add rounded corners to a button, use the border-radius property." }, { "code": null, "e": 1193, "s": 1130, "text": "You can try to run the following code to add rounded corners −" }, { "code": null, "e": 1203, "s": 1193, "text": "Live Demo" }, { "code": null, "e": 1626, "s": 1203, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .button {\n background-color: yellow;\n color: black;\n text-align: center;\n font-size: 15px;\n padding: 20px;\n border-radius: 15px;\n }\n </style>\n </head>\n <body>\n <h2>Result</h2>\n <p>Click below for result:</p>\n <button class = \"button\">Result</button>\n </body>\n</html>" } ]
Underscore.js _.range() Function - GeeksforGeeks
24 Nov, 2021 _.range() function: It is used to print the list of elements from the start given as a parameter to the end also a parameter. The start and step parameters are optional. The default value of start is 0 and that of step is 1. In the list formed the start is inclusive and the stop is exclusive. The step parameter can be either positive or negative. Syntax: _.range([start], stop, [step]) Parameters:It takes three arguments: The start (optional) The stop The step (optional) Return value:The returned value is the list from the start till the end (exclusive).Examples: Passing only the stop parameter to the _.range() function:The ._range() function takes the element from the list one by one and do the specified operations on the code. Like here the operation is addition of the elements of the list. After adding all the elements, the reduce function ends. Here the starting value of memo is taken as ‘0’.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7)); </script></body> </html>Output:Passing 2 parameters to the _.range() function:We can even use this function by passing only 2 parameters, i.e., the start and the stop parameters then also it will have no errors. Like hers the start parameter is 7 which will be included in the list. And the end parameter is 14 which is not included in the list as per the _.range function. So we will take the default parameter of the step parameter which is one. Hence we will get a list from 7 till 13.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7, 14)); </script></body> </html>Output:Passing all the 3 parameters to the _.range() function:Here we take all the 3 parameters, i.e., the start, stop and the step of the list are mentioned. So, there is no need for the default values. Here the start is from 7 and the step is 3 that means the after 7 the element will be 7+3= 10 in the list. And the calculations will continue in the same manner till the end which is 20 comes.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7, 21, 3)); </script></body> </html>Output:Passing the stop less than the start parameter to the _.range() function:Even if we pass the start parameter less than the stop parameter, the _.range() function will not give any error. It will itself adjust the step parameter as negative to reach the stop from the start given. So, the list will contain numbers from 21 till 16 as the end, 15, is not included in the list.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(21, 15)); </script></body> </html>Output: Passing only the stop parameter to the _.range() function:The ._range() function takes the element from the list one by one and do the specified operations on the code. Like here the operation is addition of the elements of the list. After adding all the elements, the reduce function ends. Here the starting value of memo is taken as ‘0’.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7)); </script></body> </html> Output: Passing 2 parameters to the _.range() function:We can even use this function by passing only 2 parameters, i.e., the start and the stop parameters then also it will have no errors. Like hers the start parameter is 7 which will be included in the list. And the end parameter is 14 which is not included in the list as per the _.range function. So we will take the default parameter of the step parameter which is one. Hence we will get a list from 7 till 13.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7, 14)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7, 14)); </script></body> </html> Output: Passing all the 3 parameters to the _.range() function:Here we take all the 3 parameters, i.e., the start, stop and the step of the list are mentioned. So, there is no need for the default values. Here the start is from 7 and the step is 3 that means the after 7 the element will be 7+3= 10 in the list. And the calculations will continue in the same manner till the end which is 20 comes.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7, 21, 3)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(7, 21, 3)); </script></body> </html> Output: Passing the stop less than the start parameter to the _.range() function:Even if we pass the start parameter less than the stop parameter, the _.range() function will not give any error. It will itself adjust the step parameter as negative to reach the stop from the start given. So, the list will contain numbers from 21 till 16 as the end, 15, is not included in the list.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(21, 15)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.range(21, 15)); </script></body> </html> Output: NOTE:These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows: <!-- Write HTML code here --><script type="text/javascript" src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> An example is shown below: shubham_singh JavaScript - Underscore.js JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer 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 ? JavaScript | console.log() with Examples Difference Between PUT and PATCH Request How to read a local text file using JavaScript? Set the value of an input field in JavaScript How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 23982, "s": 23954, "text": "\n24 Nov, 2021" }, { "code": null, "e": 24002, "s": 23982, "text": "_.range() function:" }, { "code": null, "e": 24108, "s": 24002, "text": "It is used to print the list of elements from the start given as a parameter to the end also a parameter." }, { "code": null, "e": 24152, "s": 24108, "text": "The start and step parameters are optional." }, { "code": null, "e": 24207, "s": 24152, "text": "The default value of start is 0 and that of step is 1." }, { "code": null, "e": 24276, "s": 24207, "text": "In the list formed the start is inclusive and the stop is exclusive." }, { "code": null, "e": 24331, "s": 24276, "text": "The step parameter can be either positive or negative." }, { "code": null, "e": 24339, "s": 24331, "text": "Syntax:" }, { "code": null, "e": 24370, "s": 24339, "text": "_.range([start], stop, [step])" }, { "code": null, "e": 24407, "s": 24370, "text": "Parameters:It takes three arguments:" }, { "code": null, "e": 24428, "s": 24407, "text": "The start (optional)" }, { "code": null, "e": 24437, "s": 24428, "text": "The stop" }, { "code": null, "e": 24457, "s": 24437, "text": "The step (optional)" }, { "code": null, "e": 24551, "s": 24457, "text": "Return value:The returned value is the list from the start till the end (exclusive).Examples:" }, { "code": null, "e": 27227, "s": 24551, "text": "Passing only the stop parameter to the _.range() function:The ._range() function takes the element from the list one by one and do the specified operations on the code. Like here the operation is addition of the elements of the list. After adding all the elements, the reduce function ends. Here the starting value of memo is taken as ‘0’.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7)); </script></body> </html>Output:Passing 2 parameters to the _.range() function:We can even use this function by passing only 2 parameters, i.e., the start and the stop parameters then also it will have no errors. Like hers the start parameter is 7 which will be included in the list. And the end parameter is 14 which is not included in the list as per the _.range function. So we will take the default parameter of the step parameter which is one. Hence we will get a list from 7 till 13.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7, 14)); </script></body> </html>Output:Passing all the 3 parameters to the _.range() function:Here we take all the 3 parameters, i.e., the start, stop and the step of the list are mentioned. So, there is no need for the default values. Here the start is from 7 and the step is 3 that means the after 7 the element will be 7+3= 10 in the list. And the calculations will continue in the same manner till the end which is 20 comes.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7, 21, 3)); </script></body> </html>Output:Passing the stop less than the start parameter to the _.range() function:Even if we pass the start parameter less than the stop parameter, the _.range() function will not give any error. It will itself adjust the step parameter as negative to reach the stop from the start given. So, the list will contain numbers from 21 till 16 as the end, 15, is not included in the list.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(21, 15)); </script></body> </html>Output:" }, { "code": null, "e": 27842, "s": 27227, "text": "Passing only the stop parameter to the _.range() function:The ._range() function takes the element from the list one by one and do the specified operations on the code. Like here the operation is addition of the elements of the list. After adding all the elements, the reduce function ends. Here the starting value of memo is taken as ‘0’.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7)); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7)); </script></body> </html>", "e": 28111, "s": 27842, "text": null }, { "code": null, "e": 28119, "s": 28111, "text": "Output:" }, { "code": null, "e": 28856, "s": 28119, "text": "Passing 2 parameters to the _.range() function:We can even use this function by passing only 2 parameters, i.e., the start and the stop parameters then also it will have no errors. Like hers the start parameter is 7 which will be included in the list. And the end parameter is 14 which is not included in the list as per the _.range function. So we will take the default parameter of the step parameter which is one. Hence we will get a list from 7 till 13.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7, 14)); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7, 14)); </script></body> </html>", "e": 29129, "s": 28856, "text": null }, { "code": null, "e": 29137, "s": 29129, "text": "Output:" }, { "code": null, "e": 29809, "s": 29137, "text": "Passing all the 3 parameters to the _.range() function:Here we take all the 3 parameters, i.e., the start, stop and the step of the list are mentioned. So, there is no need for the default values. Here the start is from 7 and the step is 3 that means the after 7 the element will be 7+3= 10 in the list. And the calculations will continue in the same manner till the end which is 20 comes.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7, 21, 3)); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(7, 21, 3)); </script></body> </html>", "e": 30085, "s": 29809, "text": null }, { "code": null, "e": 30093, "s": 30085, "text": "Output:" }, { "code": null, "e": 30748, "s": 30093, "text": "Passing the stop less than the start parameter to the _.range() function:Even if we pass the start parameter less than the stop parameter, the _.range() function will not give any error. It will itself adjust the step parameter as negative to reach the stop from the start given. So, the list will contain numbers from 21 till 16 as the end, 15, is not included in the list.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(21, 15)); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> console.log(_.range(21, 15)); </script></body> </html>", "e": 31022, "s": 30748, "text": null }, { "code": null, "e": 31030, "s": 31022, "text": "Output:" }, { "code": null, "e": 31258, "s": 31030, "text": "NOTE:These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows:" }, { "code": "<!-- Write HTML code here --><script type=\"text/javascript\" src =\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"></script>", "e": 31412, "s": 31258, "text": null }, { "code": null, "e": 31439, "s": 31412, "text": "An example is shown below:" }, { "code": null, "e": 31453, "s": 31439, "text": "shubham_singh" }, { "code": null, "e": 31480, "s": 31453, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 31491, "s": 31480, "text": "JavaScript" }, { "code": null, "e": 31589, "s": 31491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31598, "s": 31589, "text": "Comments" }, { "code": null, "e": 31611, "s": 31598, "text": "Old Comments" }, { "code": null, "e": 31672, "s": 31611, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31717, "s": 31672, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31789, "s": 31717, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31841, "s": 31789, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31887, "s": 31841, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31928, "s": 31887, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 31969, "s": 31928, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 32017, "s": 31969, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 32063, "s": 32017, "text": "Set the value of an input field in JavaScript" } ]
Basic Tweet Preprocessing in Python | by Parthvi Shah | Towards Data Science
Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here. Just to give you a little background as to why I am preprocessing tweets: Given the current situation as of May, 2020, I am interested in the political discourse of the US Governors with respect to the ongoing pandemic. I would like to analyse how did the two parties — Republican & Democratic Party react to the given situation, COVID-19. What were their main goals at this time? Who focused more on what? What did they care about the most? After collecting tweets from all the Governor’s of the states starting from Day 1 of Case-1 of the COVID-19 case, we merged them into a DataFrame (How to merge various JSON files into a DataFrame) and performed preprocessing. We had a total of ~30,000 tweets. A tweet contains a lot of opinions about the data it represents. Raw tweets without preprocessing is highly unstructured and contains redundant information. To overcome these issues, preprocessing of tweets is performed by taking multiple steps. Almost every social media site is known for the topic it represents in the form of hashtags. Particularly for our case, Hashtags played an important part since we were interested in #Covid19 ,#Coronavirus, #StayHome, #InThisTogether, etc. Hence, the first step was forming a separate feature based on the hashtag values and segmented them. tweets[‘hashtag’] = tweets[‘tweet_text’].apply(lambda x: re.findall(r”#(\w+)”, x)) However, hashtags with more than one word had to segmented. We segmented those hashtags into n-words using the library ekphrasis. #installing ekphrasis!pip install ekphrasis After it’s installation, I selected a segmenter built on twitter-corpus — from ekphrasis.classes.segmenter import Segmenter#segmenter using the word statistics from Twitterseg_tw = Segmenter(corpus=”twitter”) The most relevant tweet-preprocessor I found — tweet-preprocessor, which is a tweet preprocessing library in Python. It deals with — URLs Mentions Reserved words (RT, FAV) Emojis Smileys #installing tweet-preprocessor!pip install tweet-preprocessor Cleaning is done using tweet-preprocessor package. import preprocessor as p#forming a separate feature for cleaned tweetsfor i,v in enumerate(tweets['text']): tweets.loc[v,’text’] = p.clean(i) NLTK (Natural Language Toolkit) is one of the best library for preprocessing text data. #important libraries for preprocessing using NLTKimport nltkfrom nltk import word_tokenize, FreqDistfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizernltk.downloadnltk.download('wordnet')nltk.download('stopwords')from nltk.tokenize import TweetTokenizer Remove Digits and lower the text (makes it easy to deal with) data = data.astype(str).str.replace('\d+', '')lower_text = data.str.lower() Remove Punctuations def remove_punctuation(words): new_words = [] for word in words: new_word = re.sub(r'[^\w\s]', '', (word)) if new_word != '': new_words.append(new_word) return new_words Lemmatization + Tokenization — Used a built in TweetTokenizer() lemmatizer = nltk.stem.WordNetLemmatizer()w_tokenizer = TweetTokenizer()def lemmatize_text(text): return [(lemmatizer.lemmatize(w)) for w in \ w_tokenizer.tokenize((text))] The last preprocessing step is Removing stop words — There is a pre-defined stop words list in English. However, you can modify your stop words like by simply appending the words to the stop words list. stop_words = set(stopwords.words('english'))tweets['text'] = tweets['text'].apply(lambda x: [item for item in \ x if item not in stop_words]) After the pre-processing steps, We excluded all the places names and abbreviations in the tweets because it acted as a leakage variable and then we performed a frequency distribution of the most occurring hashtags and created a word cloud — This was quite expected. from wordcloud import WordCloud#Frequency of wordsfdist = FreqDist(tweets['Segmented#'])#WordCloudwc = WordCloud(width=800, height=400, max_words=50).generate_from_frequencies(fdist)plt.figure(figsize=(12,10))plt.imshow(wc, interpolation="bilinear")plt.axis("off")plt.show() The final dataset — The final code — import pandas as pdimport numpy as npimport jsonfrom collections import Counterfrom wordcloud import WordCloudimport matplotlib.pyplot as pltimport re, string, unicodedataimport nltkfrom nltk import word_tokenize, sent_tokenize, FreqDistfrom nltk.corpus import stopwordsfrom nltk.stem import LancasterStemmer, WordNetLemmatizernltk.downloadnltk.download('wordnet')nltk.download('stopwords')from nltk.tokenize import TweetTokenizer!pip install ekphrasis!pip install tweet-preprocessorimport preprocessor as ptweets['hashtag'] = tweets['tweet_text'].apply(lambda x: re.findall(r"#(\w+)", x))for i,v in enumerate(tweets['text']): tweets.loc[v,’text’] = p.clean(i)def preprocess_data(data): #Removes Numbers data = data.astype(str).str.replace('\d+', '') lower_text = data.str.lower() lemmatizer = nltk.stem.WordNetLemmatizer() w_tokenizer = TweetTokenizer() def lemmatize_text(text): return [(lemmatizer.lemmatize(w)) for w \ in w_tokenizer.tokenize((text))] def remove_punctuation(words): new_words = [] for word in words: new_word = re.sub(r'[^\w\s]', '', (word)) if new_word != '': new_words.append(new_word) return new_words words = lower_text.apply(lemmatize_text) words = words.apply(remove_punctuation) return pd.DataFrame(words)pre_tweets = preprocess_data(tweets['text'])tweets['text'] = pre_tweetsstop_words = set(stopwords.words('english'))tweets['text'] = tweets['text'].apply(lambda x: [item for item in \ x if item not in stop_words])from ekphrasis.classes.segmenter import Segmenter# segmenter using the word statistics from Twitterseg_tw = Segmenter(corpus="twitter")a = []for i in range(len(tweets)): if tweets['hashtag'][i] != a listToStr1 = ' '.join([str(elem) for elem in \ tweets['hashtag'][i]]) tweets.loc[i,'Segmented#'] = seg_tw.segment(listToStr1)#Frequency of wordsfdist = FreqDist(tweets['Segmented#'])#WordCloudwc = WordCloud(width=800, height=400, max_words=50).generate_from_frequencies(fdist)plt.figure(figsize=(12,10))plt.imshow(wc, interpolation="bilinear")plt.axis("off")plt.show() Hope I helped y’all. Text classification in general works better if the text is preprocessed well. Do give some extra time to it, it will all be worth it in the end.
[ { "code": null, "e": 508, "s": 172, "text": "Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here." }, { "code": null, "e": 950, "s": 508, "text": "Just to give you a little background as to why I am preprocessing tweets: Given the current situation as of May, 2020, I am interested in the political discourse of the US Governors with respect to the ongoing pandemic. I would like to analyse how did the two parties — Republican & Democratic Party react to the given situation, COVID-19. What were their main goals at this time? Who focused more on what? What did they care about the most?" }, { "code": null, "e": 1176, "s": 950, "text": "After collecting tweets from all the Governor’s of the states starting from Day 1 of Case-1 of the COVID-19 case, we merged them into a DataFrame (How to merge various JSON files into a DataFrame) and performed preprocessing." }, { "code": null, "e": 1456, "s": 1176, "text": "We had a total of ~30,000 tweets. A tweet contains a lot of opinions about the data it represents. Raw tweets without preprocessing is highly unstructured and contains redundant information. To overcome these issues, preprocessing of tweets is performed by taking multiple steps." }, { "code": null, "e": 1796, "s": 1456, "text": "Almost every social media site is known for the topic it represents in the form of hashtags. Particularly for our case, Hashtags played an important part since we were interested in #Covid19 ,#Coronavirus, #StayHome, #InThisTogether, etc. Hence, the first step was forming a separate feature based on the hashtag values and segmented them." }, { "code": null, "e": 1879, "s": 1796, "text": "tweets[‘hashtag’] = tweets[‘tweet_text’].apply(lambda x: re.findall(r”#(\\w+)”, x))" }, { "code": null, "e": 2009, "s": 1879, "text": "However, hashtags with more than one word had to segmented. We segmented those hashtags into n-words using the library ekphrasis." }, { "code": null, "e": 2053, "s": 2009, "text": "#installing ekphrasis!pip install ekphrasis" }, { "code": null, "e": 2127, "s": 2053, "text": "After it’s installation, I selected a segmenter built on twitter-corpus —" }, { "code": null, "e": 2262, "s": 2127, "text": "from ekphrasis.classes.segmenter import Segmenter#segmenter using the word statistics from Twitterseg_tw = Segmenter(corpus=”twitter”)" }, { "code": null, "e": 2379, "s": 2262, "text": "The most relevant tweet-preprocessor I found — tweet-preprocessor, which is a tweet preprocessing library in Python." }, { "code": null, "e": 2395, "s": 2379, "text": "It deals with —" }, { "code": null, "e": 2400, "s": 2395, "text": "URLs" }, { "code": null, "e": 2409, "s": 2400, "text": "Mentions" }, { "code": null, "e": 2434, "s": 2409, "text": "Reserved words (RT, FAV)" }, { "code": null, "e": 2441, "s": 2434, "text": "Emojis" }, { "code": null, "e": 2449, "s": 2441, "text": "Smileys" }, { "code": null, "e": 2511, "s": 2449, "text": "#installing tweet-preprocessor!pip install tweet-preprocessor" }, { "code": null, "e": 2562, "s": 2511, "text": "Cleaning is done using tweet-preprocessor package." }, { "code": null, "e": 2707, "s": 2562, "text": "import preprocessor as p#forming a separate feature for cleaned tweetsfor i,v in enumerate(tweets['text']): tweets.loc[v,’text’] = p.clean(i)" }, { "code": null, "e": 2795, "s": 2707, "text": "NLTK (Natural Language Toolkit) is one of the best library for preprocessing text data." }, { "code": null, "e": 3071, "s": 2795, "text": "#important libraries for preprocessing using NLTKimport nltkfrom nltk import word_tokenize, FreqDistfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizernltk.downloadnltk.download('wordnet')nltk.download('stopwords')from nltk.tokenize import TweetTokenizer" }, { "code": null, "e": 3133, "s": 3071, "text": "Remove Digits and lower the text (makes it easy to deal with)" }, { "code": null, "e": 3209, "s": 3133, "text": "data = data.astype(str).str.replace('\\d+', '')lower_text = data.str.lower()" }, { "code": null, "e": 3229, "s": 3209, "text": "Remove Punctuations" }, { "code": null, "e": 3411, "s": 3229, "text": "def remove_punctuation(words): new_words = [] for word in words: new_word = re.sub(r'[^\\w\\s]', '', (word)) if new_word != '': new_words.append(new_word) return new_words" }, { "code": null, "e": 3475, "s": 3411, "text": "Lemmatization + Tokenization — Used a built in TweetTokenizer()" }, { "code": null, "e": 3684, "s": 3475, "text": "lemmatizer = nltk.stem.WordNetLemmatizer()w_tokenizer = TweetTokenizer()def lemmatize_text(text): return [(lemmatizer.lemmatize(w)) for w in \\ w_tokenizer.tokenize((text))]" }, { "code": null, "e": 3715, "s": 3684, "text": "The last preprocessing step is" }, { "code": null, "e": 3887, "s": 3715, "text": "Removing stop words — There is a pre-defined stop words list in English. However, you can modify your stop words like by simply appending the words to the stop words list." }, { "code": null, "e": 4054, "s": 3887, "text": "stop_words = set(stopwords.words('english'))tweets['text'] = tweets['text'].apply(lambda x: [item for item in \\ x if item not in stop_words])" }, { "code": null, "e": 4295, "s": 4054, "text": "After the pre-processing steps, We excluded all the places names and abbreviations in the tweets because it acted as a leakage variable and then we performed a frequency distribution of the most occurring hashtags and created a word cloud —" }, { "code": null, "e": 4320, "s": 4295, "text": "This was quite expected." }, { "code": null, "e": 4595, "s": 4320, "text": "from wordcloud import WordCloud#Frequency of wordsfdist = FreqDist(tweets['Segmented#'])#WordCloudwc = WordCloud(width=800, height=400, max_words=50).generate_from_frequencies(fdist)plt.figure(figsize=(12,10))plt.imshow(wc, interpolation=\"bilinear\")plt.axis(\"off\")plt.show()" }, { "code": null, "e": 4615, "s": 4595, "text": "The final dataset —" }, { "code": null, "e": 4632, "s": 4615, "text": "The final code —" }, { "code": null, "e": 6771, "s": 4632, "text": "import pandas as pdimport numpy as npimport jsonfrom collections import Counterfrom wordcloud import WordCloudimport matplotlib.pyplot as pltimport re, string, unicodedataimport nltkfrom nltk import word_tokenize, sent_tokenize, FreqDistfrom nltk.corpus import stopwordsfrom nltk.stem import LancasterStemmer, WordNetLemmatizernltk.downloadnltk.download('wordnet')nltk.download('stopwords')from nltk.tokenize import TweetTokenizer!pip install ekphrasis!pip install tweet-preprocessorimport preprocessor as ptweets['hashtag'] = tweets['tweet_text'].apply(lambda x: re.findall(r\"#(\\w+)\", x))for i,v in enumerate(tweets['text']): tweets.loc[v,’text’] = p.clean(i)def preprocess_data(data): #Removes Numbers data = data.astype(str).str.replace('\\d+', '') lower_text = data.str.lower() lemmatizer = nltk.stem.WordNetLemmatizer() w_tokenizer = TweetTokenizer() def lemmatize_text(text): return [(lemmatizer.lemmatize(w)) for w \\ in w_tokenizer.tokenize((text))] def remove_punctuation(words): new_words = [] for word in words: new_word = re.sub(r'[^\\w\\s]', '', (word)) if new_word != '': new_words.append(new_word) return new_words words = lower_text.apply(lemmatize_text) words = words.apply(remove_punctuation) return pd.DataFrame(words)pre_tweets = preprocess_data(tweets['text'])tweets['text'] = pre_tweetsstop_words = set(stopwords.words('english'))tweets['text'] = tweets['text'].apply(lambda x: [item for item in \\ x if item not in stop_words])from ekphrasis.classes.segmenter import Segmenter# segmenter using the word statistics from Twitterseg_tw = Segmenter(corpus=\"twitter\")a = []for i in range(len(tweets)): if tweets['hashtag'][i] != a listToStr1 = ' '.join([str(elem) for elem in \\ tweets['hashtag'][i]]) tweets.loc[i,'Segmented#'] = seg_tw.segment(listToStr1)#Frequency of wordsfdist = FreqDist(tweets['Segmented#'])#WordCloudwc = WordCloud(width=800, height=400, max_words=50).generate_from_frequencies(fdist)plt.figure(figsize=(12,10))plt.imshow(wc, interpolation=\"bilinear\")plt.axis(\"off\")plt.show()" }, { "code": null, "e": 6792, "s": 6771, "text": "Hope I helped y’all." } ]
How to find items in one list that are not in another list in C#?
LINQ Except operator comes under Set operators category in LINQ The Except() method requires two collections and find those elements which are not present in second collection Except extension method doesn't return the correct result for the collection of complex types. Live Demo using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication { class Program { static void Main(string[] args) { List<string> animalsList1 = new List<string> { "tiger", "lion", "dog" }; Console.WriteLine($"Values in List1:"); foreach (var val in animalsList1) { Console.WriteLine($"{val}"); } List<string> animalsList2 = new List<string> { "tiger", "cat", "deer" }; Console.WriteLine($"Values in List2:"); foreach (var val in animalsList1) { Console.WriteLine($"{val}"); } var animalsList3 = animalsList1.Except(animalsList2); Console.WriteLine($"Value in List1 that are not in List2:"); foreach (var val in animalsList3) { Console.WriteLine($"{val}"); } Console.ReadLine(); } } } The output of the above code is Values in List1: tiger lion dog Values in List2: tiger lion dog Value in List1 that are not in List2: lion dog Live Demo using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication { class Program { static void Main(string[] args) { List<Fruit> fruitsList1 = new List<Fruit> { new Fruit { Name = "Apple", Size = "Small" }, new Fruit { Name = "Orange", Size = "Small" } }; Console.WriteLine($"Values in List1:"); foreach (var val in fruitsList1) { Console.WriteLine($"{val.Name}"); } List<Fruit> fruitsList2 = new List<Fruit> { new Fruit { Name = "Apple", Size = "Small" }, new Fruit { Name = "Mango", Size = "Small" } }; Console.WriteLine($"Values in List2:"); foreach (var val in fruitsList2) { Console.WriteLine($"{val.Name}"); } var fruitsList3 = fruitsList1.Where(f1 => fruitsList2.All(f2 => f2.Name != f1.Name)); Console.WriteLine($"Values in List1 that are not in List2:"); foreach (var val in fruitsList3) { Console.WriteLine($"{val.Name}"); } Console.ReadLine(); } } public class Fruit { public string Name { get; set; } public string Size { get; set; } } } The output of the above code is Values in List1: Apple Orange Values in List2: Apple Mango Values in List1 that are not in List2: Orange
[ { "code": null, "e": 1126, "s": 1062, "text": "LINQ Except operator comes under Set operators category in LINQ" }, { "code": null, "e": 1238, "s": 1126, "text": "The Except() method requires two collections and find those elements which are not present in second collection" }, { "code": null, "e": 1333, "s": 1238, "text": "Except extension method doesn't return the correct result for the collection of complex types." }, { "code": null, "e": 1344, "s": 1333, "text": " Live Demo" }, { "code": null, "e": 2270, "s": 1344, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n List<string> animalsList1 = new List<string> {\n \"tiger\", \"lion\", \"dog\"\n };\n Console.WriteLine($\"Values in List1:\");\n foreach (var val in animalsList1) {\n Console.WriteLine($\"{val}\");\n }\n List<string> animalsList2 = new List<string> {\n \"tiger\", \"cat\", \"deer\"\n };\n Console.WriteLine($\"Values in List2:\");\n foreach (var val in animalsList1) {\n Console.WriteLine($\"{val}\");\n }\n var animalsList3 = animalsList1.Except(animalsList2);\n Console.WriteLine($\"Value in List1 that are not in List2:\");\n foreach (var val in animalsList3) {\n Console.WriteLine($\"{val}\");\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2302, "s": 2270, "text": "The output of the above code is" }, { "code": null, "e": 2413, "s": 2302, "text": "Values in List1:\ntiger\nlion\ndog\nValues in List2:\ntiger\nlion\ndog\nValue in List1 that are not in List2:\nlion\ndog" }, { "code": null, "e": 2424, "s": 2413, "text": " Live Demo" }, { "code": null, "e": 3825, "s": 2424, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n List<Fruit> fruitsList1 = new List<Fruit> {\n new Fruit {\n Name = \"Apple\",\n Size = \"Small\"\n },\n new Fruit {\n Name = \"Orange\",\n Size = \"Small\"\n }\n };\n Console.WriteLine($\"Values in List1:\");\n foreach (var val in fruitsList1) {\n Console.WriteLine($\"{val.Name}\");\n }\n List<Fruit> fruitsList2 = new List<Fruit> {\n new Fruit {\n Name = \"Apple\",\n Size = \"Small\"\n },\n new Fruit {\n Name = \"Mango\",\n Size = \"Small\"\n }\n };\n Console.WriteLine($\"Values in List2:\");\n foreach (var val in fruitsList2) {\n Console.WriteLine($\"{val.Name}\");\n }\n var fruitsList3 = fruitsList1.Where(f1 => fruitsList2.All(f2 => f2.Name != f1.Name));\n Console.WriteLine($\"Values in List1 that are not in List2:\");\n foreach (var val in fruitsList3) {\n Console.WriteLine($\"{val.Name}\");\n }\n Console.ReadLine();\n }\n }\n public class Fruit {\n public string Name { get; set; }\n public string Size { get; set; }\n }\n}" }, { "code": null, "e": 3857, "s": 3825, "text": "The output of the above code is" }, { "code": null, "e": 3962, "s": 3857, "text": "Values in List1:\nApple\nOrange\nValues in List2:\nApple\nMango\nValues in List1 that are not in List2:\nOrange" } ]
Which are the new Null Operators introduced in PowerShell version 7?
PowerShell version 7 has introduced a few new null operators. They are as below. Null-Coalescing operator - ?? Null-Coalescing operator - ?? Null Conditional Assignment Operators - ??= Null Conditional Assignment Operators - ??= Null Conditional member access operators - ?. and ?[] Null Conditional member access operators - ?. and ?[] Null Coalescing operator ??evaluates the left-hand side condition or operand and if it is null then evaluates the right-hand side operand otherwise provides the value of the left-hand side operand. For example, Without the Null-Coalescing operator, we would have written a script like as shown below, $Name = $null if($Name -eq $null){"Name is Null"} Else {"PowerShell"} The above same condition can be written with the ?? operator. $name = $null $name ?? "PowerShell" PowerShell So the left side of the variable output is Null and hence right side of the value or expression is evaluated. Suppose if the left side operand is not null then its value will be displayed. $name = "Hello" $name ?? "PowerShell" Hello You can also add expression, $service = Get-Service abc -ErrorAction Ignore $service ?? (Get-Service Spooler) Status Name DisplayName ------ ---- ----------- Running Spooler Print Spooler Null Conditional Assignment Operator ??= in PowerShell assigns the value of the right-hand side operand to the left-hand operand only if the left-hand operand value is null. This operator doesn’t evaluate the right-hand side operand if the left-hand side operand is Null. For example, $serivce = $null $service ??= (Get-Service Winrm) $service Status Name DisplayName ------ ---- ----------- Running Winrm Windows Remote Management (WS-Managem... The above command is similar to, $service = $null if($service -eq $null){$service = Get-Service Winrm} $service Status Name DisplayName ------ ---- ----------- Running Winrm Windows Remote Management (WS-Managem... If the left-hand side operator is not null then the value won’t be changed. $val = "PowerShell" $val ??= "Hello World" $val PowerShell As their names suggest, both the operators are used for accessing the members of the object. Both operators were introduced in PS version 7 and still, it is in Preview mode and used for experimental purpose so it is not available to everyone yet. It is similar to directly accessing any property or member of the variable or an object but why we need them then? Because it evaluates the object first and if it is null then it doesn’t access the members(property or method). As we are using both operators to access properties or methods of an object, we need to wrap the object around {} brackets, and then we can use the operator. For example, $service = Get-Service WinRm ${Service}?.Status Running The above example can also be achieved by simply access property but the difference is if the service name doesn’t exist then simple command would throw an error where this operator won’t if the service name is null. For example, $services = Get-Service ABC -ErrorAction ignore $service.start() You cannot call a method on a null-valued expression. At line:1 char:1 + $service.start() + ~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull The new operator won’t give any output because the service name doesn’t exist. ${Service}?.Start()
[ { "code": null, "e": 1143, "s": 1062, "text": "PowerShell version 7 has introduced a few new null operators. They are as below." }, { "code": null, "e": 1173, "s": 1143, "text": "Null-Coalescing operator - ??" }, { "code": null, "e": 1203, "s": 1173, "text": "Null-Coalescing operator - ??" }, { "code": null, "e": 1247, "s": 1203, "text": "Null Conditional Assignment Operators - ??=" }, { "code": null, "e": 1291, "s": 1247, "text": "Null Conditional Assignment Operators - ??=" }, { "code": null, "e": 1345, "s": 1291, "text": "Null Conditional member access operators - ?. and ?[]" }, { "code": null, "e": 1399, "s": 1345, "text": "Null Conditional member access operators - ?. and ?[]" }, { "code": null, "e": 1597, "s": 1399, "text": "Null Coalescing operator ??evaluates the left-hand side condition or operand and if it is null then evaluates the right-hand side operand otherwise provides the value of the left-hand side operand." }, { "code": null, "e": 1700, "s": 1597, "text": "For example, Without the Null-Coalescing operator, we would have written a script like as shown below," }, { "code": null, "e": 1770, "s": 1700, "text": "$Name = $null\nif($Name -eq $null){\"Name is Null\"}\nElse {\"PowerShell\"}" }, { "code": null, "e": 1832, "s": 1770, "text": "The above same condition can be written with the ?? operator." }, { "code": null, "e": 1868, "s": 1832, "text": "$name = $null\n$name ?? \"PowerShell\"" }, { "code": null, "e": 1879, "s": 1868, "text": "PowerShell" }, { "code": null, "e": 1989, "s": 1879, "text": "So the left side of the variable output is Null and hence right side of the value or expression is evaluated." }, { "code": null, "e": 2068, "s": 1989, "text": "Suppose if the left side operand is not null then its value will be displayed." }, { "code": null, "e": 2112, "s": 2068, "text": "$name = \"Hello\"\n$name ?? \"PowerShell\"\nHello" }, { "code": null, "e": 2141, "s": 2112, "text": "You can also add expression," }, { "code": null, "e": 2222, "s": 2141, "text": "$service = Get-Service abc -ErrorAction Ignore\n$service ?? (Get-Service Spooler)" }, { "code": null, "e": 2300, "s": 2222, "text": "Status Name DisplayName\n------ ---- -----------\nRunning Spooler Print Spooler" }, { "code": null, "e": 2585, "s": 2300, "text": "Null Conditional Assignment Operator ??= in PowerShell assigns the value of the right-hand side\noperand to the left-hand operand only if the left-hand operand value is null. This operator doesn’t\nevaluate the right-hand side operand if the left-hand side operand is Null. For example," }, { "code": null, "e": 2635, "s": 2585, "text": "$serivce = $null\n$service ??= (Get-Service Winrm)" }, { "code": null, "e": 2747, "s": 2635, "text": "$service\nStatus Name DisplayName\n------ ---- -----------\nRunning Winrm Windows Remote Management (WS-Managem..." }, { "code": null, "e": 2780, "s": 2747, "text": "The above command is similar to," }, { "code": null, "e": 2962, "s": 2780, "text": "$service = $null\nif($service -eq $null){$service = Get-Service Winrm}\n$service\nStatus Name DisplayName\n------ ---- -----------\nRunning Winrm Windows Remote Management (WS-Managem..." }, { "code": null, "e": 3038, "s": 2962, "text": "If the left-hand side operator is not null then the value won’t be changed." }, { "code": null, "e": 3081, "s": 3038, "text": "$val = \"PowerShell\"\n$val ??= \"Hello World\"" }, { "code": null, "e": 3097, "s": 3081, "text": "$val\nPowerShell" }, { "code": null, "e": 3344, "s": 3097, "text": "As their names suggest, both the operators are used for accessing the members of the object. Both\noperators were introduced in PS version 7 and still, it is in Preview mode and used for experimental purpose so it is not available to everyone yet." }, { "code": null, "e": 3571, "s": 3344, "text": "It is similar to directly accessing any property or member of the variable or an object but why we need them then? Because it evaluates the object first and if it is null then it doesn’t access the members(property or method)." }, { "code": null, "e": 3742, "s": 3571, "text": "As we are using both operators to access properties or methods of an object, we need to wrap the\nobject around {} brackets, and then we can use the operator. For example," }, { "code": null, "e": 3790, "s": 3742, "text": "$service = Get-Service WinRm\n${Service}?.Status" }, { "code": null, "e": 3798, "s": 3790, "text": "Running" }, { "code": null, "e": 4028, "s": 3798, "text": "The above example can also be achieved by simply access property but the difference is if the service\nname doesn’t exist then simple command would throw an error where this operator won’t if the service\nname is null. For example," }, { "code": null, "e": 4307, "s": 4028, "text": "$services = Get-Service ABC -ErrorAction ignore\n$service.start()\nYou cannot call a method on a null-valued expression.\nAt line:1 char:1\n+ $service.start()\n+ ~~~~~~~~~~~~~~~~\n+ CategoryInfo : InvalidOperation: (:) [], RuntimeException\n+ FullyQualifiedErrorId : InvokeMethodOnNull" }, { "code": null, "e": 4386, "s": 4307, "text": "The new operator won’t give any output because the service name doesn’t exist." }, { "code": null, "e": 4406, "s": 4386, "text": "${Service}?.Start()" } ]
How to get a list of all the fonts currently available for Matplotlib?
To get a list of all the fonts currently available for matplotlib, we can use the font_manager.findSystemFonts() method. Print a statement. Print a statement. Use font_manager.findSystemFonts() method to get a list of fonts availabe. Use font_manager.findSystemFonts() method to get a list of fonts availabe. from matplotlib import font_manager print("List of all fonts currently available in the matplotlib:\n") print(*font_manager.findSystemFonts(fontpaths=None, fontext='ttf'), sep="\n") /usr/share/fonts/truetype/Nakula/nakula.ttf /usr/share/fonts/truetype/ubuntu/Ubuntu-L.ttf /usr/share/fonts/truetype/tlwg/Loma-BoldOblique.ttf ................................................................. ............................................................................ ................................................................................. ........ /usr/share/fonts/truetype/lohit-malayalam/Lohit-Malayalam.ttf /usr/share/fonts/truetype/tlwg/TlwgTypist-Oblique.ttf /usr/share/fonts/truetype/liberation2/LiberationMono-Bold.ttf
[ { "code": null, "e": 1183, "s": 1062, "text": "To get a list of all the fonts currently available for matplotlib, we can use the font_manager.findSystemFonts() method." }, { "code": null, "e": 1202, "s": 1183, "text": "Print a statement." }, { "code": null, "e": 1221, "s": 1202, "text": "Print a statement." }, { "code": null, "e": 1296, "s": 1221, "text": "Use font_manager.findSystemFonts() method to get a list of fonts availabe." }, { "code": null, "e": 1371, "s": 1296, "text": "Use font_manager.findSystemFonts() method to get a list of fonts availabe." }, { "code": null, "e": 1554, "s": 1371, "text": "from matplotlib import font_manager\n\nprint(\"List of all fonts currently available in the matplotlib:\\n\")\nprint(*font_manager.findSystemFonts(fontpaths=None, fontext='ttf'), sep=\"\\n\")" }, { "code": null, "e": 2108, "s": 1554, "text": "/usr/share/fonts/truetype/Nakula/nakula.ttf\n/usr/share/fonts/truetype/ubuntu/Ubuntu-L.ttf\n/usr/share/fonts/truetype/tlwg/Loma-BoldOblique.ttf\n.................................................................\n............................................................................\n.................................................................................\n........\n/usr/share/fonts/truetype/lohit-malayalam/Lohit-Malayalam.ttf\n/usr/share/fonts/truetype/tlwg/TlwgTypist-Oblique.ttf\n/usr/share/fonts/truetype/liberation2/LiberationMono-Bold.ttf" } ]
Git Pull Branch from GitHub
Now continue working on our new branch in our local Git. Lets pull from our GitHub repository again so that our code is up-to-date: git pull remote: Enumerating objects: 5, done. remote: Counting objects: 100% (5/5), done. remote: Compressing objects: 100% (3/3), done. remote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (3/3), 851 bytes | 9.00 KiB/s, done. From https://github.com/w3schools-test/hello-world * [new branch] html-skeleton -> origin/html-skeleton Already up to date. Now our main branch is up todate. And we can see that there is a new branch available on GitHub. Do a quick status check: git status On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean And confirm which branches we have, and where we are working at the moment: git branch * master So, we do not have the new branch on our local Git. But we know it is available on GitHub. So we can use the -a option to see all local and remote branches: git branch -a * master remotes/origin/html-skeleton remotes/origin/master Note: branch -r is for remote branches only. We see that the branch html-skeleton is available remotely, but not on our local git. Lets check it out: git checkout html-skeleton Switched to a new branch 'html-skeleton' Branch 'html-skeleton' set up to track remote branch 'html-skeleton' from 'origin'. And check if it is all up to date: git pull Already up to date. Which branches do we have now, and where are we working from? git branch * html-skeleton master Now, open your favourite editor and confirm that the changes from the GitHub branch carried over. That is how you pull a GitHub branch to your local Git. List all local and remote branches of the current Git. git Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 57, "s": 0, "text": "Now continue working on our new branch in our local Git." }, { "code": null, "e": 132, "s": 57, "text": "Lets pull from our GitHub repository again so that our code is up-to-date:" }, { "code": null, "e": 522, "s": 132, "text": "git pull\nremote: Enumerating objects: 5, done.\nremote: Counting objects: 100% (5/5), done.\nremote: Compressing objects: 100% (3/3), done.\nremote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0\nUnpacking objects: 100% (3/3), 851 bytes | 9.00 KiB/s, done.\nFrom https://github.com/w3schools-test/hello-world\n * [new branch] html-skeleton -> origin/html-skeleton\nAlready up to date." }, { "code": null, "e": 621, "s": 522, "text": "Now our main branch is up todate. And we can see that there is a new \nbranch \navailable on GitHub." }, { "code": null, "e": 646, "s": 621, "text": "Do a quick status check:" }, { "code": null, "e": 761, "s": 646, "text": "git status\nOn branch master\nYour branch is up to date with 'origin/master'.\n\nnothing to commit, working tree clean" }, { "code": null, "e": 837, "s": 761, "text": "And confirm which branches we have, and where we are working at the moment:" }, { "code": null, "e": 857, "s": 837, "text": "git branch\n* master" }, { "code": null, "e": 1016, "s": 857, "text": "So, we do not have the new branch on our local Git. But \nwe know it is available on \nGitHub. So we can use the -a option to see all local and remote branches:" }, { "code": null, "e": 1094, "s": 1016, "text": "git branch -a\n* master\n remotes/origin/html-skeleton\n remotes/origin/master" }, { "code": null, "e": 1139, "s": 1094, "text": "Note: branch -r is for remote branches only." }, { "code": null, "e": 1244, "s": 1139, "text": "We see that the branch html-skeleton is available remotely, but not on our local git. Lets check it out:" }, { "code": null, "e": 1396, "s": 1244, "text": "git checkout html-skeleton\nSwitched to a new branch 'html-skeleton'\nBranch 'html-skeleton' set up to track remote branch 'html-skeleton' from 'origin'." }, { "code": null, "e": 1431, "s": 1396, "text": "And check if it is all up to date:" }, { "code": null, "e": 1460, "s": 1431, "text": "git pull\nAlready up to date." }, { "code": null, "e": 1522, "s": 1460, "text": "Which branches do we have now, and where are we working from?" }, { "code": null, "e": 1558, "s": 1522, "text": "git branch\n* html-skeleton\n master" }, { "code": null, "e": 1656, "s": 1558, "text": "Now, open your favourite editor and confirm that the changes from the GitHub branch carried over." }, { "code": null, "e": 1712, "s": 1656, "text": "That is how you pull a GitHub branch to your local Git." }, { "code": null, "e": 1767, "s": 1712, "text": "List all local and remote branches of the current Git." }, { "code": null, "e": 1774, "s": 1767, "text": "git \n" }, { "code": null, "e": 1794, "s": 1774, "text": "\nStart the Exercise" }, { "code": null, "e": 1827, "s": 1794, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1869, "s": 1827, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1976, "s": 1869, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1995, "s": 1976, "text": "help@w3schools.com" } ]
Max() and Min() function in MS Access - GeeksforGeeks
02 Sep, 2020 1. Max() Function :max() function return the maximum value of given set. In the function a query is passed and in the eligible records which value will be maximum that will return as result. A expression will be pass as parameter and it will return the maximum value in the expression. Syntax : Max (expression) Demo Database for example : Table name : student Example-1 : SELECT Max(Marks) AS marks FROM student; Output – Example-2 : SELECT Max(Marks) AS marks FROM student where Marks<80; Output – 2. Min() Function :min() function works like max() function but it will return the minimum value of the expression. In this function a query will be passed as parameter and it will return the minimum record. Syntax : Min(expression) Example-1 : SELECT Min(Marks) AS marks FROM student; Output – Example-2 : SELECT Min(Marks) AS marks FROM student where Marks>50; Output – DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Convert VARCHAR to INT SQL Query to Delete Duplicate Rows SQL Query to Compare Two Dates Window functions in SQL
[ { "code": null, "e": 23877, "s": 23849, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24163, "s": 23877, "text": "1. Max() Function :max() function return the maximum value of given set. In the function a query is passed and in the eligible records which value will be maximum that will return as result. A expression will be pass as parameter and it will return the maximum value in the expression." }, { "code": null, "e": 24172, "s": 24163, "text": "Syntax :" }, { "code": null, "e": 24189, "s": 24172, "text": "Max (expression)" }, { "code": null, "e": 24217, "s": 24189, "text": "Demo Database for example :" }, { "code": null, "e": 24238, "s": 24217, "text": "Table name : student" }, { "code": null, "e": 24250, "s": 24238, "text": "Example-1 :" }, { "code": null, "e": 24292, "s": 24250, "text": "SELECT Max(Marks) AS marks \nFROM student;" }, { "code": null, "e": 24301, "s": 24292, "text": "Output –" }, { "code": null, "e": 24313, "s": 24301, "text": "Example-2 :" }, { "code": null, "e": 24370, "s": 24313, "text": "SELECT Max(Marks) AS marks \nFROM student\nwhere Marks<80;" }, { "code": null, "e": 24379, "s": 24370, "text": "Output –" }, { "code": null, "e": 24587, "s": 24379, "text": "2. Min() Function :min() function works like max() function but it will return the minimum value of the expression. In this function a query will be passed as parameter and it will return the minimum record." }, { "code": null, "e": 24596, "s": 24587, "text": "Syntax :" }, { "code": null, "e": 24613, "s": 24596, "text": " Min(expression)" }, { "code": null, "e": 24625, "s": 24613, "text": "Example-1 :" }, { "code": null, "e": 24667, "s": 24625, "text": "SELECT Min(Marks) AS marks \nFROM student;" }, { "code": null, "e": 24676, "s": 24667, "text": "Output –" }, { "code": null, "e": 24688, "s": 24676, "text": "Example-2 :" }, { "code": null, "e": 24745, "s": 24688, "text": "SELECT Min(Marks) AS marks \nFROM student\nwhere Marks>50;" }, { "code": null, "e": 24754, "s": 24745, "text": "Output –" }, { "code": null, "e": 24763, "s": 24754, "text": "DBMS-SQL" }, { "code": null, "e": 24774, "s": 24763, "text": "SQL-Server" }, { "code": null, "e": 24778, "s": 24774, "text": "SQL" }, { "code": null, "e": 24782, "s": 24778, "text": "SQL" }, { "code": null, "e": 24880, "s": 24782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24889, "s": 24880, "text": "Comments" }, { "code": null, "e": 24902, "s": 24889, "text": "Old Comments" }, { "code": null, "e": 24968, "s": 24902, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25000, "s": 24968, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25078, "s": 25000, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 25095, "s": 25078, "text": "SQL using Python" }, { "code": null, "e": 25110, "s": 25095, "text": "SQL | Subquery" }, { "code": null, "e": 25176, "s": 25110, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 25212, "s": 25176, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 25247, "s": 25212, "text": "SQL Query to Delete Duplicate Rows" }, { "code": null, "e": 25278, "s": 25247, "text": "SQL Query to Compare Two Dates" } ]
How to use diff command in linux
The diff command analyzes line by line and displays a list of changes between two files. As a special case, diff compares a copy of standard input to itself. This article describes “How to use diff command in Linux. Recognize the changes between one version of a file Compare two configuration or program files Create a patch file which can be applied with the Linux / Unix program patch For example, we have two files as file.txt and file1.txt. The data has been inserted into file.txt as shown below – I need to buy apples. I need to run the laundry. I need to wash the dog. I need to get the car detailed. file1.txt contains the data as shown below I need to buy apples. I need to do the laundry. I need to wash the car. I need to get the dog detailed. Use the diff command to compare both the files as shown below – linux@linux:~$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt The above command should give the result as shown below – linux@linux:~$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt 2,4c2,4 < I need to run the laundry. < I need to wash the dog. < I need to get the car detailed. --- > I need to do the laundry. > I need to wash the car. > I need to get the dog detailed. The options of the result should be like this – a -Added the text to file c -Changes are made in the file d -Deletion operation is performed < Lines from the first file > Lines from the second file From the output, 2,4c2,4 means “Lines 2 through 4 in the first file needs to be changed in order to match lines 2 through 4 in the second file” Let’s look at another example, two text files should be like this- file.txt I need to go to the store. I need to buy some apples. When I get home, I'll wash the dog. file1.txt I need to go to the store. I need to buy some apples. Oh yeah, I also need to buy grated cheese. When I get home, I'll wash the dog. Use the diff command to compare both files. The command should be like this- $ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt The above command should give the result as shown below – 2a3 > Oh yeah, I also need to buy grated cheese. From the output, 2a3 means “After line 2 in the first file, a line needs to be added: line 3 from the second file”. Congratulations! Now, you know “How to use diff command in Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1278, "s": 1062, "text": "The diff command analyzes line by line and displays a list of changes between two files. As a special case, diff compares a copy of standard input to itself. This article describes “How to use diff command in Linux." }, { "code": null, "e": 1330, "s": 1278, "text": "Recognize the changes between one version of a file" }, { "code": null, "e": 1373, "s": 1330, "text": "Compare two configuration or program files" }, { "code": null, "e": 1450, "s": 1373, "text": "Create a patch file which can be applied with the Linux / Unix program patch" }, { "code": null, "e": 1566, "s": 1450, "text": "For example, we have two files as file.txt and file1.txt. The data has been inserted into file.txt as shown below –" }, { "code": null, "e": 1671, "s": 1566, "text": "I need to buy apples.\nI need to run the laundry.\nI need to wash the dog.\nI need to get the car detailed." }, { "code": null, "e": 1714, "s": 1671, "text": "file1.txt contains the data as shown below" }, { "code": null, "e": 1818, "s": 1714, "text": "I need to buy apples.\nI need to do the laundry.\nI need to wash the car.\nI need to get the dog detailed." }, { "code": null, "e": 1882, "s": 1818, "text": "Use the diff command to compare both the files as shown below –" }, { "code": null, "e": 1961, "s": 1882, "text": "linux@linux:~$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt" }, { "code": null, "e": 2019, "s": 1961, "text": "The above command should give the result as shown below –" }, { "code": null, "e": 2287, "s": 2019, "text": "linux@linux:~$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt\n2,4c2,4\n< I need to run the laundry.\n< I need to wash the dog.\n< I need to get the car detailed. --- > I need to do the laundry.\n> I need to wash the car.\n> I need to get the dog detailed." }, { "code": null, "e": 2335, "s": 2287, "text": "The options of the result should be like this –" }, { "code": null, "e": 2361, "s": 2335, "text": "a -Added the text to file" }, { "code": null, "e": 2394, "s": 2361, "text": " c -Changes are made in the file" }, { "code": null, "e": 2430, "s": 2394, "text": " d -Deletion operation is performed" }, { "code": null, "e": 2460, "s": 2430, "text": " < Lines from the first file" }, { "code": null, "e": 2491, "s": 2460, "text": " > Lines from the second file" }, { "code": null, "e": 2635, "s": 2491, "text": "From the output, 2,4c2,4 means “Lines 2 through 4 in the first file needs to be changed in order to match lines 2 through 4 in the second file”" }, { "code": null, "e": 2702, "s": 2635, "text": "Let’s look at another example, two text files should be like this-" }, { "code": null, "e": 2711, "s": 2702, "text": "file.txt" }, { "code": null, "e": 2801, "s": 2711, "text": "I need to go to the store.\nI need to buy some apples.\nWhen I get home, I'll wash the dog." }, { "code": null, "e": 2811, "s": 2801, "text": "file1.txt" }, { "code": null, "e": 2944, "s": 2811, "text": "I need to go to the store.\nI need to buy some apples.\nOh yeah, I also need to buy grated cheese.\nWhen I get home, I'll wash the dog." }, { "code": null, "e": 3021, "s": 2944, "text": "Use the diff command to compare both files. The command should be like this-" }, { "code": null, "e": 3087, "s": 3021, "text": "$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt" }, { "code": null, "e": 3145, "s": 3087, "text": "The above command should give the result as shown below –" }, { "code": null, "e": 3194, "s": 3145, "text": "2a3\n> Oh yeah, I also need to buy grated cheese." }, { "code": null, "e": 3310, "s": 3194, "text": "From the output, 2a3 means “After line 2 in the first file, a line needs to be added: line 3 from the second file”." }, { "code": null, "e": 3462, "s": 3310, "text": "Congratulations! Now, you know “How to use diff command in Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
When will be an IllegalStateException (unchecked) thrown in Java?
An IllegalStateException is an unchecked exception in Java. This exception may arise in our java program mostly if we are dealing with the collection framework of java.util.package. There are many collections like List, Queue, Tree, Map out of which List and Queues (Queue and Deque) to throw this IllegalStateException at particular conditions. An IllegalStateExceptionexception will be thrown, when we try to invoke a particular method at an inappropriate time. In case of java.util.List collection, we use next() method of the ListIterator interface to traverse through the java.util.List. If we call the remove() method of the ListIterator interface before calling the next() method then this exception will be thrown as it will leave the List collection in an unstable state. If we want to modify a particular object we will use the set() method of the ListIterator interface In the case of queues, if we try to add an element to a Queue, then we must ensure that the queue is not full. If this queue is full then we cannot add that element, then it will cause an IllegalStateExceptionexception to be thrown. Live Demo import java.util.*; public class IllegalStateExceptionTest { public static void main(String args[]) { List list = new LinkedList(); list.add("Welcome"); list.add("to"); list.add("Tutorials"); list.add("Point"); ListIterator lIterator = list.listIterator(); lIterator.next(); lIterator.remove();// modifying the list lIterator.set("Tutorix"); System.out.println(list); } } Exception in thread "main" java.lang.IllegalStateException at java.util.LinkedList$ListItr.set(LinkedList.java:937) at IllegalStateExceptionTest.main(IllegalStateExceptionTest.java:15)
[ { "code": null, "e": 1408, "s": 1062, "text": "An IllegalStateException is an unchecked exception in Java. This exception may arise in our java program mostly if we are dealing with the collection framework of java.util.package. There are many collections like List, Queue, Tree, Map out of which List and Queues (Queue and Deque) to throw this IllegalStateException at particular conditions." }, { "code": null, "e": 1526, "s": 1408, "text": "An IllegalStateExceptionexception will be thrown, when we try to invoke a particular method at an inappropriate time." }, { "code": null, "e": 1843, "s": 1526, "text": "In case of java.util.List collection, we use next() method of the ListIterator interface to traverse through the java.util.List. If we call the remove() method of the ListIterator interface before calling the next() method then this exception will be thrown as it will leave the List collection in an unstable state." }, { "code": null, "e": 1943, "s": 1843, "text": "If we want to modify a particular object we will use the set() method of the ListIterator interface" }, { "code": null, "e": 2176, "s": 1943, "text": "In the case of queues, if we try to add an element to a Queue, then we must ensure that the queue is not full. If this queue is full then we cannot add that element, then it will cause an IllegalStateExceptionexception to be thrown." }, { "code": null, "e": 2186, "s": 2176, "text": "Live Demo" }, { "code": null, "e": 2624, "s": 2186, "text": "import java.util.*;\npublic class IllegalStateExceptionTest {\n public static void main(String args[]) {\n List list = new LinkedList();\n list.add(\"Welcome\");\n list.add(\"to\");\n list.add(\"Tutorials\");\n list.add(\"Point\");\n ListIterator lIterator = list.listIterator();\n lIterator.next();\n lIterator.remove();// modifying the list\n lIterator.set(\"Tutorix\");\n System.out.println(list);\n }\n}" }, { "code": null, "e": 2825, "s": 2624, "text": "Exception in thread \"main\" java.lang.IllegalStateException\n at java.util.LinkedList$ListItr.set(LinkedList.java:937)\n at IllegalStateExceptionTest.main(IllegalStateExceptionTest.java:15)" } ]
How to install PIP in Linux? - GeeksforGeeks
20 Jan, 2020 Prerequisite: Python Language Introduction Before we start with how to install pip for Python on Linux, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). pip uses PyPI as the default source for packages and their dependencies. So whenever you type: pip install package_name pip will look for that package on PyPI and if found, it will download and install the package on your local system. pip can be downloaded and installed using the terminal in Linux by going through the following command: sudo apt-get install python3-pip python-dev Beginning the installation: Getting Started: Providing Disk Space: Downloading Libraries: Unpacking File bundles: Finishing up the Installation: One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command-line and execute the following command: pip3 --version python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n20 Jan, 2020" }, { "code": null, "e": 24627, "s": 24292, "text": "Prerequisite: Python Language Introduction Before we start with how to install pip for Python on Linux, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently." }, { "code": null, "e": 24830, "s": 24627, "text": "PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI)." }, { "code": null, "e": 24925, "s": 24830, "text": "pip uses PyPI as the default source for packages and their dependencies. So whenever you type:" }, { "code": null, "e": 24950, "s": 24925, "text": "pip install package_name" }, { "code": null, "e": 25066, "s": 24950, "text": "pip will look for that package on PyPI and if found, it will download and install the package on your local system." }, { "code": null, "e": 25170, "s": 25066, "text": "pip can be downloaded and installed using the terminal in Linux by going through the following command:" }, { "code": null, "e": 25214, "s": 25170, "text": "sudo apt-get install python3-pip python-dev" }, { "code": null, "e": 25242, "s": 25214, "text": "Beginning the installation:" }, { "code": null, "e": 25259, "s": 25242, "text": "Getting Started:" }, { "code": null, "e": 25281, "s": 25259, "text": "Providing Disk Space:" }, { "code": null, "e": 25304, "s": 25281, "text": "Downloading Libraries:" }, { "code": null, "e": 25328, "s": 25304, "text": "Unpacking File bundles:" }, { "code": null, "e": 25359, "s": 25328, "text": "Finishing up the Installation:" }, { "code": null, "e": 25527, "s": 25359, "text": "One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command-line and execute the following command:" }, { "code": null, "e": 25542, "s": 25527, "text": "pip3 --version" }, { "code": null, "e": 25556, "s": 25542, "text": "python-basics" }, { "code": null, "e": 25563, "s": 25556, "text": "Python" }, { "code": null, "e": 25661, "s": 25563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25693, "s": 25661, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25735, "s": 25693, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25791, "s": 25735, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25833, "s": 25791, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25888, "s": 25833, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25919, "s": 25888, "text": "Python | os.path.join() method" }, { "code": null, "e": 25941, "s": 25919, "text": "Defaultdict in Python" }, { "code": null, "e": 25970, "s": 25941, "text": "Create a directory in Python" }, { "code": null, "e": 26009, "s": 25970, "text": "Python | Get unique values from a list" } ]
Creating sea routes from the sea of AIS data. | by Alexei Novikov | Towards Data Science
Maritime routes are important characteristics of maritime transportation. Sometimes they are clearly defined by the official guidelines “traffic separation schemes”, sometimes they are more of the recommendations. International Maritime Organization is responsible for the routeing systems, including traffic separation schemes, and they are published in the IMO Publication, Ships’ Routeing — currently 2013 Edition. Unfortunately, they are not digitised. Some commercial and freemium products are available and they provide distance and sometimes route between ports on the per route basis. At the time of the writing, we were not able to find a comprehensive library of routes that will be available off-line. So we decided to construct our own. Automatic identification system (AIS) is using transponders installed on almost all ships. Unique identification, position, course, and speed of the vessel are usually transmitted with regular intervals. These signals can be received by the nearby vessels, satellites and terrestrial antennas. There are several companies that collect, cleanse and sell this data. Mariquant has hourly data from one of the AIS data providers for the bulkers and tankers from the beginning of 2016 to the middle of 2018. This data has information from around 19 000 unique ships with records, occupying approximately 100 Gb as uncompressed parquet file. We have a library of the polygons with approximately 8 000 port harbours and 20 000 anchorage and waiting areas. Most of the time anchorage polygons lay outside of the port polygons, and we used graph algorithms to determine which anchorage belongs to which port. Having this data we started to construct routes. We will be using the notion of the distance between trajectories to construct the best representation of the route and to separate different trajectories on the same route. Most of the distance calculation algorithms are using the distance between points on the trajectories. We found that some noise prevented us from obtaining meaningful results for the calculations of the distances between trajectories. Looking at the data we found that ships spend a significant amount of time (leading to a large number of points on the trajectories) either anchoring or moving nearby the port harbour. To find at least some of these points on the trajectories, we used scikit learn[1] implementation of the Random Forest Classifier. There are various approaches to finding different clusters on the vessel trajectories, see for example [2] and references therein. We preferred to use a somewhat simplistic approach as it was easy to implement and provided us with sufficiently accurate results. We used distance to the port, distance to the previous port, speed of the ship, radial velocity of the ship (as if circling the port) and speed in the direction to the port, as the features of the classifier. We manually constructed training and testing sets separately marking ‘loitering’, anchoring, port approaching and general voyage points. We had around 6 400 points in the training and 1600 points in the testing set. Anchoring points are less represented in the sets, as they create fewer problems in the distance calculations. The difficulties in manual markup cause this small size of the set. The Confusion matrix shows that the loitering, approach and general voyage points are well defined. Even if the approach and general voyage points are misidentified, the misidentification is between two of them, not points of interest. Precision and recall, together with F1 score show that the results are good, but further improvements may be made for the classifier. We have to repeat that anchoring points are less troublesome for the calculation of the distance between trajectories and we will continue with these results. We found that distance to the port, distance to the previous port, speed of the ship are the most important features, having a score of 0.42, 0.21 and 0.28 correspondingly and radial speed and speed in the direction to the port have a score of 0.04 and 0.05. One can use standard Scikit-learn functions to calculate the scores mentioned above. from sklearn.metrics import classification_report, confusion_matrixfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)clf = RandomForestClassifier(n_estimators=20, max_depth=6, random_state=0)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)print(confusion_matrix(y_test, y_pred))print(classification_report(y_test, y_pred))print(clf.feature_importances_) We found that irrespectively from the scores of the classifiers, additional cleanup is required for our large dataset. Sometimes small parts of the port approach trajectories were mistakenly identified as loitering parts, and we had to apply conservative check requiring anchoring and loitering parts of the trajectories to be long enough and either be self-intersecting, or the distance travelled in the direction to the port should be smaller compared to the total length travelled. After all these checks we average the position of the vessel for the loitering and anchoring parts of the trajectories. Our approach was inspired by the work of the Philippe Besse, Brendan Guillouet, Jean-Michel Loubes and Franc ̧ois Royer [3]. In the original work, authors proposed a new method called ‘Symmetrized segment-path distance’ for distance calculation between trajectories to clusterize taxi voyages to predict final destination point as part of the Kaggle competition [4]. Article [3] has an in-depth description of the various methods for the trajectory distance calculation. In short, our approach is to calculate the distance between trajectories using some measureto clusterize trajectories based on their distances.to select the “best” trajectory in the cluster. to calculate the distance between trajectories using some measure to clusterize trajectories based on their distances. to select the “best” trajectory in the cluster. We tested different methods for the distance calculations and decided to use Edit Distance with Real Penalty (ERP) [5]. This method is a warping distance method and allows comparison between trajectories of different length, aligning trajectories during the computation of the distance between them. It runs in O(n2) time. The implementation of this method is part of the trajectory_distance package created by the authors of [3]. We slightly modified this package to speed-up python part of the calculations and added DASK support for the parallel computations. Due to the memory and calculation time restrictions we select at max 50 random trajectories, as the computation on the popular route may deal with hundreds of them. This leads us to the 43847 distinct routes that will be reconstructed from almost one million trips. Different trips along the same route can have completely different trajectories. So we need to clusterise these trajectories if needed. Affinity propagation clustering algorithm is the natural choice for this task as it requires neither the initial knowledge of the number of clusters, no triangle inequality for the distance (not all methods for the distance calculations generate distances that satisfy this inequality). We used scikit learn[1] implementation of the Affinity propagation algorithm. Missing points are usual for the data, collected by the satellites, due to the restrictions of the AIS protocol. We had to find a solution to this problem. First, we use the cost function that will take into account both the distance between the trajectories (we use simple average) and the number of missing points in the trajectory to define the “best” trajectory. Second, we update the trajectories iteratively: We find the “best” trajectory using only available dataWe enhance trajectories with the missing points using the “best” trajectory points. Nearest points from the “best” trajectory are found, and the “best” trajectory segment is added to the enhanced trajectory.We iterate 1 -2 with the additional data until the “best” trajectory remains stable and the value of the cost function diminishes. We find the “best” trajectory using only available data We enhance trajectories with the missing points using the “best” trajectory points. Nearest points from the “best” trajectory are found, and the “best” trajectory segment is added to the enhanced trajectory. We iterate 1 -2 with the additional data until the “best” trajectory remains stable and the value of the cost function diminishes. After the enhancement of the trajectories, we split trajectories set in the different clusters. “Best” trajectory within each cluster is found using the iterative approach described above. We use these trajectories as the routes between ports. The results are available as the Amazon s3 bucket http://worldroutes.s3.amazonaws.com. You can get and use them for any purpose under the Creative Commons Attribution 4.0 License. You can get information about the license here. The data consists of four files: Port-to-port distances calculated along the routes (distances.csv).Port-to-port routes as discussed above (routes.csv).We can’t provide you with the port polygons, however, we provide the reference data consisting of our internal index, World Port Index INDEX_NO, and PORT_NAME if any (or any available name we have) and a tuple of coordinates of the port polygon representative point. Representative point of the harbour polygon is obtained using geopandas representative_point() method (ports.csv).HTML file with the world map (WorldRoutes.html) Port-to-port distances calculated along the routes (distances.csv). Port-to-port routes as discussed above (routes.csv). We can’t provide you with the port polygons, however, we provide the reference data consisting of our internal index, World Port Index INDEX_NO, and PORT_NAME if any (or any available name we have) and a tuple of coordinates of the port polygon representative point. Representative point of the harbour polygon is obtained using geopandas representative_point() method (ports.csv). HTML file with the world map (WorldRoutes.html) Mariquant is a company formed with a strong focus on the development of analytical tools. We believe there is a tremendous value yet to be realised from consistent and broad adoption of data-driven analytics in the maritime industry. However, poor data quality, coverage and the sheer amount of data presents a hurdle for many, leading them down the path of top-down analysis frequently with the significant manual effort involved. At Marquant we challenge those barriers by adopting cutting-edge technology developed by the likes of Amazon and Google, but keeping the sharp focus on the needs of the maritime industry. Introduction of the fully automated, data-driven analytics allows scaling to the magnitude of individual cases found in the maritime allowing timely, accurate and measured commercial decisions. Pedregosa et al., Scikit-learn: Machine Learning in Python, JMLR 12, pp. 2825–2830, 2011.Sheng, Pan, and Jingbo Yin. “Extracting Shipping Route Patterns by Trajectory Clustering Model Based on Automatic Identification System Data.” Sustainability 10.7 (2018): 2327.P. Besse, B. Guillouet, J.-M. Loubes, and R. Francois, “Review and perspective for distance based trajectory clustering” arXiv preprint arXiv:1508.04904, 2015.ECML/PKDD 15: Taxi Trajectory Prediction (I)L. Chen and R. Ng, “On the marriage of lp-norms and edit distance,” Proceedings of the Thirtieth international conference on Very large data bases-Volume 30. VLDB Endowment, 2004, pp. 792–803. Pedregosa et al., Scikit-learn: Machine Learning in Python, JMLR 12, pp. 2825–2830, 2011. Sheng, Pan, and Jingbo Yin. “Extracting Shipping Route Patterns by Trajectory Clustering Model Based on Automatic Identification System Data.” Sustainability 10.7 (2018): 2327. P. Besse, B. Guillouet, J.-M. Loubes, and R. Francois, “Review and perspective for distance based trajectory clustering” arXiv preprint arXiv:1508.04904, 2015. ECML/PKDD 15: Taxi Trajectory Prediction (I) L. Chen and R. Ng, “On the marriage of lp-norms and edit distance,” Proceedings of the Thirtieth international conference on Very large data bases-Volume 30. VLDB Endowment, 2004, pp. 792–803.
[ { "code": null, "e": 629, "s": 172, "text": "Maritime routes are important characteristics of maritime transportation. Sometimes they are clearly defined by the official guidelines “traffic separation schemes”, sometimes they are more of the recommendations. International Maritime Organization is responsible for the routeing systems, including traffic separation schemes, and they are published in the IMO Publication, Ships’ Routeing — currently 2013 Edition. Unfortunately, they are not digitised." }, { "code": null, "e": 921, "s": 629, "text": "Some commercial and freemium products are available and they provide distance and sometimes route between ports on the per route basis. At the time of the writing, we were not able to find a comprehensive library of routes that will be available off-line. So we decided to construct our own." }, { "code": null, "e": 1285, "s": 921, "text": "Automatic identification system (AIS) is using transponders installed on almost all ships. Unique identification, position, course, and speed of the vessel are usually transmitted with regular intervals. These signals can be received by the nearby vessels, satellites and terrestrial antennas. There are several companies that collect, cleanse and sell this data." }, { "code": null, "e": 1557, "s": 1285, "text": "Mariquant has hourly data from one of the AIS data providers for the bulkers and tankers from the beginning of 2016 to the middle of 2018. This data has information from around 19 000 unique ships with records, occupying approximately 100 Gb as uncompressed parquet file." }, { "code": null, "e": 1870, "s": 1557, "text": "We have a library of the polygons with approximately 8 000 port harbours and 20 000 anchorage and waiting areas. Most of the time anchorage polygons lay outside of the port polygons, and we used graph algorithms to determine which anchorage belongs to which port. Having this data we started to construct routes." }, { "code": null, "e": 2463, "s": 1870, "text": "We will be using the notion of the distance between trajectories to construct the best representation of the route and to separate different trajectories on the same route. Most of the distance calculation algorithms are using the distance between points on the trajectories. We found that some noise prevented us from obtaining meaningful results for the calculations of the distances between trajectories. Looking at the data we found that ships spend a significant amount of time (leading to a large number of points on the trajectories) either anchoring or moving nearby the port harbour." }, { "code": null, "e": 3460, "s": 2463, "text": "To find at least some of these points on the trajectories, we used scikit learn[1] implementation of the Random Forest Classifier. There are various approaches to finding different clusters on the vessel trajectories, see for example [2] and references therein. We preferred to use a somewhat simplistic approach as it was easy to implement and provided us with sufficiently accurate results. We used distance to the port, distance to the previous port, speed of the ship, radial velocity of the ship (as if circling the port) and speed in the direction to the port, as the features of the classifier. We manually constructed training and testing sets separately marking ‘loitering’, anchoring, port approaching and general voyage points. We had around 6 400 points in the training and 1600 points in the testing set. Anchoring points are less represented in the sets, as they create fewer problems in the distance calculations. The difficulties in manual markup cause this small size of the set." }, { "code": null, "e": 3696, "s": 3460, "text": "The Confusion matrix shows that the loitering, approach and general voyage points are well defined. Even if the approach and general voyage points are misidentified, the misidentification is between two of them, not points of interest." }, { "code": null, "e": 3989, "s": 3696, "text": "Precision and recall, together with F1 score show that the results are good, but further improvements may be made for the classifier. We have to repeat that anchoring points are less troublesome for the calculation of the distance between trajectories and we will continue with these results." }, { "code": null, "e": 4248, "s": 3989, "text": "We found that distance to the port, distance to the previous port, speed of the ship are the most important features, having a score of 0.42, 0.21 and 0.28 correspondingly and radial speed and speed in the direction to the port have a score of 0.04 and 0.05." }, { "code": null, "e": 4333, "s": 4248, "text": "One can use standard Scikit-learn functions to calculate the scores mentioned above." }, { "code": null, "e": 4833, "s": 4333, "text": "from sklearn.metrics import classification_report, confusion_matrixfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)clf = RandomForestClassifier(n_estimators=20, max_depth=6, random_state=0)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)print(confusion_matrix(y_test, y_pred))print(classification_report(y_test, y_pred))print(clf.feature_importances_)" }, { "code": null, "e": 5318, "s": 4833, "text": "We found that irrespectively from the scores of the classifiers, additional cleanup is required for our large dataset. Sometimes small parts of the port approach trajectories were mistakenly identified as loitering parts, and we had to apply conservative check requiring anchoring and loitering parts of the trajectories to be long enough and either be self-intersecting, or the distance travelled in the direction to the port should be smaller compared to the total length travelled." }, { "code": null, "e": 5438, "s": 5318, "text": "After all these checks we average the position of the vessel for the loitering and anchoring parts of the trajectories." }, { "code": null, "e": 5909, "s": 5438, "text": "Our approach was inspired by the work of the Philippe Besse, Brendan Guillouet, Jean-Michel Loubes and Franc ̧ois Royer [3]. In the original work, authors proposed a new method called ‘Symmetrized segment-path distance’ for distance calculation between trajectories to clusterize taxi voyages to predict final destination point as part of the Kaggle competition [4]. Article [3] has an in-depth description of the various methods for the trajectory distance calculation." }, { "code": null, "e": 5935, "s": 5909, "text": "In short, our approach is" }, { "code": null, "e": 6100, "s": 5935, "text": "to calculate the distance between trajectories using some measureto clusterize trajectories based on their distances.to select the “best” trajectory in the cluster." }, { "code": null, "e": 6166, "s": 6100, "text": "to calculate the distance between trajectories using some measure" }, { "code": null, "e": 6219, "s": 6166, "text": "to clusterize trajectories based on their distances." }, { "code": null, "e": 6267, "s": 6219, "text": "to select the “best” trajectory in the cluster." }, { "code": null, "e": 7096, "s": 6267, "text": "We tested different methods for the distance calculations and decided to use Edit Distance with Real Penalty (ERP) [5]. This method is a warping distance method and allows comparison between trajectories of different length, aligning trajectories during the computation of the distance between them. It runs in O(n2) time. The implementation of this method is part of the trajectory_distance package created by the authors of [3]. We slightly modified this package to speed-up python part of the calculations and added DASK support for the parallel computations. Due to the memory and calculation time restrictions we select at max 50 random trajectories, as the computation on the popular route may deal with hundreds of them. This leads us to the 43847 distinct routes that will be reconstructed from almost one million trips." }, { "code": null, "e": 7597, "s": 7096, "text": "Different trips along the same route can have completely different trajectories. So we need to clusterise these trajectories if needed. Affinity propagation clustering algorithm is the natural choice for this task as it requires neither the initial knowledge of the number of clusters, no triangle inequality for the distance (not all methods for the distance calculations generate distances that satisfy this inequality). We used scikit learn[1] implementation of the Affinity propagation algorithm." }, { "code": null, "e": 7753, "s": 7597, "text": "Missing points are usual for the data, collected by the satellites, due to the restrictions of the AIS protocol. We had to find a solution to this problem." }, { "code": null, "e": 7964, "s": 7753, "text": "First, we use the cost function that will take into account both the distance between the trajectories (we use simple average) and the number of missing points in the trajectory to define the “best” trajectory." }, { "code": null, "e": 8012, "s": 7964, "text": "Second, we update the trajectories iteratively:" }, { "code": null, "e": 8405, "s": 8012, "text": "We find the “best” trajectory using only available dataWe enhance trajectories with the missing points using the “best” trajectory points. Nearest points from the “best” trajectory are found, and the “best” trajectory segment is added to the enhanced trajectory.We iterate 1 -2 with the additional data until the “best” trajectory remains stable and the value of the cost function diminishes." }, { "code": null, "e": 8461, "s": 8405, "text": "We find the “best” trajectory using only available data" }, { "code": null, "e": 8669, "s": 8461, "text": "We enhance trajectories with the missing points using the “best” trajectory points. Nearest points from the “best” trajectory are found, and the “best” trajectory segment is added to the enhanced trajectory." }, { "code": null, "e": 8800, "s": 8669, "text": "We iterate 1 -2 with the additional data until the “best” trajectory remains stable and the value of the cost function diminishes." }, { "code": null, "e": 9044, "s": 8800, "text": "After the enhancement of the trajectories, we split trajectories set in the different clusters. “Best” trajectory within each cluster is found using the iterative approach described above. We use these trajectories as the routes between ports." }, { "code": null, "e": 9272, "s": 9044, "text": "The results are available as the Amazon s3 bucket http://worldroutes.s3.amazonaws.com. You can get and use them for any purpose under the Creative Commons Attribution 4.0 License. You can get information about the license here." }, { "code": null, "e": 9305, "s": 9272, "text": "The data consists of four files:" }, { "code": null, "e": 9853, "s": 9305, "text": "Port-to-port distances calculated along the routes (distances.csv).Port-to-port routes as discussed above (routes.csv).We can’t provide you with the port polygons, however, we provide the reference data consisting of our internal index, World Port Index INDEX_NO, and PORT_NAME if any (or any available name we have) and a tuple of coordinates of the port polygon representative point. Representative point of the harbour polygon is obtained using geopandas representative_point() method (ports.csv).HTML file with the world map (WorldRoutes.html)" }, { "code": null, "e": 9921, "s": 9853, "text": "Port-to-port distances calculated along the routes (distances.csv)." }, { "code": null, "e": 9974, "s": 9921, "text": "Port-to-port routes as discussed above (routes.csv)." }, { "code": null, "e": 10356, "s": 9974, "text": "We can’t provide you with the port polygons, however, we provide the reference data consisting of our internal index, World Port Index INDEX_NO, and PORT_NAME if any (or any available name we have) and a tuple of coordinates of the port polygon representative point. Representative point of the harbour polygon is obtained using geopandas representative_point() method (ports.csv)." }, { "code": null, "e": 10404, "s": 10356, "text": "HTML file with the world map (WorldRoutes.html)" }, { "code": null, "e": 10836, "s": 10404, "text": "Mariquant is a company formed with a strong focus on the development of analytical tools. We believe there is a tremendous value yet to be realised from consistent and broad adoption of data-driven analytics in the maritime industry. However, poor data quality, coverage and the sheer amount of data presents a hurdle for many, leading them down the path of top-down analysis frequently with the significant manual effort involved." }, { "code": null, "e": 11218, "s": 10836, "text": "At Marquant we challenge those barriers by adopting cutting-edge technology developed by the likes of Amazon and Google, but keeping the sharp focus on the needs of the maritime industry. Introduction of the fully automated, data-driven analytics allows scaling to the magnitude of individual cases found in the maritime allowing timely, accurate and measured commercial decisions." }, { "code": null, "e": 11879, "s": 11218, "text": "Pedregosa et al., Scikit-learn: Machine Learning in Python, JMLR 12, pp. 2825–2830, 2011.Sheng, Pan, and Jingbo Yin. “Extracting Shipping Route Patterns by Trajectory Clustering Model Based on Automatic Identification System Data.” Sustainability 10.7 (2018): 2327.P. Besse, B. Guillouet, J.-M. Loubes, and R. Francois, “Review and perspective for distance based trajectory clustering” arXiv preprint arXiv:1508.04904, 2015.ECML/PKDD 15: Taxi Trajectory Prediction (I)L. Chen and R. Ng, “On the marriage of lp-norms and edit distance,” Proceedings of the Thirtieth international conference on Very large data bases-Volume 30. VLDB Endowment, 2004, pp. 792–803." }, { "code": null, "e": 11969, "s": 11879, "text": "Pedregosa et al., Scikit-learn: Machine Learning in Python, JMLR 12, pp. 2825–2830, 2011." }, { "code": null, "e": 12146, "s": 11969, "text": "Sheng, Pan, and Jingbo Yin. “Extracting Shipping Route Patterns by Trajectory Clustering Model Based on Automatic Identification System Data.” Sustainability 10.7 (2018): 2327." }, { "code": null, "e": 12306, "s": 12146, "text": "P. Besse, B. Guillouet, J.-M. Loubes, and R. Francois, “Review and perspective for distance based trajectory clustering” arXiv preprint arXiv:1508.04904, 2015." }, { "code": null, "e": 12351, "s": 12306, "text": "ECML/PKDD 15: Taxi Trajectory Prediction (I)" } ]
What is a pageContext Object in JSP?
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page. This object is intended as a means to access information about the page while avoiding most of the implementation details. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object. The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope. The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp.JspContext class. One of the important methods is removeAttribute. This method accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope − pageContext.removeAttribute("attrName", PAGE_SCOPE);
[ { "code": null, "e": 1208, "s": 1062, "text": "The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page." }, { "code": null, "e": 1331, "s": 1208, "text": "This object is intended as a means to access information about the page while avoiding most of the implementation details." }, { "code": null, "e": 1517, "s": 1331, "text": "This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object." }, { "code": null, "e": 1682, "s": 1517, "text": "The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope." }, { "code": null, "e": 1953, "s": 1682, "text": "The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp.JspContext class." }, { "code": null, "e": 2207, "s": 1953, "text": "One of the important methods is removeAttribute. This method accepts either one or two arguments. For example, pageContext.removeAttribute (\"attrName\") removes the attribute from all scopes, while the following code only removes it from the page scope −" }, { "code": null, "e": 2260, "s": 2207, "text": "pageContext.removeAttribute(\"attrName\", PAGE_SCOPE);" } ]
Is it better to have one big JavaScript file or multiple light files?
To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file. If you are using multiple files, then minify all of your scripts and separate them into categories. <script src =”/js/core.js”> - Place JavaScript to be used in every page. This can be the core script of the file. <script src =”/js/plugins.js”> - Place your plugins here Rest, add other scripts in a JavaScript file. It’s good to maintain it in different files.
[ { "code": null, "e": 1236, "s": 1062, "text": "To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page." }, { "code": null, "e": 1323, "s": 1236, "text": "If you are using single page application, then group all the scripts in a single file." }, { "code": null, "e": 1423, "s": 1323, "text": "If you are using multiple files, then minify all of your scripts and separate them into categories." }, { "code": null, "e": 1594, "s": 1423, "text": "<script src =”/js/core.js”> - Place JavaScript to be used in every page.\nThis can be the core script of the file.\n<script src =”/js/plugins.js”> - Place your plugins here" }, { "code": null, "e": 1685, "s": 1594, "text": "Rest, add other scripts in a JavaScript file. It’s good to maintain it in different files." } ]
Tryit Editor v3.7
Padding & Spacing Tryit: HTML table - cellpadding
[ { "code": null, "e": 40, "s": 22, "text": "Padding & Spacing" } ]
regexp_replace(string, pattern, replacement)
presto:default> SELECT regexp_replace('1a 2b 3c 6f', '(\d+)([abc]) ', 'aa$2 ') as expression; expression ---------------- aaa aab aac 6f (1 row) Replace the instance of the string matched for the expression with the pattern and replacement string ‘aa’. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2101, "s": 2006, "text": "presto:default> SELECT regexp_replace('1a 2b 3c 6f', '(\\d+)([abc]) ', 'aa$2 ') \nas expression;" }, { "code": null, "e": 2159, "s": 2101, "text": " expression \n---------------- \n aaa aab aac 6f \n (1 row)\n" }, { "code": null, "e": 2267, "s": 2159, "text": "Replace the instance of the string matched for the expression with the pattern and replacement string ‘aa’." }, { "code": null, "e": 2302, "s": 2267, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2321, "s": 2302, "text": " Arnab Chakraborty" }, { "code": null, "e": 2356, "s": 2321, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2377, "s": 2356, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 2410, "s": 2377, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2423, "s": 2410, "text": " Nilay Mehta" }, { "code": null, "e": 2458, "s": 2423, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2476, "s": 2458, "text": " Bigdata Engineer" }, { "code": null, "e": 2509, "s": 2476, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2527, "s": 2509, "text": " Bigdata Engineer" }, { "code": null, "e": 2560, "s": 2527, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 2578, "s": 2560, "text": " Bigdata Engineer" }, { "code": null, "e": 2585, "s": 2578, "text": " Print" }, { "code": null, "e": 2596, "s": 2585, "text": " Add Notes" } ]
Selenium and Headless Environment.
We can execute Selenium in a headless environment. The headless execution is a new trend followed in industry today since it is fast and supports more than one browser. Firefox in headless mode, can be run once we configure the geckodriver path. We shall then use the FirefoxOptions class, and send the headless knowledge to the browser with setHeadless method and pass true as a parameter to it. FirefoxOptions o = new FirefoxOptions(); o.setHeadless(true); WebDriver driver = new FirefoxDriver(o); Code Implementation. import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import java.util.concurrent.TimeUnit; public class HeadlessFirefox{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); //FirefoxOptions object creation FirefoxOptions o = new FirefoxOptions(); //set true to headless mode o.setHeadless(true); // add options parameter to Firefox driver WebDriver driver = new FirefoxDriver(o); // wait of 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/questions/index.php"); // get page title System.out.println("Page Title in headless mode: " + driver.getTitle()); } }
[ { "code": null, "e": 1231, "s": 1062, "text": "We can execute Selenium in a headless environment. The headless execution is a new trend followed in industry today since it is fast and supports more than one browser." }, { "code": null, "e": 1459, "s": 1231, "text": "Firefox in headless mode, can be run once we configure the geckodriver path. We shall then use the FirefoxOptions class, and send the headless knowledge to the browser with setHeadless method and pass true as a parameter to it." }, { "code": null, "e": 1562, "s": 1459, "text": "FirefoxOptions o = new FirefoxOptions();\no.setHeadless(true);\nWebDriver driver = new FirefoxDriver(o);" }, { "code": null, "e": 1583, "s": 1562, "text": "Code Implementation." }, { "code": null, "e": 2501, "s": 1583, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.firefox.FirefoxOptions;\nimport java.util.concurrent.TimeUnit;\npublic class HeadlessFirefox{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n //FirefoxOptions object creation\n FirefoxOptions o = new FirefoxOptions();\n //set true to headless mode\n o.setHeadless(true);\n // add options parameter to Firefox driver\n WebDriver driver = new FirefoxDriver(o);\n // wait of 5 seconds\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/questions/index.php\");\n // get page title\n System.out.println(\"Page Title in headless mode: \" + driver.getTitle());\n }\n}" } ]
Robot Framework - Environment Setup
Robot framework is built using python. In this chapter, we will learn how to set up Robot Framework. To work with Robot Framework, we need to install the following − Python pip Robot Framework wxPython for Ride IDE Robot Framework Ride To install python, go to python official site − https://www.python.org/downloads/ and download the latest version or the prior version of python as per your operating system (Windows, Linux/Unix, Mac, and OS X) you are going to use. Here is the screenshot of the python download site − The latest version available as per release dates are as follows − Before you download python, it is recommended you check your system if python is already present by running the following command in the command line − python --version If we get the version of python as output then, we have python installed in our system. Otherwise, you will get a display as shown above. Here, we will download python version 2.7 as it is compatible to the windows 8 we are using right now. Once downloaded, install python on your system by double-clicking on .exe python download. Follow the installation steps to install Python on your system. Once installed, to make python available globally, we need to add the path to environment variables in windows as follows − Right-click on My Computer icon and select properties. Click on Advanced System setting and the following screen will be displayed. Click on Environment Variables button highlighted above and it will show you the screen as follows − Select the Variable Path and click the Edit button. Get the path where python is installed and add the same to Variable value at the end as shown above. Once this is done, you can check if python is installed from any path or directory as shown below − 17 Lectures 1 hours Musab Zayadneh 11 Lectures 31 mins Musab Zayadneh 20 Lectures 1.5 hours Maksym Rudnyi 25 Lectures 3 hours Kamal Kishor Girdher 16 Lectures 3.5 hours Onur 10 Lectures 34 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2335, "s": 2169, "text": "Robot framework is built using python. In this chapter, we will learn how to set up Robot Framework. To work with Robot Framework, we need to install the following −" }, { "code": null, "e": 2342, "s": 2335, "text": "Python" }, { "code": null, "e": 2346, "s": 2342, "text": "pip" }, { "code": null, "e": 2362, "s": 2346, "text": "Robot Framework" }, { "code": null, "e": 2384, "s": 2362, "text": "wxPython for Ride IDE" }, { "code": null, "e": 2405, "s": 2384, "text": "Robot Framework Ride" }, { "code": null, "e": 2638, "s": 2405, "text": "To install python, go to python official site − https://www.python.org/downloads/ and download the latest version or the prior version of python as per your operating system (Windows, Linux/Unix, Mac, and OS X) you are going to use." }, { "code": null, "e": 2691, "s": 2638, "text": "Here is the screenshot of the python download site −" }, { "code": null, "e": 2758, "s": 2691, "text": "The latest version available as per release dates are as follows −" }, { "code": null, "e": 2910, "s": 2758, "text": "Before you download python, it is recommended you check your system if python is already present by running the following command in the command line −" }, { "code": null, "e": 2928, "s": 2910, "text": "python --version\n" }, { "code": null, "e": 3066, "s": 2928, "text": "If we get the version of python as output then, we have python installed in our system. Otherwise, you will get a display as shown above." }, { "code": null, "e": 3448, "s": 3066, "text": "Here, we will download python version 2.7 as it is compatible to the windows 8 we are using right now. Once downloaded, install python on your system by double-clicking on .exe python download. Follow the installation steps to install Python on your system. Once installed, to make python available globally, we need to add the path to environment variables in windows as follows −" }, { "code": null, "e": 3580, "s": 3448, "text": "Right-click on My Computer icon and select properties. Click on Advanced System setting and the following screen will be displayed." }, { "code": null, "e": 3681, "s": 3580, "text": "Click on Environment Variables button highlighted above and it will show you the screen as follows −" }, { "code": null, "e": 3733, "s": 3681, "text": "Select the Variable Path and click the Edit button." }, { "code": null, "e": 3834, "s": 3733, "text": "Get the path where python is installed and add the same to Variable value at the end as shown above." }, { "code": null, "e": 3934, "s": 3834, "text": "Once this is done, you can check if python is installed from any path or directory as shown below −" }, { "code": null, "e": 3967, "s": 3934, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3983, "s": 3967, "text": " Musab Zayadneh" }, { "code": null, "e": 4015, "s": 3983, "text": "\n 11 Lectures \n 31 mins\n" }, { "code": null, "e": 4031, "s": 4015, "text": " Musab Zayadneh" }, { "code": null, "e": 4066, "s": 4031, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4081, "s": 4066, "text": " Maksym Rudnyi" }, { "code": null, "e": 4114, "s": 4081, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 4136, "s": 4114, "text": " Kamal Kishor Girdher" }, { "code": null, "e": 4171, "s": 4136, "text": "\n 16 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4177, "s": 4171, "text": " Onur" }, { "code": null, "e": 4209, "s": 4177, "text": "\n 10 Lectures \n 34 mins\n" }, { "code": null, "e": 4222, "s": 4209, "text": " Ashraf Said" }, { "code": null, "e": 4229, "s": 4222, "text": " Print" }, { "code": null, "e": 4240, "s": 4229, "text": " Add Notes" } ]
Java NIO - Pipe
In Java NIO pipe is a component which is used to write and read data between two threads.Pipe mainly consist of two channels which are responsible for data propagation. Among two constituent channels one is called as Sink channel which is mainly for writing data and other is Source channel whose main purpose is to read data from Sink channel. Data synchronization is kept in order during data writing and reading as it must be ensured that data must be read in a same order in which it is written to the Pipe. It must kept in notice that it is a unidirectional flow of data in Pipe i.e data is written in Sink channel only and could only be read from Source channel. In Java NIO pipe is defined as a abstract class with mainly three methods out of which two are abstract. open() − This method is used get an instance of Pipe or we can say pipe is created by calling out this method. open() − This method is used get an instance of Pipe or we can say pipe is created by calling out this method. sink() − This method returns the Pipe's sink channel which is used to write data by calling its write method. sink() − This method returns the Pipe's sink channel which is used to write data by calling its write method. source() − This method returns the Pipe's source channel which is used to read data by calling its read method. source() − This method returns the Pipe's source channel which is used to read data by calling its read method. The following example shows the implementation of Java NIO pipe. import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; public class PipeDemo { public static void main(String[] args) throws IOException { //An instance of Pipe is created Pipe pipe = Pipe.open(); // gets the pipe's sink channel Pipe.SinkChannel skChannel = pipe.sink(); String testData = "Test Data to Check java NIO Channels Pipe."; ByteBuffer buffer = ByteBuffer.allocate(512); buffer.clear(); buffer.put(testData.getBytes()); buffer.flip(); //write data into sink channel. while(buffer.hasRemaining()) { skChannel.write(buffer); } //gets pipe's source channel Pipe.SourceChannel sourceChannel = pipe.source(); buffer = ByteBuffer.allocate(512); //write data into console while(sourceChannel.read(buffer) > 0){ //limit is set to current position and position is set to zero buffer.flip(); while(buffer.hasRemaining()){ char ch = (char) buffer.get(); System.out.print(ch); } //position is set to zero and limit is set to capacity to clear the buffer. buffer.clear(); } } } Test Data to Check java NIO Channels Pipe. Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2153, "s": 1984, "text": "In Java NIO pipe is a component which is used to write and read data between two threads.Pipe mainly consist of two channels which are responsible for data propagation." }, { "code": null, "e": 2329, "s": 2153, "text": "Among two constituent channels one is called as Sink channel which is mainly for writing data and other is Source channel whose main purpose is to read data from Sink channel." }, { "code": null, "e": 2496, "s": 2329, "text": "Data synchronization is kept in order during data writing and reading as it must be ensured that data must be read in a same order in which it is written to the Pipe." }, { "code": null, "e": 2653, "s": 2496, "text": "It must kept in notice that it is a unidirectional flow of data in Pipe i.e data is written in Sink channel only and could only be read from Source channel." }, { "code": null, "e": 2758, "s": 2653, "text": "In Java NIO pipe is defined as a abstract class with mainly three methods out of which two are abstract." }, { "code": null, "e": 2869, "s": 2758, "text": "open() − This method is used get an instance of Pipe or we can say pipe is created by calling out this method." }, { "code": null, "e": 2980, "s": 2869, "text": "open() − This method is used get an instance of Pipe or we can say pipe is created by calling out this method." }, { "code": null, "e": 3090, "s": 2980, "text": "sink() − This method returns the Pipe's sink channel which is used to write data by calling its write method." }, { "code": null, "e": 3200, "s": 3090, "text": "sink() − This method returns the Pipe's sink channel which is used to write data by calling its write method." }, { "code": null, "e": 3312, "s": 3200, "text": "source() − This method returns the Pipe's source channel which is used to read data by calling its read method." }, { "code": null, "e": 3424, "s": 3312, "text": "source() − This method returns the Pipe's source channel which is used to read data by calling its read method." }, { "code": null, "e": 3489, "s": 3424, "text": "The following example shows the implementation of Java NIO pipe." }, { "code": null, "e": 4704, "s": 3489, "text": "import java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.Pipe;\n\npublic class PipeDemo {\n public static void main(String[] args) throws IOException {\n //An instance of Pipe is created\n Pipe pipe = Pipe.open();\n // gets the pipe's sink channel\n Pipe.SinkChannel skChannel = pipe.sink();\n String testData = \"Test Data to Check java NIO Channels Pipe.\";\n ByteBuffer buffer = ByteBuffer.allocate(512);\n buffer.clear();\n buffer.put(testData.getBytes());\n buffer.flip();\n //write data into sink channel.\n while(buffer.hasRemaining()) {\n skChannel.write(buffer);\n }\n //gets pipe's source channel\n Pipe.SourceChannel sourceChannel = pipe.source();\n buffer = ByteBuffer.allocate(512);\n //write data into console \n while(sourceChannel.read(buffer) > 0){\n //limit is set to current position and position is set to zero\n buffer.flip();\n while(buffer.hasRemaining()){\n char ch = (char) buffer.get();\n System.out.print(ch);\n }\n //position is set to zero and limit is set to capacity to clear the buffer.\n buffer.clear();\n }\n }\n}" }, { "code": null, "e": 4748, "s": 4704, "text": "Test Data to Check java NIO Channels Pipe.\n" }, { "code": null, "e": 4883, "s": 4748, "text": "Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program." }, { "code": null, "e": 4916, "s": 4883, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4932, "s": 4916, "text": " Malhar Lathkar" }, { "code": null, "e": 4965, "s": 4932, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4981, "s": 4965, "text": " Malhar Lathkar" }, { "code": null, "e": 5016, "s": 4981, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5030, "s": 5016, "text": " Anadi Sharma" }, { "code": null, "e": 5064, "s": 5030, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5078, "s": 5064, "text": " Tushar Kale" }, { "code": null, "e": 5115, "s": 5078, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5130, "s": 5115, "text": " Monica Mittal" }, { "code": null, "e": 5163, "s": 5130, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5182, "s": 5163, "text": " Arnab Chakraborty" }, { "code": null, "e": 5189, "s": 5182, "text": " Print" }, { "code": null, "e": 5200, "s": 5189, "text": " Add Notes" } ]
How to pass arrays as function arguments in JavaScript?
In olden days if we need to pass arrays as function arguments then apply() and null should be used. The use of null makes a code unclean. So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread operator we don't need to use apply() function. Lets' discuss it in a nutshell. In the following example, we have used null and apply() to pass an array as a function argument. This is an obsolete method. This method is replaced by a modern method in which spread operator is used. Live Demo <html> <body> <script> function shareMar(a, b, c) { document.write(a); document.write("</br>"); document.write(b); document.write("</br>"); document.write(c); } var names = ['NSE', 'BSE', 'NIFTY']; shareMar.apply(null, names); </script> </body> </html> NSE BSE NIFTY If we observe the following example, apply() function and null weren't used, instead of those ES6 spread operator is used. The use of spread operator makes the code urbane and there is no need to use useless null value. Live Demo <html> <body> <script> function shareMar(a, b, c) { document.write(a); document.write("</br>"); document.write(b); document.write("</br>"); document.write(c); } var names = ['NSE', 'BSE', 'NIFTY']; shareMar(...names); </script> </body> </html> NSE BSE NIFTY
[ { "code": null, "e": 1413, "s": 1062, "text": "In olden days if we need to pass arrays as function arguments then apply() and null should be used. The use of null makes a code unclean. So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread operator we don't need to use apply() function. Lets' discuss it in a nutshell." }, { "code": null, "e": 1615, "s": 1413, "text": "In the following example, we have used null and apply() to pass an array as a function argument. This is an obsolete method. This method is replaced by a modern method in which spread operator is used." }, { "code": null, "e": 1625, "s": 1615, "text": "Live Demo" }, { "code": null, "e": 1920, "s": 1625, "text": "<html>\n<body>\n<script>\n function shareMar(a, b, c) {\n document.write(a);\n document.write(\"</br>\");\n document.write(b);\n document.write(\"</br>\");\n document.write(c);\n }\n var names = ['NSE', 'BSE', 'NIFTY'];\n shareMar.apply(null, names);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1934, "s": 1920, "text": "NSE\nBSE\nNIFTY" }, { "code": null, "e": 2154, "s": 1934, "text": "If we observe the following example, apply() function and null weren't used, instead of those ES6 spread operator is used. The use of spread operator makes the code urbane and there is no need to use useless null value." }, { "code": null, "e": 2164, "s": 2154, "text": "Live Demo" }, { "code": null, "e": 2450, "s": 2164, "text": "<html>\n<body>\n<script>\n function shareMar(a, b, c) {\n document.write(a);\n document.write(\"</br>\");\n document.write(b);\n document.write(\"</br>\");\n document.write(c);\n }\n var names = ['NSE', 'BSE', 'NIFTY'];\n shareMar(...names);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2464, "s": 2450, "text": "NSE\nBSE\nNIFTY" } ]
Keras - Time Series Prediction using LSTM RNN
In this chapter, let us write a simple Long Short Term Memory (LSTM) based RNN to do sequence analysis. A sequence is a set of values where each value corresponds to a particular instance of time. Let us consider a simple example of reading a sentence. Reading and understanding a sentence involves reading the word in the given order and trying to understand each word and its meaning in the given context and finally understanding the sentence in a positive or negative sentiment. Here, the words are considered as values, and first value corresponds to first word, second value corresponds to second word, etc., and the order will be strictly maintained. Sequence Analysis is used frequently in natural language processing to find the sentiment analysis of the given text. Let us create a LSTM model to analyze the IMDB movie reviews and find its positive/negative sentiment. The model for the sequence analysis can be represented as below − The core features of the model are as follows − Input layer using Embedding layer with 128 features. Input layer using Embedding layer with 128 features. First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2. First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2. Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function. Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function. Use binary_crossentropy as loss function. Use binary_crossentropy as loss function. Use adam as Optimizer. Use adam as Optimizer. Use accuracy as metrics. Use accuracy as metrics. Use 32 as batch size. Use 32 as batch size. Use 15 as epochs. Use 15 as epochs. Use 80 as the maximum length of the word. Use 80 as the maximum length of the word. Use 2000 as the maximum number of word in a given sentence. Use 2000 as the maximum number of word in a given sentence. Let us import the necessary modules. from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding from keras.layers import LSTM from keras.datasets import imdb Let us import the imdb dataset. (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words = 2000) Here, imdb is a dataset provided by Keras. It represents a collection of movies and its reviews. imdb is a dataset provided by Keras. It represents a collection of movies and its reviews. num_words represent the maximum number of words in the review. num_words represent the maximum number of words in the review. Let us change the dataset according to our model, so that it can be fed into our model. The data can be changed using the below code − x_train = sequence.pad_sequences(x_train, maxlen=80) x_test = sequence.pad_sequences(x_test, maxlen=80) Here, sequence.pad_sequences convert the list of input data with shape, (data) into 2D NumPy array of shape (data, timesteps). Basically, it adds timesteps concept into the given data. It generates the timesteps of length, maxlen. Let us create the actual model. model = Sequential() model.add(Embedding(2000, 128)) model.add(LSTM(128, dropout = 0.2, recurrent_dropout = 0.2)) model.add(Dense(1, activation = 'sigmoid')) Here, We have used Embedding layer as input layer and then added the LSTM layer. Finally, a Dense layer is used as output layer. Let us compile the model using selected loss function, optimizer and metrics. model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) LLet us train the model using fit() method. model.fit( x_train, y_train, batch_size = 32, epochs = 15, validation_data = (x_test, y_test) ) Executing the application will output the below information − Epoch 1/15 2019-09-24 01:19:01.151247: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not co mpiled to use: AVX2 25000/25000 [==============================] - 101s 4ms/step - loss: 0.4707 - acc: 0.7716 - val_loss: 0.3769 - val_acc: 0.8349 Epoch 2/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.3058 - acc: 0.8756 - val_loss: 0.3763 - val_acc: 0.8350 Epoch 3/15 25000/25000 [==============================] - 91s 4ms/step - loss: 0.2100 - acc: 0.9178 - val_loss: 0.5065 - val_acc: 0.8110 Epoch 4/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.1394 - acc: 0.9495 - val_loss: 0.6046 - val_acc: 0.8146 Epoch 5/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.0973 - acc: 0.9652 - val_loss: 0.5969 - val_acc: 0.8147 Epoch 6/15 25000/25000 [==============================] - 98s 4ms/step - loss: 0.0759 - acc: 0.9730 - val_loss: 0.6368 - val_acc: 0.8208 Epoch 7/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.0578 - acc: 0.9811 - val_loss: 0.6657 - val_acc: 0.8184 Epoch 8/15 25000/25000 [==============================] - 97s 4ms/step - loss: 0.0448 - acc: 0.9850 - val_loss: 0.7452 - val_acc: 0.8136 Epoch 9/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.0324 - acc: 0.9894 - val_loss: 0.7616 - val_acc: 0.8162Epoch 10/15 25000/25000 [==============================] - 100s 4ms/step - loss: 0.0247 - acc: 0.9922 - val_loss: 0.9654 - val_acc: 0.8148 Epoch 11/15 25000/25000 [==============================] - 99s 4ms/step - loss: 0.0169 - acc: 0.9946 - val_loss: 1.0013 - val_acc: 0.8104 Epoch 12/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.0154 - acc: 0.9948 - val_loss: 1.0316 - val_acc: 0.8100 Epoch 13/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0113 - acc: 0.9963 - val_loss: 1.1138 - val_acc: 0.8108 Epoch 14/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0106 - acc: 0.9971 - val_loss: 1.0538 - val_acc: 0.8102 Epoch 15/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0090 - acc: 0.9972 - val_loss: 1.1453 - val_acc: 0.8129 25000/25000 [==============================] - 10s 390us/step Let us evaluate the model using test data. score, acc = model.evaluate(x_test, y_test, batch_size = 32) print('Test score:', score) print('Test accuracy:', acc) Executing the above code will output the below information − Test score: 1.145306069601178 Test accuracy: 0.81292 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2534, "s": 2051, "text": "In this chapter, let us write a simple Long Short Term Memory (LSTM) based RNN to do sequence analysis. A sequence is a set of values where each value corresponds to a particular instance of time. Let us consider a simple example of reading a sentence. Reading and understanding a sentence involves reading the word in the given order and trying to understand each word and its meaning in the given context and finally understanding the sentence in a positive or negative sentiment." }, { "code": null, "e": 2827, "s": 2534, "text": "Here, the words are considered as values, and first value corresponds to first word, second value corresponds to second word, etc., and the order will be strictly maintained. Sequence Analysis is used frequently in natural language processing to find the sentiment analysis of the given text." }, { "code": null, "e": 2930, "s": 2827, "text": "Let us create a LSTM model to analyze the IMDB movie reviews and find its positive/negative sentiment." }, { "code": null, "e": 2996, "s": 2930, "text": "The model for the sequence analysis can be represented as below −" }, { "code": null, "e": 3044, "s": 2996, "text": "The core features of the model are as follows −" }, { "code": null, "e": 3097, "s": 3044, "text": "Input layer using Embedding layer with 128 features." }, { "code": null, "e": 3150, "s": 3097, "text": "Input layer using Embedding layer with 128 features." }, { "code": null, "e": 3245, "s": 3150, "text": "First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2." }, { "code": null, "e": 3340, "s": 3245, "text": "First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2." }, { "code": null, "e": 3414, "s": 3340, "text": "Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function." }, { "code": null, "e": 3488, "s": 3414, "text": "Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function." }, { "code": null, "e": 3530, "s": 3488, "text": "Use binary_crossentropy as loss function." }, { "code": null, "e": 3572, "s": 3530, "text": "Use binary_crossentropy as loss function." }, { "code": null, "e": 3595, "s": 3572, "text": "Use adam as Optimizer." }, { "code": null, "e": 3618, "s": 3595, "text": "Use adam as Optimizer." }, { "code": null, "e": 3643, "s": 3618, "text": "Use accuracy as metrics." }, { "code": null, "e": 3668, "s": 3643, "text": "Use accuracy as metrics." }, { "code": null, "e": 3690, "s": 3668, "text": "Use 32 as batch size." }, { "code": null, "e": 3712, "s": 3690, "text": "Use 32 as batch size." }, { "code": null, "e": 3730, "s": 3712, "text": "Use 15 as epochs." }, { "code": null, "e": 3748, "s": 3730, "text": "Use 15 as epochs." }, { "code": null, "e": 3790, "s": 3748, "text": "Use 80 as the maximum length of the word." }, { "code": null, "e": 3832, "s": 3790, "text": "Use 80 as the maximum length of the word." }, { "code": null, "e": 3892, "s": 3832, "text": "Use 2000 as the maximum number of word in a given sentence." }, { "code": null, "e": 3952, "s": 3892, "text": "Use 2000 as the maximum number of word in a given sentence." }, { "code": null, "e": 3989, "s": 3952, "text": "Let us import the necessary modules." }, { "code": null, "e": 4174, "s": 3989, "text": "from keras.preprocessing import sequence \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Embedding \nfrom keras.layers import LSTM \nfrom keras.datasets import imdb" }, { "code": null, "e": 4206, "s": 4174, "text": "Let us import the imdb dataset." }, { "code": null, "e": 4279, "s": 4206, "text": "(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words = 2000)\n" }, { "code": null, "e": 4285, "s": 4279, "text": "Here," }, { "code": null, "e": 4376, "s": 4285, "text": "imdb is a dataset provided by Keras. It represents a collection of movies and its reviews." }, { "code": null, "e": 4467, "s": 4376, "text": "imdb is a dataset provided by Keras. It represents a collection of movies and its reviews." }, { "code": null, "e": 4530, "s": 4467, "text": "num_words represent the maximum number of words in the review." }, { "code": null, "e": 4593, "s": 4530, "text": "num_words represent the maximum number of words in the review." }, { "code": null, "e": 4728, "s": 4593, "text": "Let us change the dataset according to our model, so that it can be fed into our model. The data can be changed using the below code −" }, { "code": null, "e": 4833, "s": 4728, "text": "x_train = sequence.pad_sequences(x_train, maxlen=80) \nx_test = sequence.pad_sequences(x_test, maxlen=80)" }, { "code": null, "e": 4839, "s": 4833, "text": "Here," }, { "code": null, "e": 5064, "s": 4839, "text": "sequence.pad_sequences convert the list of input data with shape, (data) into 2D NumPy array of shape (data, timesteps). Basically, it adds timesteps concept into the given data. It generates the timesteps of length, maxlen." }, { "code": null, "e": 5096, "s": 5064, "text": "Let us create the actual model." }, { "code": null, "e": 5257, "s": 5096, "text": "model = Sequential() \nmodel.add(Embedding(2000, 128)) \nmodel.add(LSTM(128, dropout = 0.2, recurrent_dropout = 0.2)) \nmodel.add(Dense(1, activation = 'sigmoid'))" }, { "code": null, "e": 5263, "s": 5257, "text": "Here," }, { "code": null, "e": 5386, "s": 5263, "text": "We have used Embedding layer as input layer and then added the LSTM layer. Finally, a Dense layer is used as output layer." }, { "code": null, "e": 5464, "s": 5386, "text": "Let us compile the model using selected loss function, optimizer and metrics." }, { "code": null, "e": 5556, "s": 5464, "text": "model.compile(loss = 'binary_crossentropy', \n optimizer = 'adam', metrics = ['accuracy'])" }, { "code": null, "e": 5600, "s": 5556, "text": "LLet us train the model using fit() method." }, { "code": null, "e": 5711, "s": 5600, "text": "model.fit(\n x_train, y_train, \n batch_size = 32, \n epochs = 15, \n validation_data = (x_test, y_test)\n)" }, { "code": null, "e": 5773, "s": 5711, "text": "Executing the application will output the below information −" }, { "code": null, "e": 8103, "s": 5773, "text": "Epoch 1/15 2019-09-24 01:19:01.151247: I \ntensorflow/core/platform/cpu_feature_guard.cc:142] \nYour CPU supports instructions that this \nTensorFlow binary was not co mpiled to use: AVX2 \n25000/25000 [==============================] - 101s 4ms/step - loss: 0.4707 \n- acc: 0.7716 - val_loss: 0.3769 - val_acc: 0.8349 Epoch 2/15 \n25000/25000 [==============================] - 95s 4ms/step - loss: 0.3058 \n- acc: 0.8756 - val_loss: 0.3763 - val_acc: 0.8350 Epoch 3/15 \n25000/25000 [==============================] - 91s 4ms/step - loss: 0.2100 \n- acc: 0.9178 - val_loss: 0.5065 - val_acc: 0.8110 Epoch 4/15 \n25000/25000 [==============================] - 90s 4ms/step - loss: 0.1394 \n- acc: 0.9495 - val_loss: 0.6046 - val_acc: 0.8146 Epoch 5/15 \n25000/25000 [==============================] - 90s 4ms/step - loss: 0.0973 \n- acc: 0.9652 - val_loss: 0.5969 - val_acc: 0.8147 Epoch 6/15 \n25000/25000 [==============================] - 98s 4ms/step - loss: 0.0759 \n- acc: 0.9730 - val_loss: 0.6368 - val_acc: 0.8208 Epoch 7/15 \n25000/25000 [==============================] - 95s 4ms/step - loss: 0.0578 \n- acc: 0.9811 - val_loss: 0.6657 - val_acc: 0.8184 Epoch 8/15 \n25000/25000 [==============================] - 97s 4ms/step - loss: 0.0448 \n- acc: 0.9850 - val_loss: 0.7452 - val_acc: 0.8136 Epoch 9/15 \n25000/25000 [==============================] - 95s 4ms/step - loss: 0.0324 \n- acc: 0.9894 - val_loss: 0.7616 - val_acc: 0.8162Epoch 10/15 \n25000/25000 [==============================] - 100s 4ms/step - loss: 0.0247 \n- acc: 0.9922 - val_loss: 0.9654 - val_acc: 0.8148 Epoch 11/15 \n25000/25000 [==============================] - 99s 4ms/step - loss: 0.0169 \n- acc: 0.9946 - val_loss: 1.0013 - val_acc: 0.8104 Epoch 12/15 \n25000/25000 [==============================] - 90s 4ms/step - loss: 0.0154 \n- acc: 0.9948 - val_loss: 1.0316 - val_acc: 0.8100 Epoch 13/15 \n25000/25000 [==============================] - 89s 4ms/step - loss: 0.0113 \n- acc: 0.9963 - val_loss: 1.1138 - val_acc: 0.8108 Epoch 14/15 \n25000/25000 [==============================] - 89s 4ms/step - loss: 0.0106 \n- acc: 0.9971 - val_loss: 1.0538 - val_acc: 0.8102 Epoch 15/15 \n25000/25000 [==============================] - 89s 4ms/step - loss: 0.0090 \n- acc: 0.9972 - val_loss: 1.1453 - val_acc: 0.8129 \n25000/25000 [==============================] - 10s 390us/step\n" }, { "code": null, "e": 8146, "s": 8103, "text": "Let us evaluate the model using test data." }, { "code": null, "e": 8270, "s": 8146, "text": "score, acc = model.evaluate(x_test, y_test, batch_size = 32) \n \nprint('Test score:', score) \nprint('Test accuracy:', acc)" }, { "code": null, "e": 8331, "s": 8270, "text": "Executing the above code will output the below information −" }, { "code": null, "e": 8386, "s": 8331, "text": "Test score: 1.145306069601178 \nTest accuracy: 0.81292\n" }, { "code": null, "e": 8420, "s": 8386, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 8437, "s": 8420, "text": " Abhilash Nelson" }, { "code": null, "e": 8470, "s": 8437, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 8492, "s": 8470, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8525, "s": 8492, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 8547, "s": 8525, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8580, "s": 8547, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 8602, "s": 8580, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8635, "s": 8602, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 8657, "s": 8635, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8690, "s": 8657, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 8701, "s": 8690, "text": " Mike West" }, { "code": null, "e": 8708, "s": 8701, "text": " Print" }, { "code": null, "e": 8719, "s": 8708, "text": " Add Notes" } ]
HTML5 Input type=number removes leading zero
The leading zero issues may arise when you want to add an international phone number. To solve this − <input type="tel" pattern="[0-9]*"> On iOS, the numeric keyboard appears with only numbers. On Android phones, the "tel" is rightly interpreted but not the pattern. You can also use − <input type="text" pattern="[0-9]*" ... The above will call and display the numeric keypad on iPhone and Android devices.
[ { "code": null, "e": 1148, "s": 1062, "text": "The leading zero issues may arise when you want to add an international phone number." }, { "code": null, "e": 1164, "s": 1148, "text": "To solve this −" }, { "code": null, "e": 1200, "s": 1164, "text": "<input type=\"tel\" pattern=\"[0-9]*\">" }, { "code": null, "e": 1256, "s": 1200, "text": "On iOS, the numeric keyboard appears with only numbers." }, { "code": null, "e": 1329, "s": 1256, "text": "On Android phones, the \"tel\" is rightly interpreted but not the pattern." }, { "code": null, "e": 1348, "s": 1329, "text": "You can also use −" }, { "code": null, "e": 1388, "s": 1348, "text": "<input type=\"text\" pattern=\"[0-9]*\" ..." }, { "code": null, "e": 1470, "s": 1388, "text": "The above will call and display the numeric keypad on iPhone and Android devices." } ]
Go - Passing pointers to functions
Go programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type. In the following example, we pass two pointers to a function and change the value inside the function which reflects back in the calling function − package main import "fmt" func main() { /* local variable definition */ var a int = 100 var b int = 200 fmt.Printf("Before swap, value of a : %d\n", a ) fmt.Printf("Before swap, value of b : %d\n", b ) /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); fmt.Printf("After swap, value of a : %d\n", a ) fmt.Printf("After swap, value of b : %d\n", b ) } func swap(x *int, y *int) { var temp int temp = *x /* save the value at address x */ *x = *y /* put y into x */ *y = temp /* put temp into y */ } When the above code is compiled and executed, it produces the following result − Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2072, "s": 1937, "text": "Go programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type." }, { "code": null, "e": 2220, "s": 2072, "text": "In the following example, we pass two pointers to a function and change the value inside the function which reflects back in the calling function −" }, { "code": null, "e": 2903, "s": 2220, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var a int = 100\n var b int = 200\n\n fmt.Printf(\"Before swap, value of a : %d\\n\", a )\n fmt.Printf(\"Before swap, value of b : %d\\n\", b )\n\n /* calling a function to swap the values.\n * &a indicates pointer to a ie. address of variable a and \n * &b indicates pointer to b ie. address of variable b.\n */\n swap(&a, &b);\n\n fmt.Printf(\"After swap, value of a : %d\\n\", a )\n fmt.Printf(\"After swap, value of b : %d\\n\", b )\n}\nfunc swap(x *int, y *int) {\n var temp int\n temp = *x /* save the value at address x */\n *x = *y /* put y into x */\n *y = temp /* put temp into y */\n}" }, { "code": null, "e": 2984, "s": 2903, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3099, "s": 2984, "text": "Before swap, value of a :100\nBefore swap, value of b :200\nAfter swap, value of a :200\nAfter swap, value of b :100\n" }, { "code": null, "e": 3134, "s": 3099, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3147, "s": 3134, "text": " Ridhi Arora" }, { "code": null, "e": 3182, "s": 3147, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3196, "s": 3182, "text": " Asif Hussain" }, { "code": null, "e": 3229, "s": 3196, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3248, "s": 3229, "text": " Dilip Padmanabhan" }, { "code": null, "e": 3281, "s": 3248, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 3300, "s": 3281, "text": " Arnab Chakraborty" }, { "code": null, "e": 3332, "s": 3300, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3349, "s": 3332, "text": " Aditya Kulkarni" }, { "code": null, "e": 3382, "s": 3349, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3401, "s": 3382, "text": " Arnab Chakraborty" }, { "code": null, "e": 3408, "s": 3401, "text": " Print" }, { "code": null, "e": 3419, "s": 3408, "text": " Add Notes" } ]
How I Made a Website with Python and AWS | Towards Data Science
As coders and programmers, we must be able to present the projects and applications that we’ve created to various individuals without having a laptop on us at all times. In order to do so, we can host our applications on our own websites to be viewed by anyone with access to the internet. The first step in creating our own websites is to find a website hosting service such as Amazon Web Services (AWS). These hosting services will make sure our websites are available at anytime from any computer with internet access. The look of our website will be entirely dependent on the code we utilize. In our case, we implemented the Streamlit Python library to build a user-interface for a Data Science based application. To see how we created our web application with Streamlit, check out the article below: towardsdatascience.com This article delves into the development and design of a web application that we created using Streamlit and its respective functions. Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks! Let’s begin the process of creating a website. First, we will need to find a website hosting service that we find appropriate for us. There are numerous web hosting services out there but we will be utilizing AWS for now. To start, you must first create an AWS account. This is a separate account different from a normal Amazon account used for shopping or selling. There are free tier accounts, which is the one we will be using. We will need this account in order to create a server to host our website. Once an account has been created, we can proceed to creating an AWS EC2 Instance. An AWS EC2 Instance or Amazon Elastic Compute Cloud is used to launch an Instance, which is a virtual server in the cloud. To create an Instance, from the homepage, navigate to the My Account tab and click on the AWS Management Console. AWS Mangement Console Once you find yourself in the Management Console, navigate to the All Services section, and click on EC2. EC2 Dashboard Here you will find many different resources and options. However, we will be focusing on the Launch Instance section. Click the Launch Instance button to proceed. Next, we will be presented with a page to customize that Instance. The first step here is to choose an Amazon Machine Image (AMI). Here we select the Amazon Linux AMI 2018.03.0 (HVM). We selected this one because it already includes numerous programming languages (i.e. Python) and it is free tier eligible. Choosing an Instance Type Once we have selected the appropriate AMI, we move on to the next step, choosing the right instance type. Select the free tier eligible option: t2.micro. Configure Security Group Proceed past the next steps all the way to step 6. There we will need to configure the security group. Click Add Rule. After clicking Add Rule, you will see a new row added. We need to configure this new row for our Streamlit app. Under Type, select Custom TCP. Under Port Range, enter 8501. Under Source, select Anywhere. Finish it up by clicking Review and Launch on the bottom right corner. Launch the Instance After clicking Review and Launch, you will see a Review page. Ensure that everything is correct, then click Launch on the bottom right. Once Launch is clicked, the following pop-up appears. Here you will need to create a new key pair by navigating to Choose an existing key pair and select Create a new key pair. Enter any name you wish for the Key pair name. Then, click Download Key Pair. You will need this .pem file in order to access our Instance from the command terminal. (Move the .pem file into an .ssh folder in a secure location, which you can create if you don’t have one). After you have downloaded the private key file (.pem), you can click Launch Instances. This will bring you to the next page displaying the Launch Status. Now that our EC2 Instance is up and running, we need to find the Public DNS address to access the Instance in the command terminal. To do so, navigate to the Management Console, click on EC2, click on Instances, then select the Instance we just created. You will find the Public DNS (IPv4) address on the lower right. Copy the address because you will need it for later. If the steps were followed, you have successfully launched and created an EC2 Instance using AWS. Next, you will need to SSH into the Instance in order to establish the website. SSH or Secure Shell is a network protocol that will allow us to operate our EC2 instance through the terminal using a command line interface. If you have a Mac or Linux, you will then already have SSH. Windows users will probably need to use PuTTY. For the following steps, we will be using the MacOS command terminal to access our EC2 instance. To SSH into our Instance, we must first open the command terminal, then navigate (CD) into the same folder that contains the .pem file we downloaded before. (Make sure the .pem file is in a .ssh folder, which is stored in a secure location on your computer). Once we are in that folder, run the following command: $ ssh -i key_pair.pem ec2-user@your_public_dns_address Use the .pem file you created and downloaded. Add “ec2-user@” to the beginning of your PublicDNS (IPv4) address. After entering this command, you should see the following in your command terminal: This means we are successfully in our EC2 Instance! Now we will need to install all the packages and files we need for our Streamlit app. Even though our AMI contains some required packages, we still need some more. While we are still in our command terminal of the EC2 instance, run the following commands: The Python included in the AMI is Python 2 not Python 3, which is what our Streamlit app runs on. So we will need to install Python 3. $ sudo yum install python36 We will also need to install Git in order to download the repository that contains our Streamlit app. $ sudo yum install git We will be cloning the Github repository that contains our Streamlit web application: $ git clone your_github_repo After we have successfully cloned the Github repo into our EC2 Instance, navigate (CD) into the repo folder. Navigate into the folder containing a requirements.txt file. Once we are in the folder containing our requirements.txt file, we can install all the libraries necessary to run our Streamlit app. $ python36 -m pip install -r requirements.txt --user This will install all the libraries specified in the requirements.txt file. The --user command will make sure our libraries are installed with the correct permissions. With everything installed, we can finally run our app. In the folder that contains the .py file, enter the Streamlit command: $ streamlit run your_app.py Now our web app is available online by using the External URL to view in our preferred browser. However, the link will no longer be available when we log out of our EC2 instance, which closes the current session. In order for the URL to be active even when we log out, we will need to install one more thing: TMUX. TMUX gives us the ability to keep a session running even when we logout. But first, close out of the current Streamlit session with ctrl+C. Then, navigate back to the beginning of the Instance. To install, enter the following command while still in the EC2 instance: $ sudo yum install tmux Then, create a new session with: $ tmux new -s name_of_session This starts a new session with any name that you wish from which we can run our app. From there just do as done before and move to the folder with your app.py file. Once there, you can run Streamlit again: $ streamlit run your_app.py Now you have the Streamlit app running inside the TMUX session. To exit out of the tmux session but still keep it running you’ll have to detach the tmux session. You can do this by pressing: ctrl+B, then D. Once detached you can check on the status of the tmux session by running: $ tmux ls You should see that you have one tmux session still live. Now you can logout from the EC2 instance without having to worry about the URL going down. Just press: ctrl+D. Success! We were able to get our Streamlit app live by using an AWS EC2 Instance. The specific web application we have up is our Dating App that utilizes Data Science and Machine Learning: towardsdatascience.com The URL for the website may not be pretty but that can be solved by creating our own custom domain name for our instance. However, that process requires some more steps and is more complicated than expected. It also may cost some money to register a domain name. At the end of this we hope you were able to successfully create a website that will host your own web application by utilizing Streamlit and an AWS EC2 Instance. Feel free to check out the other articles that show the development of our web app with Streamlit or the development of the dating application. Follow me on Twitter: @_Marco_Santos_
[ { "code": null, "e": 694, "s": 172, "text": "As coders and programmers, we must be able to present the projects and applications that we’ve created to various individuals without having a laptop on us at all times. In order to do so, we can host our applications on our own websites to be viewed by anyone with access to the internet. The first step in creating our own websites is to find a website hosting service such as Amazon Web Services (AWS). These hosting services will make sure our websites are available at anytime from any computer with internet access." }, { "code": null, "e": 977, "s": 694, "text": "The look of our website will be entirely dependent on the code we utilize. In our case, we implemented the Streamlit Python library to build a user-interface for a Data Science based application. To see how we created our web application with Streamlit, check out the article below:" }, { "code": null, "e": 1000, "s": 977, "text": "towardsdatascience.com" }, { "code": null, "e": 1135, "s": 1000, "text": "This article delves into the development and design of a web application that we created using Streamlit and its respective functions." }, { "code": null, "e": 1300, "s": 1135, "text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!" }, { "code": null, "e": 1522, "s": 1300, "text": "Let’s begin the process of creating a website. First, we will need to find a website hosting service that we find appropriate for us. There are numerous web hosting services out there but we will be utilizing AWS for now." }, { "code": null, "e": 1806, "s": 1522, "text": "To start, you must first create an AWS account. This is a separate account different from a normal Amazon account used for shopping or selling. There are free tier accounts, which is the one we will be using. We will need this account in order to create a server to host our website." }, { "code": null, "e": 2011, "s": 1806, "text": "Once an account has been created, we can proceed to creating an AWS EC2 Instance. An AWS EC2 Instance or Amazon Elastic Compute Cloud is used to launch an Instance, which is a virtual server in the cloud." }, { "code": null, "e": 2125, "s": 2011, "text": "To create an Instance, from the homepage, navigate to the My Account tab and click on the AWS Management Console." }, { "code": null, "e": 2147, "s": 2125, "text": "AWS Mangement Console" }, { "code": null, "e": 2253, "s": 2147, "text": "Once you find yourself in the Management Console, navigate to the All Services section, and click on EC2." }, { "code": null, "e": 2267, "s": 2253, "text": "EC2 Dashboard" }, { "code": null, "e": 2430, "s": 2267, "text": "Here you will find many different resources and options. However, we will be focusing on the Launch Instance section. Click the Launch Instance button to proceed." }, { "code": null, "e": 2561, "s": 2430, "text": "Next, we will be presented with a page to customize that Instance. The first step here is to choose an Amazon Machine Image (AMI)." }, { "code": null, "e": 2738, "s": 2561, "text": "Here we select the Amazon Linux AMI 2018.03.0 (HVM). We selected this one because it already includes numerous programming languages (i.e. Python) and it is free tier eligible." }, { "code": null, "e": 2764, "s": 2738, "text": "Choosing an Instance Type" }, { "code": null, "e": 2918, "s": 2764, "text": "Once we have selected the appropriate AMI, we move on to the next step, choosing the right instance type. Select the free tier eligible option: t2.micro." }, { "code": null, "e": 2943, "s": 2918, "text": "Configure Security Group" }, { "code": null, "e": 3062, "s": 2943, "text": "Proceed past the next steps all the way to step 6. There we will need to configure the security group. Click Add Rule." }, { "code": null, "e": 3174, "s": 3062, "text": "After clicking Add Rule, you will see a new row added. We need to configure this new row for our Streamlit app." }, { "code": null, "e": 3205, "s": 3174, "text": "Under Type, select Custom TCP." }, { "code": null, "e": 3235, "s": 3205, "text": "Under Port Range, enter 8501." }, { "code": null, "e": 3266, "s": 3235, "text": "Under Source, select Anywhere." }, { "code": null, "e": 3337, "s": 3266, "text": "Finish it up by clicking Review and Launch on the bottom right corner." }, { "code": null, "e": 3357, "s": 3337, "text": "Launch the Instance" }, { "code": null, "e": 3493, "s": 3357, "text": "After clicking Review and Launch, you will see a Review page. Ensure that everything is correct, then click Launch on the bottom right." }, { "code": null, "e": 3547, "s": 3493, "text": "Once Launch is clicked, the following pop-up appears." }, { "code": null, "e": 3670, "s": 3547, "text": "Here you will need to create a new key pair by navigating to Choose an existing key pair and select Create a new key pair." }, { "code": null, "e": 3943, "s": 3670, "text": "Enter any name you wish for the Key pair name. Then, click Download Key Pair. You will need this .pem file in order to access our Instance from the command terminal. (Move the .pem file into an .ssh folder in a secure location, which you can create if you don’t have one)." }, { "code": null, "e": 4097, "s": 3943, "text": "After you have downloaded the private key file (.pem), you can click Launch Instances. This will bring you to the next page displaying the Launch Status." }, { "code": null, "e": 4468, "s": 4097, "text": "Now that our EC2 Instance is up and running, we need to find the Public DNS address to access the Instance in the command terminal. To do so, navigate to the Management Console, click on EC2, click on Instances, then select the Instance we just created. You will find the Public DNS (IPv4) address on the lower right. Copy the address because you will need it for later." }, { "code": null, "e": 4646, "s": 4468, "text": "If the steps were followed, you have successfully launched and created an EC2 Instance using AWS. Next, you will need to SSH into the Instance in order to establish the website." }, { "code": null, "e": 4895, "s": 4646, "text": "SSH or Secure Shell is a network protocol that will allow us to operate our EC2 instance through the terminal using a command line interface. If you have a Mac or Linux, you will then already have SSH. Windows users will probably need to use PuTTY." }, { "code": null, "e": 5251, "s": 4895, "text": "For the following steps, we will be using the MacOS command terminal to access our EC2 instance. To SSH into our Instance, we must first open the command terminal, then navigate (CD) into the same folder that contains the .pem file we downloaded before. (Make sure the .pem file is in a .ssh folder, which is stored in a secure location on your computer)." }, { "code": null, "e": 5306, "s": 5251, "text": "Once we are in that folder, run the following command:" }, { "code": null, "e": 5361, "s": 5306, "text": "$ ssh -i key_pair.pem ec2-user@your_public_dns_address" }, { "code": null, "e": 5407, "s": 5361, "text": "Use the .pem file you created and downloaded." }, { "code": null, "e": 5474, "s": 5407, "text": "Add “ec2-user@” to the beginning of your PublicDNS (IPv4) address." }, { "code": null, "e": 5558, "s": 5474, "text": "After entering this command, you should see the following in your command terminal:" }, { "code": null, "e": 5610, "s": 5558, "text": "This means we are successfully in our EC2 Instance!" }, { "code": null, "e": 5866, "s": 5610, "text": "Now we will need to install all the packages and files we need for our Streamlit app. Even though our AMI contains some required packages, we still need some more. While we are still in our command terminal of the EC2 instance, run the following commands:" }, { "code": null, "e": 6001, "s": 5866, "text": "The Python included in the AMI is Python 2 not Python 3, which is what our Streamlit app runs on. So we will need to install Python 3." }, { "code": null, "e": 6029, "s": 6001, "text": "$ sudo yum install python36" }, { "code": null, "e": 6131, "s": 6029, "text": "We will also need to install Git in order to download the repository that contains our Streamlit app." }, { "code": null, "e": 6154, "s": 6131, "text": "$ sudo yum install git" }, { "code": null, "e": 6240, "s": 6154, "text": "We will be cloning the Github repository that contains our Streamlit web application:" }, { "code": null, "e": 6269, "s": 6240, "text": "$ git clone your_github_repo" }, { "code": null, "e": 6378, "s": 6269, "text": "After we have successfully cloned the Github repo into our EC2 Instance, navigate (CD) into the repo folder." }, { "code": null, "e": 6572, "s": 6378, "text": "Navigate into the folder containing a requirements.txt file. Once we are in the folder containing our requirements.txt file, we can install all the libraries necessary to run our Streamlit app." }, { "code": null, "e": 6625, "s": 6572, "text": "$ python36 -m pip install -r requirements.txt --user" }, { "code": null, "e": 6793, "s": 6625, "text": "This will install all the libraries specified in the requirements.txt file. The --user command will make sure our libraries are installed with the correct permissions." }, { "code": null, "e": 6919, "s": 6793, "text": "With everything installed, we can finally run our app. In the folder that contains the .py file, enter the Streamlit command:" }, { "code": null, "e": 6947, "s": 6919, "text": "$ streamlit run your_app.py" }, { "code": null, "e": 7160, "s": 6947, "text": "Now our web app is available online by using the External URL to view in our preferred browser. However, the link will no longer be available when we log out of our EC2 instance, which closes the current session." }, { "code": null, "e": 7262, "s": 7160, "text": "In order for the URL to be active even when we log out, we will need to install one more thing: TMUX." }, { "code": null, "e": 7456, "s": 7262, "text": "TMUX gives us the ability to keep a session running even when we logout. But first, close out of the current Streamlit session with ctrl+C. Then, navigate back to the beginning of the Instance." }, { "code": null, "e": 7529, "s": 7456, "text": "To install, enter the following command while still in the EC2 instance:" }, { "code": null, "e": 7553, "s": 7529, "text": "$ sudo yum install tmux" }, { "code": null, "e": 7586, "s": 7553, "text": "Then, create a new session with:" }, { "code": null, "e": 7616, "s": 7586, "text": "$ tmux new -s name_of_session" }, { "code": null, "e": 7781, "s": 7616, "text": "This starts a new session with any name that you wish from which we can run our app. From there just do as done before and move to the folder with your app.py file." }, { "code": null, "e": 7822, "s": 7781, "text": "Once there, you can run Streamlit again:" }, { "code": null, "e": 7850, "s": 7822, "text": "$ streamlit run your_app.py" }, { "code": null, "e": 8057, "s": 7850, "text": "Now you have the Streamlit app running inside the TMUX session. To exit out of the tmux session but still keep it running you’ll have to detach the tmux session. You can do this by pressing: ctrl+B, then D." }, { "code": null, "e": 8131, "s": 8057, "text": "Once detached you can check on the status of the tmux session by running:" }, { "code": null, "e": 8141, "s": 8131, "text": "$ tmux ls" }, { "code": null, "e": 8310, "s": 8141, "text": "You should see that you have one tmux session still live. Now you can logout from the EC2 instance without having to worry about the URL going down. Just press: ctrl+D." }, { "code": null, "e": 8499, "s": 8310, "text": "Success! We were able to get our Streamlit app live by using an AWS EC2 Instance. The specific web application we have up is our Dating App that utilizes Data Science and Machine Learning:" }, { "code": null, "e": 8522, "s": 8499, "text": "towardsdatascience.com" }, { "code": null, "e": 8785, "s": 8522, "text": "The URL for the website may not be pretty but that can be solved by creating our own custom domain name for our instance. However, that process requires some more steps and is more complicated than expected. It also may cost some money to register a domain name." }, { "code": null, "e": 9091, "s": 8785, "text": "At the end of this we hope you were able to successfully create a website that will host your own web application by utilizing Streamlit and an AWS EC2 Instance. Feel free to check out the other articles that show the development of our web app with Streamlit or the development of the dating application." } ]
Difference between throw and throws in Java
Both throw and throws are the concepts of exception handing in which throw is used to explicitly throw an exception from a method or any block of code while throws are used in the signature of the method to indicate that this method might throw one of the listed type exceptions. The following are the important differences between throw and throws. JavaTester.java Live Demo public class JavaTester{ public void checkAge(int age){ if(age<18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); } public static void main(String args[]){ JavaTester obj = new JavaTester(); obj.checkAge(13); System.out.println("End Of Program"); } } Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at JavaTester.checkAge(JavaTester.java:4) at JavaTester.main(JavaTester.java:10) JavaTester.java Live Demo public class JavaTester{ public int division(int a, int b) throws ArithmeticException{ int t = a/b; return t; } public static void main(String args[]){ JavaTester obj = new JavaTester(); try{ System.out.println(obj.division(15,0)); } catch(ArithmeticException e){ System.out.println("You shouldn't divide number by zero"); } } } You shouldn't divide number by zero
[ { "code": null, "e": 1342, "s": 1062, "text": "Both throw and throws are the concepts of exception handing in which throw is used to explicitly throw an exception from a method or any block of code while throws are used in the signature of the method to indicate that this method might throw one of the listed type exceptions." }, { "code": null, "e": 1412, "s": 1342, "text": "The following are the important differences between throw and throws." }, { "code": null, "e": 1428, "s": 1412, "text": "JavaTester.java" }, { "code": null, "e": 1439, "s": 1428, "text": " Live Demo" }, { "code": null, "e": 1809, "s": 1439, "text": "public class JavaTester{\n public void checkAge(int age){\n if(age<18)\n throw new ArithmeticException(\"Not Eligible for voting\");\n else\n System.out.println(\"Eligible for voting\");\n }\n public static void main(String args[]){\n JavaTester obj = new JavaTester();\n obj.checkAge(13);\n System.out.println(\"End Of Program\");\n }\n}" }, { "code": null, "e": 1972, "s": 1809, "text": "Exception in thread \"main\" java.lang.ArithmeticException:\nNot Eligible for voting\nat JavaTester.checkAge(JavaTester.java:4)\nat JavaTester.main(JavaTester.java:10)" }, { "code": null, "e": 1988, "s": 1972, "text": "JavaTester.java" }, { "code": null, "e": 1999, "s": 1988, "text": " Live Demo" }, { "code": null, "e": 2400, "s": 1999, "text": "public class JavaTester{\n public int division(int a, int b) throws ArithmeticException{\n int t = a/b;\n return t;\n }\n public static void main(String args[]){\n JavaTester obj = new JavaTester();\n try{\n System.out.println(obj.division(15,0));\n }\n catch(ArithmeticException e){\n System.out.println(\"You shouldn't divide number by zero\");\n }\n }\n}" }, { "code": null, "e": 2436, "s": 2400, "text": "You shouldn't divide number by zero" } ]
How do I access subdocuments in MongoDB queries?
To access subdocuments in MongoDB, use find() with dot notation. Let us create a collection with documents − > db.demo670.insertOne({ ... id:101, ... "details": ... { ... Name:"Chris", ... Age:21, ... CountryName:"US", ... SubjectName:"MongoDB" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea3e31d04263e90dac943de") } > db.demo670.insertOne({ id:102, "details": { Name:"David", Age:22, CountryName:"UK", SubjectName:"MySQL" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ea3e33604263e90dac943df") } Display all documents from a collection with the help of find() method − > db.demo670.find(); This will produce the following output − { "_id" : ObjectId("5ea3e31d04263e90dac943de"), "id" : 101, "details" : { "Name" : "Chris", "Age" : 21, "CountryName" : "US", "SubjectName" : "MongoDB" } } { "_id" : ObjectId("5ea3e33604263e90dac943df"), "id" : 102, "details" : { "Name" : "David", "Age" : 22, "CountryName" : "UK", "SubjectName" : "MySQL" } } Following is the query to access subdocuments − > db.demo670.find({"details.SubjectName":"MongoDB"},{"details.CountryName":1});7 This will produce the following output − { "_id" : ObjectId("5ea3e31d04263e90dac943de"), "details" : { "CountryName" : "US" } }
[ { "code": null, "e": 1171, "s": 1062, "text": "To access subdocuments in MongoDB, use find() with dot notation. Let us create a collection with documents −" }, { "code": null, "e": 1609, "s": 1171, "text": "> db.demo670.insertOne({\n... id:101,\n... \"details\":\n... {\n... Name:\"Chris\",\n... Age:21,\n... CountryName:\"US\",\n... SubjectName:\"MongoDB\"\n... }\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea3e31d04263e90dac943de\")\n}\n> db.demo670.insertOne({ id:102, \"details\": { Name:\"David\", Age:22, CountryName:\"UK\", SubjectName:\"MySQL\" } } );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea3e33604263e90dac943df\")\n}" }, { "code": null, "e": 1682, "s": 1609, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1703, "s": 1682, "text": "> db.demo670.find();" }, { "code": null, "e": 1744, "s": 1703, "text": "This will produce the following output −" }, { "code": null, "e": 2054, "s": 1744, "text": "{ \"_id\" : ObjectId(\"5ea3e31d04263e90dac943de\"), \"id\" : 101, \"details\" : { \"Name\" : \"Chris\", \"Age\" : 21, \"CountryName\" : \"US\", \"SubjectName\" : \"MongoDB\" } }\n{ \"_id\" : ObjectId(\"5ea3e33604263e90dac943df\"), \"id\" : 102, \"details\" : { \"Name\" : \"David\", \"Age\" : 22, \"CountryName\" : \"UK\", \"SubjectName\" : \"MySQL\" } }" }, { "code": null, "e": 2102, "s": 2054, "text": "Following is the query to access subdocuments −" }, { "code": null, "e": 2183, "s": 2102, "text": "> db.demo670.find({\"details.SubjectName\":\"MongoDB\"},{\"details.CountryName\":1});7" }, { "code": null, "e": 2224, "s": 2183, "text": "This will produce the following output −" }, { "code": null, "e": 2311, "s": 2224, "text": "{ \"_id\" : ObjectId(\"5ea3e31d04263e90dac943de\"), \"details\" : { \"CountryName\" : \"US\" } }" } ]
Most Popular Convolutional Neural Networks Architectures | by Victor Roman | Towards Data Science
The objective of this article is to explore in-depth the concepts of: Most popular CNN architectures How to implement them with Keras to perform image classification There are research teams fully dedicated to developing deep learning architectures for CNN and to training them in huge datasets, so we will take advantage of this and use them instead of creating a new architecture every time we face a new problem. This will provide us with stability and precision. The most common deep learning architectures for CNN today are: VGG ResNet Inception Xception Let’s explore them. This architecture, which was one of the first to appear, was introduced by Simonyan and Zisserman in 2014 with their paper entitled Very Deep Convolutional Networks for Large Scale Image Recognition. This paper is available here: https://arxiv.org/abs/1409.1556. It is a simple architecture, using only blocks composed of an incremental number of convolutional layers with 3x3 size filters. Besides, to reduce the size of the activation maps obtained, max-pooling blocks are interspersed between the convolutional ones, reducing the size of these activation maps by half. Finally, a classification block is used, consisting of two dense layers of 4096 neurons each, and the last layer, which is the output layer, of 1000 neurons. The 16 and 19 refer to the number of weighted layers that each network has (convolutional and dense layers, pooling layers are not counted). They correspond to columns D and E in the table below. The rest of the architectures in the table are there because, at that time, Simonyan and Zisserman had a hard time training their architecture to converge. Since they couldn’t do it, what they came up with was to train networks with simpler architectures first, and once these converged and were trained, they took advantage of their weights to initialize the next network, which was a little more complex, and so on until they got to the VGG19. This process is known as “pre-training”. However, this was in those times, now it is no longer done, as it requires too much time. Now we can achieve the same thing using the initialization of Xavier/Glorot or He et al. You can find more about it in this article. This network, however, has a couple of disadvantages: It takes too long to train It has a very high number of parameters The ResNet architecture, developed by He et al. in 2015 (you can see their paper called “Deep Residual Learning for Image Recognition” here: https://arxiv.org/abs/1512.03385), was a milestone in introducing an exotic type of architecture based on “modules”, or as it is now known, “networks within networks”. These networks introduced the concept of “residual connections”, which you can see in the following image: These blocks allow to reach the layer l+1l+1 part of the previous activation map without modification, and partly modified by the block belonging to the layer ll, as you can see in the image above. In 2016 they improved this architecture by including more layers in these residual blocks, as you can see in the following image: There are variations of ResNet with a different number of layers, but the most used is ResNet50, which consists of 50 layers with weights. It is remarkable that although it has many more layers than the VGG, it needs much less memory, almost 5 times less. This is because this network, instead of dense layers in the classification stage, uses a type of layer called GlobalAveragePooling, which converts the 2D activity maps of the last layer in the feature extraction stage to an n-classes vector that is used to calculate the probability of belonging to each class. This type of architecture, which was introduced in 2014 by Szegedy et al. in their paper “Going Deeper with Convolutions” (https://arxiv.org/abs/1409.4842), uses blocks with filters of different sizes that are then concatenated to extract features at different scales. Look at the image: To help you understand this, the goal of the inception block is to calculate activation maps with 1x1, 3x3 and 5x5 convolutions to extract features at different scales. Then you simply concatenate all these activation maps into one. This architecture requires even less memory than the VGG and ResNet. This architecture was proposed by François Chollet (the creator of Keras) and the only thing he brings to Inception is that he optimally makes the convolutions so that they take less time. This is achieved by separating the 2D convolutions into 2 1D convolutions. If you are interested in knowing more, here is the paper: “Xception: Deep Learning with Depthwise Separable Convolutions”, https://arxiv.org/abs/1610.02357. In terms of memory, it is very similar to Xception, and this is the outline of its architecture: This network is extremely light (its weight is 5MB, compared to the 500MB of the VGG, or the 100MB of the Inception, for example) and achieves an accuracy of ~57% rank-1 or ~80% rank-5 with the ImageNet. What do rank-1 and rank-5 or top-1 and top-5 mean? rank-1 accuracy: we compare if the class with the highest probability according to our network matches the real tag rank-5 accuracy: we compare if one of the 5 classes with higher probation according to our network matches the real label How does this network manage to occupy so little and yet be so precise? It does so by using an architecture that “compresses” the data and then expands it, as you can see in the following image: There are infinite architectures, but these are by far the most used. Normally, when we have a problem, we are not going to define our architecture, but we will use one of the previous ones. Ok, now that you have seen them, let’s see how we can implement them in Keras As usual, we’ll open up a Google Colaboratory notebook. Choose the code to run on GPUs to improve the speed and execute the following code. !pip install imageio # Import the necessary librariesfrom keras.applications import ResNet50from keras.applications import InceptionV3from keras.applications import Xception # solo con el backend de TensorFlowfrom keras.applications import VGG16from keras.applications import VGG19from keras.applications import imagenet_utilsfrom keras.applications.inception_v3 import preprocess_inputfrom keras.preprocessing.image import img_to_arrayfrom keras.preprocessing.image import load_imgimport numpy as npimport urllibimport cv2import matplotlib.pyplot as pltimport imageio as iodef predict_image(model_name, image_source): # We define a dictionary that maps the network name with the Keras imported model MODELS = { "vgg16": VGG16, "vgg19": VGG19, "inception": InceptionV3, "xception": Xception, # TensorFlow solo! "resnet": ResNet50 }# We stablish the input size and image preprocessing function input_shape = (224, 224) preprocess = imagenet_utils.preprocess_input# If we use InceptionV3 or Xception, we need to stablish a different input image size (299x299) and use a different preprocessing function if model_name in ("inception", "xception"): input_shape = (299, 299) preprocess = preprocess_inputprint("[INFO] loading {}...".format(model_name)) Network = MODELS[model_name] model = Network(weights="imagenet") # We load the network with the weights already trained with the ImageNet, the first time we execute keras it will lead the weights, which size is about 500MB, so it will last a bit# We load the image and make sure it is in the appropiate size print("[INFO] loading and pre-processing image...") if type(image_source) == str: image = load_img(image_source, target_size=input_shape) image = np.resize(image, (input_shape[0], input_shape[1], 3)) image = img_to_array(image) else: image = np.resize(image_source, (input_shape[0], input_shape[1], 3)) image = img_to_array(image)# The image is represented as an array of size: (inputShape[0], inputShape[1], 3) and we need: (1, inputShape[0]. inputShape[1], 3), so we expand the dimensions image = np.expand_dims(image, axis=0)# we preprocess the image image = preprocess(image)# We predict the class of the image print("[INFO] classifying image with '{}'...".format(model_name)) preds = model.predict(image) P = imagenet_utils.decode_predictions(preds)# We show the predictions rank-5 and their likelihood for (i, (imagenetID, label, prob)) in enumerate(P[0]): print("{}. {}: {:.2f}%".format(i + 1, label, prob * 100))img = io.imread(image_source) (imagenetID, label, prob) = P[0][0] cv2.putText(img, "Label: {}, {:.2f}%".format(label, prob * 100), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2) plt.imshow(img) plt.axis('off') return model # download images!wget https://image.ibb.co/cuw6pd/soccer_ball.jpg!wget https://image.ibb.co/hdoVFJ/bmw.png!wget https://image.ibb.co/h0B6pd/boat.png!wget https://image.ibb.co/eCyVFJ/clint_eastwood.jpg !ls -la *.* model = predict_image('resnet', 'soccer_ball.jpg') model = predict_image('vgg16', 'bmw.png') model.summary() model = predidct_image('inception', 'clint_eastwood.jpg') model.summary() The result of the network architecture is so big that won’t fit here: As always, I hope you enjoyed the post, and that you gained an intuition about how to implement and develop a convolutional neural network! If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here. If you want to learn more about Machine Learning, Data Science and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
[ { "code": null, "e": 242, "s": 172, "text": "The objective of this article is to explore in-depth the concepts of:" }, { "code": null, "e": 273, "s": 242, "text": "Most popular CNN architectures" }, { "code": null, "e": 338, "s": 273, "text": "How to implement them with Keras to perform image classification" }, { "code": null, "e": 588, "s": 338, "text": "There are research teams fully dedicated to developing deep learning architectures for CNN and to training them in huge datasets, so we will take advantage of this and use them instead of creating a new architecture every time we face a new problem." }, { "code": null, "e": 639, "s": 588, "text": "This will provide us with stability and precision." }, { "code": null, "e": 702, "s": 639, "text": "The most common deep learning architectures for CNN today are:" }, { "code": null, "e": 706, "s": 702, "text": "VGG" }, { "code": null, "e": 713, "s": 706, "text": "ResNet" }, { "code": null, "e": 723, "s": 713, "text": "Inception" }, { "code": null, "e": 732, "s": 723, "text": "Xception" }, { "code": null, "e": 752, "s": 732, "text": "Let’s explore them." }, { "code": null, "e": 1015, "s": 752, "text": "This architecture, which was one of the first to appear, was introduced by Simonyan and Zisserman in 2014 with their paper entitled Very Deep Convolutional Networks for Large Scale Image Recognition. This paper is available here: https://arxiv.org/abs/1409.1556." }, { "code": null, "e": 1482, "s": 1015, "text": "It is a simple architecture, using only blocks composed of an incremental number of convolutional layers with 3x3 size filters. Besides, to reduce the size of the activation maps obtained, max-pooling blocks are interspersed between the convolutional ones, reducing the size of these activation maps by half. Finally, a classification block is used, consisting of two dense layers of 4096 neurons each, and the last layer, which is the output layer, of 1000 neurons." }, { "code": null, "e": 1678, "s": 1482, "text": "The 16 and 19 refer to the number of weighted layers that each network has (convolutional and dense layers, pooling layers are not counted). They correspond to columns D and E in the table below." }, { "code": null, "e": 2165, "s": 1678, "text": "The rest of the architectures in the table are there because, at that time, Simonyan and Zisserman had a hard time training their architecture to converge. Since they couldn’t do it, what they came up with was to train networks with simpler architectures first, and once these converged and were trained, they took advantage of their weights to initialize the next network, which was a little more complex, and so on until they got to the VGG19. This process is known as “pre-training”." }, { "code": null, "e": 2388, "s": 2165, "text": "However, this was in those times, now it is no longer done, as it requires too much time. Now we can achieve the same thing using the initialization of Xavier/Glorot or He et al. You can find more about it in this article." }, { "code": null, "e": 2442, "s": 2388, "text": "This network, however, has a couple of disadvantages:" }, { "code": null, "e": 2469, "s": 2442, "text": "It takes too long to train" }, { "code": null, "e": 2509, "s": 2469, "text": "It has a very high number of parameters" }, { "code": null, "e": 2818, "s": 2509, "text": "The ResNet architecture, developed by He et al. in 2015 (you can see their paper called “Deep Residual Learning for Image Recognition” here: https://arxiv.org/abs/1512.03385), was a milestone in introducing an exotic type of architecture based on “modules”, or as it is now known, “networks within networks”." }, { "code": null, "e": 2925, "s": 2818, "text": "These networks introduced the concept of “residual connections”, which you can see in the following image:" }, { "code": null, "e": 3123, "s": 2925, "text": "These blocks allow to reach the layer l+1l+1 part of the previous activation map without modification, and partly modified by the block belonging to the layer ll, as you can see in the image above." }, { "code": null, "e": 3253, "s": 3123, "text": "In 2016 they improved this architecture by including more layers in these residual blocks, as you can see in the following image:" }, { "code": null, "e": 3392, "s": 3253, "text": "There are variations of ResNet with a different number of layers, but the most used is ResNet50, which consists of 50 layers with weights." }, { "code": null, "e": 3821, "s": 3392, "text": "It is remarkable that although it has many more layers than the VGG, it needs much less memory, almost 5 times less. This is because this network, instead of dense layers in the classification stage, uses a type of layer called GlobalAveragePooling, which converts the 2D activity maps of the last layer in the feature extraction stage to an n-classes vector that is used to calculate the probability of belonging to each class." }, { "code": null, "e": 4109, "s": 3821, "text": "This type of architecture, which was introduced in 2014 by Szegedy et al. in their paper “Going Deeper with Convolutions” (https://arxiv.org/abs/1409.4842), uses blocks with filters of different sizes that are then concatenated to extract features at different scales. Look at the image:" }, { "code": null, "e": 4342, "s": 4109, "text": "To help you understand this, the goal of the inception block is to calculate activation maps with 1x1, 3x3 and 5x5 convolutions to extract features at different scales. Then you simply concatenate all these activation maps into one." }, { "code": null, "e": 4411, "s": 4342, "text": "This architecture requires even less memory than the VGG and ResNet." }, { "code": null, "e": 4833, "s": 4411, "text": "This architecture was proposed by François Chollet (the creator of Keras) and the only thing he brings to Inception is that he optimally makes the convolutions so that they take less time. This is achieved by separating the 2D convolutions into 2 1D convolutions. If you are interested in knowing more, here is the paper: “Xception: Deep Learning with Depthwise Separable Convolutions”, https://arxiv.org/abs/1610.02357." }, { "code": null, "e": 4930, "s": 4833, "text": "In terms of memory, it is very similar to Xception, and this is the outline of its architecture:" }, { "code": null, "e": 5134, "s": 4930, "text": "This network is extremely light (its weight is 5MB, compared to the 500MB of the VGG, or the 100MB of the Inception, for example) and achieves an accuracy of ~57% rank-1 or ~80% rank-5 with the ImageNet." }, { "code": null, "e": 5185, "s": 5134, "text": "What do rank-1 and rank-5 or top-1 and top-5 mean?" }, { "code": null, "e": 5301, "s": 5185, "text": "rank-1 accuracy: we compare if the class with the highest probability according to our network matches the real tag" }, { "code": null, "e": 5423, "s": 5301, "text": "rank-5 accuracy: we compare if one of the 5 classes with higher probation according to our network matches the real label" }, { "code": null, "e": 5618, "s": 5423, "text": "How does this network manage to occupy so little and yet be so precise? It does so by using an architecture that “compresses” the data and then expands it, as you can see in the following image:" }, { "code": null, "e": 5809, "s": 5618, "text": "There are infinite architectures, but these are by far the most used. Normally, when we have a problem, we are not going to define our architecture, but we will use one of the previous ones." }, { "code": null, "e": 5887, "s": 5809, "text": "Ok, now that you have seen them, let’s see how we can implement them in Keras" }, { "code": null, "e": 6027, "s": 5887, "text": "As usual, we’ll open up a Google Colaboratory notebook. Choose the code to run on GPUs to improve the speed and execute the following code." }, { "code": null, "e": 6048, "s": 6027, "text": "!pip install imageio" }, { "code": null, "e": 8801, "s": 6048, "text": "# Import the necessary librariesfrom keras.applications import ResNet50from keras.applications import InceptionV3from keras.applications import Xception # solo con el backend de TensorFlowfrom keras.applications import VGG16from keras.applications import VGG19from keras.applications import imagenet_utilsfrom keras.applications.inception_v3 import preprocess_inputfrom keras.preprocessing.image import img_to_arrayfrom keras.preprocessing.image import load_imgimport numpy as npimport urllibimport cv2import matplotlib.pyplot as pltimport imageio as iodef predict_image(model_name, image_source): # We define a dictionary that maps the network name with the Keras imported model MODELS = { \"vgg16\": VGG16, \"vgg19\": VGG19, \"inception\": InceptionV3, \"xception\": Xception, # TensorFlow solo! \"resnet\": ResNet50 }# We stablish the input size and image preprocessing function input_shape = (224, 224) preprocess = imagenet_utils.preprocess_input# If we use InceptionV3 or Xception, we need to stablish a different input image size (299x299) and use a different preprocessing function if model_name in (\"inception\", \"xception\"): input_shape = (299, 299) preprocess = preprocess_inputprint(\"[INFO] loading {}...\".format(model_name)) Network = MODELS[model_name] model = Network(weights=\"imagenet\") # We load the network with the weights already trained with the ImageNet, the first time we execute keras it will lead the weights, which size is about 500MB, so it will last a bit# We load the image and make sure it is in the appropiate size print(\"[INFO] loading and pre-processing image...\") if type(image_source) == str: image = load_img(image_source, target_size=input_shape) image = np.resize(image, (input_shape[0], input_shape[1], 3)) image = img_to_array(image) else: image = np.resize(image_source, (input_shape[0], input_shape[1], 3)) image = img_to_array(image)# The image is represented as an array of size: (inputShape[0], inputShape[1], 3) and we need: (1, inputShape[0]. inputShape[1], 3), so we expand the dimensions image = np.expand_dims(image, axis=0)# we preprocess the image image = preprocess(image)# We predict the class of the image print(\"[INFO] classifying image with '{}'...\".format(model_name)) preds = model.predict(image) P = imagenet_utils.decode_predictions(preds)# We show the predictions rank-5 and their likelihood for (i, (imagenetID, label, prob)) in enumerate(P[0]): print(\"{}. {}: {:.2f}%\".format(i + 1, label, prob * 100))img = io.imread(image_source) (imagenetID, label, prob) = P[0][0] cv2.putText(img, \"Label: {}, {:.2f}%\".format(label, prob * 100), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2) plt.imshow(img) plt.axis('off') return model" }, { "code": null, "e": 9003, "s": 8801, "text": "# download images!wget https://image.ibb.co/cuw6pd/soccer_ball.jpg!wget https://image.ibb.co/hdoVFJ/bmw.png!wget https://image.ibb.co/h0B6pd/boat.png!wget https://image.ibb.co/eCyVFJ/clint_eastwood.jpg" }, { "code": null, "e": 9015, "s": 9003, "text": "!ls -la *.*" }, { "code": null, "e": 9066, "s": 9015, "text": "model = predict_image('resnet', 'soccer_ball.jpg')" }, { "code": null, "e": 9108, "s": 9066, "text": "model = predict_image('vgg16', 'bmw.png')" }, { "code": null, "e": 9124, "s": 9108, "text": "model.summary()" }, { "code": null, "e": 9182, "s": 9124, "text": "model = predidct_image('inception', 'clint_eastwood.jpg')" }, { "code": null, "e": 9198, "s": 9182, "text": "model.summary()" }, { "code": null, "e": 9268, "s": 9198, "text": "The result of the network architecture is so big that won’t fit here:" }, { "code": null, "e": 9408, "s": 9268, "text": "As always, I hope you enjoyed the post, and that you gained an intuition about how to implement and develop a convolutional neural network!" }, { "code": null, "e": 9517, "s": 9408, "text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here." } ]
Multiple Ways to Create Kubernetes Secrets | by Tibor Fabian | Towards Data Science
This article describes how to create Kubernetes (K8s) secrets as part of an installation guide to the Machine Learning Operations (MLOps) pipeline detailed in my post “MLOps on Kubernetes with Docker Desktop”. The installation in the above-mentioned article uses the following secrets on the K8s pod: github-repo-cred to access the GitHub repo; used as an environment variable or file mountgitlab-registry-cred to push Docker images to GitLab Container Registry (CR); used as an environment variable or file mountgitlab-pull-cred to allow K8s to pull images from GitLab CR; used with imagePullSecrets in the pod definition or added to the service accountkubectl-config to perform kubectl operations within the container; used as file mount github-repo-cred to access the GitHub repo; used as an environment variable or file mount gitlab-registry-cred to push Docker images to GitLab Container Registry (CR); used as an environment variable or file mount gitlab-pull-cred to allow K8s to pull images from GitLab CR; used with imagePullSecrets in the pod definition or added to the service account kubectl-config to perform kubectl operations within the container; used as file mount In the following, I detail how to create each of them. 1. github-repo-cred holds GitHub credentials and is used to clone a repository from inside the container. Before the secret actually can be created, base64-coded valid GitHub credentials need to be inserted into the data section for the keys GH_REPO_USER and GH_REPO_TOKEN. And this is how to generate the base64 code for the user tibfab (that’s me) in the terminal on the Mac. % echo -n tibfab | base64dGliZmFi The secret itself is then created with kubectl apply. % kubectl apply -f dss-at-k8s/installation/github-repo-cred-secret.yamlsecret/github-repo-cred created 2. gitlab-registry-cred stores GitLab credentials needed for read/write access to GitLab CR to commit and push a running Docker container’s status whenever necessary. The secret is created similarly to github-repo-cred above, but this time with appropriate GitLab credentials. I used a so-called GitLab deploy token to restrict access to a specific project. % kubectl apply -f dss-at-k8s/installation/gitlab-registry-cred-secret.yamlsecret/gitlab-registry-cred created 3. gitlab-pull-cred is used by K8s to pull images from GitLab CR upon pod creation. The easiest way to create the image pull secret is from a Docker login. So if not logged in already, then login to GitLab CR first. % docker login https://gitlab.com/<user>/<project> -u <user> -p <token> And create the pull secret with kubectl as follows. % kubectl create secret generic gitlab-pull-cred \ --from-file=.dockerconfigjson=.docker/config.json \ --type=kubernetes.io/dockerconfigjsonsecret/gitlab-pull-cred created After the pull secret was created, it needs to be referenced by K8s upon pod startup to pull the image from GitLab CR. This can be achieved in two ways. Either set imagePullSecrets in the pod configuration or add the image pull secret to a service account as described here. % kubectl patch serviceaccount default -p '{"imagePullSecrets": [{"name": "gitlab-pull-cred"}]}'serviceaccount/default patched 4. kubectl-config is a file mount used to manage K8s from inside the DSS container running on the pod and created as follows: % kubectl create secret generic kubectl-config --from-file=.kube/configsecret/kubectl-config created If all secrets above were created successfully, the list given by kubectl looks like the following: % kubectl get secrets NAME TYPE DATA AGEdefault-token-2spdb kubernetes.io/service-account-token 3github-repo-cred Opaque 2gitlab-pull-cred kubernetes.io/dockerconfigjson 1gitlab-registry-cred Opaque 2kubectl-config Opaque 1 There are different ways to make credentials available from secrets in the container. The easiest: Environments defined from a secret in the pod configuration make credentials as environment variables visible in the container. Check out the code snippet below. It sets GL_REG_USER and GL_REG_TOKEN from the secret gitlab-registry-cred. Another possibility is to volume mount a secret as a file whose name becomes the name of the configuration variable, and it’s content the value of the variable. This has the advantage of being able to apply permission control directly to the pod configuration with the keyword defaultMode. The following code snippet demonstrates that. An example usage of the credentials is given in a pod configuration below as part of the start command of the container. Where the command $(cat /github-repo/credentials/GH_REPO_USER) in line 9 returns the content of the secret key GH_REPO_USER and $(cat /github-repo/credentials/GH_REPO_TOKEN) returns the content GH_REPO_TOKEN respectively. There are multiple ways to create and employ K8s secrets. This post shows how various types of secrets are applied creatively in different parts of an entire MLOps pipeline.
[ { "code": null, "e": 382, "s": 172, "text": "This article describes how to create Kubernetes (K8s) secrets as part of an installation guide to the Machine Learning Operations (MLOps) pipeline detailed in my post “MLOps on Kubernetes with Docker Desktop”." }, { "code": null, "e": 473, "s": 382, "text": "The installation in the above-mentioned article uses the following secrets on the K8s pod:" }, { "code": null, "e": 912, "s": 473, "text": "github-repo-cred to access the GitHub repo; used as an environment variable or file mountgitlab-registry-cred to push Docker images to GitLab Container Registry (CR); used as an environment variable or file mountgitlab-pull-cred to allow K8s to pull images from GitLab CR; used with imagePullSecrets in the pod definition or added to the service accountkubectl-config to perform kubectl operations within the container; used as file mount" }, { "code": null, "e": 1002, "s": 912, "text": "github-repo-cred to access the GitHub repo; used as an environment variable or file mount" }, { "code": null, "e": 1126, "s": 1002, "text": "gitlab-registry-cred to push Docker images to GitLab Container Registry (CR); used as an environment variable or file mount" }, { "code": null, "e": 1268, "s": 1126, "text": "gitlab-pull-cred to allow K8s to pull images from GitLab CR; used with imagePullSecrets in the pod definition or added to the service account" }, { "code": null, "e": 1354, "s": 1268, "text": "kubectl-config to perform kubectl operations within the container; used as file mount" }, { "code": null, "e": 1409, "s": 1354, "text": "In the following, I detail how to create each of them." }, { "code": null, "e": 1515, "s": 1409, "text": "1. github-repo-cred holds GitHub credentials and is used to clone a repository from inside the container." }, { "code": null, "e": 1683, "s": 1515, "text": "Before the secret actually can be created, base64-coded valid GitHub credentials need to be inserted into the data section for the keys GH_REPO_USER and GH_REPO_TOKEN." }, { "code": null, "e": 1787, "s": 1683, "text": "And this is how to generate the base64 code for the user tibfab (that’s me) in the terminal on the Mac." }, { "code": null, "e": 1821, "s": 1787, "text": "% echo -n tibfab | base64dGliZmFi" }, { "code": null, "e": 1875, "s": 1821, "text": "The secret itself is then created with kubectl apply." }, { "code": null, "e": 1978, "s": 1875, "text": "% kubectl apply -f dss-at-k8s/installation/github-repo-cred-secret.yamlsecret/github-repo-cred created" }, { "code": null, "e": 2145, "s": 1978, "text": "2. gitlab-registry-cred stores GitLab credentials needed for read/write access to GitLab CR to commit and push a running Docker container’s status whenever necessary." }, { "code": null, "e": 2336, "s": 2145, "text": "The secret is created similarly to github-repo-cred above, but this time with appropriate GitLab credentials. I used a so-called GitLab deploy token to restrict access to a specific project." }, { "code": null, "e": 2447, "s": 2336, "text": "% kubectl apply -f dss-at-k8s/installation/gitlab-registry-cred-secret.yamlsecret/gitlab-registry-cred created" }, { "code": null, "e": 2531, "s": 2447, "text": "3. gitlab-pull-cred is used by K8s to pull images from GitLab CR upon pod creation." }, { "code": null, "e": 2663, "s": 2531, "text": "The easiest way to create the image pull secret is from a Docker login. So if not logged in already, then login to GitLab CR first." }, { "code": null, "e": 2735, "s": 2663, "text": "% docker login https://gitlab.com/<user>/<project> -u <user> -p <token>" }, { "code": null, "e": 2787, "s": 2735, "text": "And create the pull secret with kubectl as follows." }, { "code": null, "e": 2963, "s": 2787, "text": "% kubectl create secret generic gitlab-pull-cred \\ --from-file=.dockerconfigjson=.docker/config.json \\ --type=kubernetes.io/dockerconfigjsonsecret/gitlab-pull-cred created" }, { "code": null, "e": 3116, "s": 2963, "text": "After the pull secret was created, it needs to be referenced by K8s upon pod startup to pull the image from GitLab CR. This can be achieved in two ways." }, { "code": null, "e": 3169, "s": 3116, "text": "Either set imagePullSecrets in the pod configuration" }, { "code": null, "e": 3238, "s": 3169, "text": "or add the image pull secret to a service account as described here." }, { "code": null, "e": 3365, "s": 3238, "text": "% kubectl patch serviceaccount default -p '{\"imagePullSecrets\": [{\"name\": \"gitlab-pull-cred\"}]}'serviceaccount/default patched" }, { "code": null, "e": 3491, "s": 3365, "text": "4. kubectl-config is a file mount used to manage K8s from inside the DSS container running on the pod and created as follows:" }, { "code": null, "e": 3592, "s": 3491, "text": "% kubectl create secret generic kubectl-config --from-file=.kube/configsecret/kubectl-config created" }, { "code": null, "e": 3692, "s": 3592, "text": "If all secrets above were created successfully, the list given by kubectl looks like the following:" }, { "code": null, "e": 4139, "s": 3692, "text": "% kubectl get secrets NAME TYPE DATA AGEdefault-token-2spdb kubernetes.io/service-account-token 3github-repo-cred Opaque 2gitlab-pull-cred kubernetes.io/dockerconfigjson 1gitlab-registry-cred Opaque 2kubectl-config Opaque 1" }, { "code": null, "e": 4225, "s": 4139, "text": "There are different ways to make credentials available from secrets in the container." }, { "code": null, "e": 4475, "s": 4225, "text": "The easiest: Environments defined from a secret in the pod configuration make credentials as environment variables visible in the container. Check out the code snippet below. It sets GL_REG_USER and GL_REG_TOKEN from the secret gitlab-registry-cred." }, { "code": null, "e": 4811, "s": 4475, "text": "Another possibility is to volume mount a secret as a file whose name becomes the name of the configuration variable, and it’s content the value of the variable. This has the advantage of being able to apply permission control directly to the pod configuration with the keyword defaultMode. The following code snippet demonstrates that." }, { "code": null, "e": 4932, "s": 4811, "text": "An example usage of the credentials is given in a pod configuration below as part of the start command of the container." }, { "code": null, "e": 5154, "s": 4932, "text": "Where the command $(cat /github-repo/credentials/GH_REPO_USER) in line 9 returns the content of the secret key GH_REPO_USER and $(cat /github-repo/credentials/GH_REPO_TOKEN) returns the content GH_REPO_TOKEN respectively." } ]
IMS DB - Recovery
The database administrator needs to plan for the database recovery in case of system failures. Failures can be of many types such as application crashes, hardware errors, power failures, etc. Some simple approaches to database recovery are as follows − Make periodical backup copies of important datasets so that all transactions posted against the datasets are retained. Make periodical backup copies of important datasets so that all transactions posted against the datasets are retained. If a dataset is damaged due to a system failure, that problem is corrected by restoring the backup copy. Then the accumulated transactions are re-posted to the backup copy to bring them up-to-date. If a dataset is damaged due to a system failure, that problem is corrected by restoring the backup copy. Then the accumulated transactions are re-posted to the backup copy to bring them up-to-date. The disadvantages of simple approach to database recovery are as follows − Re-posting the accumulated transactions consumes a lot of time. Re-posting the accumulated transactions consumes a lot of time. All other applications need to wait for execution until the recovery is finished. All other applications need to wait for execution until the recovery is finished. Database recovery is lengthier than file recovery, if logical and secondary index relationships are involved. Database recovery is lengthier than file recovery, if logical and secondary index relationships are involved. A DL/I program crashes in a way that is different from the way a standard program crashes because a standard program is executed directly by the operating system, while a DL/I program is not. By employing an abnormal termination routine, the system interferes so that recovery can be done after the ABnormal END (ABEND). The abnormal termination routine performs the following actions − Closes all datasets Cancels all pending jobs in the queue Creates a storage dump to find out the root cause of ABEND The limitation of this routine is that it does not ensure if the data in use is accurate or not. When an application program ABENDs, it is necessary to revert the changes done by the application program, correct the error, and re-run the application program. To do this, it is required to have the DL/I log. Here are the key points about DL/I logging − A DL/I records all the changes made by an application program in a file which is known as the log file. A DL/I records all the changes made by an application program in a file which is known as the log file. When the application program changes a segment, its before image and after images are created by the DL/I. When the application program changes a segment, its before image and after images are created by the DL/I. These segment images can be used to restore the segments, in case the application program crashes. These segment images can be used to restore the segments, in case the application program crashes. DL/I uses a technique called write-ahead logging to record database changes. With write-ahead logging, a database change is written to the log dataset before it is written to the actual dataset. DL/I uses a technique called write-ahead logging to record database changes. With write-ahead logging, a database change is written to the log dataset before it is written to the actual dataset. As the log is always ahead of the database, the recovery utilities can determine the status of any database change. As the log is always ahead of the database, the recovery utilities can determine the status of any database change. When the program executes a call to change a database segment, the DL/I takes care of its logging part. When the program executes a call to change a database segment, the DL/I takes care of its logging part. The two approaches of database recovery are − Forward Recovery − DL/I uses the log file to store the change data. The accumulated transactions are re-posted using this log file. Forward Recovery − DL/I uses the log file to store the change data. The accumulated transactions are re-posted using this log file. Backward Recovery − Backward recovery is also known as backout recovery. The log records for the program are read backwards and their effects are reversed in the database. When the backout is complete, the databases are in the same state as they were in before the failure, assuming that no another application program altered the database in the meantime. Backward Recovery − Backward recovery is also known as backout recovery. The log records for the program are read backwards and their effects are reversed in the database. When the backout is complete, the databases are in the same state as they were in before the failure, assuming that no another application program altered the database in the meantime. A checkpoint is a stage where the database changes done by the application program are considered complete and accurate. Listed below are the points to note about a checkpoint − Database changes made before the most recent checkpoint are not reversed by backward recovery. Database changes made before the most recent checkpoint are not reversed by backward recovery. Database changes logged after the most recent checkpoint are not applied to an image copy of the database during forward recovery. Database changes logged after the most recent checkpoint are not applied to an image copy of the database during forward recovery. Using checkpoint method, the database is restored to its condition at the most recent checkpoint when the recovery process completes. Using checkpoint method, the database is restored to its condition at the most recent checkpoint when the recovery process completes. The default for batch programs is that the checkpoint is the beginning of the program. The default for batch programs is that the checkpoint is the beginning of the program. A checkpoint can be established using a checkpoint call (CHKP). A checkpoint can be established using a checkpoint call (CHKP). A checkpoint call causes a checkpoint record to be written on the DL/I log. A checkpoint call causes a checkpoint record to be written on the DL/I log. Shown below is the syntax of a CHKP call − CALL 'CBLTDLI' USING DLI-CHKP PCB-NAME CHECKPOINT-ID There are two checkpoint methods − Basic Checkpointing − It allows the programmer to issue checkpoint calls that the DL/I recovery utilities use during recovery processing. Basic Checkpointing − It allows the programmer to issue checkpoint calls that the DL/I recovery utilities use during recovery processing. Symbolic Checkpointing − It is an advanced form of checkpointing that is used in combination with the extended restart facility. Symbolic checkpointing and extended restart together let the application programmer code the programs so that they can resume processing at the point just after the checkpoint. Symbolic Checkpointing − It is an advanced form of checkpointing that is used in combination with the extended restart facility. Symbolic checkpointing and extended restart together let the application programmer code the programs so that they can resume processing at the point just after the checkpoint. Print Add Notes Bookmark this page
[ { "code": null, "e": 2138, "s": 1946, "text": "The database administrator needs to plan for the database recovery in case of system failures. Failures can be of many types such as application crashes, hardware errors, power failures, etc." }, { "code": null, "e": 2199, "s": 2138, "text": "Some simple approaches to database recovery are as follows −" }, { "code": null, "e": 2318, "s": 2199, "text": "Make periodical backup copies of important datasets so that all transactions posted against the datasets are retained." }, { "code": null, "e": 2437, "s": 2318, "text": "Make periodical backup copies of important datasets so that all transactions posted against the datasets are retained." }, { "code": null, "e": 2635, "s": 2437, "text": "If a dataset is damaged due to a system failure, that problem is corrected by restoring the backup copy. Then the accumulated transactions are re-posted to the backup copy to bring them up-to-date." }, { "code": null, "e": 2833, "s": 2635, "text": "If a dataset is damaged due to a system failure, that problem is corrected by restoring the backup copy. Then the accumulated transactions are re-posted to the backup copy to bring them up-to-date." }, { "code": null, "e": 2908, "s": 2833, "text": "The disadvantages of simple approach to database recovery are as follows −" }, { "code": null, "e": 2972, "s": 2908, "text": "Re-posting the accumulated transactions consumes a lot of time." }, { "code": null, "e": 3036, "s": 2972, "text": "Re-posting the accumulated transactions consumes a lot of time." }, { "code": null, "e": 3118, "s": 3036, "text": "All other applications need to wait for execution until the recovery is finished." }, { "code": null, "e": 3200, "s": 3118, "text": "All other applications need to wait for execution until the recovery is finished." }, { "code": null, "e": 3310, "s": 3200, "text": "Database recovery is lengthier than file recovery, if logical and secondary index relationships are involved." }, { "code": null, "e": 3420, "s": 3310, "text": "Database recovery is lengthier than file recovery, if logical and secondary index relationships are involved." }, { "code": null, "e": 3807, "s": 3420, "text": "A DL/I program crashes in a way that is different from the way a standard program crashes because a standard program is executed directly by the operating system, while a DL/I program is not. By employing an abnormal termination routine, the system interferes so that recovery can be done after the ABnormal END (ABEND). The abnormal termination routine performs the following actions −" }, { "code": null, "e": 3827, "s": 3807, "text": "Closes all datasets" }, { "code": null, "e": 3865, "s": 3827, "text": "Cancels all pending jobs in the queue" }, { "code": null, "e": 3924, "s": 3865, "text": "Creates a storage dump to find out the root cause of ABEND" }, { "code": null, "e": 4021, "s": 3924, "text": "The limitation of this routine is that it does not ensure if the data in use is accurate or not." }, { "code": null, "e": 4277, "s": 4021, "text": "When an application program ABENDs, it is necessary to revert the changes done by the application program, correct the error, and re-run the application program. To do this, it is required to have the DL/I log. Here are the key points about DL/I logging −" }, { "code": null, "e": 4381, "s": 4277, "text": "A DL/I records all the changes made by an application program in a file which is known as the log file." }, { "code": null, "e": 4485, "s": 4381, "text": "A DL/I records all the changes made by an application program in a file which is known as the log file." }, { "code": null, "e": 4592, "s": 4485, "text": "When the application program changes a segment, its before image and after images are created by the DL/I." }, { "code": null, "e": 4699, "s": 4592, "text": "When the application program changes a segment, its before image and after images are created by the DL/I." }, { "code": null, "e": 4798, "s": 4699, "text": "These segment images can be used to restore the segments, in case the application program crashes." }, { "code": null, "e": 4897, "s": 4798, "text": "These segment images can be used to restore the segments, in case the application program crashes." }, { "code": null, "e": 5092, "s": 4897, "text": "DL/I uses a technique called write-ahead logging to record database changes. With write-ahead logging, a database change is written to the log dataset before it is written to the actual dataset." }, { "code": null, "e": 5287, "s": 5092, "text": "DL/I uses a technique called write-ahead logging to record database changes. With write-ahead logging, a database change is written to the log dataset before it is written to the actual dataset." }, { "code": null, "e": 5403, "s": 5287, "text": "As the log is always ahead of the database, the recovery utilities can determine the status of any database change." }, { "code": null, "e": 5519, "s": 5403, "text": "As the log is always ahead of the database, the recovery utilities can determine the status of any database change." }, { "code": null, "e": 5623, "s": 5519, "text": "When the program executes a call to change a database segment, the DL/I takes care of its logging part." }, { "code": null, "e": 5727, "s": 5623, "text": "When the program executes a call to change a database segment, the DL/I takes care of its logging part." }, { "code": null, "e": 5773, "s": 5727, "text": "The two approaches of database recovery are −" }, { "code": null, "e": 5905, "s": 5773, "text": "Forward Recovery −\tDL/I uses the log file to store the change data. The accumulated transactions are re-posted using this log file." }, { "code": null, "e": 6037, "s": 5905, "text": "Forward Recovery −\tDL/I uses the log file to store the change data. The accumulated transactions are re-posted using this log file." }, { "code": null, "e": 6394, "s": 6037, "text": "Backward Recovery − Backward recovery is also known as backout recovery. The log records for the program are read backwards and their effects are reversed in the database. When the backout is complete, the databases are in the same state as they were in before the failure, assuming that no another application program altered the database in the meantime." }, { "code": null, "e": 6751, "s": 6394, "text": "Backward Recovery − Backward recovery is also known as backout recovery. The log records for the program are read backwards and their effects are reversed in the database. When the backout is complete, the databases are in the same state as they were in before the failure, assuming that no another application program altered the database in the meantime." }, { "code": null, "e": 6929, "s": 6751, "text": "A checkpoint is a stage where the database changes done by the application program are considered complete and accurate. Listed below are the points to note about a checkpoint −" }, { "code": null, "e": 7024, "s": 6929, "text": "Database changes made before the most recent checkpoint are not reversed by backward recovery." }, { "code": null, "e": 7119, "s": 7024, "text": "Database changes made before the most recent checkpoint are not reversed by backward recovery." }, { "code": null, "e": 7250, "s": 7119, "text": "Database changes logged after the most recent checkpoint are not applied to an image copy of the database during forward recovery." }, { "code": null, "e": 7381, "s": 7250, "text": "Database changes logged after the most recent checkpoint are not applied to an image copy of the database during forward recovery." }, { "code": null, "e": 7515, "s": 7381, "text": "Using checkpoint method, the database is restored to its condition at the most recent checkpoint when the recovery process completes." }, { "code": null, "e": 7649, "s": 7515, "text": "Using checkpoint method, the database is restored to its condition at the most recent checkpoint when the recovery process completes." }, { "code": null, "e": 7736, "s": 7649, "text": "The default for batch programs is that the checkpoint is the beginning of the program." }, { "code": null, "e": 7823, "s": 7736, "text": "The default for batch programs is that the checkpoint is the beginning of the program." }, { "code": null, "e": 7887, "s": 7823, "text": "A checkpoint can be established using a checkpoint call (CHKP)." }, { "code": null, "e": 7951, "s": 7887, "text": "A checkpoint can be established using a checkpoint call (CHKP)." }, { "code": null, "e": 8027, "s": 7951, "text": "A checkpoint call causes a checkpoint record to be written on the DL/I log." }, { "code": null, "e": 8103, "s": 8027, "text": "A checkpoint call causes a checkpoint record to be written on the DL/I log." }, { "code": null, "e": 8146, "s": 8103, "text": "Shown below is the syntax of a CHKP call −" }, { "code": null, "e": 8242, "s": 8146, "text": "CALL 'CBLTDLI' USING DLI-CHKP\n PCB-NAME\n CHECKPOINT-ID\n" }, { "code": null, "e": 8277, "s": 8242, "text": "There are two checkpoint methods −" }, { "code": null, "e": 8415, "s": 8277, "text": "Basic Checkpointing − It allows the programmer to issue checkpoint calls that the DL/I recovery utilities use during recovery processing." }, { "code": null, "e": 8553, "s": 8415, "text": "Basic Checkpointing − It allows the programmer to issue checkpoint calls that the DL/I recovery utilities use during recovery processing." }, { "code": null, "e": 8859, "s": 8553, "text": "Symbolic Checkpointing − It is an advanced form of checkpointing that is used in combination with the extended restart facility. Symbolic checkpointing and extended restart together let the application programmer code the programs so that they can resume processing at the point just after the checkpoint." }, { "code": null, "e": 9165, "s": 8859, "text": "Symbolic Checkpointing − It is an advanced form of checkpointing that is used in combination with the extended restart facility. Symbolic checkpointing and extended restart together let the application programmer code the programs so that they can resume processing at the point just after the checkpoint." }, { "code": null, "e": 9172, "s": 9165, "text": " Print" }, { "code": null, "e": 9183, "s": 9172, "text": " Add Notes" } ]
BitArray.RightShift() Method in C# with Examples - GeeksforGeeks
27 Mar, 2019 BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.RightShift(Int32) method is used to shift the bits of the bit array to the right by one position and adds zeros on the shifted position. Original BitArray object will be modified on performing the operation right shift. Syntax: public System.Collections.BitArray RightShift (int count); Parameter:count is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 through positive 2,147,483,647. Return value : It returns Bit Array. Example 1: Suppose we have the bit array 10011 we want to shift it right by two positions. The final result is 00100. // C# program to illustrate the // RightShift(Int32) Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray of // size 5 named BitArr BitArray BitArr = new BitArray(5); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = true; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; // function calling Display(BitArr.RightShift(2)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }} False False True False False Example 2: Suppose we have the bit array 100011 we want to shift it right by three positions. The final result is 011000. // C# program to illustrate the // RightShift(Int32) Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray BitArray BitArr = new BitArray(6); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = false; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; BitArr[5] = true; // function calling Display(BitArr.RightShift(3)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }} False True True False False False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.rightshift?view=netcore-2.2 CSharp-Collections-BitArray CSharp-Collections-Namespace CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Method Overriding C# Dictionary with examples C# | Delegates Difference between Ref and Out keywords in C# Destructors in C# Extension Method in C# C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Abstract Classes
[ { "code": null, "e": 24394, "s": 24366, "text": "\n27 Mar, 2019" }, { "code": null, "e": 24822, "s": 24394, "text": "BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.RightShift(Int32) method is used to shift the bits of the bit array to the right by one position and adds zeros on the shifted position. Original BitArray object will be modified on performing the operation right shift." }, { "code": null, "e": 24889, "s": 24822, "text": "Syntax: public System.Collections.BitArray RightShift (int count);" }, { "code": null, "e": 25047, "s": 24889, "text": "Parameter:count is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 through positive 2,147,483,647." }, { "code": null, "e": 25084, "s": 25047, "text": "Return value : It returns Bit Array." }, { "code": null, "e": 25175, "s": 25084, "text": "Example 1: Suppose we have the bit array 10011 we want to shift it right by two positions." }, { "code": null, "e": 25202, "s": 25175, "text": "The final result is 00100." }, { "code": "// C# program to illustrate the // RightShift(Int32) Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray of // size 5 named BitArr BitArray BitArr = new BitArray(5); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = true; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; // function calling Display(BitArr.RightShift(2)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}", "e": 25907, "s": 25202, "text": null }, { "code": null, "e": 25937, "s": 25907, "text": "False\nFalse\nTrue\nFalse\nFalse\n" }, { "code": null, "e": 26031, "s": 25937, "text": "Example 2: Suppose we have the bit array 100011 we want to shift it right by three positions." }, { "code": null, "e": 26059, "s": 26031, "text": "The final result is 011000." }, { "code": "// C# program to illustrate the // RightShift(Int32) Methodusing System;using System.Collections; class GeeksforGeeks { // Main Method public static void Main() { // Creating a BitArray BitArray BitArr = new BitArray(6); // Initializing values in BitArr BitArr[0] = true; BitArr[1] = false; BitArr[2] = false; BitArr[3] = false; BitArr[4] = true; BitArr[5] = true; // function calling Display(BitArr.RightShift(3)); } // Displaying the result public static void Display(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}", "e": 26756, "s": 26059, "text": null }, { "code": null, "e": 26791, "s": 26756, "text": "False\nTrue\nTrue\nFalse\nFalse\nFalse\n" }, { "code": null, "e": 26802, "s": 26791, "text": "Reference:" }, { "code": null, "e": 26902, "s": 26802, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.rightshift?view=netcore-2.2" }, { "code": null, "e": 26930, "s": 26902, "text": "CSharp-Collections-BitArray" }, { "code": null, "e": 26959, "s": 26930, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 26973, "s": 26959, "text": "CSharp-method" }, { "code": null, "e": 26980, "s": 26973, "text": "Picked" }, { "code": null, "e": 26983, "s": 26980, "text": "C#" }, { "code": null, "e": 27081, "s": 26983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27104, "s": 27081, "text": "C# | Method Overriding" }, { "code": null, "e": 27132, "s": 27104, "text": "C# Dictionary with examples" }, { "code": null, "e": 27147, "s": 27132, "text": "C# | Delegates" }, { "code": null, "e": 27193, "s": 27147, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27211, "s": 27193, "text": "Destructors in C#" }, { "code": null, "e": 27234, "s": 27211, "text": "Extension Method in C#" }, { "code": null, "e": 27252, "s": 27234, "text": "C# | Constructors" }, { "code": null, "e": 27292, "s": 27252, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27323, "s": 27292, "text": "Introduction to .NET Framework" } ]
Lua - Math library
We often need math operations in scientific and engineering calculations and we can avail this using the standard Lua library math. The list of functions available in math library is shown in the following table. math.abs (x) Returns the absolute value of x. math.acos (x) Returns the arc cosine of x (in radians). math.asin (x) Returns the arc sine of x (in radians). math.atan (x) Returns the arc tangent of x (in radians). math.atan2 (y, x) Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of x being zero.) math.ceil (x) Returns the smallest integer larger than or equal to x. math.cos (x) Returns the cosine of x (assumed to be in radians). math.cosh (x) Returns the hyperbolic cosine of x. math.deg (x) Returns the angle x (given in radians) in degrees. math.exp (x) Returns the value e power x. math.floor (x) Returns the largest integer smaller than or equal to x. math.fmod (x, y) Returns the remainder of the division of x by y that rounds the quotient towards zero. math.frexp (x) Returns m and e such that x = m2e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero). math.huge The value HUGE_VAL, a value larger than or equal to any other numerical valu. math.ldexp (m, e) Returns m2e (e should be an integer). math.log (x) Returns the natural logarithm of x. math.log10 (x) Returns the base-10 logarithm of x. math.max (x, ...) Returns the maximum value among its arguments. math.min (x, ...) Returns the minimum value among its arguments. math.modf (x) Returns two numbers, the integral part of x and the fractional part of x. math.pi The value of pi. math.pow (x, y) Returns xy. (You can also use the expression x^y to compute this value.) math.rad (x) Returns the angle x (given in degrees) in radians. math.random ([m [, n]]) This function is an interface to the simple pseudo-random generator function rand provided by ANSI C.When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n]. math.randomseed (x) Sets x as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers. math.sin (x) Returns the sine of x (assumed to be in radians). math.sinh (x) Returns the hyperbolic sine of x. math.sqrt (x) Returns the square root of x. (You can also use the expression x^0.5 to compute this value.) math.tan (x) Returns the tangent of x (assumed to be in radians). math.tanh (x) Returns the hyperbolic tangent of x. A simple example using trigonometric function is shown below. radianVal = math.rad(math.pi / 2) io.write(radianVal,"\n") -- Sin value of 90(math.pi / 2) degrees io.write(string.format("%.1f ", math.sin(radianVal)),"\n") -- Cos value of 90(math.pi / 2) degrees io.write(string.format("%.1f ", math.cos(radianVal)),"\n") -- Tan value of 90(math.pi / 2) degrees io.write(string.format("%.1f ", math.tan(radianVal)),"\n") -- Cosh value of 90(math.pi / 2) degrees io.write(string.format("%.1f ", math.cosh(radianVal)),"\n") -- Pi Value in degrees io.write(math.deg(math.pi),"\n") When we run the above program, we will get the following output. 0.027415567780804 0.0 1.0 0.0 1.0 180 A simple example using common math functions is shown below. -- Floor io.write("Floor of 10.5055 is ", math.floor(10.5055),"\n") -- Ceil io.write("Ceil of 10.5055 is ", math.ceil(10.5055),"\n") -- Square root io.write("Square root of 16 is ",math.sqrt(16),"\n") -- Power io.write("10 power 2 is ",math.pow(10,2),"\n") io.write("100 power 0.5 is ",math.pow(100,0.5),"\n") -- Absolute io.write("Absolute value of -10 is ",math.abs(-10),"\n") --Random math.randomseed(os.time()) io.write("Random number between 1 and 100 is ",math.random(),"\n") --Random between 1 to 100 io.write("Random number between 1 and 100 is ",math.random(1,100),"\n") --Max io.write("Maximum in the input array is ",math.max(1,100,101,99,999),"\n") --Min io.write("Minimum in the input array is ",math.min(1,100,101,99,999),"\n") When we run the above program, we will get the following output. Floor of 10.5055 is 10 Ceil of 10.5055 is 11 Square root of 16 is 4 10 power 2 is 100 100 power 0.5 is 10 Absolute value of -10 is 10 Random number between 1 and 100 is 0.22876674703207 Random number between 1 and 100 is 7 Maximum in the input array is 999 Minimum in the input array is 1 The above examples are just a few of the common examples, we can use math library based on our need, so try using all the functions to be more familiar. 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2316, "s": 2103, "text": "We often need math operations in scientific and engineering calculations and we can avail this using the standard Lua library math. The list of functions available in math library is shown in the following table." }, { "code": null, "e": 2329, "s": 2316, "text": "math.abs (x)" }, { "code": null, "e": 2362, "s": 2329, "text": "Returns the absolute value of x." }, { "code": null, "e": 2376, "s": 2362, "text": "math.acos (x)" }, { "code": null, "e": 2418, "s": 2376, "text": "Returns the arc cosine of x (in radians)." }, { "code": null, "e": 2432, "s": 2418, "text": "math.asin (x)" }, { "code": null, "e": 2472, "s": 2432, "text": "Returns the arc sine of x (in radians)." }, { "code": null, "e": 2486, "s": 2472, "text": "math.atan (x)" }, { "code": null, "e": 2529, "s": 2486, "text": "Returns the arc tangent of x (in radians)." }, { "code": null, "e": 2547, "s": 2529, "text": "math.atan2 (y, x)" }, { "code": null, "e": 2720, "s": 2547, "text": "Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of x being zero.)" }, { "code": null, "e": 2734, "s": 2720, "text": "math.ceil (x)" }, { "code": null, "e": 2790, "s": 2734, "text": "Returns the smallest integer larger than or equal to x." }, { "code": null, "e": 2803, "s": 2790, "text": "math.cos (x)" }, { "code": null, "e": 2855, "s": 2803, "text": "Returns the cosine of x (assumed to be in radians)." }, { "code": null, "e": 2869, "s": 2855, "text": "math.cosh (x)" }, { "code": null, "e": 2905, "s": 2869, "text": "Returns the hyperbolic cosine of x." }, { "code": null, "e": 2918, "s": 2905, "text": "math.deg (x)" }, { "code": null, "e": 2969, "s": 2918, "text": "Returns the angle x (given in radians) in degrees." }, { "code": null, "e": 2982, "s": 2969, "text": "math.exp (x)" }, { "code": null, "e": 3011, "s": 2982, "text": "Returns the value e power x." }, { "code": null, "e": 3026, "s": 3011, "text": "math.floor (x)" }, { "code": null, "e": 3082, "s": 3026, "text": "Returns the largest integer smaller than or equal to x." }, { "code": null, "e": 3099, "s": 3082, "text": "math.fmod (x, y)" }, { "code": null, "e": 3186, "s": 3099, "text": "Returns the remainder of the division of x by y that rounds the quotient towards zero." }, { "code": null, "e": 3201, "s": 3186, "text": "math.frexp (x)" }, { "code": null, "e": 3331, "s": 3201, "text": "Returns m and e such that x = m2e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero)." }, { "code": null, "e": 3341, "s": 3331, "text": "math.huge" }, { "code": null, "e": 3419, "s": 3341, "text": "The value HUGE_VAL, a value larger than or equal to any other numerical valu." }, { "code": null, "e": 3437, "s": 3419, "text": "math.ldexp (m, e)" }, { "code": null, "e": 3475, "s": 3437, "text": "Returns m2e (e should be an integer)." }, { "code": null, "e": 3488, "s": 3475, "text": "math.log (x)" }, { "code": null, "e": 3524, "s": 3488, "text": "Returns the natural logarithm of x." }, { "code": null, "e": 3539, "s": 3524, "text": "math.log10 (x)" }, { "code": null, "e": 3575, "s": 3539, "text": "Returns the base-10 logarithm of x." }, { "code": null, "e": 3593, "s": 3575, "text": "math.max (x, ...)" }, { "code": null, "e": 3640, "s": 3593, "text": "Returns the maximum value among its arguments." }, { "code": null, "e": 3658, "s": 3640, "text": "math.min (x, ...)" }, { "code": null, "e": 3705, "s": 3658, "text": "Returns the minimum value among its arguments." }, { "code": null, "e": 3719, "s": 3705, "text": "math.modf (x)" }, { "code": null, "e": 3793, "s": 3719, "text": "Returns two numbers, the integral part of x and the fractional part of x." }, { "code": null, "e": 3801, "s": 3793, "text": "math.pi" }, { "code": null, "e": 3818, "s": 3801, "text": "The value of pi." }, { "code": null, "e": 3834, "s": 3818, "text": "math.pow (x, y)" }, { "code": null, "e": 3907, "s": 3834, "text": "Returns xy. (You can also use the expression x^y to compute this value.)" }, { "code": null, "e": 3920, "s": 3907, "text": "math.rad (x)" }, { "code": null, "e": 3971, "s": 3920, "text": "Returns the angle x (given in degrees) in radians." }, { "code": null, "e": 3995, "s": 3971, "text": "math.random ([m [, n]])" }, { "code": null, "e": 4421, "s": 3995, "text": "This function is an interface to the simple pseudo-random generator function rand provided by ANSI C.When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n]." }, { "code": null, "e": 4441, "s": 4421, "text": "math.randomseed (x)" }, { "code": null, "e": 4543, "s": 4441, "text": "Sets x as the \"seed\" for the pseudo-random generator: equal seeds produce equal sequences of numbers." }, { "code": null, "e": 4556, "s": 4543, "text": "math.sin (x)" }, { "code": null, "e": 4606, "s": 4556, "text": "Returns the sine of x (assumed to be in radians)." }, { "code": null, "e": 4620, "s": 4606, "text": "math.sinh (x)" }, { "code": null, "e": 4654, "s": 4620, "text": "Returns the hyperbolic sine of x." }, { "code": null, "e": 4668, "s": 4654, "text": "math.sqrt (x)" }, { "code": null, "e": 4761, "s": 4668, "text": "Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)" }, { "code": null, "e": 4774, "s": 4761, "text": "math.tan (x)" }, { "code": null, "e": 4827, "s": 4774, "text": "Returns the tangent of x (assumed to be in radians)." }, { "code": null, "e": 4841, "s": 4827, "text": "math.tanh (x)" }, { "code": null, "e": 4878, "s": 4841, "text": "Returns the hyperbolic tangent of x." }, { "code": null, "e": 4940, "s": 4878, "text": "A simple example using trigonometric function is shown below." }, { "code": null, "e": 5459, "s": 4940, "text": "radianVal = math.rad(math.pi / 2)\n\nio.write(radianVal,\"\\n\")\n\n-- Sin value of 90(math.pi / 2) degrees\nio.write(string.format(\"%.1f \", math.sin(radianVal)),\"\\n\")\n\n-- Cos value of 90(math.pi / 2) degrees\nio.write(string.format(\"%.1f \", math.cos(radianVal)),\"\\n\")\n\n-- Tan value of 90(math.pi / 2) degrees\nio.write(string.format(\"%.1f \", math.tan(radianVal)),\"\\n\")\n\n-- Cosh value of 90(math.pi / 2) degrees\nio.write(string.format(\"%.1f \", math.cosh(radianVal)),\"\\n\")\n\n-- Pi Value in degrees\nio.write(math.deg(math.pi),\"\\n\")" }, { "code": null, "e": 5524, "s": 5459, "text": "When we run the above program, we will get the following output." }, { "code": null, "e": 5567, "s": 5524, "text": "0.027415567780804\n0.0 \n1.0 \n0.0 \n1.0 \n180\n" }, { "code": null, "e": 5628, "s": 5567, "text": "A simple example using common math functions is shown below." }, { "code": null, "e": 6378, "s": 5628, "text": "-- Floor\nio.write(\"Floor of 10.5055 is \", math.floor(10.5055),\"\\n\")\n\n-- Ceil\nio.write(\"Ceil of 10.5055 is \", math.ceil(10.5055),\"\\n\")\n\n-- Square root\nio.write(\"Square root of 16 is \",math.sqrt(16),\"\\n\")\n\n-- Power\nio.write(\"10 power 2 is \",math.pow(10,2),\"\\n\")\nio.write(\"100 power 0.5 is \",math.pow(100,0.5),\"\\n\")\n\n-- Absolute\nio.write(\"Absolute value of -10 is \",math.abs(-10),\"\\n\")\n\n--Random\nmath.randomseed(os.time())\nio.write(\"Random number between 1 and 100 is \",math.random(),\"\\n\")\n\n--Random between 1 to 100\nio.write(\"Random number between 1 and 100 is \",math.random(1,100),\"\\n\")\n\n--Max\nio.write(\"Maximum in the input array is \",math.max(1,100,101,99,999),\"\\n\")\n\n--Min\nio.write(\"Minimum in the input array is \",math.min(1,100,101,99,999),\"\\n\")" }, { "code": null, "e": 6443, "s": 6378, "text": "When we run the above program, we will get the following output." }, { "code": null, "e": 6733, "s": 6443, "text": "Floor of 10.5055 is 10\nCeil of 10.5055 is 11\nSquare root of 16 is 4\n10 power 2 is 100\n100 power 0.5 is 10\nAbsolute value of -10 is 10\nRandom number between 1 and 100 is 0.22876674703207\nRandom number between 1 and 100 is 7\nMaximum in the input array is 999\nMinimum in the input array is 1\n" }, { "code": null, "e": 6886, "s": 6733, "text": "The above examples are just a few of the common examples, we can use math library based on our need, so try using all the functions to be more familiar." }, { "code": null, "e": 6919, "s": 6886, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 6933, "s": 6919, "text": " Manish Gupta" }, { "code": null, "e": 6966, "s": 6933, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 6982, "s": 6966, "text": " Sanjeev Mittal" }, { "code": null, "e": 7017, "s": 6982, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7033, "s": 7017, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 7040, "s": 7033, "text": " Print" }, { "code": null, "e": 7051, "s": 7040, "text": " Add Notes" } ]
How to use href attribute in HTML Page?
The href attribute in an HTML page is used to specify the URL for a page. If the href attribute is not present, then the <a> tag will not be considered as a hyperlink. Just keep in mind the href attribute should get included as an attribute for <a> tag. It should be used inside the <body>...</body> tags. You can try the following code to make page links in an HTML page using the href attribute <!DOCTYPE html> <html> <head> <title>HTML href attribute</title> </head> <body> <h1>Learn about the company</h1> <a href="/about/index.htm">About</a> <a href="/about/about_team.htm">Team</a> </body> </html>
[ { "code": null, "e": 1230, "s": 1062, "text": "The href attribute in an HTML page is used to specify the URL for a page. If the href attribute is not present, then the <a> tag will not be considered as a hyperlink." }, { "code": null, "e": 1368, "s": 1230, "text": "Just keep in mind the href attribute should get included as an attribute for <a> tag. It should be used inside the <body>...</body> tags." }, { "code": null, "e": 1459, "s": 1368, "text": "You can try the following code to make page links in an HTML page using the href attribute" }, { "code": null, "e": 1703, "s": 1459, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML href attribute</title>\n </head>\n\n <body>\n <h1>Learn about the company</h1>\n <a href=\"/about/index.htm\">About</a>\n <a href=\"/about/about_team.htm\">Team</a>\n </body>\n</html>" } ]
How to navigate to a parent route from a child route? - GeeksforGeeks
12 Nov, 2020 In angular, a root component that serves as the parent component of all the components and rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component which is the parent of a child lies above the child component and this there is no direct link between them but in general, a parent component can be routed from the child component via two ways: Directly using the routerLink directive in case of linkage of child to parent.Using Route class in case of navigation to happen on a triggered event. Directly using the routerLink directive in case of linkage of child to parent. Using Route class in case of navigation to happen on a triggered event. Approach: Before performing the above two operations, there is a need to register this component in the Route class’s instance which lies inside the app-routing.module.ts file. This will be further used to navigate from child to parent. The routing should be defined within the app-routing.module.ts file as follows: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ParentComponent } from './parent/parent.component'; import { ChildComponent } from './parent/child/child.component'; const routes: Routes = [ {path: 'parent' , component: ParentComponent}, {path: 'parent/child' , component: ChildComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Once it is done, anyone of the two methods can be used to route to parent from a child.Syntax: To register routes in angular for any component, set the path and the class name of the component inside the app-routing.module.ts file. The syntax for the same is given as follows: import { Routes, RouterModule } from '@angular/router'; import { Component_1 } from 'path_to_component_1'; import { Component_2 } from 'path_to_component_2'; const routes: Routes = [ {path: 'URL_mapping_component_1' , component: Component_1}, {path: 'URL_mapping_component_2' , component: Component_2} ]; As components are different from web pages and thus are to be registered with proper URL paths, which will map the respective path to the respective component. Basic Examples and Explanations Using routerLink directive: This is a simplest method that can be used to redirect to any component allover the project. It is used within the template as a option acting equivalent to the href option in in the anchor tag, the difference is that, that it links a anchor to the components within the angular project. It is used as a directive within the anchor tag. The child template file code is given as follows: html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <a [routerLink]= "[ '/parent']" [queryParams]="{GfG: 'Geeks for Geeks'}"> Redirect message to parent </a></body></html> The routerLink is set to the parent component route. Just to add up, queryParams directive is used to send a message to the parent component via the query string. In the parent component file the query parameter can be accessed as follows: @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { constructor( private activateRoute: ActivatedRoute) { } message = this.activateRoute.snapshot.queryParamMap.get('GfG') ngOnInit() { } } Within the message variable the parameter is received and the message s stored. It captures using the ActivatedRoute class. html <!DOCTYPE html><html> <head> <title>Page Title</title> </head><body> <p>On the Parent page </p> <p> Message By Child is {{message}}</p> </body></html> Using the Route.navigate() method: In this we will be using the Route class from @angular/route module. The route object is used to route to the page dynamically via component part of the .ts file. This object has a .navigate() method to route to different modules. It takes two parameters, first is the routing path, and 2nd is the object consisting of information about the query parameters to send, relativity to the path for route etc. This method is used when there is a need to conditionally trigger an event via template. import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { constructor( private router: Router, private activatedRoute: ActivatedRoute) {} ngOnInit(){} redirect_to_parent(){ this.router.navigate(["../../parent"], { relativeTo: this.activatedRoute, queryParams: {GfG: 'Geeks for Geeks'}}); } } The code above is for the child’s component file, within which a method redirect_to_parent() is triggered using a button in the template to perform the action of redirection and send a message to the parent component. The template file for the child is given as follows: html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <button (click)="redirect_to_parent()"> Click to redirect </button></body></html> Output: bunnyram19 AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24398, "s": 24370, "text": "\n12 Nov, 2020" }, { "code": null, "e": 24825, "s": 24398, "text": "In angular, a root component that serves as the parent component of all the components and rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component which is the parent of a child lies above the child component and this there is no direct link between them but in general, a parent component can be routed from the child component via two ways:" }, { "code": null, "e": 24975, "s": 24825, "text": "Directly using the routerLink directive in case of linkage of child to parent.Using Route class in case of navigation to happen on a triggered event." }, { "code": null, "e": 25054, "s": 24975, "text": "Directly using the routerLink directive in case of linkage of child to parent." }, { "code": null, "e": 25126, "s": 25054, "text": "Using Route class in case of navigation to happen on a triggered event." }, { "code": null, "e": 25137, "s": 25126, "text": "Approach: " }, { "code": null, "e": 25364, "s": 25137, "text": "Before performing the above two operations, there is a need to register this component in the Route class’s instance which lies inside the app-routing.module.ts file. This will be further used to navigate from child to parent." }, { "code": null, "e": 25444, "s": 25364, "text": "The routing should be defined within the app-routing.module.ts file as follows:" }, { "code": null, "e": 25920, "s": 25444, "text": "import { NgModule } from '@angular/core';\nimport { Routes, RouterModule } from '@angular/router';\nimport { ParentComponent } from './parent/parent.component';\nimport { ChildComponent } from './parent/child/child.component';\n\n\nconst routes: Routes = [\n {path: 'parent' , component: ParentComponent},\n {path: 'parent/child' , component: ChildComponent}\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n})\nexport class AppRoutingModule { }\n" }, { "code": null, "e": 26017, "s": 25920, "text": "Once it is done, anyone of the two methods can be used to route to parent from a child.Syntax: " }, { "code": null, "e": 26200, "s": 26017, "text": "To register routes in angular for any component, set the path and the class name of the component inside the app-routing.module.ts file. The syntax for the same is given as follows: " }, { "code": null, "e": 26511, "s": 26200, "text": "import { Routes, RouterModule } from '@angular/router';\nimport { Component_1 } from 'path_to_component_1';\nimport { Component_2 } from 'path_to_component_2';\n\nconst routes: Routes = [\n {path: 'URL_mapping_component_1' , component: Component_1},\n {path: 'URL_mapping_component_2' , component: Component_2}\n];\n" }, { "code": null, "e": 26671, "s": 26511, "text": "As components are different from web pages and thus are to be registered with proper URL paths, which will map the respective path to the respective component." }, { "code": null, "e": 26704, "s": 26671, "text": "Basic Examples and Explanations " }, { "code": null, "e": 26733, "s": 26704, "text": "Using routerLink directive: " }, { "code": null, "e": 27021, "s": 26733, "text": "This is a simplest method that can be used to redirect to any component allover the project. It is used within the template as a option acting equivalent to the href option in in the anchor tag, the difference is that, that it links a anchor to the components within the angular project." }, { "code": null, "e": 27120, "s": 27021, "text": "It is used as a directive within the anchor tag. The child template file code is given as follows:" }, { "code": null, "e": 27125, "s": 27120, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <a [routerLink]= \"[ '/parent']\" [queryParams]=\"{GfG: 'Geeks for Geeks'}\"> Redirect message to parent </a></body></html>", "e": 27482, "s": 27125, "text": null }, { "code": null, "e": 27645, "s": 27482, "text": "The routerLink is set to the parent component route. Just to add up, queryParams directive is used to send a message to the parent component via the query string." }, { "code": null, "e": 27722, "s": 27645, "text": "In the parent component file the query parameter can be accessed as follows:" }, { "code": null, "e": 28049, "s": 27722, "text": "@Component({\n selector: 'app-parent',\n templateUrl: './parent.component.html',\n styleUrls: ['./parent.component.css']\n})\nexport class ParentComponent implements OnInit {\n constructor( private activateRoute: ActivatedRoute) {\n }\n message = this.activateRoute.snapshot.queryParamMap.get('GfG')\n ngOnInit() {\n \n }\n \n}\n" }, { "code": null, "e": 28173, "s": 28049, "text": "Within the message variable the parameter is received and the message s stored. It captures using the ActivatedRoute class." }, { "code": null, "e": 28178, "s": 28173, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Page Title</title> </head><body> <p>On the Parent page </p> <p> Message By Child is {{message}}</p> </body></html>", "e": 28344, "s": 28178, "text": null }, { "code": null, "e": 28380, "s": 28344, "text": "Using the Route.navigate() method: " }, { "code": null, "e": 28874, "s": 28380, "text": "In this we will be using the Route class from @angular/route module. The route object is used to route to the page dynamically via component part of the .ts file. This object has a .navigate() method to route to different modules. It takes two parameters, first is the routing path, and 2nd is the object consisting of information about the query parameters to send, relativity to the path for route etc. This method is used when there is a need to conditionally trigger an event via template." }, { "code": null, "e": 29414, "s": 28874, "text": "import { Component, OnInit } from '@angular/core';\nimport { Router, ActivatedRoute } from '@angular/router';\n\n@Component({\n selector: 'app-child',\n templateUrl: './child.component.html',\n styleUrls: ['./child.component.css']\n})\nexport class ChildComponent implements OnInit {\n\n constructor(\nprivate router: Router, \nprivate activatedRoute: ActivatedRoute) {}\n\n ngOnInit(){}\n redirect_to_parent(){ \n this.router.navigate([\"../../parent\"], {\n relativeTo: this.activatedRoute, queryParams: \n {GfG: 'Geeks for Geeks'}});\n} \n}\n\n" }, { "code": null, "e": 29685, "s": 29414, "text": "The code above is for the child’s component file, within which a method redirect_to_parent() is triggered using a button in the template to perform the action of redirection and send a message to the parent component. The template file for the child is given as follows:" }, { "code": null, "e": 29690, "s": 29685, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <button (click)=\"redirect_to_parent()\"> Click to redirect </button></body></html>", "e": 29999, "s": 29690, "text": null }, { "code": null, "e": 30008, "s": 29999, "text": "Output: " }, { "code": null, "e": 30024, "s": 30013, "text": "bunnyram19" }, { "code": null, "e": 30039, "s": 30024, "text": "AngularJS-Misc" }, { "code": null, "e": 30046, "s": 30039, "text": "Picked" }, { "code": null, "e": 30056, "s": 30046, "text": "AngularJS" }, { "code": null, "e": 30073, "s": 30056, "text": "Web Technologies" }, { "code": null, "e": 30171, "s": 30073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30180, "s": 30171, "text": "Comments" }, { "code": null, "e": 30193, "s": 30180, "text": "Old Comments" }, { "code": null, "e": 30224, "s": 30193, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 30266, "s": 30224, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 30301, "s": 30266, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30375, "s": 30301, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 30428, "s": 30375, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 30484, "s": 30428, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30517, "s": 30484, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30579, "s": 30517, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30622, "s": 30579, "text": "How to fetch data from an API in ReactJS ?" } ]
LightGBM vs XGBOOST - Which algorithm is better - GeeksforGeeks
12 Feb, 2021 There are a lot of Data Enthusiasts who are taking part in a number of online competitive competitions in the domain of Machine Learning. Everyone has their own unique independent approach to determine the best model and predict the accurate output of the given problem statement. In Machine Learning, Feature Engineering is very much an integral part of the process and also consumes most of the time. On the other hand, Modeling becomes an important part where you cannot have much preprocessing or have certain constraints on the features. There are different ensemble methods that help in making strong robust models that can give very accurate predictions. But exactly what is this buzz of the word ‘Ensemble’? Let us understand what the term Ensemble means in detail. Ensemble: Before moving into a technical definition straightaway let us take a simple real-life example and understand the same. Let us assume that you want to buy an electronic device – Mobile Phone. Your first approach would be searching on the Internet about different latest smartphones and comparing rates of different companies. You will also see the features in different models. After this first step, you will ask your friends about their opinion about the mobile phones which you have short-listed. In this fashion, you will take opinions and suggestions from a couple of people. Once you get a couple of positive reviews about a particular mobile phone you will go ahead and buy that mobile phone. This is the exact concept of the term ‘Ensemble’. Ensemble Methods is a machine learning technique in which several base models (weak learners) are combined in order to produce one powerful model. Let us now go further into detail with the Boosting Method. Boosting: Boosting is one of the Sequential Ensemble techniques. This technique is usually applied to the data with high bias and low variance. Here we have a dataset ‘D’ with n records. We take a random sample of 5 records from the dataset. Here there is an equal probability of all the records to be selected. So, by random sampling, we have 1,3,5,7,25 records selected. We train a model (let us say decision tree) on this sample data. After that, we provide all the records of D dataset to this model to classify it. There would be some records that may be misclassified since Model 1 is a weak learner. The records misclassified are given more weight for the next sampling selection. So, these misclassified records will have a higher probability of selection than the other records in the dataset. Here records 2,8, 1,16 were misclassified and record 5 also had a probability of selection so it got selected. Now again we train Model 2 and then provide the full data to the second model. This process is repeated for n models. These all models are weak learners. In the end, these models are aggregated and a final M* model is built which is a better performing model since the misclassification error has been minimized. The Below diagram represents the entire process neatly: So, having understood what is Boosting let us discuss the competition between the two popular boosting algorithms that is Light Gradient Boosting Machine and Extreme Gradient Boosting (xgboost). These algorithms yield the best results in a lot of competitions and hackathons hosted on multiple platforms. Let us now understand in-depth the Algorithms and have a comparative study on the same. LGBM is a quick, distributed, and high-performance gradient lifting framework which is based upon a popular machine learning algorithm – Decision Tree. It can be used in classification, regression, and many more machine learning tasks. This algorithm grows leaf wise and chooses the maximum delta value to grow. LightGBM uses histogram-based algorithms. The advantages of this are as follows: Less Memory Usage Reduction in Communication Cost for parallel learning Reduction in Cost for calculating gain for each split in the decision tree. So as LightGBM gets trained much faster but also it can lead to the case of overfitting sometimes. So, let us see what parameters can be tuned to get a better optimal model. To get the best fit following parameters must be tuned: num_leaves: Since LightGBM grows leaf-wise this value must be less than 2^(max_depth) to avoid an overfitting scenario. min_data_in_leaf: For large datasets, its value should be set in hundreds to thousands.max_depth: A key parameter whose value should be set accordingly to avoid overfitting. num_leaves: Since LightGBM grows leaf-wise this value must be less than 2^(max_depth) to avoid an overfitting scenario. min_data_in_leaf: For large datasets, its value should be set in hundreds to thousands. max_depth: A key parameter whose value should be set accordingly to avoid overfitting. For Achieving Better Accuracy following parameters must be tuned: More Training Data Added to the Model can increase accuracy. (can be also external unseen data)num_leaves: Increasing its value will increase accuracy as the splitting is taking leaf-wise but overfitting also may occur.max_bin: High value will have a major impact on accuracy but will eventually go to overfitting. More Training Data Added to the Model can increase accuracy. (can be also external unseen data) num_leaves: Increasing its value will increase accuracy as the splitting is taking leaf-wise but overfitting also may occur. max_bin: High value will have a major impact on accuracy but will eventually go to overfitting. A very popular and in-demand algorithm often referred to as the winning algorithm for various competitions on different platforms. XGBOOST stands for Extreme Gradient Boosting. This algorithm is an improved version of the Gradient Boosting Algorithm. The base algorithm is Gradient Boosting Decision Tree Algorithm. Its powerful predictive power and easy to implement approach has made it float throughout many machine learning notebooks. Some key points of the algorithm are as follows: It does not build the full tree structure but builds it greedily.As compared to LightGBM it splits level-wise rather than leaf-wise.In Gradient Boosting, negative gradients are taken into account to optimize the loss function but here Taylor’s expansion is taken into account.The regularization term penalizes from building complex tree models. It does not build the full tree structure but builds it greedily. As compared to LightGBM it splits level-wise rather than leaf-wise. In Gradient Boosting, negative gradients are taken into account to optimize the loss function but here Taylor’s expansion is taken into account. The regularization term penalizes from building complex tree models. Some parameters which can be tuned to increase the performance are as follows: General Parameters include the following: booster: It has 2 options — gbtree and gblinear.silent: If kept to 1 no running messages will be shown while the code is executing.nthread: Mainly used for parallel processing. The number of cores is specified here. booster: It has 2 options — gbtree and gblinear. silent: If kept to 1 no running messages will be shown while the code is executing. nthread: Mainly used for parallel processing. The number of cores is specified here. Booster Parameters include the following: eta: Makes model robust by shrinkage of weights at each step.max_depth: Should be set accordingly to avoid overfitting.max_leaf_nodes: If this parameter is defined then the model will ignore max_depth.gamma: Specifies the minimum loss reduction which is required to make a split.lambda: L2 regularization term on the weights. eta: Makes model robust by shrinkage of weights at each step. max_depth: Should be set accordingly to avoid overfitting. max_leaf_nodes: If this parameter is defined then the model will ignore max_depth. gamma: Specifies the minimum loss reduction which is required to make a split. lambda: L2 regularization term on the weights. Learning Task Parameters include the following: 1) objective: This will define the loss function which is to be used. binary: logistic –logistic regression for binary classification, returns predicted probability (not the class) multi: softmax –multiclass classification using the softmax objective, returns predicted class (not the probabilities) 2) seed: the default value set for this is zero. Can be used for parameter tuning. So, we have gone through the basics of the algorithm and the parameters which need to be tuned for the respective algorithms. Now we will take a dataset and then compare both the algorithms on the basis of accuracy and execution time. Below is the Dataset Description which we are going to use: Dataset Description: The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers were selected for generating the training data and 30% for the test data. The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low-frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain. Data link: https://github.com/pranavkotak8/Datasets/blob/master/smartphone_activity_dataset.zip Python code implementation: Python3 # Importing the basic librariespip install pandasimport timeimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport gc gc.enable() # Importing LGBM and XGBOOSTimport lightgbm as lgbimport xgboost as xgb # Reading the Data and Inspecting itdata=pd.read_csv('/content/drive/MyDrive/GeeksforGeeks_Datasets/smartphone_activity_dataset.csv')data Python3 # Checking for missing values across the 562 features of the datasetdata.isna().sum()*100/len(data) # Checking for Target Distributionsns.countplot(data['activity'])plt.show() Python3 # Saving the target variable(dependent variable) to target # variable and dropping it from the original "data" dataframetarget=data['activity']data.drop(columns={'activity'},inplace=True) # As the dataset contains all numerical features and also # the target classes are also encoded there is no more preprocessing# needed at this stage. There are no missing values in the # dataset hence no missing data imputation is being needed. # Let us split the dataset and move to the modeling part. # Splitting the Dataset into Training and Testing Datasetfrom sklearn.model_selection import train_test_splitX_train,X_test,y_train,y_test=train_test_split( data,target,test_size=0.15,random_state=100) # Applying the XGBOOST Model# Setting Parameters required for XGBOOST Model # and Training the Model # Starting to track the Timestart = time.time() xg=xgb.XGBClassifier(max_depth=7,learning_rate=0.05, silent=1,eta=1,objective='multi:softprob', num_round=50,num_classes=6) # Setting the Parameters. More parameters can be set# according to the requirement. # Here we have set the main parameters. # Fitting the Modelxg.fit(X_train,y_train) # Stopping the tracking of time stop = time.time() exec_time_xgb=stop-start # Measuring the time taken for the model to build exec_time_xgb # Predicting the Output Classypred_xgb=xg.predict(X_test) ypred_xgb # Getting the Accuracy Score for the XGBOOST Modelfrom sklearn.metrics import accuracy_scoreaccuracy_xgb = accuracy_score(y_test,ypred_xgb) # Setting the Parameters and Training data for LightGBM Modeldata_train = lgb.Dataset(X_train,label = y_train)params= {} # Usually set between 0 to 1.params['learning_rate']=0.5 # GradientBoostingDecisionTreeparams['boosting_type']='gbdt' # Multi-class since the target class has 6 classes.params['objective']='multiclass' # Metric for multi-classparams['metric']='multi_logloss' params['max_depth']=7params['num_class']=7 # This value is not inclusive of the end value.# Hence we have 6 classes the value is set to 7. # Training the LightGBM Modelnum_round =50start = time.time()lgbm = lgb.train(params,data_train,num_round)stop = time.time() #Execution time of the LightGBM Modelexec_time_lgbm = stop-startexec_time_lgbm # Predicting the output on the Test Dataset ypred_lgbm = lgbm.predict(X_test)ypred_lgbmy_pred_lgbm_class = [np.argmax(line) for line in ypred_lgbm] Python3 # Accuracy Score for the LightGBM Modelfrom sklearn.metrics import accuracy_scoreaccuracy_lgbm=accuracy_score(y_test,y_pred_lgbm_class) # Comparing the Accuracy and Execution Time for both the Algorithmscomparison = {'Accuracy:':(accuracy_lgbm,accuracy_xgb),\ 'Execution Time(in seconds):':(exec_time_lgbm,exec_time_xgb)}LGBM_XGB = pd.DataFrame(comparison)LGBM_XGB .index = ['LightGBM','XGBoost']LGBM_XGB # On comparison we notice that LightGBM is # faster and gives better accuracy.comp_ratio=(203.594708/29.443264)comp_ratioprint("LightGBM is "+" "+str(np.ceil(comp_ratio))+" "+\ str("times")+" "+"faster than XGBOOST Algorithm") Final Output: Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Difference between Informed and Uninformed Search in AI Normalization vs Standardization 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": 24344, "s": 24316, "text": "\n12 Feb, 2021" }, { "code": null, "e": 25118, "s": 24344, "text": "There are a lot of Data Enthusiasts who are taking part in a number of online competitive competitions in the domain of Machine Learning. Everyone has their own unique independent approach to determine the best model and predict the accurate output of the given problem statement. In Machine Learning, Feature Engineering is very much an integral part of the process and also consumes most of the time. On the other hand, Modeling becomes an important part where you cannot have much preprocessing or have certain constraints on the features. There are different ensemble methods that help in making strong robust models that can give very accurate predictions. But exactly what is this buzz of the word ‘Ensemble’? Let us understand what the term Ensemble means in detail." }, { "code": null, "e": 26084, "s": 25118, "text": "Ensemble: Before moving into a technical definition straightaway let us take a simple real-life example and understand the same. Let us assume that you want to buy an electronic device – Mobile Phone. Your first approach would be searching on the Internet about different latest smartphones and comparing rates of different companies. You will also see the features in different models. After this first step, you will ask your friends about their opinion about the mobile phones which you have short-listed. In this fashion, you will take opinions and suggestions from a couple of people. Once you get a couple of positive reviews about a particular mobile phone you will go ahead and buy that mobile phone. This is the exact concept of the term ‘Ensemble’. Ensemble Methods is a machine learning technique in which several base models (weak learners) are combined in order to produce one powerful model. Let us now go further into detail with the Boosting Method." }, { "code": null, "e": 27368, "s": 26084, "text": "Boosting: Boosting is one of the Sequential Ensemble techniques. This technique is usually applied to the data with high bias and low variance. Here we have a dataset ‘D’ with n records. We take a random sample of 5 records from the dataset. Here there is an equal probability of all the records to be selected. So, by random sampling, we have 1,3,5,7,25 records selected. We train a model (let us say decision tree) on this sample data. After that, we provide all the records of D dataset to this model to classify it. There would be some records that may be misclassified since Model 1 is a weak learner. The records misclassified are given more weight for the next sampling selection. So, these misclassified records will have a higher probability of selection than the other records in the dataset. Here records 2,8, 1,16 were misclassified and record 5 also had a probability of selection so it got selected. Now again we train Model 2 and then provide the full data to the second model. This process is repeated for n models. These all models are weak learners. In the end, these models are aggregated and a final M* model is built which is a better performing model since the misclassification error has been minimized. The Below diagram represents the entire process neatly:" }, { "code": null, "e": 27761, "s": 27368, "text": "So, having understood what is Boosting let us discuss the competition between the two popular boosting algorithms that is Light Gradient Boosting Machine and Extreme Gradient Boosting (xgboost). These algorithms yield the best results in a lot of competitions and hackathons hosted on multiple platforms. Let us now understand in-depth the Algorithms and have a comparative study on the same." }, { "code": null, "e": 28154, "s": 27761, "text": "LGBM is a quick, distributed, and high-performance gradient lifting framework which is based upon a popular machine learning algorithm – Decision Tree. It can be used in classification, regression, and many more machine learning tasks. This algorithm grows leaf wise and chooses the maximum delta value to grow. LightGBM uses histogram-based algorithms. The advantages of this are as follows:" }, { "code": null, "e": 28172, "s": 28154, "text": "Less Memory Usage" }, { "code": null, "e": 28226, "s": 28172, "text": "Reduction in Communication Cost for parallel learning" }, { "code": null, "e": 28302, "s": 28226, "text": "Reduction in Cost for calculating gain for each split in the decision tree." }, { "code": null, "e": 28476, "s": 28302, "text": "So as LightGBM gets trained much faster but also it can lead to the case of overfitting sometimes. So, let us see what parameters can be tuned to get a better optimal model." }, { "code": null, "e": 28532, "s": 28476, "text": "To get the best fit following parameters must be tuned:" }, { "code": null, "e": 28826, "s": 28532, "text": "num_leaves: Since LightGBM grows leaf-wise this value must be less than 2^(max_depth) to avoid an overfitting scenario. min_data_in_leaf: For large datasets, its value should be set in hundreds to thousands.max_depth: A key parameter whose value should be set accordingly to avoid overfitting." }, { "code": null, "e": 28947, "s": 28826, "text": "num_leaves: Since LightGBM grows leaf-wise this value must be less than 2^(max_depth) to avoid an overfitting scenario. " }, { "code": null, "e": 29035, "s": 28947, "text": "min_data_in_leaf: For large datasets, its value should be set in hundreds to thousands." }, { "code": null, "e": 29122, "s": 29035, "text": "max_depth: A key parameter whose value should be set accordingly to avoid overfitting." }, { "code": null, "e": 29188, "s": 29122, "text": "For Achieving Better Accuracy following parameters must be tuned:" }, { "code": null, "e": 29503, "s": 29188, "text": "More Training Data Added to the Model can increase accuracy. (can be also external unseen data)num_leaves: Increasing its value will increase accuracy as the splitting is taking leaf-wise but overfitting also may occur.max_bin: High value will have a major impact on accuracy but will eventually go to overfitting." }, { "code": null, "e": 29599, "s": 29503, "text": "More Training Data Added to the Model can increase accuracy. (can be also external unseen data)" }, { "code": null, "e": 29724, "s": 29599, "text": "num_leaves: Increasing its value will increase accuracy as the splitting is taking leaf-wise but overfitting also may occur." }, { "code": null, "e": 29820, "s": 29724, "text": "max_bin: High value will have a major impact on accuracy but will eventually go to overfitting." }, { "code": null, "e": 30309, "s": 29820, "text": "A very popular and in-demand algorithm often referred to as the winning algorithm for various competitions on different platforms. XGBOOST stands for Extreme Gradient Boosting. This algorithm is an improved version of the Gradient Boosting Algorithm. The base algorithm is Gradient Boosting Decision Tree Algorithm. Its powerful predictive power and easy to implement approach has made it float throughout many machine learning notebooks. Some key points of the algorithm are as follows:" }, { "code": null, "e": 30654, "s": 30309, "text": "It does not build the full tree structure but builds it greedily.As compared to LightGBM it splits level-wise rather than leaf-wise.In Gradient Boosting, negative gradients are taken into account to optimize the loss function but here Taylor’s expansion is taken into account.The regularization term penalizes from building complex tree models." }, { "code": null, "e": 30720, "s": 30654, "text": "It does not build the full tree structure but builds it greedily." }, { "code": null, "e": 30788, "s": 30720, "text": "As compared to LightGBM it splits level-wise rather than leaf-wise." }, { "code": null, "e": 30933, "s": 30788, "text": "In Gradient Boosting, negative gradients are taken into account to optimize the loss function but here Taylor’s expansion is taken into account." }, { "code": null, "e": 31002, "s": 30933, "text": "The regularization term penalizes from building complex tree models." }, { "code": null, "e": 31081, "s": 31002, "text": "Some parameters which can be tuned to increase the performance are as follows:" }, { "code": null, "e": 31123, "s": 31081, "text": "General Parameters include the following:" }, { "code": null, "e": 31339, "s": 31123, "text": "booster: It has 2 options — gbtree and gblinear.silent: If kept to 1 no running messages will be shown while the code is executing.nthread: Mainly used for parallel processing. The number of cores is specified here." }, { "code": null, "e": 31388, "s": 31339, "text": "booster: It has 2 options — gbtree and gblinear." }, { "code": null, "e": 31472, "s": 31388, "text": "silent: If kept to 1 no running messages will be shown while the code is executing." }, { "code": null, "e": 31557, "s": 31472, "text": "nthread: Mainly used for parallel processing. The number of cores is specified here." }, { "code": null, "e": 31599, "s": 31557, "text": "Booster Parameters include the following:" }, { "code": null, "e": 31925, "s": 31599, "text": "eta: Makes model robust by shrinkage of weights at each step.max_depth: Should be set accordingly to avoid overfitting.max_leaf_nodes: If this parameter is defined then the model will ignore max_depth.gamma: Specifies the minimum loss reduction which is required to make a split.lambda: L2 regularization term on the weights." }, { "code": null, "e": 31987, "s": 31925, "text": "eta: Makes model robust by shrinkage of weights at each step." }, { "code": null, "e": 32046, "s": 31987, "text": "max_depth: Should be set accordingly to avoid overfitting." }, { "code": null, "e": 32129, "s": 32046, "text": "max_leaf_nodes: If this parameter is defined then the model will ignore max_depth." }, { "code": null, "e": 32208, "s": 32129, "text": "gamma: Specifies the minimum loss reduction which is required to make a split." }, { "code": null, "e": 32255, "s": 32208, "text": "lambda: L2 regularization term on the weights." }, { "code": null, "e": 32303, "s": 32255, "text": "Learning Task Parameters include the following:" }, { "code": null, "e": 32373, "s": 32303, "text": "1) objective: This will define the loss function which is to be used." }, { "code": null, "e": 32486, "s": 32373, "text": "binary: logistic –logistic regression for binary classification, returns predicted probability (not the class) " }, { "code": null, "e": 32605, "s": 32486, "text": "multi: softmax –multiclass classification using the softmax objective, returns predicted class (not the probabilities)" }, { "code": null, "e": 32688, "s": 32605, "text": "2) seed: the default value set for this is zero. Can be used for parameter tuning." }, { "code": null, "e": 32983, "s": 32688, "text": "So, we have gone through the basics of the algorithm and the parameters which need to be tuned for the respective algorithms. Now we will take a dataset and then compare both the algorithms on the basis of accuracy and execution time. Below is the Dataset Description which we are going to use:" }, { "code": null, "e": 33004, "s": 32983, "text": "Dataset Description:" }, { "code": null, "e": 33661, "s": 33004, "text": "The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers were selected for generating the training data and 30% for the test data." }, { "code": null, "e": 34269, "s": 33661, "text": "The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low-frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain." }, { "code": null, "e": 34365, "s": 34269, "text": "Data link: https://github.com/pranavkotak8/Datasets/blob/master/smartphone_activity_dataset.zip" }, { "code": null, "e": 34393, "s": 34365, "text": "Python code implementation:" }, { "code": null, "e": 34401, "s": 34393, "text": "Python3" }, { "code": "# Importing the basic librariespip install pandasimport timeimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport gc gc.enable() # Importing LGBM and XGBOOSTimport lightgbm as lgbimport xgboost as xgb # Reading the Data and Inspecting itdata=pd.read_csv('/content/drive/MyDrive/GeeksforGeeks_Datasets/smartphone_activity_dataset.csv')data", "e": 34803, "s": 34401, "text": null }, { "code": null, "e": 34811, "s": 34803, "text": "Python3" }, { "code": "# Checking for missing values across the 562 features of the datasetdata.isna().sum()*100/len(data) # Checking for Target Distributionsns.countplot(data['activity'])plt.show()", "e": 34988, "s": 34811, "text": null }, { "code": null, "e": 34996, "s": 34988, "text": "Python3" }, { "code": "# Saving the target variable(dependent variable) to target # variable and dropping it from the original \"data\" dataframetarget=data['activity']data.drop(columns={'activity'},inplace=True) # As the dataset contains all numerical features and also # the target classes are also encoded there is no more preprocessing# needed at this stage. There are no missing values in the # dataset hence no missing data imputation is being needed. # Let us split the dataset and move to the modeling part. # Splitting the Dataset into Training and Testing Datasetfrom sklearn.model_selection import train_test_splitX_train,X_test,y_train,y_test=train_test_split( data,target,test_size=0.15,random_state=100) # Applying the XGBOOST Model# Setting Parameters required for XGBOOST Model # and Training the Model # Starting to track the Timestart = time.time() xg=xgb.XGBClassifier(max_depth=7,learning_rate=0.05, silent=1,eta=1,objective='multi:softprob', num_round=50,num_classes=6) # Setting the Parameters. More parameters can be set# according to the requirement. # Here we have set the main parameters. # Fitting the Modelxg.fit(X_train,y_train) # Stopping the tracking of time stop = time.time() exec_time_xgb=stop-start # Measuring the time taken for the model to build exec_time_xgb # Predicting the Output Classypred_xgb=xg.predict(X_test) ypred_xgb # Getting the Accuracy Score for the XGBOOST Modelfrom sklearn.metrics import accuracy_scoreaccuracy_xgb = accuracy_score(y_test,ypred_xgb) # Setting the Parameters and Training data for LightGBM Modeldata_train = lgb.Dataset(X_train,label = y_train)params= {} # Usually set between 0 to 1.params['learning_rate']=0.5 # GradientBoostingDecisionTreeparams['boosting_type']='gbdt' # Multi-class since the target class has 6 classes.params['objective']='multiclass' # Metric for multi-classparams['metric']='multi_logloss' params['max_depth']=7params['num_class']=7 # This value is not inclusive of the end value.# Hence we have 6 classes the value is set to 7. # Training the LightGBM Modelnum_round =50start = time.time()lgbm = lgb.train(params,data_train,num_round)stop = time.time() #Execution time of the LightGBM Modelexec_time_lgbm = stop-startexec_time_lgbm # Predicting the output on the Test Dataset ypred_lgbm = lgbm.predict(X_test)ypred_lgbmy_pred_lgbm_class = [np.argmax(line) for line in ypred_lgbm]", "e": 37438, "s": 34996, "text": null }, { "code": null, "e": 37446, "s": 37438, "text": "Python3" }, { "code": "# Accuracy Score for the LightGBM Modelfrom sklearn.metrics import accuracy_scoreaccuracy_lgbm=accuracy_score(y_test,y_pred_lgbm_class) # Comparing the Accuracy and Execution Time for both the Algorithmscomparison = {'Accuracy:':(accuracy_lgbm,accuracy_xgb),\\ 'Execution Time(in seconds):':(exec_time_lgbm,exec_time_xgb)}LGBM_XGB = pd.DataFrame(comparison)LGBM_XGB .index = ['LightGBM','XGBoost']LGBM_XGB # On comparison we notice that LightGBM is # faster and gives better accuracy.comp_ratio=(203.594708/29.443264)comp_ratioprint(\"LightGBM is \"+\" \"+str(np.ceil(comp_ratio))+\" \"+\\ str(\"times\")+\" \"+\"faster than XGBOOST Algorithm\")", "e": 38098, "s": 37446, "text": null }, { "code": null, "e": 38112, "s": 38098, "text": "Final Output:" }, { "code": null, "e": 38129, "s": 38112, "text": "Machine Learning" }, { "code": null, "e": 38136, "s": 38129, "text": "Python" }, { "code": null, "e": 38153, "s": 38136, "text": "Machine Learning" }, { "code": null, "e": 38251, "s": 38153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38260, "s": 38251, "text": "Comments" }, { "code": null, "e": 38273, "s": 38260, "text": "Old Comments" }, { "code": null, "e": 38306, "s": 38273, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 38345, "s": 38306, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 38380, "s": 38345, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 38436, "s": 38380, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 38469, "s": 38436, "text": "Normalization vs Standardization" }, { "code": null, "e": 38497, "s": 38469, "text": "Read JSON file using Python" }, { "code": null, "e": 38547, "s": 38497, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 38569, "s": 38547, "text": "Python map() function" } ]
Creating a Table in MySQL to set current date as default
Following is the syntax for creating a table and adding DEFAULT constraint to set default value − CREATE TABLE yourTableName ( yourColumnName1 dataType not null , yourColumnName2 dataType default anyValue, . . . N );; Let us create a table wherein we have set “employee_joining_date” with default constraint for current date as default − mysql> create table demo43 −> ( −> employee_id int not null auto_increment primary key, −> employee_name varchar(40) not null, −> employee_status varchar(60) default "NOT JOINED", −> employee_joining_date date default(CURRENT_DATE) −> ); Query OK, 0 rows affected (0.66 sec) Insert some records into the table with the help of insert command − mysql> insert into demo43(employee_name,employee_status,employee_joining_date) values('John','JOINED','2020-05-10'); Query OK, 1 row affected (0.12 sec) mysql> insert into demo43(employee_name,employee_status,employee_joining_date) values('David','JOINED','2020-10-12'); Query OK, 1 row affected (0.21 sec) mysql> insert into demo43(employee_name) values('Bob'); Query OK, 1 row affected (0.15 sec) Display records from the table using select statement − mysql> select *from demo43; This will produce the following output − +-------------+---------------+-----------------+-----------------------+ | employee_id | employee_name | employee_status | employee_joining_date | +-------------+---------------+-----------------+-----------------------+ | 1 | John | JOINED | 2020−05−10 | | 2 | David | JOINED | 2020−10−12 | | 3 | Bob | NOT JOINED | 2020−10−31 | +-------------+---------------+-----------------+-----------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1160, "s": 1062, "text": "Following is the syntax for creating a table and adding DEFAULT constraint to set default value −" }, { "code": null, "e": 1280, "s": 1160, "text": "CREATE TABLE yourTableName\n(\nyourColumnName1 dataType not null ,\nyourColumnName2 dataType default anyValue,\n.\n.\n.\nN\n);;" }, { "code": null, "e": 1400, "s": 1280, "text": "Let us create a table wherein we have set “employee_joining_date” with default constraint for current date as default −" }, { "code": null, "e": 1675, "s": 1400, "text": "mysql> create table demo43\n−> (\n−> employee_id int not null auto_increment primary key,\n−> employee_name varchar(40) not null,\n−> employee_status varchar(60) default \"NOT JOINED\",\n−> employee_joining_date date default(CURRENT_DATE)\n−> );\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1744, "s": 1675, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 2143, "s": 1744, "text": "mysql> insert into demo43(employee_name,employee_status,employee_joining_date) values('John','JOINED','2020-05-10');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into demo43(employee_name,employee_status,employee_joining_date) values('David','JOINED','2020-10-12');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into demo43(employee_name) values('Bob');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2199, "s": 2143, "text": "Display records from the table using select statement −" }, { "code": null, "e": 2227, "s": 2199, "text": "mysql> select *from demo43;" }, { "code": null, "e": 2268, "s": 2227, "text": "This will produce the following output −" }, { "code": null, "e": 2811, "s": 2268, "text": "+-------------+---------------+-----------------+-----------------------+\n| employee_id | employee_name | employee_status | employee_joining_date |\n+-------------+---------------+-----------------+-----------------------+\n| 1 | John | JOINED | 2020−05−10 |\n| 2 | David | JOINED | 2020−10−12 |\n| 3 | Bob | NOT JOINED | 2020−10−31 |\n+-------------+---------------+-----------------+-----------------------+\n3 rows in set (0.00 sec)" } ]
Semi-Supervised Learning with K-Means Clustering | by Yufeng | Towards Data Science
Supervised learning and unsupervised learning are the two major tasks in machine learning. Supervised learning models are used when the output of all the instances is available, whereas unsupervised learning is applied when we don’t have the “true label”. Even though the exploration of unsupervised learning has huge potential in future research, supervised learning is still dominating the field. However, it’s common that we need to build a supervised learning model when we don’t have sufficient labeled samples in our data. In such a case, the semi-supervised learning can be taken into consideration. The idea is to build a supervised learning model based on the output of the unsupervised learning process. I would like to go through a simple example. I collected the NBA players’ per game stats in the season of 2018–2019. The players’ positions are defined as the conventional basketball positions: point guard (PG), shooting guard (SG), small forward (SF), power forward (PF), and center (C). Before the modeling process, I did some pre-processing on the dataset. First, remove the players who played less than 10 minutes per game. Then, fill NA values with 0 (For example, center players never shoot 3 pointers). df_used = df_num.loc[df.MP.astype('float32') >= 10]df_used.fillna(0,inplace=True) After the pre-processing, the data looks like below: df_used.head() Then I separated the data to the training and testing set. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df_used, labels_) If all the labels (players’ positions) are given, it’s a simple supervised classification problem. I fitted a simple logistic regression model to the training dataset. from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalerpipeline = Pipeline([ ("scaler", StandardScaler()), ("log_reg", LogisticRegression()), ])pipeline.fit(X_train, y_train) I evaluated the model on the testing dataset. pipeline.score(X_test, y_test) This procedure gives 0.644, which means 64.4% of the predictions are correct. From this result, we know that the room for improvement on the classifier is very large. However, I am not focused on the classifier development in this article. I am going to talk about the situation when the data labels are only partially seen. If I am only allowed to see the position information of 100 players in the training data, how will it change the performance of the model? There are a lot of strategies that can be applied to select the 100 players as the input of the classifier. The first strategy is to randomly choose 100 players, the first 100 players, for example. I checked the performance of the logistic regression model trained only on this subset. n_labeled = 100pipeline.fit(X_train[:n_labeled], y_train[:n_labeled])pipeline.score(X_test, y_test) This time I got only 56.8% of the accuracy. It is as expected because I have only seen a subset of the true labels. However, can we improve the performance by selecting a different subset of 100 labels? The answer is yes. The second strategy is to apply the unsupervised learning procedure to cluster the data in the entire training dataset, and to expose the labels of the representative of each cluster. In this way, we can assume the data points that are close to each other in the clustering space should have a high chance to own the same label. In another word, the players who have similar game stats should play the same position on the court. from sklearn.cluster import KMeansk=100kmeans = KMeans(n_clusters=k)X_dist = kmeans.fit_transform(X_train) representative_idx = np.argmin(X_dist, axis=0) X_representative = X_train.values[representative_idx] In the code, X_dist is the distance matrix to the cluster centroids. representative_idx is the index of the data points that are closest to each cluster centroid. After selecting the representatives in the feature space, we collected the true labels of these data points. Here, I just need to extract the labels from the raw data. y_representative = [list(y_train)[x] for x in representative_idx] However, please note that the practical situation is that we don’t know any true label, so it’s necessary to manually label these selected data points. Let’s check the performance of the model trained on this subset of training data. pipeline.fit(X_representative, y_representative)pipeline.score(X_test, y_test) I got 59.6% accuracy! Even though it is not comparable to that of the model trained on the entire training set, it’s better than that of the randomly chosen 100 data points. With the evolution of basketball, it’s becoming harder and harder to tell the player’s positions based on their game stats. That’s why we only have an accuracy of around 60%. Even though the performance of the model trained on the cluster centroids is better than that trained on random data points, the improvement is limited. It could be interpreted as that the game stats of the players in the same position could vary a lot in the current NBA. hands-on machine learning with scikit-learn keras and tensorflowBasketball Reference. hands-on machine learning with scikit-learn keras and tensorflow Basketball Reference. I hope you find this short article useful! Cheers!
[ { "code": null, "e": 428, "s": 172, "text": "Supervised learning and unsupervised learning are the two major tasks in machine learning. Supervised learning models are used when the output of all the instances is available, whereas unsupervised learning is applied when we don’t have the “true label”." }, { "code": null, "e": 701, "s": 428, "text": "Even though the exploration of unsupervised learning has huge potential in future research, supervised learning is still dominating the field. However, it’s common that we need to build a supervised learning model when we don’t have sufficient labeled samples in our data." }, { "code": null, "e": 886, "s": 701, "text": "In such a case, the semi-supervised learning can be taken into consideration. The idea is to build a supervised learning model based on the output of the unsupervised learning process." }, { "code": null, "e": 931, "s": 886, "text": "I would like to go through a simple example." }, { "code": null, "e": 1175, "s": 931, "text": "I collected the NBA players’ per game stats in the season of 2018–2019. The players’ positions are defined as the conventional basketball positions: point guard (PG), shooting guard (SG), small forward (SF), power forward (PF), and center (C)." }, { "code": null, "e": 1396, "s": 1175, "text": "Before the modeling process, I did some pre-processing on the dataset. First, remove the players who played less than 10 minutes per game. Then, fill NA values with 0 (For example, center players never shoot 3 pointers)." }, { "code": null, "e": 1478, "s": 1396, "text": "df_used = df_num.loc[df.MP.astype('float32') >= 10]df_used.fillna(0,inplace=True)" }, { "code": null, "e": 1531, "s": 1478, "text": "After the pre-processing, the data looks like below:" }, { "code": null, "e": 1546, "s": 1531, "text": "df_used.head()" }, { "code": null, "e": 1605, "s": 1546, "text": "Then I separated the data to the training and testing set." }, { "code": null, "e": 1727, "s": 1605, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df_used, labels_)" }, { "code": null, "e": 1895, "s": 1727, "text": "If all the labels (players’ positions) are given, it’s a simple supervised classification problem. I fitted a simple logistic regression model to the training dataset." }, { "code": null, "e": 2169, "s": 1895, "text": "from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalerpipeline = Pipeline([ (\"scaler\", StandardScaler()), (\"log_reg\", LogisticRegression()), ])pipeline.fit(X_train, y_train)" }, { "code": null, "e": 2215, "s": 2169, "text": "I evaluated the model on the testing dataset." }, { "code": null, "e": 2246, "s": 2215, "text": "pipeline.score(X_test, y_test)" }, { "code": null, "e": 2486, "s": 2246, "text": "This procedure gives 0.644, which means 64.4% of the predictions are correct. From this result, we know that the room for improvement on the classifier is very large. However, I am not focused on the classifier development in this article." }, { "code": null, "e": 2571, "s": 2486, "text": "I am going to talk about the situation when the data labels are only partially seen." }, { "code": null, "e": 2818, "s": 2571, "text": "If I am only allowed to see the position information of 100 players in the training data, how will it change the performance of the model? There are a lot of strategies that can be applied to select the 100 players as the input of the classifier." }, { "code": null, "e": 2996, "s": 2818, "text": "The first strategy is to randomly choose 100 players, the first 100 players, for example. I checked the performance of the logistic regression model trained only on this subset." }, { "code": null, "e": 3096, "s": 2996, "text": "n_labeled = 100pipeline.fit(X_train[:n_labeled], y_train[:n_labeled])pipeline.score(X_test, y_test)" }, { "code": null, "e": 3212, "s": 3096, "text": "This time I got only 56.8% of the accuracy. It is as expected because I have only seen a subset of the true labels." }, { "code": null, "e": 3318, "s": 3212, "text": "However, can we improve the performance by selecting a different subset of 100 labels? The answer is yes." }, { "code": null, "e": 3647, "s": 3318, "text": "The second strategy is to apply the unsupervised learning procedure to cluster the data in the entire training dataset, and to expose the labels of the representative of each cluster. In this way, we can assume the data points that are close to each other in the clustering space should have a high chance to own the same label." }, { "code": null, "e": 3748, "s": 3647, "text": "In another word, the players who have similar game stats should play the same position on the court." }, { "code": null, "e": 3956, "s": 3748, "text": "from sklearn.cluster import KMeansk=100kmeans = KMeans(n_clusters=k)X_dist = kmeans.fit_transform(X_train) representative_idx = np.argmin(X_dist, axis=0) X_representative = X_train.values[representative_idx]" }, { "code": null, "e": 4119, "s": 3956, "text": "In the code, X_dist is the distance matrix to the cluster centroids. representative_idx is the index of the data points that are closest to each cluster centroid." }, { "code": null, "e": 4287, "s": 4119, "text": "After selecting the representatives in the feature space, we collected the true labels of these data points. Here, I just need to extract the labels from the raw data." }, { "code": null, "e": 4353, "s": 4287, "text": "y_representative = [list(y_train)[x] for x in representative_idx]" }, { "code": null, "e": 4505, "s": 4353, "text": "However, please note that the practical situation is that we don’t know any true label, so it’s necessary to manually label these selected data points." }, { "code": null, "e": 4587, "s": 4505, "text": "Let’s check the performance of the model trained on this subset of training data." }, { "code": null, "e": 4666, "s": 4587, "text": "pipeline.fit(X_representative, y_representative)pipeline.score(X_test, y_test)" }, { "code": null, "e": 4840, "s": 4666, "text": "I got 59.6% accuracy! Even though it is not comparable to that of the model trained on the entire training set, it’s better than that of the randomly chosen 100 data points." }, { "code": null, "e": 5015, "s": 4840, "text": "With the evolution of basketball, it’s becoming harder and harder to tell the player’s positions based on their game stats. That’s why we only have an accuracy of around 60%." }, { "code": null, "e": 5288, "s": 5015, "text": "Even though the performance of the model trained on the cluster centroids is better than that trained on random data points, the improvement is limited. It could be interpreted as that the game stats of the players in the same position could vary a lot in the current NBA." }, { "code": null, "e": 5374, "s": 5288, "text": "hands-on machine learning with scikit-learn keras and tensorflowBasketball Reference." }, { "code": null, "e": 5439, "s": 5374, "text": "hands-on machine learning with scikit-learn keras and tensorflow" }, { "code": null, "e": 5461, "s": 5439, "text": "Basketball Reference." } ]
Entity Level Evaluation for NER Task | by Xu LIANG | Towards Data Science
When we evaluate the NER (Named Entity Recognition) task, there are two kinds of methods, the token-level method, and the entity-level method. For example, we have this sentence predicted below: “Foreign Ministry spokesman Shen Guofang told Reuters”. If we use the token-level evaluation, the token “Shen” is correct, and the token “Guofang” is wrong. But if we use the entity-level evaluation, “Shen Guofang” is a complete named entity, so the predictions for “Shen” and “Guofang” have to be “PER” and “PER”. Otherwise, this is the wrong predicted entity, even token “Shen” is predicted as “PER”. So which method we should use? The answer is the entity-level evaluation. As the task name “Named Entity” indicates, what we really care about is how our model predicts the whole entity, instead of separate tokens. I usually use the sklearn-crfsuite to implement the CRF model, which is a great library. But one shortcoming of it is the evaluation method used is the token-level evaluation. precision recall f1-score support B-LOC 0.775 0.757 0.766 1084 I-LOC 0.601 0.631 0.616 325 B-MISC 0.698 0.499 0.582 339 I-MISC 0.644 0.567 0.603 557 B-ORG 0.795 0.801 0.798 1400 I-ORG 0.831 0.773 0.801 1104 B-PER 0.812 0.876 0.843 735 I-PER 0.873 0.931 0.901 634avg / total 0.779 0.764 0.770 6178 We want to change these to result in entity-level evaluation like below: precision recall f1-score support LOC 0.775 0.757 0.766 1084 MISC 0.698 0.499 0.582 339 ORG 0.795 0.801 0.798 1400 PER 0.812 0.876 0.843 735avg/total 0.779 0.764 0.770 6178 Instead of using the official evaluation method, I recommend using this tool, seqeval. This library could run the evaluation at entity-level. >>> from seqeval.metrics import accuracy_score>>> from seqeval.metrics import classification_report>>> from seqeval.metrics import f1_score>>> >>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]>>>>>> f1_score(y_true, y_pred)0.50>>> accuracy_score(y_true, y_pred)0.80>>> classification_report(y_true, y_pred) precision recall f1-score support MISC 0.00 0.00 0.00 1 PER 1.00 1.00 1.00 1 micro avg 0.50 0.50 0.50 2 macro avg 0.50 0.50 0.50 2 Ok, we already have a great tool to solve the metric calculation, why do we have to care about the calculations behind the scenes? Give a man a fish, and you feed him for a day; teach a man to fish, and you feed him for a lifetime. The confusion matrix is an important topic in the machine learning field, but there are few posts about how to calculate it for the NER task, so I hope this post can clear the uncertainty. First, we write the confusion matrix table: And then calculate precision, recall, and F1: We use the above example to fill the confusion matrix table: The “Foreign Ministry” is counted as an FN, and “Reuters” is counted as a TP. These two are easy to distinguish. The tricky one is when the prediction makes the boundary error. If the model makes the boundary error, we count it as two errors. For example, we count the entity “Shen Guofang” as two errors, one is the FN, and one is FP. We ignore the entity type and fill the confusion matrix table like this: And then calculate the matrices: We ignore the entity type and only calculate the confusion matrix for one sentence in the above example. For better generalization, the code implementation has to consider the entity type and calculate the confusion matrix for all sentences. Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu.com
[ { "code": null, "e": 770, "s": 172, "text": "When we evaluate the NER (Named Entity Recognition) task, there are two kinds of methods, the token-level method, and the entity-level method. For example, we have this sentence predicted below: “Foreign Ministry spokesman Shen Guofang told Reuters”. If we use the token-level evaluation, the token “Shen” is correct, and the token “Guofang” is wrong. But if we use the entity-level evaluation, “Shen Guofang” is a complete named entity, so the predictions for “Shen” and “Guofang” have to be “PER” and “PER”. Otherwise, this is the wrong predicted entity, even token “Shen” is predicted as “PER”." }, { "code": null, "e": 801, "s": 770, "text": "So which method we should use?" }, { "code": null, "e": 985, "s": 801, "text": "The answer is the entity-level evaluation. As the task name “Named Entity” indicates, what we really care about is how our model predicts the whole entity, instead of separate tokens." }, { "code": null, "e": 1161, "s": 985, "text": "I usually use the sklearn-crfsuite to implement the CRF model, which is a great library. But one shortcoming of it is the evaluation method used is the token-level evaluation." }, { "code": null, "e": 1669, "s": 1161, "text": "precision recall f1-score support B-LOC 0.775 0.757 0.766 1084 I-LOC 0.601 0.631 0.616 325 B-MISC 0.698 0.499 0.582 339 I-MISC 0.644 0.567 0.603 557 B-ORG 0.795 0.801 0.798 1400 I-ORG 0.831 0.773 0.801 1104 B-PER 0.812 0.876 0.843 735 I-PER 0.873 0.931 0.901 634avg / total 0.779 0.764 0.770 6178" }, { "code": null, "e": 1742, "s": 1669, "text": "We want to change these to result in entity-level evaluation like below:" }, { "code": null, "e": 2032, "s": 1742, "text": "precision recall f1-score support LOC 0.775 0.757 0.766 1084 MISC 0.698 0.499 0.582 339 ORG 0.795 0.801 0.798 1400 PER 0.812 0.876 0.843 735avg/total 0.779 0.764 0.770 6178" }, { "code": null, "e": 2174, "s": 2032, "text": "Instead of using the official evaluation method, I recommend using this tool, seqeval. This library could run the evaluation at entity-level." }, { "code": null, "e": 2877, "s": 2174, "text": ">>> from seqeval.metrics import accuracy_score>>> from seqeval.metrics import classification_report>>> from seqeval.metrics import f1_score>>> >>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]>>>>>> f1_score(y_true, y_pred)0.50>>> accuracy_score(y_true, y_pred)0.80>>> classification_report(y_true, y_pred) precision recall f1-score support MISC 0.00 0.00 0.00 1 PER 1.00 1.00 1.00 1 micro avg 0.50 0.50 0.50 2 macro avg 0.50 0.50 0.50 2" }, { "code": null, "e": 3008, "s": 2877, "text": "Ok, we already have a great tool to solve the metric calculation, why do we have to care about the calculations behind the scenes?" }, { "code": null, "e": 3109, "s": 3008, "text": "Give a man a fish, and you feed him for a day; teach a man to fish, and you feed him for a lifetime." }, { "code": null, "e": 3298, "s": 3109, "text": "The confusion matrix is an important topic in the machine learning field, but there are few posts about how to calculate it for the NER task, so I hope this post can clear the uncertainty." }, { "code": null, "e": 3342, "s": 3298, "text": "First, we write the confusion matrix table:" }, { "code": null, "e": 3388, "s": 3342, "text": "And then calculate precision, recall, and F1:" }, { "code": null, "e": 3449, "s": 3388, "text": "We use the above example to fill the confusion matrix table:" }, { "code": null, "e": 3785, "s": 3449, "text": "The “Foreign Ministry” is counted as an FN, and “Reuters” is counted as a TP. These two are easy to distinguish. The tricky one is when the prediction makes the boundary error. If the model makes the boundary error, we count it as two errors. For example, we count the entity “Shen Guofang” as two errors, one is the FN, and one is FP." }, { "code": null, "e": 3858, "s": 3785, "text": "We ignore the entity type and fill the confusion matrix table like this:" }, { "code": null, "e": 3891, "s": 3858, "text": "And then calculate the matrices:" }, { "code": null, "e": 4133, "s": 3891, "text": "We ignore the entity type and only calculate the confusion matrix for one sentence in the above example. For better generalization, the code implementation has to consider the entity type and calculate the confusion matrix for all sentences." } ]
Access metadata of various audio and video file formats using Python - tinytag library - GeeksforGeeks
12 Nov, 2020 Metadata extraction is a necessary task while making music players or other related applications. The best python library to read music metadata of various audio and video file formats is tinytag. This library allows you to access metadata of various audio and video file formats like mp3, m4a, mp4, flac, wav etc. The list of attributes you can access the album, album artist, artist, audio_offset, bitrate, comment, composer, disc, disc_total, duration, filesize, genre, sample rate, title, track, track_total, and year. Note that you can only read and not edit the metadata. This module does not come built-in with Python. To install this module type the below command in the terminal. pip install tinytag This library supports python 2.7+ and 3.4+ and pypy. First, import the Tinytag method from the tinytag library. Then, pass the file name to the Tinytag.get() method if it is present in the same directory, if not, pass the full path and assign this to any variable. Now, the attributes can be accessed using the following format: variable_name.attribute_name. You can check if the file format you are using is supported or not using the method: TinyTag.is_supported(filename) which returns a bool value. Note: Missing metadata will be shown as None If you’d like to follow along, the download link for the audio and video file used in this article is given: m4a(audio) and mp4(video). Example 1(Audio): Python3 # Python3 program to illustrate# accessing of audio metadata# using tinytag library # Import Tinytag method from# tinytag libraryfrom tinytag import TinyTag # Pass the filename into the# Tinytag.get() method and store# the result in audio variableaudio = TinyTag.get("GeeksForGeeks_Audio.m4a") # Use the attributes# and Displayprint("Title:" + audio.title)print("Artist: " + audio.artist)print("Genre:" + audio.genre)print("Year Released: " + audio.year)print("Bitrate:" + str(audio.bitrate) + " kBits/s")print("Composer: " + audio.composer)print("Filesize: " + str(audio.filesize) + " bytes")print("AlbumArtist: " + audio.albumartist)print("Duration: " + str(audio.duration) + " seconds")print("TrackTotal: " + str(audio.track_total)) Output: Title:GeeksForGeeks_Audio Artist: Neeraj Rana/GFG Genre:Geek Music Year Released: 2020 Bitrate:182.72 kBits/s Composer: GeeksForGeeks Team Filesize: 63076 bytes AlbumArtist: Voice Recorder Duration: 2.7306458333333334 seconds TrackTotal: None Example 2(Video): Python3 # Python3 program to illustrate# accessing of video metadata# using tinytag library # Import Tinytag method from# tinytag libraryfrom tinytag import TinyTag # Pass the filename into the# Tinytag.get() method and store# the result in audio variablevideo = TinyTag.get("GeeksForGeeks_Video.mp4") # Use the attributes# and displayprint("Title:" + video.title)print("Artist: " + video.artist)print("Genre:" + video.genre)print("Year Released: " + video.year)print("Bitrate:" + str(video.bitrate) + " kBits/s")print("Composer: " + video.composer)print("Filesize: " + str(video.filesize) + " bytes")print("AlbumArtist: " + str(video.albumartist))print("Duration: " + str(video.duration) + " seconds")print("TrackTotal: " + str(video.track_total)) Output: Title:GeeksForGeeks_Video Artist: Neeraj Rana/GFG Genre:Geek Video Year Released: 2020 Bitrate:294651.393 kBits/s Composer: GFG Video Team Filesize: 511940 bytes AlbumArtist: None Duration: 1.8239333333333334 seconds TrackTotal: None If you come across any TypeError, you can use typecasting. python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n12 Nov, 2020" }, { "code": null, "e": 24216, "s": 23901, "text": "Metadata extraction is a necessary task while making music players or other related applications. The best python library to read music metadata of various audio and video file formats is tinytag. This library allows you to access metadata of various audio and video file formats like mp3, m4a, mp4, flac, wav etc." }, { "code": null, "e": 24479, "s": 24216, "text": "The list of attributes you can access the album, album artist, artist, audio_offset, bitrate, comment, composer, disc, disc_total, duration, filesize, genre, sample rate, title, track, track_total, and year. Note that you can only read and not edit the metadata." }, { "code": null, "e": 24590, "s": 24479, "text": "This module does not come built-in with Python. To install this module type the below command in the terminal." }, { "code": null, "e": 24611, "s": 24590, "text": "pip install tinytag\n" }, { "code": null, "e": 24664, "s": 24611, "text": "This library supports python 2.7+ and 3.4+ and pypy." }, { "code": null, "e": 24970, "s": 24664, "text": "First, import the Tinytag method from the tinytag library. Then, pass the file name to the Tinytag.get() method if it is present in the same directory, if not, pass the full path and assign this to any variable. Now, the attributes can be accessed using the following format: variable_name.attribute_name." }, { "code": null, "e": 25114, "s": 24970, "text": "You can check if the file format you are using is supported or not using the method: TinyTag.is_supported(filename) which returns a bool value." }, { "code": null, "e": 25159, "s": 25114, "text": "Note: Missing metadata will be shown as None" }, { "code": null, "e": 25295, "s": 25159, "text": "If you’d like to follow along, the download link for the audio and video file used in this article is given: m4a(audio) and mp4(video)." }, { "code": null, "e": 25313, "s": 25295, "text": "Example 1(Audio):" }, { "code": null, "e": 25321, "s": 25313, "text": "Python3" }, { "code": "# Python3 program to illustrate# accessing of audio metadata# using tinytag library # Import Tinytag method from# tinytag libraryfrom tinytag import TinyTag # Pass the filename into the# Tinytag.get() method and store# the result in audio variableaudio = TinyTag.get(\"GeeksForGeeks_Audio.m4a\") # Use the attributes# and Displayprint(\"Title:\" + audio.title)print(\"Artist: \" + audio.artist)print(\"Genre:\" + audio.genre)print(\"Year Released: \" + audio.year)print(\"Bitrate:\" + str(audio.bitrate) + \" kBits/s\")print(\"Composer: \" + audio.composer)print(\"Filesize: \" + str(audio.filesize) + \" bytes\")print(\"AlbumArtist: \" + audio.albumartist)print(\"Duration: \" + str(audio.duration) + \" seconds\")print(\"TrackTotal: \" + str(audio.track_total))", "e": 26060, "s": 25321, "text": null }, { "code": null, "e": 26068, "s": 26060, "text": "Output:" }, { "code": null, "e": 26312, "s": 26068, "text": "Title:GeeksForGeeks_Audio\nArtist: Neeraj Rana/GFG\nGenre:Geek Music\nYear Released: 2020\nBitrate:182.72 kBits/s\nComposer: GeeksForGeeks Team\nFilesize: 63076 bytes\nAlbumArtist: Voice Recorder\nDuration: 2.7306458333333334 seconds\nTrackTotal: None\n" }, { "code": null, "e": 26330, "s": 26312, "text": "Example 2(Video):" }, { "code": null, "e": 26338, "s": 26330, "text": "Python3" }, { "code": "# Python3 program to illustrate# accessing of video metadata# using tinytag library # Import Tinytag method from# tinytag libraryfrom tinytag import TinyTag # Pass the filename into the# Tinytag.get() method and store# the result in audio variablevideo = TinyTag.get(\"GeeksForGeeks_Video.mp4\") # Use the attributes# and displayprint(\"Title:\" + video.title)print(\"Artist: \" + video.artist)print(\"Genre:\" + video.genre)print(\"Year Released: \" + video.year)print(\"Bitrate:\" + str(video.bitrate) + \" kBits/s\")print(\"Composer: \" + video.composer)print(\"Filesize: \" + str(video.filesize) + \" bytes\")print(\"AlbumArtist: \" + str(video.albumartist))print(\"Duration: \" + str(video.duration) + \" seconds\")print(\"TrackTotal: \" + str(video.track_total))", "e": 27082, "s": 26338, "text": null }, { "code": null, "e": 27090, "s": 27082, "text": "Output:" }, { "code": null, "e": 27325, "s": 27090, "text": "Title:GeeksForGeeks_Video\nArtist: Neeraj Rana/GFG\nGenre:Geek Video\nYear Released: 2020\nBitrate:294651.393 kBits/s\nComposer: GFG Video Team\nFilesize: 511940 bytes\nAlbumArtist: None\nDuration: 1.8239333333333334 seconds\nTrackTotal: None\n" }, { "code": null, "e": 27384, "s": 27325, "text": "If you come across any TypeError, you can use typecasting." }, { "code": null, "e": 27399, "s": 27384, "text": "python-modules" }, { "code": null, "e": 27406, "s": 27399, "text": "Python" }, { "code": null, "e": 27504, "s": 27406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27513, "s": 27504, "text": "Comments" }, { "code": null, "e": 27526, "s": 27513, "text": "Old Comments" }, { "code": null, "e": 27558, "s": 27526, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27614, "s": 27558, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27656, "s": 27614, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27698, "s": 27656, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27734, "s": 27698, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27756, "s": 27734, "text": "Defaultdict in Python" }, { "code": null, "e": 27795, "s": 27756, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27822, "s": 27795, "text": "Python Classes and Objects" }, { "code": null, "e": 27853, "s": 27822, "text": "Python | os.path.join() method" } ]
Display the dropdown’s (select) selected value on console in JavaScript?
Let’s say the following is our dropdown (select) − <select onchange="selectedSubjectName()" id="subjectName"> <option>Javascript</option> <option>MySQL</option> <option>MongoDB</option> <option>Java</option> </select> Following is the code to display the selected value on Console − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css"> </head> <body> <select onchange="selectedSubjectName()" id="subjectName"> <option>Javascript</option> <option>MySQL</option> <option>MongoDB</option> <option>Java</option> </select> <script> function selectedSubjectName() { var subjectIdNode = document.getElementById('subjectName'); var value = subjectIdNode.options[subjectIdNode.selectedIndex].text; console.log("The selected value=" + value); } </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output − Now, I am going to select Java. The snapshot is as follows − After that I am going to select MongoDB. The snapshot is as follows −
[ { "code": null, "e": 1113, "s": 1062, "text": "Let’s say the following is our dropdown (select) −" }, { "code": null, "e": 1292, "s": 1113, "text": "<select onchange=\"selectedSubjectName()\" id=\"subjectName\">\n <option>Javascript</option>\n <option>MySQL</option>\n <option>MongoDB</option>\n <option>Java</option>\n</select>" }, { "code": null, "e": 1357, "s": 1292, "text": "Following is the code to display the selected value on Console −" }, { "code": null, "e": 1368, "s": 1357, "text": " Live Demo" }, { "code": null, "e": 2314, "s": 1368, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<select onchange=\"selectedSubjectName()\" id=\"subjectName\">\n<option>Javascript</option>\n<option>MySQL</option>\n<option>MongoDB</option>\n<option>Java</option>\n</select>\n<script>\n function selectedSubjectName() {\n var subjectIdNode = document.getElementById('subjectName');\n var value =\n subjectIdNode.options[subjectIdNode.selectedIndex].text;\n console.log(\"The selected value=\" + value);\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2476, "s": 2314, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2517, "s": 2476, "text": "This will produce the following output −" }, { "code": null, "e": 2578, "s": 2517, "text": "Now, I am going to select Java. The snapshot is as follows −" }, { "code": null, "e": 2648, "s": 2578, "text": "After that I am going to select MongoDB. The snapshot is as follows −" } ]
Clear a StringBuilder in C#
To clear a StringBuilder, use the Clear() method. Let’s say we have set the following StringBuilder − string[] myStr = { "One", "Two", "Three", "Four" }; StringBuilder str = new StringBuilder("We will print now...").AppendLine(); Now, use the Clear() method to clear the StringBuilder − str.Clear(); Let us see the complete code − Live Demo using System; using System.Text; public class Demo { public static void Main() { // string array string[] myStr = { "One", "Two", "Three", "Four" }; StringBuilder str = new StringBuilder("We will print now...").AppendLine(); // foreach loop to append elements foreach (string item in myStr) { str.Append(item).AppendLine(); } Console.WriteLine(str.ToString()); int len = str.Length; Console.WriteLine("Length: "+len); // clearing str.Clear(); int len2 = str.Length; Console.WriteLine("Length after using Clear: "+len2); Console.ReadLine(); } } We will print now... One Two Three Four Length: 40 Length after using Clear: 0
[ { "code": null, "e": 1112, "s": 1062, "text": "To clear a StringBuilder, use the Clear() method." }, { "code": null, "e": 1164, "s": 1112, "text": "Let’s say we have set the following StringBuilder −" }, { "code": null, "e": 1292, "s": 1164, "text": "string[] myStr = { \"One\", \"Two\", \"Three\", \"Four\" };\nStringBuilder str = new StringBuilder(\"We will print now...\").AppendLine();" }, { "code": null, "e": 1349, "s": 1292, "text": "Now, use the Clear() method to clear the StringBuilder −" }, { "code": null, "e": 1362, "s": 1349, "text": "str.Clear();" }, { "code": null, "e": 1393, "s": 1362, "text": "Let us see the complete code −" }, { "code": null, "e": 1404, "s": 1393, "text": " Live Demo" }, { "code": null, "e": 2050, "s": 1404, "text": "using System;\nusing System.Text;\n\npublic class Demo {\n public static void Main() {\n // string array\n string[] myStr = { \"One\", \"Two\", \"Three\", \"Four\" };\n StringBuilder str = new StringBuilder(\"We will print now...\").AppendLine();\n\n // foreach loop to append elements\n foreach (string item in myStr) {\n str.Append(item).AppendLine();\n }\n Console.WriteLine(str.ToString());\n int len = str.Length;\n Console.WriteLine(\"Length: \"+len);\n\n // clearing\n str.Clear();\n int len2 = str.Length;\n Console.WriteLine(\"Length after using Clear: \"+len2);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2130, "s": 2050, "text": "We will print now...\nOne\nTwo\nThree\nFour\n\nLength: 40\nLength after using Clear: 0" } ]
Get Started: 3 Ways to Load CSV files into Colab | by A Apte | Towards Data Science
Data science is nothing without data. Yes, that’s obvious. What is not so obvious is the series of steps involved in getting the data into a format which allows you to explore the data. You may be in possession of a dataset in CSV format (short for comma-separated values) but no idea what to do next. This post will help you get started in data science by allowing you to load your CSV file into Colab. Colab (short for Colaboratory) is a free platform from Google that allows users to code in Python. Colab is essentially the Google Suite version of a Jupyter Notebook. Some of the advantages of Colab over Jupyter include an easier installation of packages and sharing of documents. Yet, when loading files like CSV files, it requires some extra coding. I will show you three ways to load a CSV file into Colab and insert it into a Pandas dataframe. (Note: there are Python packages that carry common datasets in them. I will not discuss loading those datasets in this article.) To start, log into your Google Account and go to Google Drive. Click on the New button on the left and select Colaboratory if it is installed (if not click on Connect more apps, search for Colaboratory and install it). From there, import Pandas as shown below (Colab has it installed already). import pandas as pd The easiest way to upload a CSV file is from your GitHub repository. Click on the dataset in your repository, then click on View Raw. Copy the link to the raw dataset and store it as a string variable called url in Colab as shown below (a cleaner method but it’s not necessary). The last step is to load the url into Pandas read_csv to get the dataframe. url = 'copied_raw_GH_link'df1 = pd.read_csv(url)# Dataset is now stored in a Pandas Dataframe To upload from your local drive, start with the following code: from google.colab import filesuploaded = files.upload() It will prompt you to select a file. Click on “Choose Files” then select and upload the file. Wait for the file to be 100% uploaded. You should see the name of the file once Colab has uploaded it. Finally, type in the following code to import it into a dataframe (make sure the filename matches the name of the uploaded file). import iodf2 = pd.read_csv(io.BytesIO(uploaded['Filename.csv']))# Dataset is now stored in a Pandas Dataframe This is the most complicated of the three methods. I’ll show it for those that have uploaded CSV files into their Google Drive for workflow control. First, type in the following code: # Code to read csv file into Colaboratory:!pip install -U -q PyDrivefrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials# Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth) When prompted, click on the link to get authentication to allow Google to access your Drive. You should see a screen with “Google Cloud SDK wants to access your Google Account” at the top. After you allow permission, copy the given verification code and paste it in the box in Colab. Once you have completed verification, go to the CSV file in Google Drive, right-click on it and select “Get shareable link”. The link will be copied into your clipboard. Paste this link into a string variable in Colab. link = 'https://drive.google.com/open?id=1DPZZQ43w8brRhbEMolgLqOWKbZbE-IQu' # The shareable link What you want is the id portion after the equal sign. To get that portion, type in the following code: fluff, id = link.split('=')print (id) # Verify that you have everything after '=' Finally, type in the following code to get this file into a dataframe downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('Filename.csv') df3 = pd.read_csv('Filename.csv')# Dataset is now stored in a Pandas Dataframe These are three approaches to uploading CSV files into Colab. Each has its benefits depending on the size of the file and how one wants to organize the workflow. Once the data is in a nicer format like a Pandas Dataframe, you are ready to go to work. Thank you so much for your support. In honor of this article reaching 50k Views and 25k Reads, I’m offering a bonus method for getting CSV files into Colab. This one is quite simple and clean. In your Google Drive (“My Drive”), create a folder called data in the location of your choosing. This is where you will upload your data. From a Colab notebook, type the following: from google.colab import drivedrive.mount('/content/drive') Just like with the third method, the commands will bring you to a Google Authentication step. You should see a screen with Google Drive File Stream wants to access your Google Account. After you allow permission, copy the given verification code and paste it in the box in Colab. In the notebook, click on the charcoal > on the top left of the notebook and click on Files. Locate the data folder you created earlier and find your data. Right-click on your data and select Copy Path. Store this copied path into a variable and you are ready to go. path = "copied path"df_bonus = pd.read_csv(path)# Dataset is now stored in a Pandas Dataframe What is great about this method is that you can access a dataset from a separate dataset folder you created in your own Google Drive without the extra steps involved in the third method.
[ { "code": null, "e": 576, "s": 172, "text": "Data science is nothing without data. Yes, that’s obvious. What is not so obvious is the series of steps involved in getting the data into a format which allows you to explore the data. You may be in possession of a dataset in CSV format (short for comma-separated values) but no idea what to do next. This post will help you get started in data science by allowing you to load your CSV file into Colab." }, { "code": null, "e": 1025, "s": 576, "text": "Colab (short for Colaboratory) is a free platform from Google that allows users to code in Python. Colab is essentially the Google Suite version of a Jupyter Notebook. Some of the advantages of Colab over Jupyter include an easier installation of packages and sharing of documents. Yet, when loading files like CSV files, it requires some extra coding. I will show you three ways to load a CSV file into Colab and insert it into a Pandas dataframe." }, { "code": null, "e": 1154, "s": 1025, "text": "(Note: there are Python packages that carry common datasets in them. I will not discuss loading those datasets in this article.)" }, { "code": null, "e": 1448, "s": 1154, "text": "To start, log into your Google Account and go to Google Drive. Click on the New button on the left and select Colaboratory if it is installed (if not click on Connect more apps, search for Colaboratory and install it). From there, import Pandas as shown below (Colab has it installed already)." }, { "code": null, "e": 1468, "s": 1448, "text": "import pandas as pd" }, { "code": null, "e": 1823, "s": 1468, "text": "The easiest way to upload a CSV file is from your GitHub repository. Click on the dataset in your repository, then click on View Raw. Copy the link to the raw dataset and store it as a string variable called url in Colab as shown below (a cleaner method but it’s not necessary). The last step is to load the url into Pandas read_csv to get the dataframe." }, { "code": null, "e": 1917, "s": 1823, "text": "url = 'copied_raw_GH_link'df1 = pd.read_csv(url)# Dataset is now stored in a Pandas Dataframe" }, { "code": null, "e": 1981, "s": 1917, "text": "To upload from your local drive, start with the following code:" }, { "code": null, "e": 2037, "s": 1981, "text": "from google.colab import filesuploaded = files.upload()" }, { "code": null, "e": 2234, "s": 2037, "text": "It will prompt you to select a file. Click on “Choose Files” then select and upload the file. Wait for the file to be 100% uploaded. You should see the name of the file once Colab has uploaded it." }, { "code": null, "e": 2364, "s": 2234, "text": "Finally, type in the following code to import it into a dataframe (make sure the filename matches the name of the uploaded file)." }, { "code": null, "e": 2474, "s": 2364, "text": "import iodf2 = pd.read_csv(io.BytesIO(uploaded['Filename.csv']))# Dataset is now stored in a Pandas Dataframe" }, { "code": null, "e": 2658, "s": 2474, "text": "This is the most complicated of the three methods. I’ll show it for those that have uploaded CSV files into their Google Drive for workflow control. First, type in the following code:" }, { "code": null, "e": 3055, "s": 2658, "text": "# Code to read csv file into Colaboratory:!pip install -U -q PyDrivefrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials# Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth)" }, { "code": null, "e": 3339, "s": 3055, "text": "When prompted, click on the link to get authentication to allow Google to access your Drive. You should see a screen with “Google Cloud SDK wants to access your Google Account” at the top. After you allow permission, copy the given verification code and paste it in the box in Colab." }, { "code": null, "e": 3558, "s": 3339, "text": "Once you have completed verification, go to the CSV file in Google Drive, right-click on it and select “Get shareable link”. The link will be copied into your clipboard. Paste this link into a string variable in Colab." }, { "code": null, "e": 3655, "s": 3558, "text": "link = 'https://drive.google.com/open?id=1DPZZQ43w8brRhbEMolgLqOWKbZbE-IQu' # The shareable link" }, { "code": null, "e": 3758, "s": 3655, "text": "What you want is the id portion after the equal sign. To get that portion, type in the following code:" }, { "code": null, "e": 3840, "s": 3758, "text": "fluff, id = link.split('=')print (id) # Verify that you have everything after '='" }, { "code": null, "e": 3910, "s": 3840, "text": "Finally, type in the following code to get this file into a dataframe" }, { "code": null, "e": 4073, "s": 3910, "text": "downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('Filename.csv') df3 = pd.read_csv('Filename.csv')# Dataset is now stored in a Pandas Dataframe" }, { "code": null, "e": 4324, "s": 4073, "text": "These are three approaches to uploading CSV files into Colab. Each has its benefits depending on the size of the file and how one wants to organize the workflow. Once the data is in a nicer format like a Pandas Dataframe, you are ready to go to work." }, { "code": null, "e": 4655, "s": 4324, "text": "Thank you so much for your support. In honor of this article reaching 50k Views and 25k Reads, I’m offering a bonus method for getting CSV files into Colab. This one is quite simple and clean. In your Google Drive (“My Drive”), create a folder called data in the location of your choosing. This is where you will upload your data." }, { "code": null, "e": 4698, "s": 4655, "text": "From a Colab notebook, type the following:" }, { "code": null, "e": 4758, "s": 4698, "text": "from google.colab import drivedrive.mount('/content/drive')" }, { "code": null, "e": 5038, "s": 4758, "text": "Just like with the third method, the commands will bring you to a Google Authentication step. You should see a screen with Google Drive File Stream wants to access your Google Account. After you allow permission, copy the given verification code and paste it in the box in Colab." }, { "code": null, "e": 5305, "s": 5038, "text": "In the notebook, click on the charcoal > on the top left of the notebook and click on Files. Locate the data folder you created earlier and find your data. Right-click on your data and select Copy Path. Store this copied path into a variable and you are ready to go." }, { "code": null, "e": 5399, "s": 5305, "text": "path = \"copied path\"df_bonus = pd.read_csv(path)# Dataset is now stored in a Pandas Dataframe" } ]
PyQt - QSplitter Widget
This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls. The widgets in a QSplitter object are laid horizontally by default although the orientation can be changed to Qt.Vertical. Following are the methods and signals of QSplitter class − addWidget() Adds the widget to splitter’s layout indexOf() Returns the index of the widget in the layout insetWidget() Inserts a widget at the specified index setOrientation() Sets the layout of splitter to Qt.Horizontal or Qt.Vertical setSizes() Sets the initial size of each widget count() Returns the number of widgets in splitter widget splitterMoved() is the only signal emitted by QSplitter object whenever the splitter handle is dragged. The following example has a splitter object, splitter1, in which a frame and QTextEdit object are horizontally added. topleft = QFrame() textedit = QTextEdit() splitter1.addWidget(topleft) splitter1.addWidget(textedit) This splitter object splitter1 and a bottom frame object are added in another splitter, splitter2, vertically. The object splitters is finally added in the top level window. bottom = QFrame() splitter2 = QSplitter(Qt.Vertical) splitter2.addWidget(splitter1) splitter2.addWidget(bottom) hbox.addWidget(splitter2) self.setLayout(hbox) The complete code is as follows − import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): hbox = QHBoxLayout(self) topleft = QFrame() topleft.setFrameShape(QFrame.StyledPanel) bottom = QFrame() bottom.setFrameShape(QFrame.StyledPanel) splitter1 = QSplitter(Qt.Horizontal) textedit = QTextEdit() splitter1.addWidget(topleft) splitter1.addWidget(textedit) splitter1.setSizes([100,200]) splitter2 = QSplitter(Qt.Vertical) splitter2.addWidget(splitter1) splitter2.addWidget(bottom) hbox.addWidget(splitter2) self.setLayout(hbox) QApplication.setStyle(QStyleFactory.create('Cleanlooks')) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('QSplitter demo') self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output −
[ { "code": null, "e": 2289, "s": 2060, "text": "This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls." }, { "code": null, "e": 2412, "s": 2289, "text": "The widgets in a QSplitter object are laid horizontally by default although the orientation can be changed to Qt.Vertical." }, { "code": null, "e": 2471, "s": 2412, "text": "Following are the methods and signals of QSplitter class −" }, { "code": null, "e": 2483, "s": 2471, "text": "addWidget()" }, { "code": null, "e": 2520, "s": 2483, "text": "Adds the widget to splitter’s layout" }, { "code": null, "e": 2530, "s": 2520, "text": "indexOf()" }, { "code": null, "e": 2576, "s": 2530, "text": "Returns the index of the widget in the layout" }, { "code": null, "e": 2590, "s": 2576, "text": "insetWidget()" }, { "code": null, "e": 2630, "s": 2590, "text": "Inserts a widget at the specified index" }, { "code": null, "e": 2647, "s": 2630, "text": "setOrientation()" }, { "code": null, "e": 2707, "s": 2647, "text": "Sets the layout of splitter to Qt.Horizontal or Qt.Vertical" }, { "code": null, "e": 2718, "s": 2707, "text": "setSizes()" }, { "code": null, "e": 2755, "s": 2718, "text": "Sets the initial size of each widget" }, { "code": null, "e": 2763, "s": 2755, "text": "count()" }, { "code": null, "e": 2812, "s": 2763, "text": "Returns the number of widgets in splitter widget" }, { "code": null, "e": 2916, "s": 2812, "text": "splitterMoved() is the only signal emitted by QSplitter object whenever the splitter handle is dragged." }, { "code": null, "e": 3034, "s": 2916, "text": "The following example has a splitter object, splitter1, in which a frame and QTextEdit object are horizontally added." }, { "code": null, "e": 3136, "s": 3034, "text": "topleft = QFrame()\ntextedit = QTextEdit()\nsplitter1.addWidget(topleft)\nsplitter1.addWidget(textedit)\n" }, { "code": null, "e": 3310, "s": 3136, "text": "This splitter object splitter1 and a bottom frame object are added in another splitter, splitter2, vertically. The object splitters is finally added in the top level window." }, { "code": null, "e": 3471, "s": 3310, "text": "bottom = QFrame()\nsplitter2 = QSplitter(Qt.Vertical)\nsplitter2.addWidget(splitter1)\nsplitter2.addWidget(bottom)\n\nhbox.addWidget(splitter2)\nself.setLayout(hbox)\n" }, { "code": null, "e": 3505, "s": 3471, "text": "The complete code is as follows −" }, { "code": null, "e": 4542, "s": 3505, "text": "import sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\nclass Example(QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n\t\t\n self.initUI()\n\t\n def initUI(self):\n\t\n hbox = QHBoxLayout(self)\n\t\t\n topleft = QFrame()\n topleft.setFrameShape(QFrame.StyledPanel)\n bottom = QFrame()\n bottom.setFrameShape(QFrame.StyledPanel)\n\t\t\n splitter1 = QSplitter(Qt.Horizontal)\n textedit = QTextEdit()\n splitter1.addWidget(topleft)\n splitter1.addWidget(textedit)\n splitter1.setSizes([100,200])\n\t\t\n splitter2 = QSplitter(Qt.Vertical)\n splitter2.addWidget(splitter1)\n splitter2.addWidget(bottom)\n\t\t\n hbox.addWidget(splitter2)\n\t\t\n self.setLayout(hbox)\n QApplication.setStyle(QStyleFactory.create('Cleanlooks'))\n\t\t\n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('QSplitter demo')\n self.show()\n\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()" } ]
Scala | Functions – Basics
17 Jan, 2019 A function is a collection of statements that perform a certain task. One can divide up the code into separate functions, keeping in mind that each function must perform a specific task. Functions are used to put some common and repeated task into a single function, so instead of writing the same code again and again for different inputs, we can simply call the function. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values. Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object. In general, function declaration & definition have 6 components: def keyword: “def” keyword is used to declare a function in Scala. function_name: It should be valid name in lower camel case. Function name in Scala can have characters like +, ~, &, –, ++, \, / etc. parameter_list: In Scala, comma-separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. return_type: User must mention return type of parameters while defining function and return type of a function is optional. If you don’t specify any return type of a function, default return type is Unit which is equivalent to void in Java. = : In Scala, a user can create function with or without = (equal) operator. If the user uses it, the function will return the desired value. If he doesn’t use it, the function will not return any value and will work like a subroutine. Method body: Method body is enclosed between braces { }. The code you need to be executed to perform your intended operations. Syntax: def function_name ([parameter_list]) : [return_type] = { // function body } Note: If the user will not use the equals sign and body then implicitly method is declared abstract. There are mainly two ways to call the function in Scala. First way is the standard way as follows: function_name(paramter_list) In the Second way, a user can also call the function with the help of the instance and dot notation as follows: [instance].function_name(paramter_list) Example: object GeeksforGeeks { def main(args: Array[String]) { // Calling the function println("Sum is: " + functionToAdd(5,3)); } // declaration and definition of function def functionToAdd(a:Int, b:Int) : Int = { var sum:Int = 0 sum = a + b // returning the value of sum return sum }} Output: Sum is: 8 Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2019" }, { "code": null, "e": 573, "s": 28, "text": "A function is a collection of statements that perform a certain task. One can divide up the code into separate functions, keeping in mind that each function must perform a specific task. Functions are used to put some common and repeated task into a single function, so instead of writing the same code again and again for different inputs, we can simply call the function. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values." }, { "code": null, "e": 836, "s": 573, "text": "Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object." }, { "code": null, "e": 901, "s": 836, "text": "In general, function declaration & definition have 6 components:" }, { "code": null, "e": 968, "s": 901, "text": "def keyword: “def” keyword is used to declare a function in Scala." }, { "code": null, "e": 1102, "s": 968, "text": "function_name: It should be valid name in lower camel case. Function name in Scala can have characters like +, ~, &, –, ++, \\, / etc." }, { "code": null, "e": 1250, "s": 1102, "text": "parameter_list: In Scala, comma-separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis." }, { "code": null, "e": 1491, "s": 1250, "text": "return_type: User must mention return type of parameters while defining function and return type of a function is optional. If you don’t specify any return type of a function, default return type is Unit which is equivalent to void in Java." }, { "code": null, "e": 1727, "s": 1491, "text": "= : In Scala, a user can create function with or without = (equal) operator. If the user uses it, the function will return the desired value. If he doesn’t use it, the function will not return any value and will work like a subroutine." }, { "code": null, "e": 1854, "s": 1727, "text": "Method body: Method body is enclosed between braces { }. The code you need to be executed to perform your intended operations." }, { "code": null, "e": 1862, "s": 1854, "text": "Syntax:" }, { "code": null, "e": 1946, "s": 1862, "text": "def function_name ([parameter_list]) : [return_type] = {\n \n // function body\n\n}\n" }, { "code": null, "e": 2047, "s": 1946, "text": "Note: If the user will not use the equals sign and body then implicitly method is declared abstract." }, { "code": null, "e": 2146, "s": 2047, "text": "There are mainly two ways to call the function in Scala. First way is the standard way as follows:" }, { "code": null, "e": 2175, "s": 2146, "text": "function_name(paramter_list)" }, { "code": null, "e": 2287, "s": 2175, "text": "In the Second way, a user can also call the function with the help of the instance and dot notation as follows:" }, { "code": null, "e": 2327, "s": 2287, "text": "[instance].function_name(paramter_list)" }, { "code": null, "e": 2336, "s": 2327, "text": "Example:" }, { "code": "object GeeksforGeeks { def main(args: Array[String]) { // Calling the function println(\"Sum is: \" + functionToAdd(5,3)); } // declaration and definition of function def functionToAdd(a:Int, b:Int) : Int = { var sum:Int = 0 sum = a + b // returning the value of sum return sum }}", "e": 2698, "s": 2336, "text": null }, { "code": null, "e": 2706, "s": 2698, "text": "Output:" }, { "code": null, "e": 2716, "s": 2706, "text": "Sum is: 8" }, { "code": null, "e": 2729, "s": 2716, "text": "Scala-Method" }, { "code": null, "e": 2735, "s": 2729, "text": "Scala" } ]
GATE | GATE CS 2010 | Question 26
28 Jun, 2021 Consider a company that assembles computers. The probability of a faulty assembly of any computer is p. The company therefore subjects each computer to a testing process.This testing process gives the correct result for any computer with a probability of q. What is the probability of a computer being declared faulty?(A) pq + (1 – p)(1 – q)(B) (1 – q) p(C) (1 – p) q(D) pqAnswer: (A)Explanation: A computer can be declared faulty in two cases 1) It is actually faulty and correctly declared so (p*q) 2) Not faulty and incorrectly declared (1-p)*(1-q). Quiz of this Question My Personal Notes arrow_drop_up Save GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | Gate IT 2005 | Question 11 GATE | GATE MOCK 2017 | Question 45 GATE | GATE-CS-2004 | Question 90 GATE | GATE-CS-2000 | Question 2 GATE | GATE CS 2013 | Question 50 GATE | GATE CS 2012 | Question 65 GATE | GATE-CS-2003 | Question 64 GATE | GATE-CS-2004 | Question 90 GATE | GATE-CS-2015 (Set 1) | Question 30
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 451, "s": 54, "text": "Consider a company that assembles computers. The probability of a faulty assembly of any computer is p. The company therefore subjects each computer to a testing process.This testing process gives the correct result for any computer with a probability of q. What is the probability of a computer being declared faulty?(A) pq + (1 – p)(1 – q)(B) (1 – q) p(C) (1 – p) q(D) pqAnswer: (A)Explanation:" }, { "code": null, "e": 780, "s": 451, "text": "A computer can be declared faulty in two cases\n1) It is actually faulty and correctly declared so (p*q)\n2) Not faulty and incorrectly declared (1-p)*(1-q). Quiz of this Question\n\n \n My Personal Notes\n arrow_drop_up\n \n \n \n \n \n Save\n \n \n " }, { "code": null, "e": 795, "s": 780, "text": "\nGATE-CS-2010\n" }, { "code": null, "e": 815, "s": 795, "text": "\nGATE-GATE CS 2010\n" }, { "code": null, "e": 822, "s": 815, "text": "\nGATE\n" }, { "code": null, "e": 1027, "s": 822, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 1069, "s": 1027, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 1103, "s": 1069, "text": "GATE | Gate IT 2005 | Question 11" }, { "code": null, "e": 1139, "s": 1103, "text": "GATE | GATE MOCK 2017 | Question 45" }, { "code": null, "e": 1173, "s": 1139, "text": "GATE | GATE-CS-2004 | Question 90" }, { "code": null, "e": 1206, "s": 1173, "text": "GATE | GATE-CS-2000 | Question 2" }, { "code": null, "e": 1240, "s": 1206, "text": "GATE | GATE CS 2013 | Question 50" }, { "code": null, "e": 1274, "s": 1240, "text": "GATE | GATE CS 2012 | Question 65" }, { "code": null, "e": 1308, "s": 1274, "text": "GATE | GATE-CS-2003 | Question 64" }, { "code": null, "e": 1342, "s": 1308, "text": "GATE | GATE-CS-2004 | Question 90" } ]
How to Truncate the Double Value to Given Decimal Places in Java?
15 Dec, 2020 In simplest terms, truncation means to chop off the decimal portion of a number. A method of approximating a decimal number by dropping all decimal places past a certain point without rounding. Given a double value and a decimal place truncate the value to the given decimal point. Example: Input: val = 3.142857142857143 Decimal point = 3 Output = 3.142 Upto 3 decimal places Approach 1: Using Mathematically : Shift the decimal of the given value to the given decimal point by multiplying 10^n Take the floor of the number and divide the number by 10^n The final value is the truncated value Java // Java program to truncate the double value to// a particular decimal point import java.io.*; class GFG { static void change(double value, int decimalpoint) { // Using the pow() method value = value * Math.pow(10, decimalpoint); value = Math.floor(value); value = value / Math.pow(10, decimalpoint); System.out.println(value); return; } // Main Method public static void main(String[] args) { double firstvalue = 1212.12131131; int decimalpoint = 4; change(firstvalue, decimalpoint); double secondvalue = 3.142857142857143; int decimalpoint2 = 3; change(secondvalue, decimalpoint2); }} 1212.1213 3.142 Approach 2: Using String matching approach Convert the number into String Start the counter variable when “.” found in the String Increment the counter till decimal point Store the new String and parse it in double format Java // Java program to truncate the double// value using string matching import java.io.*; class GFG { public static void main(String[] args) { double firstvalue = 1212.12131131; // decimal point int decimalpoint = 6; // convert the double value in string String temp_value = "" + firstvalue; String string_value = ""; int counter = -1; for (int i = 0; i < temp_value.length(); ++i) { // checking the condition if (counter > decimalpoint) { break; } else if (temp_value.charAt(i) == '.') { counter = 1; } else if (counter >= 1) { ++counter; } // converting the number into string string_value += temp_value.charAt(i); } // parse the string double new_value = Double.parseDouble(string_value); System.out.println(new_value); }} 1212.121311 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Dec, 2020" }, { "code": null, "e": 222, "s": 28, "text": "In simplest terms, truncation means to chop off the decimal portion of a number. A method of approximating a decimal number by dropping all decimal places past a certain point without rounding." }, { "code": null, "e": 310, "s": 222, "text": "Given a double value and a decimal place truncate the value to the given decimal point." }, { "code": null, "e": 320, "s": 310, "text": "Example: " }, { "code": null, "e": 408, "s": 320, "text": "Input: val = 3.142857142857143\nDecimal point = 3\nOutput = 3.142\n\nUpto 3 decimal places" }, { "code": null, "e": 444, "s": 408, "text": " Approach 1: Using Mathematically :" }, { "code": null, "e": 528, "s": 444, "text": "Shift the decimal of the given value to the given decimal point by multiplying 10^n" }, { "code": null, "e": 587, "s": 528, "text": "Take the floor of the number and divide the number by 10^n" }, { "code": null, "e": 626, "s": 587, "text": "The final value is the truncated value" }, { "code": null, "e": 631, "s": 626, "text": "Java" }, { "code": "// Java program to truncate the double value to// a particular decimal point import java.io.*; class GFG { static void change(double value, int decimalpoint) { // Using the pow() method value = value * Math.pow(10, decimalpoint); value = Math.floor(value); value = value / Math.pow(10, decimalpoint); System.out.println(value); return; } // Main Method public static void main(String[] args) { double firstvalue = 1212.12131131; int decimalpoint = 4; change(firstvalue, decimalpoint); double secondvalue = 3.142857142857143; int decimalpoint2 = 3; change(secondvalue, decimalpoint2); }}", "e": 1347, "s": 631, "text": null }, { "code": null, "e": 1363, "s": 1347, "text": "1212.1213\n3.142" }, { "code": null, "e": 1406, "s": 1363, "text": "Approach 2: Using String matching approach" }, { "code": null, "e": 1437, "s": 1406, "text": "Convert the number into String" }, { "code": null, "e": 1493, "s": 1437, "text": "Start the counter variable when “.” found in the String" }, { "code": null, "e": 1534, "s": 1493, "text": "Increment the counter till decimal point" }, { "code": null, "e": 1585, "s": 1534, "text": "Store the new String and parse it in double format" }, { "code": null, "e": 1590, "s": 1585, "text": "Java" }, { "code": "// Java program to truncate the double// value using string matching import java.io.*; class GFG { public static void main(String[] args) { double firstvalue = 1212.12131131; // decimal point int decimalpoint = 6; // convert the double value in string String temp_value = \"\" + firstvalue; String string_value = \"\"; int counter = -1; for (int i = 0; i < temp_value.length(); ++i) { // checking the condition if (counter > decimalpoint) { break; } else if (temp_value.charAt(i) == '.') { counter = 1; } else if (counter >= 1) { ++counter; } // converting the number into string string_value += temp_value.charAt(i); } // parse the string double new_value = Double.parseDouble(string_value); System.out.println(new_value); }}", "e": 2587, "s": 1590, "text": null }, { "code": null, "e": 2599, "s": 2587, "text": "1212.121311" }, { "code": null, "e": 2606, "s": 2599, "text": "Picked" }, { "code": null, "e": 2630, "s": 2606, "text": "Technical Scripter 2020" }, { "code": null, "e": 2635, "s": 2630, "text": "Java" }, { "code": null, "e": 2649, "s": 2635, "text": "Java Programs" }, { "code": null, "e": 2668, "s": 2649, "text": "Technical Scripter" }, { "code": null, "e": 2673, "s": 2668, "text": "Java" } ]
numpy.pmt() in Python
29 Nov, 2018 numpy.pmt(rate, nper, pv, fv, when = ‘end’): This financial function helps user to compute payment value as per the principal and interest. Parameters :rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodnper : [scalar or (M, )array] total compounding periodsfv : [scalar or (M, )array] Future valuepv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period.Default is {‘end’, 0} Return :Payment value Equation being solved : fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper – 1) == 0 or when rate == 0fv + pv + pmt * nper == 0 Code: # Python program explaining # pmt() function import numpy as np ''' Question : monthly payment needed to pay off a $10, 000 loanin 12 years at an annual interest rate of 10 %''' # rate np pv Solution = np.pmt(0.10 / 12, 12 * 12, 10, 000) # Here fv = 0 ; Also Default value of fv = 0 print("Solution : ", Solution) Output: Solution : -0.1195078262827336 Python numpy-Financial Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 168, "s": 28, "text": "numpy.pmt(rate, nper, pv, fv, when = ‘end’): This financial function helps user to compute payment value as per the principal and interest." }, { "code": null, "e": 513, "s": 168, "text": "Parameters :rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodnper : [scalar or (M, )array] total compounding periodsfv : [scalar or (M, )array] Future valuepv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period.Default is {‘end’, 0}" }, { "code": null, "e": 535, "s": 513, "text": "Return :Payment value" }, { "code": null, "e": 559, "s": 535, "text": "Equation being solved :" }, { "code": null, "e": 637, "s": 559, "text": "fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper – 1) == 0" }, { "code": null, "e": 680, "s": 637, "text": "or when rate == 0fv + pv + pmt * nper == 0" }, { "code": null, "e": 686, "s": 680, "text": "Code:" }, { "code": "# Python program explaining # pmt() function import numpy as np ''' Question : monthly payment needed to pay off a $10, 000 loanin 12 years at an annual interest rate of 10 %''' # rate np pv Solution = np.pmt(0.10 / 12, 12 * 12, 10, 000) # Here fv = 0 ; Also Default value of fv = 0 print(\"Solution : \", Solution) ", "e": 1012, "s": 686, "text": null }, { "code": null, "e": 1020, "s": 1012, "text": "Output:" }, { "code": null, "e": 1052, "s": 1020, "text": "Solution : -0.1195078262827336" }, { "code": null, "e": 1085, "s": 1052, "text": "Python numpy-Financial Functions" }, { "code": null, "e": 1098, "s": 1085, "text": "Python-numpy" }, { "code": null, "e": 1105, "s": 1098, "text": "Python" }, { "code": null, "e": 1203, "s": 1105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1221, "s": 1203, "text": "Python Dictionary" }, { "code": null, "e": 1263, "s": 1221, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1285, "s": 1263, "text": "Enumerate() in Python" }, { "code": null, "e": 1320, "s": 1285, "text": "Read a file line by line in Python" }, { "code": null, "e": 1346, "s": 1320, "text": "Python String | replace()" }, { "code": null, "e": 1378, "s": 1346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1407, "s": 1378, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1437, "s": 1407, "text": "Iterate over a list in Python" }, { "code": null, "e": 1464, "s": 1437, "text": "Python Classes and Objects" } ]
Print all numbers in given range having digits in strictly increasing order
23 May, 2021 Given two positive integers L and R, the task is to print the numbers in the range [L, R] which have their digits in strictly increasing order. Examples: Input: L = 10, R = 15 Output: 12 13 14 15 Explanation: In the range [10, 15], only the numbers {12, 13, 14, 15} have their digits in strictly increasing order. Input: L = 60, R = 70 Output: 67 68 69 Explanation: In the range [60, 70], only the numbers {67, 68, 69} have their digits in strictly increasing order. Approach: The idea is to iterate over the range [L, R] and for each number in this range check if digits of this number are in strictly increasing order or not. If yes then print that number else check for the next number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all numbers// in the range [L, R] having digits// in strictly increasing ordervoid printNum(int L, int R){ // Iterate over the range for (int i = L; i <= R; i++) { int temp = i; int c = 10; int flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) cout << i << " "; }} // Driver Codeint main(){// Given range L and R int L = 10, R = 15; // Function Call printNum(L, R); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to print all numbers// in the range [L, R] having digits// in strictly increasing orderstatic void printNum(int L, int R){ // Iterate over the range for(int i = L; i <= R; i++) { int temp = i; int c = 10; int flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) System.out.print(i + " "); }} // Driver codepublic static void main(String[] args){ // Given range L and R int L = 10, R = 15; // Function call printNum(L, R);}} // This code is contributed by offbeat # Python3 program for the above approach # Function to print all numbers in# the range [L, R] having digits# in strictly increasing orderdef printNum(L, R): # Iterate over the range for i in range(L, R + 1): temp = i c = 10 flag = 0 # Iterate over the digits while (temp > 0): # Check if the current digit # is >= the previous digit if (temp % 10 >= c): flag = 1 break c = temp % 10 temp //= 10 # If the digits are in # ascending order if (flag == 0): print(i, end = " ") # Driver Code # Given range L and RL = 10R = 15 # Function callprintNum(L, R) # This code is contributed by code_hunt // C# program for the above approachusing System; class GFG{ // Function to print all numbers// in the range [L, R] having digits// in strictly increasing orderstatic void printNum(int L, int R){ // Iterate over the range for(int i = L; i <= R; i++) { int temp = i; int c = 10; int flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) Console.Write(i + " "); }} // Driver Codepublic static void Main(){ // Given range L and R int L = 10, R = 15; // Function call printNum(L, R);}} // This code is contributed by jrishabh99 <script> // Javascript program for the above approach // Function to print all numbers// in the range [L, R] having digits// in strictly increasing orderfunction printNum(L, R){ // Iterate over the range for(let i = L; i <= R; i++) { let temp = i; let c = 10; let flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) document.write(i + " "); }} // Driver code // Given range L and Rlet L = 10, R = 15; // Function callprintNum(L, R); // This code is contributed by sravan kumar </script> 12 13 14 15 Time Complexity O(N), N is absolute difference between L and R. Auxiliary Space: O(1) offbeat jrishabh99 nidhi_biet code_hunt sravankumar8128 khushboogoyal499 number-digits Numbers Greedy Mathematical School Programming Searching Sorting Searching Greedy Mathematical Sorting Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Job Sequencing Problem Minimum Number of Platforms Required for a Railway/Bus Station Policemen catch thieves Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2021" }, { "code": null, "e": 196, "s": 52, "text": "Given two positive integers L and R, the task is to print the numbers in the range [L, R] which have their digits in strictly increasing order." }, { "code": null, "e": 206, "s": 196, "text": "Examples:" }, { "code": null, "e": 366, "s": 206, "text": "Input: L = 10, R = 15 Output: 12 13 14 15 Explanation: In the range [10, 15], only the numbers {12, 13, 14, 15} have their digits in strictly increasing order." }, { "code": null, "e": 519, "s": 366, "text": "Input: L = 60, R = 70 Output: 67 68 69 Explanation: In the range [60, 70], only the numbers {67, 68, 69} have their digits in strictly increasing order." }, { "code": null, "e": 742, "s": 519, "text": "Approach: The idea is to iterate over the range [L, R] and for each number in this range check if digits of this number are in strictly increasing order or not. If yes then print that number else check for the next number." }, { "code": null, "e": 793, "s": 742, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 797, "s": 793, "text": "C++" }, { "code": null, "e": 802, "s": 797, "text": "Java" }, { "code": null, "e": 810, "s": 802, "text": "Python3" }, { "code": null, "e": 813, "s": 810, "text": "C#" }, { "code": null, "e": 824, "s": 813, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all numbers// in the range [L, R] having digits// in strictly increasing ordervoid printNum(int L, int R){ // Iterate over the range for (int i = L; i <= R; i++) { int temp = i; int c = 10; int flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) cout << i << \" \"; }} // Driver Codeint main(){// Given range L and R int L = 10, R = 15; // Function Call printNum(L, R); return 0;}", "e": 1690, "s": 824, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to print all numbers// in the range [L, R] having digits// in strictly increasing orderstatic void printNum(int L, int R){ // Iterate over the range for(int i = L; i <= R; i++) { int temp = i; int c = 10; int flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) System.out.print(i + \" \"); }} // Driver codepublic static void main(String[] args){ // Given range L and R int L = 10, R = 15; // Function call printNum(L, R);}} // This code is contributed by offbeat", "e": 2686, "s": 1690, "text": null }, { "code": "# Python3 program for the above approach # Function to print all numbers in# the range [L, R] having digits# in strictly increasing orderdef printNum(L, R): # Iterate over the range for i in range(L, R + 1): temp = i c = 10 flag = 0 # Iterate over the digits while (temp > 0): # Check if the current digit # is >= the previous digit if (temp % 10 >= c): flag = 1 break c = temp % 10 temp //= 10 # If the digits are in # ascending order if (flag == 0): print(i, end = \" \") # Driver Code # Given range L and RL = 10R = 15 # Function callprintNum(L, R) # This code is contributed by code_hunt", "e": 3467, "s": 2686, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to print all numbers// in the range [L, R] having digits// in strictly increasing orderstatic void printNum(int L, int R){ // Iterate over the range for(int i = L; i <= R; i++) { int temp = i; int c = 10; int flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) Console.Write(i + \" \"); }} // Driver Codepublic static void Main(){ // Given range L and R int L = 10, R = 15; // Function call printNum(L, R);}} // This code is contributed by jrishabh99", "e": 4418, "s": 3467, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to print all numbers// in the range [L, R] having digits// in strictly increasing orderfunction printNum(L, R){ // Iterate over the range for(let i = L; i <= R; i++) { let temp = i; let c = 10; let flag = 0; // Iterate over the digits while (temp > 0) { // Check if the current digit // is >= the previous digit if (temp % 10 >= c) { flag = 1; break; } c = temp % 10; temp /= 10; } // If the digits are in // ascending order if (flag == 0) document.write(i + \" \"); }} // Driver code // Given range L and Rlet L = 10, R = 15; // Function callprintNum(L, R); // This code is contributed by sravan kumar </script>", "e": 5323, "s": 4418, "text": null }, { "code": null, "e": 5335, "s": 5323, "text": "12 13 14 15" }, { "code": null, "e": 5422, "s": 5335, "text": "Time Complexity O(N), N is absolute difference between L and R. Auxiliary Space: O(1) " }, { "code": null, "e": 5430, "s": 5422, "text": "offbeat" }, { "code": null, "e": 5441, "s": 5430, "text": "jrishabh99" }, { "code": null, "e": 5452, "s": 5441, "text": "nidhi_biet" }, { "code": null, "e": 5462, "s": 5452, "text": "code_hunt" }, { "code": null, "e": 5478, "s": 5462, "text": "sravankumar8128" }, { "code": null, "e": 5495, "s": 5478, "text": "khushboogoyal499" }, { "code": null, "e": 5509, "s": 5495, "text": "number-digits" }, { "code": null, "e": 5517, "s": 5509, "text": "Numbers" }, { "code": null, "e": 5524, "s": 5517, "text": "Greedy" }, { "code": null, "e": 5537, "s": 5524, "text": "Mathematical" }, { "code": null, "e": 5556, "s": 5537, "text": "School Programming" }, { "code": null, "e": 5566, "s": 5556, "text": "Searching" }, { "code": null, "e": 5574, "s": 5566, "text": "Sorting" }, { "code": null, "e": 5584, "s": 5574, "text": "Searching" }, { "code": null, "e": 5591, "s": 5584, "text": "Greedy" }, { "code": null, "e": 5604, "s": 5591, "text": "Mathematical" }, { "code": null, "e": 5612, "s": 5604, "text": "Sorting" }, { "code": null, "e": 5620, "s": 5612, "text": "Numbers" }, { "code": null, "e": 5718, "s": 5620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5741, "s": 5718, "text": "Job Sequencing Problem" }, { "code": null, "e": 5804, "s": 5741, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 5828, "s": 5804, "text": "Policemen catch thieves" }, { "code": null, "e": 5909, "s": 5828, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 5980, "s": 5909, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 6010, "s": 5980, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 6053, "s": 6010, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6068, "s": 6053, "text": "C++ Data Types" }, { "code": null, "e": 6092, "s": 6068, "text": "Merge two sorted arrays" } ]
What is column ordering in Bootstrap ?
19 Aug, 2021 Column ordering classes in Bootstrap helps to change the order of our grid system based on different screen sizes eg: desktop, mobile, tablet, smartwatches. This makes the website more responsive for different screen sizes. For example, let’s say we have 4 columns (V, X, Y, and Z). We want the appearance to be On large screens: V X Y Z On large screens: V X Y Z On small screens(mobile): Y Z V X On small screens(mobile): Y Z V X We can easily change the order of built-in grid columns with push and pull column classes. The Push and Pull Classes: The push class will move columns to the right while the pull class will move columns to the left. Syntax: .col-md-pull-# or .col-md-push-# Note: # is a number ranging from 1 to 12 (Grid system of bootstrap) Column Re-ordering: Create your content mobile-first (code written for the mobile screen) because it is easier to push and pull columns on larger devices. Therefore, you should focus on your mobile ordering first, and then on larger screens like tablets or desktops. Step by step guide for the implementation: Step 1: Include Bootstrap CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css”> Step 1: Include Bootstrap CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css”> Step 2: Add <div> tag in the HTML body with class row. Step 2: Add <div> tag in the HTML body with class row. Step 3: Add <div> tag for different columns with .push , .pull classes and so on classes in the <body> tag. Step 3: Add <div> tag for different columns with .push , .pull classes and so on classes in the <body> tag. Example 1: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css"/> </head> <body> <div class="row"> <div class="well well-lg clearfix"> <div class="col-xs-12 col-md-4 col-md-push-4"> <div class="alert alert-success">2</div> </div> <div class="col-xs-6 col-md-4 col-md-pull-4"> <div class="alert alert-info">1</div> </div> <div class="col-xs-6 col-md-4"> <div class="alert alert-warning">3</div> </div> </div> </div> </body></html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css"/> </head> <body> <div class="row"> <div class="well well-lg clearfix"> <div class="col-xs-6 col-md-4"> <div class="alert alert-info">1</div> </div> <div class="col-xs-6 col-md-4 col-md-push-4"> <div class="alert alert-warning">3</div> </div> <div class="col-xs-12 col-md-4 col-md-pull-4"> <div class="alert alert-success">2</div> </div> </div> </div> </body></html> Output: Conclusion: By using these procedure we can make our website responsive for different screen sizes and write mobile content. Bootstrap-4 Bootstrap-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Aug, 2021" }, { "code": null, "e": 278, "s": 54, "text": "Column ordering classes in Bootstrap helps to change the order of our grid system based on different screen sizes eg: desktop, mobile, tablet, smartwatches. This makes the website more responsive for different screen sizes." }, { "code": null, "e": 366, "s": 278, "text": "For example, let’s say we have 4 columns (V, X, Y, and Z). We want the appearance to be" }, { "code": null, "e": 436, "s": 366, "text": "On large screens: V X \n Y Z " }, { "code": null, "e": 455, "s": 436, "text": "On large screens: " }, { "code": null, "e": 507, "s": 455, "text": " V X \n Y Z " }, { "code": null, "e": 558, "s": 507, "text": " On small screens(mobile): Y Z \n V X" }, { "code": null, "e": 587, "s": 558, "text": " On small screens(mobile): " }, { "code": null, "e": 610, "s": 587, "text": " Y Z \n V X" }, { "code": null, "e": 701, "s": 610, "text": "We can easily change the order of built-in grid columns with push and pull column classes." }, { "code": null, "e": 827, "s": 701, "text": "The Push and Pull Classes: The push class will move columns to the right while the pull class will move columns to the left. " }, { "code": null, "e": 835, "s": 827, "text": "Syntax:" }, { "code": null, "e": 852, "s": 835, "text": " .col-md-pull-# " }, { "code": null, "e": 857, "s": 852, "text": " or " }, { "code": null, "e": 874, "s": 857, "text": " .col-md-push-# " }, { "code": null, "e": 942, "s": 874, "text": "Note: # is a number ranging from 1 to 12 (Grid system of bootstrap)" }, { "code": null, "e": 1209, "s": 942, "text": "Column Re-ordering: Create your content mobile-first (code written for the mobile screen) because it is easier to push and pull columns on larger devices. Therefore, you should focus on your mobile ordering first, and then on larger screens like tablets or desktops." }, { "code": null, "e": 1252, "s": 1209, "text": "Step by step guide for the implementation:" }, { "code": null, "e": 1456, "s": 1252, "text": "Step 1: Include Bootstrap CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css”>" }, { "code": null, "e": 1552, "s": 1456, "text": "Step 1: Include Bootstrap CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 1662, "s": 1554, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css”>" }, { "code": null, "e": 1717, "s": 1662, "text": "Step 2: Add <div> tag in the HTML body with class row." }, { "code": null, "e": 1772, "s": 1717, "text": "Step 2: Add <div> tag in the HTML body with class row." }, { "code": null, "e": 1880, "s": 1772, "text": "Step 3: Add <div> tag for different columns with .push , .pull classes and so on classes in the <body> tag." }, { "code": null, "e": 1988, "s": 1880, "text": "Step 3: Add <div> tag for different columns with .push , .pull classes and so on classes in the <body> tag." }, { "code": null, "e": 1999, "s": 1988, "text": "Example 1:" }, { "code": null, "e": 2004, "s": 1999, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css\"/> </head> <body> <div class=\"row\"> <div class=\"well well-lg clearfix\"> <div class=\"col-xs-12 col-md-4 col-md-push-4\"> <div class=\"alert alert-success\">2</div> </div> <div class=\"col-xs-6 col-md-4 col-md-pull-4\"> <div class=\"alert alert-info\">1</div> </div> <div class=\"col-xs-6 col-md-4\"> <div class=\"alert alert-warning\">3</div> </div> </div> </div> </body></html>", "e": 2612, "s": 2004, "text": null }, { "code": null, "e": 2620, "s": 2612, "text": "Output:" }, { "code": null, "e": 2631, "s": 2620, "text": "Example 2:" }, { "code": null, "e": 2636, "s": 2631, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css\"/> </head> <body> <div class=\"row\"> <div class=\"well well-lg clearfix\"> <div class=\"col-xs-6 col-md-4\"> <div class=\"alert alert-info\">1</div> </div> <div class=\"col-xs-6 col-md-4 col-md-push-4\"> <div class=\"alert alert-warning\">3</div> </div> <div class=\"col-xs-12 col-md-4 col-md-pull-4\"> <div class=\"alert alert-success\">2</div> </div> </div> </div> </body></html>", "e": 3244, "s": 2636, "text": null }, { "code": null, "e": 3252, "s": 3244, "text": "Output:" }, { "code": null, "e": 3377, "s": 3252, "text": "Conclusion: By using these procedure we can make our website responsive for different screen sizes and write mobile content." }, { "code": null, "e": 3389, "s": 3377, "text": "Bootstrap-4" }, { "code": null, "e": 3409, "s": 3389, "text": "Bootstrap-Questions" }, { "code": null, "e": 3416, "s": 3409, "text": "Picked" }, { "code": null, "e": 3426, "s": 3416, "text": "Bootstrap" }, { "code": null, "e": 3431, "s": 3426, "text": "HTML" }, { "code": null, "e": 3448, "s": 3431, "text": "Web Technologies" }, { "code": null, "e": 3453, "s": 3448, "text": "HTML" } ]
Python – Bitwise AND of List
06 Oct, 2020 Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Let’s discuss certain ways in which this task can be performed.Method #1 : Using reduce() + lambda + “&” operator The above functions can be combined to perform this task. We can employ reduce() to accumulate the result of AND logic specified by the lambda function. Works only with Python2. Python3 # Python code to demonstrate working of# Bitwise AND of List# Using reduce() + lambda + "&" operator # initializing listtest_list = [4, 6, 2, 3, 8, 9] # printing original listprint("The original list is : " + str(test_list)) # Bitwise AND of List# Using reduce() + lambda + "&" operatorres = reduce(lambda x, y: x & y, test_list) # printing resultprint("The Bitwise AND of list elements are : " + str(res)) The original list is : [4, 6, 2, 3, 8, 9] The Bitwise AND of list elements are : 0 Method #2 : Using reduce() + operator.iand This task can also be performed using this method. In this the task performed by lambda function in above method is performed using iand function for cumulative AND operation. Works with Python2 only. Python3 # Python code to demonstrate working of# Bitwise AND of List# Using functools.reduce() + operator.iandfrom operator import iandfrom functools import reduce# initializing listtest_list = [4, 6, 2, 3, 8, 9] # printing original listprint("The original list is : " + str(test_list)) # Bitwise AND of List# Using functools.reduce() + operator.iandres = reduce(iand, test_list) # printing resultprint("The Bitwise AND of list elements are : " + str(res)) The original list is : [4, 6, 2, 3, 8, 9] The Bitwise AND of list elements are : 0 sujy Python list-programs Python Python Programs 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() Python program to convert a list to string Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Oct, 2020" }, { "code": null, "e": 555, "s": 54, "text": "Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Let’s discuss certain ways in which this task can be performed.Method #1 : Using reduce() + lambda + “&” operator The above functions can be combined to perform this task. We can employ reduce() to accumulate the result of AND logic specified by the lambda function. Works only with Python2. " }, { "code": null, "e": 563, "s": 555, "text": "Python3" }, { "code": "# Python code to demonstrate working of# Bitwise AND of List# Using reduce() + lambda + \"&\" operator # initializing listtest_list = [4, 6, 2, 3, 8, 9] # printing original listprint(\"The original list is : \" + str(test_list)) # Bitwise AND of List# Using reduce() + lambda + \"&\" operatorres = reduce(lambda x, y: x & y, test_list) # printing resultprint(\"The Bitwise AND of list elements are : \" + str(res))", "e": 970, "s": 563, "text": null }, { "code": null, "e": 1055, "s": 970, "text": "The original list is : [4, 6, 2, 3, 8, 9]\nThe Bitwise AND of list elements are : 0\n\n" }, { "code": null, "e": 1303, "s": 1057, "text": " Method #2 : Using reduce() + operator.iand This task can also be performed using this method. In this the task performed by lambda function in above method is performed using iand function for cumulative AND operation. Works with Python2 only. " }, { "code": null, "e": 1311, "s": 1303, "text": "Python3" }, { "code": "# Python code to demonstrate working of# Bitwise AND of List# Using functools.reduce() + operator.iandfrom operator import iandfrom functools import reduce# initializing listtest_list = [4, 6, 2, 3, 8, 9] # printing original listprint(\"The original list is : \" + str(test_list)) # Bitwise AND of List# Using functools.reduce() + operator.iandres = reduce(iand, test_list) # printing resultprint(\"The Bitwise AND of list elements are : \" + str(res))", "e": 1760, "s": 1311, "text": null }, { "code": null, "e": 1845, "s": 1760, "text": "The original list is : [4, 6, 2, 3, 8, 9]\nThe Bitwise AND of list elements are : 0\n\n" }, { "code": null, "e": 1852, "s": 1847, "text": "sujy" }, { "code": null, "e": 1873, "s": 1852, "text": "Python list-programs" }, { "code": null, "e": 1880, "s": 1873, "text": "Python" }, { "code": null, "e": 1896, "s": 1880, "text": "Python Programs" }, { "code": null, "e": 1994, "s": 1896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2012, "s": 1994, "text": "Python Dictionary" }, { "code": null, "e": 2054, "s": 2012, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2076, "s": 2054, "text": "Enumerate() in Python" }, { "code": null, "e": 2111, "s": 2076, "text": "Read a file line by line in Python" }, { "code": null, "e": 2137, "s": 2111, "text": "Python String | replace()" }, { "code": null, "e": 2180, "s": 2137, "text": "Python program to convert a list to string" }, { "code": null, "e": 2219, "s": 2180, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2257, "s": 2219, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2306, "s": 2257, "text": "Python | Convert string dictionary to dictionary" } ]
Implementation of Composition (Has-A Relation) in Python
19 Apr, 2021 We can access the member of one class inside a class using these 2 concepts: By Composition(Has-A Relation) By Inheritance(Is-A Relation) Here we will study how to use implement Has-A Relation in Python. Implementation of Composition in Python By using the class names or by creating an object we can access the member of one class inside another class. Example: class Engine: # engine specific functionality ''' ''' ''' class Car: e = Engine() e.method1() e.method2() ''' ''' In these above example class Car has-A Engine class reference. Here inside class Car also we can create different variables and methods. Using object reference of Engine class inside Car class we can easily access each and every member of Engine class inside Car class. Example 1: Executable code for composition Python3 class Employee: # constructor for initialization def __init__(self, name, age): self.name = name self.age = age # instance method def emp_data(self): print('Name of Employee : ', self.name) print('Age of Employee : ', self.age) class Data: def __init__(self, address, salary, emp_obj): self.address = address self.salary = salary # creating object of Employee class self.emp_obj = emp_obj # instance method def display(self): # calling Employee class emp_data() # method self.emp_obj.emp_data() print('Address of Employee : ', self.address) print('Salary of Employee : ', self.salary) # creating Employee class objectemp = Employee('Ronil', 20) # passing obj. of Emp. class during creation# of Data class objectdata = Data('Indore', 25000, emp) # call Data class instance methoddata.display() Name of Employee : Ronil Age of Employee : 20 Address of Employee : Indore Salary of Employee : 25000 Here in the above example, we have 2 classes ‘Employee’ and ‘Data’. Inside ‘Data’ class Constructor we are creating an object of Employee class due to which we can access the members of the Employee class easily. Inside the Data class Employee class object becomes an instance variable of “Data” class. We are creating objects inside the constructor so whenever we will call any method or variable of class Employee we must use self keyword. We can replace “self.emp_obj” to “Employee”, but by using the class name Employee we can access only the static method or variable of the Employee class. Example 2: Another simple example using Composition Python3 class A: def __init__(self): print('Class - A Constructor') def m1(self): print('M1 method of Class - A.') class B: def __init__(self): print('Class - B Constructor.') # instance method def m2(self): # creating object of class A inside # B class instance method obj = A() # calling m1() method of class-A obj.m1() print('M2 method of Class - B.') # creating object of class-Bobj = B() # calling B class m2() methodobj.m2() Output Class - B Constructor. Class - A Constructor M1 method of Class - A. M2 method of Class - B. Here in the above example, we are creating an object of class A inside instance method of class B that is m2() method. So the flow of execution will be Initially, the object of class B will be created so the constructor of class B will get executed. Now object of class B is calling m2() method, so the cursor will go to the m2() method of class B. Inside the m2() method of class B object of class A is created so the constructor of class A will be executed then m1() method of class A will be executed finally it will print the final statement of m2() method and execution end’s here. arorakashish0911 python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2021" }, { "code": null, "e": 106, "s": 28, "text": "We can access the member of one class inside a class using these 2 concepts: " }, { "code": null, "e": 137, "s": 106, "text": "By Composition(Has-A Relation)" }, { "code": null, "e": 167, "s": 137, "text": "By Inheritance(Is-A Relation)" }, { "code": null, "e": 233, "s": 167, "text": "Here we will study how to use implement Has-A Relation in Python." }, { "code": null, "e": 273, "s": 233, "text": "Implementation of Composition in Python" }, { "code": null, "e": 384, "s": 273, "text": "By using the class names or by creating an object we can access the member of one class inside another class. " }, { "code": null, "e": 393, "s": 384, "text": "Example:" }, { "code": null, "e": 535, "s": 393, "text": "class Engine:\n # engine specific functionality\n '''\n '''\n '''\n\nclass Car:\n e = Engine()\n e.method1()\n e.method2()\n '''\n '''" }, { "code": null, "e": 805, "s": 535, "text": "In these above example class Car has-A Engine class reference. Here inside class Car also we can create different variables and methods. Using object reference of Engine class inside Car class we can easily access each and every member of Engine class inside Car class." }, { "code": null, "e": 848, "s": 805, "text": "Example 1: Executable code for composition" }, { "code": null, "e": 856, "s": 848, "text": "Python3" }, { "code": "class Employee: # constructor for initialization def __init__(self, name, age): self.name = name self.age = age # instance method def emp_data(self): print('Name of Employee : ', self.name) print('Age of Employee : ', self.age) class Data: def __init__(self, address, salary, emp_obj): self.address = address self.salary = salary # creating object of Employee class self.emp_obj = emp_obj # instance method def display(self): # calling Employee class emp_data() # method self.emp_obj.emp_data() print('Address of Employee : ', self.address) print('Salary of Employee : ', self.salary) # creating Employee class objectemp = Employee('Ronil', 20) # passing obj. of Emp. class during creation# of Data class objectdata = Data('Indore', 25000, emp) # call Data class instance methoddata.display()", "e": 1767, "s": 856, "text": null }, { "code": null, "e": 1876, "s": 1770, "text": "Name of Employee : Ronil\nAge of Employee : 20\nAddress of Employee : Indore\nSalary of Employee : 25000" }, { "code": null, "e": 2474, "s": 1878, "text": "Here in the above example, we have 2 classes ‘Employee’ and ‘Data’. Inside ‘Data’ class Constructor we are creating an object of Employee class due to which we can access the members of the Employee class easily. Inside the Data class Employee class object becomes an instance variable of “Data” class. We are creating objects inside the constructor so whenever we will call any method or variable of class Employee we must use self keyword. We can replace “self.emp_obj” to “Employee”, but by using the class name Employee we can access only the static method or variable of the Employee class." }, { "code": null, "e": 2528, "s": 2476, "text": "Example 2: Another simple example using Composition" }, { "code": null, "e": 2538, "s": 2530, "text": "Python3" }, { "code": "class A: def __init__(self): print('Class - A Constructor') def m1(self): print('M1 method of Class - A.') class B: def __init__(self): print('Class - B Constructor.') # instance method def m2(self): # creating object of class A inside # B class instance method obj = A() # calling m1() method of class-A obj.m1() print('M2 method of Class - B.') # creating object of class-Bobj = B() # calling B class m2() methodobj.m2()", "e": 3045, "s": 2538, "text": null }, { "code": null, "e": 3052, "s": 3045, "text": "Output" }, { "code": null, "e": 3145, "s": 3052, "text": "Class - B Constructor.\nClass - A Constructor\nM1 method of Class - A.\nM2 method of Class - B." }, { "code": null, "e": 3734, "s": 3147, "text": "Here in the above example, we are creating an object of class A inside instance method of class B that is m2() method. So the flow of execution will be Initially, the object of class B will be created so the constructor of class B will get executed. Now object of class B is calling m2() method, so the cursor will go to the m2() method of class B. Inside the m2() method of class B object of class A is created so the constructor of class A will be executed then m1() method of class A will be executed finally it will print the final statement of m2() method and execution end’s here." }, { "code": null, "e": 3753, "s": 3736, "text": "arorakashish0911" }, { "code": null, "e": 3773, "s": 3753, "text": "python-oop-concepts" }, { "code": null, "e": 3780, "s": 3773, "text": "Python" }, { "code": null, "e": 3878, "s": 3780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3896, "s": 3878, "text": "Python Dictionary" }, { "code": null, "e": 3938, "s": 3896, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3960, "s": 3938, "text": "Enumerate() in Python" }, { "code": null, "e": 3995, "s": 3960, "text": "Read a file line by line in Python" }, { "code": null, "e": 4021, "s": 3995, "text": "Python String | replace()" }, { "code": null, "e": 4053, "s": 4021, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4082, "s": 4053, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4109, "s": 4082, "text": "Python Classes and Objects" }, { "code": null, "e": 4139, "s": 4109, "text": "Iterate over a list in Python" } ]
Python 3 - os.unlink() Method
The method unlink() removes (deletes) the file path.If the path is a directory, OSError is raised. function is identical to remove(); the unlink name is its traditional Unix name. Following is the syntax for unlink() method − os.unlink(path) path − This is the path, which is to be removed. This method does not return any value. The following example shows the usage of unlink() method. # !/usr/bin/python3 import os, sys os.chdir("d:\\tmp") # listing directories print ("The dir is: %s" %os.listdir(os.getcwd())) os.unlink("foo.txt") # listing directories after removing path print ("The dir after removal of path : %s" %os.listdir(os.getcwd())) When we run the above program, it produces the following result − The dir is: [ 'Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 'java.ppt', 'python2' ] The dir after removal of path : [ 'Applicationdocs.docx', 'book.zip', 'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 'java.ppt', 'python2'
[ { "code": null, "e": 2654, "s": 2474, "text": "The method unlink() removes (deletes) the file path.If the path is a directory, OSError is raised. function is identical to remove(); the unlink name is its traditional Unix name." }, { "code": null, "e": 2700, "s": 2654, "text": "Following is the syntax for unlink() method −" }, { "code": null, "e": 2717, "s": 2700, "text": "os.unlink(path)\n" }, { "code": null, "e": 2766, "s": 2717, "text": "path − This is the path, which is to be removed." }, { "code": null, "e": 2805, "s": 2766, "text": "This method does not return any value." }, { "code": null, "e": 2863, "s": 2805, "text": "The following example shows the usage of unlink() method." }, { "code": null, "e": 3125, "s": 2863, "text": "# !/usr/bin/python3\nimport os, sys\nos.chdir(\"d:\\\\tmp\")\n\n# listing directories\nprint (\"The dir is: %s\" %os.listdir(os.getcwd()))\nos.unlink(\"foo.txt\")\n\n# listing directories after removing path\nprint (\"The dir after removal of path : %s\" %os.listdir(os.getcwd()))" }, { "code": null, "e": 3191, "s": 3125, "text": "When we run the above program, it produces the following result −" } ]
Import multiple excel sheets into in R
17 Jun, 2021 In this article, we are going to see how to import multiple Excel sheets into the R language. Excel provides us with multiple worksheets. For example, in the below Excel workbook StudentData, we have two worksheets – sheet 1 is Student Details and sheet 2 is Subject Details. For importing multiple Excel sheets into R, we have to, first install a package in R which is known as readxl. After successfully installing the package, we have to load the package using the library function is R. install.packages('readxl') Once we have completely installed and loaded the package in RStudio, the next job is to import the excel workbook and check the number of sheet it contains. We can do this using the excel_sheets function. R library("read_excel") # Importing the excel workbook for# checking the number of sheets it containsexcel_sheets("StudentData.xlsx") Output: 'StudentDetails' 'SubjectDetails' We have an Excel file named as “StudentData” and we have already saved it in our working directory. It contains two sheets named StudentDetails and SubjectDetails. We have a function in R called read_excel() which we will use to import specific sheet into R. If no argument is specified, then the read_excel() will by default import the first Excel sheet. Syntax: read_excel(arg) Code: R # Importing specific sheets into R using the read_excel()StudentDet<-read_excel("StudentData.xlsx", sheet = 1)StudentDet<-read_excel("StudentData.xlsx", sheet = "StudentDetails")SubjectDet<-read_excel("StudentData.xlsx", sheet = "SubjectDetails") # For viewing the details of sheet 1head(StudentDet)# For viewing the details of sheet 2head(SubjectDet) Output: Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2021" }, { "code": null, "e": 147, "s": 52, "text": "In this article, we are going to see how to import multiple Excel sheets into the R language. " }, { "code": null, "e": 329, "s": 147, "text": "Excel provides us with multiple worksheets. For example, in the below Excel workbook StudentData, we have two worksheets – sheet 1 is Student Details and sheet 2 is Subject Details." }, { "code": null, "e": 544, "s": 329, "text": "For importing multiple Excel sheets into R, we have to, first install a package in R which is known as readxl. After successfully installing the package, we have to load the package using the library function is R." }, { "code": null, "e": 571, "s": 544, "text": "install.packages('readxl')" }, { "code": null, "e": 778, "s": 571, "text": "Once we have completely installed and loaded the package in RStudio, the next job is to import the excel workbook and check the number of sheet it contains. We can do this using the excel_sheets function. " }, { "code": null, "e": 780, "s": 778, "text": "R" }, { "code": "library(\"read_excel\") # Importing the excel workbook for# checking the number of sheets it containsexcel_sheets(\"StudentData.xlsx\")", "e": 916, "s": 780, "text": null }, { "code": null, "e": 924, "s": 916, "text": "Output:" }, { "code": null, "e": 958, "s": 924, "text": "'StudentDetails' 'SubjectDetails'" }, { "code": null, "e": 1314, "s": 958, "text": "We have an Excel file named as “StudentData” and we have already saved it in our working directory. It contains two sheets named StudentDetails and SubjectDetails. We have a function in R called read_excel() which we will use to import specific sheet into R. If no argument is specified, then the read_excel() will by default import the first Excel sheet." }, { "code": null, "e": 1338, "s": 1314, "text": "Syntax: read_excel(arg)" }, { "code": null, "e": 1344, "s": 1338, "text": "Code:" }, { "code": null, "e": 1346, "s": 1344, "text": "R" }, { "code": "# Importing specific sheets into R using the read_excel()StudentDet<-read_excel(\"StudentData.xlsx\", sheet = 1)StudentDet<-read_excel(\"StudentData.xlsx\", sheet = \"StudentDetails\")SubjectDet<-read_excel(\"StudentData.xlsx\", sheet = \"SubjectDetails\") # For viewing the details of sheet 1head(StudentDet)# For viewing the details of sheet 2head(SubjectDet)", "e": 1767, "s": 1346, "text": null }, { "code": null, "e": 1775, "s": 1767, "text": "Output:" }, { "code": null, "e": 1782, "s": 1775, "text": "Picked" }, { "code": null, "e": 1790, "s": 1782, "text": "R-Excel" }, { "code": null, "e": 1801, "s": 1790, "text": "R Language" }, { "code": null, "e": 1899, "s": 1801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1951, "s": 1899, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2003, "s": 1951, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2061, "s": 2003, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2093, "s": 2061, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2128, "s": 2093, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2172, "s": 2128, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2210, "s": 2172, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2259, "s": 2210, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2276, "s": 2259, "text": "R - if statement" } ]
Wildcard Selectors (*, ^ and $) in CSS for classes
19 May, 2022 Wildcard selector is used to select multiple elements simultaneously. It selects similar type of class name or attribute and use CSS property. * wildcard also known as containing wildcard. [attribute*=”str”] Selector: The [attribute*=”str”] selector is used to select that elements whose attribute value contains the specified sub string str. This example shows how to use a wildcard to select all div with a class that contains str. This could be at the start, the end or in the middle of the class. Syntax: [attribute*="value"] { // CSS property } Example: html <!DOCTYPE html><html> <head> <style> /* Define styles of selected items, h1 and rest of the body */ [class*="str"] { /* WE USE * HERE */ background: green; color: white; } h1 { color:green; } body { text-align:center; width:60%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <!-- Since we have used * with str, all items with str in them are selected --> <div class="first_str">The first div element.</div> <div class="second">The second div element.</div> <div class="my-strt">The third div element.</div> <p class="mystr">Paragraph Text</p> </body></html> Output: [attribute^=”str”] Selector: The [attribute^=”value”] selector is used to select those elements whose attribute value begins with a specified value str. This example shows how to use a wildcard to select all div with a class that starts with str. Syntax: [attribute^="str"] { // CSS property } Example: html <!DOCTYPE html><html> <head> <style> [class^="str"] { /*WE USE ^ HERE */ background: green; color: white; } h1 { color:green; } body { text-align:center; width:60%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <!-- All items beginning with str are highlighted --> <div class="strfirst">The first div element.</div> <div class="strsecond">The second div element.</div> <div class="str-start">The third div element.</div> <div class="end-str">The fourth div element.</div> <p class="my">Paragraph Text</p> </body></html> Output: [attribute$=”str”] Selector: The [attribute$=”value”] selector is used to select those elements whose attribute value ends with a specified value str. The following example selects all elements with a class attribute value that ends with str. Syntax: [attribute$="str"] { // CSS property } Example: html <!DOCTYPE html><html> <head> <style> [class$="str"] { /* WE USE $ HERE */ background: green; color: white; } h1 { color:green; } body { text-align:center; width:60%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <!-- All items ending with str are highlighted --> <div class="firststr">The first div element.</div> <div class="stsecondstr">The second div element.</div> <div class="start">The third div element.</div> <p class="mystr">This is some text in a paragraph.</p> </body></html> Output: CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. hardikkoriintern CSS-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2022" }, { "code": null, "e": 530, "s": 28, "text": "Wildcard selector is used to select multiple elements simultaneously. It selects similar type of class name or attribute and use CSS property. * wildcard also known as containing wildcard. [attribute*=”str”] Selector: The [attribute*=”str”] selector is used to select that elements whose attribute value contains the specified sub string str. This example shows how to use a wildcard to select all div with a class that contains str. This could be at the start, the end or in the middle of the class. " }, { "code": null, "e": 538, "s": 530, "text": "Syntax:" }, { "code": null, "e": 583, "s": 538, "text": "[attribute*=\"value\"] {\n // CSS property\n}" }, { "code": null, "e": 593, "s": 583, "text": "Example: " }, { "code": null, "e": 598, "s": 593, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> /* Define styles of selected items, h1 and rest of the body */ [class*=\"str\"] { /* WE USE * HERE */ background: green; color: white; } h1 { color:green; } body { text-align:center; width:60%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <!-- Since we have used * with str, all items with str in them are selected --> <div class=\"first_str\">The first div element.</div> <div class=\"second\">The second div element.</div> <div class=\"my-strt\">The third div element.</div> <p class=\"mystr\">Paragraph Text</p> </body></html>", "e": 1424, "s": 598, "text": null }, { "code": null, "e": 1432, "s": 1424, "text": "Output:" }, { "code": null, "e": 1683, "s": 1435, "text": "[attribute^=”str”] Selector: The [attribute^=”value”] selector is used to select those elements whose attribute value begins with a specified value str. This example shows how to use a wildcard to select all div with a class that starts with str. " }, { "code": null, "e": 1691, "s": 1683, "text": "Syntax:" }, { "code": null, "e": 1734, "s": 1691, "text": "[attribute^=\"str\"] {\n // CSS property\n}" }, { "code": null, "e": 1744, "s": 1734, "text": "Example: " }, { "code": null, "e": 1749, "s": 1744, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> [class^=\"str\"] { /*WE USE ^ HERE */ background: green; color: white; } h1 { color:green; } body { text-align:center; width:60%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <!-- All items beginning with str are highlighted --> <div class=\"strfirst\">The first div element.</div> <div class=\"strsecond\">The second div element.</div> <div class=\"str-start\">The third div element.</div> <div class=\"end-str\">The fourth div element.</div> <p class=\"my\">Paragraph Text</p> </body></html>", "e": 2497, "s": 1749, "text": null }, { "code": null, "e": 2505, "s": 2497, "text": "Output:" }, { "code": null, "e": 2752, "s": 2507, "text": " [attribute$=”str”] Selector: The [attribute$=”value”] selector is used to select those elements whose attribute value ends with a specified value str. The following example selects all elements with a class attribute value that ends with str. " }, { "code": null, "e": 2760, "s": 2752, "text": "Syntax:" }, { "code": null, "e": 2803, "s": 2760, "text": "[attribute$=\"str\"] {\n // CSS property\n}" }, { "code": null, "e": 2813, "s": 2803, "text": "Example: " }, { "code": null, "e": 2818, "s": 2813, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> [class$=\"str\"] { /* WE USE $ HERE */ background: green; color: white; } h1 { color:green; } body { text-align:center; width:60%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <!-- All items ending with str are highlighted --> <div class=\"firststr\">The first div element.</div> <div class=\"stsecondstr\">The second div element.</div> <div class=\"start\">The third div element.</div> <p class=\"mystr\">This is some text in a paragraph.</p> </body></html> ", "e": 3558, "s": 2818, "text": null }, { "code": null, "e": 3566, "s": 3558, "text": "Output:" }, { "code": null, "e": 3845, "s": 3658, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 3862, "s": 3845, "text": "hardikkoriintern" }, { "code": null, "e": 3871, "s": 3862, "text": "CSS-Misc" }, { "code": null, "e": 3875, "s": 3871, "text": "CSS" }, { "code": null, "e": 3880, "s": 3875, "text": "HTML" }, { "code": null, "e": 3897, "s": 3880, "text": "Web Technologies" }, { "code": null, "e": 3902, "s": 3897, "text": "HTML" }, { "code": null, "e": 4000, "s": 3902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4048, "s": 4000, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4110, "s": 4048, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4160, "s": 4110, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4218, "s": 4160, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4268, "s": 4218, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4316, "s": 4268, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4378, "s": 4316, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4428, "s": 4378, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4452, "s": 4428, "text": "REST API (Introduction)" } ]
How to download the public companies’ earnings calendar in Python | by Eryk Lewinson | Towards Data Science
At the moment of writing, we are currently close to the end of the Q1 2020 earnings season. For many investors and quantitative finance hobbyists, this is a specially interesting period, with multiple short-term investment opportunities. That is why in this article, I wanted to briefly introduce the concept of the earnings season and show how to easily extract all the important information using Python. The term earnings season refers to the time periods of the year during which most publicly listed companies release their quarterly corporate earnings reports to the public. The earnings seasons occur in the months immediately following the end of each fiscal quarter, so this would correspond to the months of January, April, July, and October. Typically, the earnings seasons last for about 6 weeks, after which the number of reported earnings subsidies to the off-season frequency (there are still some companies reporting off-season, as their financial calendars might be a bit different than the most). Why is the earnings season an important time for potential investors? Simply because around the date of the given company’s earnings release (and mostly on the date itself), one can expect some significant price movements of the stock. That is caused by the fact that the public companies report their financial and general situation: profits/losses made in the past quarter, any significant changes to the organization, etc. Financial analysts use that information for assessing the intrinsic value of the stock — in order to determine if its current market price is over- or under-valued. This, in turn, is a potential signal for the investors to buy/sell/hold the stock. Most of the companies have a dedicated part of their websites for potential/current investors, where they provide access to the earnings reports and also to the dates of the incoming earnings releases. Naturally, getting information from individual websites would not be feasible (or at least it would not be a pleasant experience). That is why we will refer to the popular source of financial data — Yahoo! Finance. Below you can see an image coming from the current earnings calendar. In one of my previous articles, I showed how to leverage some popular Python libraries to easily download information related to the stock prices (and some additional information about the companies themselves). In this article, I extend the toolkit with a new library called yahoo-earnings-calendar (yes, the name is pretty self-explanatory). It definitely has a few advantages over the previously described solutions, as you will see below. Aside from the standard libraries, we need to install yahoo_earnings_calendar by running the following line of code in the terminal: pip install yahoo_earnings_calendar Having done that, we import all the libraries we will use in this article: Below, we will go over the three available methods used for downloading the earnings calendar. The first method we explore is used for downloading the earnings for a specific date. To download the data, we first define the date using the datetime library. In this example, we use the current day (15th of May, 2020). Then, we instantiate an object of the YahooEarningsCalendar class. Using the earnings_on method, we download the data in the form of a list of dictionaries. Lastly, we store the downloaded data in a pandas.DataFrame. Running the code generates the preview of the DataFrame. The startdatetimetype column contains information about the time of the earnings call. Traditionally, the earnings (and any other important information about the company’s situation) are announced during an earnings call with the interested investors. Summing up, this is when the earnings are announced to the public. Legend for the startdatetimetype column: BMO — before the market opens AMC — after the market closes TAS/TNS — time not specified By running df_earnings.shape we see that the DataFrame has 119 rows, which is in line with the screenshot presented above. A potential shortcoming of downloading the calendar this way is the fact that we only receive earnings data about US companies. That is the default setting of the filter used on the Yahoo! Finance website. The easiest and most certain solution to download information about non-US companies is to do so by using the stock’s ticker. We discuss that method below. Downloading the calendar for a range of dates is very similar to what we already described. This time, we use the earnings_between method and provide the start and end dates of the period of interest. For the example below, we download the earnings’ dates for the next 7 days. This time earnings_df contains 312 positions. One important thing to take into account while working with the earnings data is the fact that the calendar can change over time. So in the case of downloading the earnings a few weeks/months ahead of time, you might want to refresh the download every now and then to make sure the data is still valid. Lastly, we download the earnings dates for a specific product, Twitter in this case. We do that by using the get_earnings_of method and providing the stock’s ticker. What is different this time around is that the request will return a list of past and future earnings. That is why we extract the date from the timestamp string (it is stored in the ISO-8601 format) and use the between method to filter out only the earnings from the upcoming 180 days. The code returns the following table, which contains the 2 earnings release dates for Twitter in the upcoming 180 days. In this article, I explained what is the earnings season and how to easily get all the earnings releases dates from Yahoo! Finance. Having the data available for use in Python, I can think of a few potential use-cases: Building an automated email /Slack bot notifying you about relevant earnings releases. Including the earnings release dates in your ML model used for predicting the price of the stock. For example, you can indicate the earnings dates as changepoints in Facebook's Prophet. The yahoo-earnings-calendar library is pretty compact in terms of lines of code, so I would definitely recommend inspecting the code to understand how the data is actually scraped from Yahoo! Finance. This might be especially important, as Yahoo! tends to change the website rather frequently, what can result in the library becoming unusable, at least until it is fixed. That is why you should be cautious when putting any code based on it into production. Additionally, it definitely makes sense to be familiar with the methodology used for scraping the data, so you can potentially fix any issues before they are fixed by the author. And you can always do a pull request with that update :) You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. Not that long ago I published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website. [1] Yahoo! Earnings Calendar Scraper — GitHub
[ { "code": null, "e": 579, "s": 172, "text": "At the moment of writing, we are currently close to the end of the Q1 2020 earnings season. For many investors and quantitative finance hobbyists, this is a specially interesting period, with multiple short-term investment opportunities. That is why in this article, I wanted to briefly introduce the concept of the earnings season and show how to easily extract all the important information using Python." }, { "code": null, "e": 1187, "s": 579, "text": "The term earnings season refers to the time periods of the year during which most publicly listed companies release their quarterly corporate earnings reports to the public. The earnings seasons occur in the months immediately following the end of each fiscal quarter, so this would correspond to the months of January, April, July, and October. Typically, the earnings seasons last for about 6 weeks, after which the number of reported earnings subsidies to the off-season frequency (there are still some companies reporting off-season, as their financial calendars might be a bit different than the most)." }, { "code": null, "e": 1861, "s": 1187, "text": "Why is the earnings season an important time for potential investors? Simply because around the date of the given company’s earnings release (and mostly on the date itself), one can expect some significant price movements of the stock. That is caused by the fact that the public companies report their financial and general situation: profits/losses made in the past quarter, any significant changes to the organization, etc. Financial analysts use that information for assessing the intrinsic value of the stock — in order to determine if its current market price is over- or under-valued. This, in turn, is a potential signal for the investors to buy/sell/hold the stock." }, { "code": null, "e": 2348, "s": 1861, "text": "Most of the companies have a dedicated part of their websites for potential/current investors, where they provide access to the earnings reports and also to the dates of the incoming earnings releases. Naturally, getting information from individual websites would not be feasible (or at least it would not be a pleasant experience). That is why we will refer to the popular source of financial data — Yahoo! Finance. Below you can see an image coming from the current earnings calendar." }, { "code": null, "e": 2791, "s": 2348, "text": "In one of my previous articles, I showed how to leverage some popular Python libraries to easily download information related to the stock prices (and some additional information about the companies themselves). In this article, I extend the toolkit with a new library called yahoo-earnings-calendar (yes, the name is pretty self-explanatory). It definitely has a few advantages over the previously described solutions, as you will see below." }, { "code": null, "e": 2924, "s": 2791, "text": "Aside from the standard libraries, we need to install yahoo_earnings_calendar by running the following line of code in the terminal:" }, { "code": null, "e": 2960, "s": 2924, "text": "pip install yahoo_earnings_calendar" }, { "code": null, "e": 3035, "s": 2960, "text": "Having done that, we import all the libraries we will use in this article:" }, { "code": null, "e": 3130, "s": 3035, "text": "Below, we will go over the three available methods used for downloading the earnings calendar." }, { "code": null, "e": 3569, "s": 3130, "text": "The first method we explore is used for downloading the earnings for a specific date. To download the data, we first define the date using the datetime library. In this example, we use the current day (15th of May, 2020). Then, we instantiate an object of the YahooEarningsCalendar class. Using the earnings_on method, we download the data in the form of a list of dictionaries. Lastly, we store the downloaded data in a pandas.DataFrame." }, { "code": null, "e": 3626, "s": 3569, "text": "Running the code generates the preview of the DataFrame." }, { "code": null, "e": 3945, "s": 3626, "text": "The startdatetimetype column contains information about the time of the earnings call. Traditionally, the earnings (and any other important information about the company’s situation) are announced during an earnings call with the interested investors. Summing up, this is when the earnings are announced to the public." }, { "code": null, "e": 3986, "s": 3945, "text": "Legend for the startdatetimetype column:" }, { "code": null, "e": 4016, "s": 3986, "text": "BMO — before the market opens" }, { "code": null, "e": 4046, "s": 4016, "text": "AMC — after the market closes" }, { "code": null, "e": 4075, "s": 4046, "text": "TAS/TNS — time not specified" }, { "code": null, "e": 4326, "s": 4075, "text": "By running df_earnings.shape we see that the DataFrame has 119 rows, which is in line with the screenshot presented above. A potential shortcoming of downloading the calendar this way is the fact that we only receive earnings data about US companies." }, { "code": null, "e": 4560, "s": 4326, "text": "That is the default setting of the filter used on the Yahoo! Finance website. The easiest and most certain solution to download information about non-US companies is to do so by using the stock’s ticker. We discuss that method below." }, { "code": null, "e": 4837, "s": 4560, "text": "Downloading the calendar for a range of dates is very similar to what we already described. This time, we use the earnings_between method and provide the start and end dates of the period of interest. For the example below, we download the earnings’ dates for the next 7 days." }, { "code": null, "e": 4883, "s": 4837, "text": "This time earnings_df contains 312 positions." }, { "code": null, "e": 5186, "s": 4883, "text": "One important thing to take into account while working with the earnings data is the fact that the calendar can change over time. So in the case of downloading the earnings a few weeks/months ahead of time, you might want to refresh the download every now and then to make sure the data is still valid." }, { "code": null, "e": 5638, "s": 5186, "text": "Lastly, we download the earnings dates for a specific product, Twitter in this case. We do that by using the get_earnings_of method and providing the stock’s ticker. What is different this time around is that the request will return a list of past and future earnings. That is why we extract the date from the timestamp string (it is stored in the ISO-8601 format) and use the between method to filter out only the earnings from the upcoming 180 days." }, { "code": null, "e": 5758, "s": 5638, "text": "The code returns the following table, which contains the 2 earnings release dates for Twitter in the upcoming 180 days." }, { "code": null, "e": 5890, "s": 5758, "text": "In this article, I explained what is the earnings season and how to easily get all the earnings releases dates from Yahoo! Finance." }, { "code": null, "e": 5977, "s": 5890, "text": "Having the data available for use in Python, I can think of a few potential use-cases:" }, { "code": null, "e": 6064, "s": 5977, "text": "Building an automated email /Slack bot notifying you about relevant earnings releases." }, { "code": null, "e": 6250, "s": 6064, "text": "Including the earnings release dates in your ML model used for predicting the price of the stock. For example, you can indicate the earnings dates as changepoints in Facebook's Prophet." }, { "code": null, "e": 6944, "s": 6250, "text": "The yahoo-earnings-calendar library is pretty compact in terms of lines of code, so I would definitely recommend inspecting the code to understand how the data is actually scraped from Yahoo! Finance. This might be especially important, as Yahoo! tends to change the website rather frequently, what can result in the library becoming unusable, at least until it is fixed. That is why you should be cautious when putting any code based on it into production. Additionally, it definitely makes sense to be familiar with the methodology used for scraping the data, so you can potentially fix any issues before they are fixed by the author. And you can always do a pull request with that update :)" }, { "code": null, "e": 7106, "s": 6944, "text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments." }, { "code": null, "e": 7344, "s": 7106, "text": "Not that long ago I published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website." } ]
Spaghetti Code - GeeksforGeeks
17 Jun, 2021 In this article, we will discuss Spaghetti Code, and We often hear this term, Spaghetti Code, and we should avoid it. But what exactly is Spaghetti Code? And Why should we Avoid it? Overview :Spaghetti Code is nothing but a generalized common-usage term for unstructured and difficult-to-read code. Such a type of code in any large code-base can create problems of its own, if not resolved on time. It can lead to a huge wastage of important resources like time and energy to find bugs and fix them because the code has no structure. Example :Given below is an example of Spaghetti codes as follows. Unstructured code in BASIC Language – 1 i=0 2 i=i+1 3 PRINT i; "squared=";i*i 4 IF i>=100 THEN GOTO 6 5 GOTO 2 6 PRINT "Program Completed." 7 END Structured code for above example – 1 FOR i=1 TO 100 2 PRINT i;"squared=";i*i 3 NEXT i 4 PRINT "Program Completed." 5 END How does Spaghetti Code end up in your code-base :There can several reasons for this to happen in a very large code-base. It occurs mostly when the following scenarios will be there as follows. The Best development practices get outdated with time, and existing systems fail to be optimized with the latest practices.Developers get changed or transferred to a new team, they tend to write code that suits their style and habit and unintentionally disturb the entire code base.Less experienced programmers alter the code-base with unstructured code, excessive GOTO statements, or very little comments. The Best development practices get outdated with time, and existing systems fail to be optimized with the latest practices. Developers get changed or transferred to a new team, they tend to write code that suits their style and habit and unintentionally disturb the entire code base. Less experienced programmers alter the code-base with unstructured code, excessive GOTO statements, or very little comments. Prevention Steps :By the above discussion, it has become quite clear that Spaghetti code is the perfect recipe for failure in the long term. So, every organization and programmer must take precautions to avoid accumulation of spaghetti code in their code-base. There are a number of basic rules and methods one can keep in mind to maintain efficiency and avoid spaghetti code. They are as follows: Write comments – Writing comments is considered as a very good practice among coders. Comments not only help the programmer writing the actual code, but also the one reading it. It gives clarity of what a particular portion of code does and saves valuable time. Understanding the Code-base – When starting a new position at a company, it is often advised that you first learn their methods and styles before taking any significant programming-related work. This will help you understand how things work there, and it will help you get a better understanding of the structure of their code-base. Perform Unit Tests – You can reduce the probability of spaghetti code occurring if you perform routine unit tests. Use Light Frameworks – There are tons of frameworks and libraries available in all modern programming languages that help you execute hundreds of functions with just a few lines of code. This was, your code gets leaner and finding and fixing bugs easier. Always Double Check – It will never hurt you to go through some part of the code one more time, more than when it will take you hours to find your bug in thousands of lines of spaghetti. Picked Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is DFD(Data Flow Diagram)? DFD for Library Management System Software Engineering | Black box testing System Testing Software Engineering | Software Design Process Software Development Life Cycle (SDLC) Difference between IAAS, PAAS and SAAS Software Engineering | Incremental process model Software Engineering | Project size estimation techniques Software Engineering | Software Quality Assurance
[ { "code": null, "e": 24990, "s": 24962, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25172, "s": 24990, "text": "In this article, we will discuss Spaghetti Code, and We often hear this term, Spaghetti Code, and we should avoid it. But what exactly is Spaghetti Code? And Why should we Avoid it?" }, { "code": null, "e": 25525, "s": 25172, "text": "Overview :Spaghetti Code is nothing but a generalized common-usage term for unstructured and difficult-to-read code. Such a type of code in any large code-base can create problems of its own, if not resolved on time. It can lead to a huge wastage of important resources like time and energy to find bugs and fix them because the code has no structure. " }, { "code": null, "e": 25591, "s": 25525, "text": "Example :Given below is an example of Spaghetti codes as follows." }, { "code": null, "e": 25629, "s": 25591, "text": "Unstructured code in BASIC Language –" }, { "code": null, "e": 25737, "s": 25629, "text": "1 i=0\n2 i=i+1\n3 PRINT i; \"squared=\";i*i\n4 IF i>=100 THEN GOTO 6\n5 GOTO 2\n6 PRINT \"Program Completed.\"\n7 END" }, { "code": null, "e": 25773, "s": 25737, "text": "Structured code for above example –" }, { "code": null, "e": 25863, "s": 25773, "text": "1 FOR i=1 TO 100\n2 PRINT i;\"squared=\";i*i\n3 NEXT i\n4 PRINT \"Program Completed.\"\n5 END" }, { "code": null, "e": 26057, "s": 25863, "text": "How does Spaghetti Code end up in your code-base :There can several reasons for this to happen in a very large code-base. It occurs mostly when the following scenarios will be there as follows." }, { "code": null, "e": 26464, "s": 26057, "text": "The Best development practices get outdated with time, and existing systems fail to be optimized with the latest practices.Developers get changed or transferred to a new team, they tend to write code that suits their style and habit and unintentionally disturb the entire code base.Less experienced programmers alter the code-base with unstructured code, excessive GOTO statements, or very little comments." }, { "code": null, "e": 26588, "s": 26464, "text": "The Best development practices get outdated with time, and existing systems fail to be optimized with the latest practices." }, { "code": null, "e": 26748, "s": 26588, "text": "Developers get changed or transferred to a new team, they tend to write code that suits their style and habit and unintentionally disturb the entire code base." }, { "code": null, "e": 26873, "s": 26748, "text": "Less experienced programmers alter the code-base with unstructured code, excessive GOTO statements, or very little comments." }, { "code": null, "e": 27271, "s": 26873, "text": "Prevention Steps :By the above discussion, it has become quite clear that Spaghetti code is the perfect recipe for failure in the long term. So, every organization and programmer must take precautions to avoid accumulation of spaghetti code in their code-base. There are a number of basic rules and methods one can keep in mind to maintain efficiency and avoid spaghetti code. They are as follows:" }, { "code": null, "e": 27534, "s": 27271, "text": "Write comments – Writing comments is considered as a very good practice among coders. Comments not only help the programmer writing the actual code, but also the one reading it. It gives clarity of what a particular portion of code does and saves valuable time. " }, { "code": null, "e": 27868, "s": 27534, "text": "Understanding the Code-base – When starting a new position at a company, it is often advised that you first learn their methods and styles before taking any significant programming-related work. This will help you understand how things work there, and it will help you get a better understanding of the structure of their code-base. " }, { "code": null, "e": 27984, "s": 27868, "text": "Perform Unit Tests – You can reduce the probability of spaghetti code occurring if you perform routine unit tests. " }, { "code": null, "e": 28240, "s": 27984, "text": "Use Light Frameworks – There are tons of frameworks and libraries available in all modern programming languages that help you execute hundreds of functions with just a few lines of code. This was, your code gets leaner and finding and fixing bugs easier. " }, { "code": null, "e": 28427, "s": 28240, "text": "Always Double Check – It will never hurt you to go through some part of the code one more time, more than when it will take you hours to find your bug in thousands of lines of spaghetti." }, { "code": null, "e": 28434, "s": 28427, "text": "Picked" }, { "code": null, "e": 28455, "s": 28434, "text": "Software Engineering" }, { "code": null, "e": 28553, "s": 28455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28585, "s": 28553, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 28619, "s": 28585, "text": "DFD for Library Management System" }, { "code": null, "e": 28660, "s": 28619, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 28675, "s": 28660, "text": "System Testing" }, { "code": null, "e": 28722, "s": 28675, "text": "Software Engineering | Software Design Process" }, { "code": null, "e": 28761, "s": 28722, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 28800, "s": 28761, "text": "Difference between IAAS, PAAS and SAAS" }, { "code": null, "e": 28849, "s": 28800, "text": "Software Engineering | Incremental process model" }, { "code": null, "e": 28907, "s": 28849, "text": "Software Engineering | Project size estimation techniques" } ]
Find all possible interpretations of an array of digits - GeeksforGeeks
17 Feb, 2022 Consider a coding system for alphabets to integers where ‘a’ is represented as 1, ‘b’ as 2, .. ‘z’ as 26. Given an array of digits (1 to 9) as input, write a function that prints all valid interpretations of input array. Examples Input: {1, 1} Output: ("aa", 'k") [2 interpretations: aa(1, 1), k(11)] Input: {1, 2, 1} Output: ("aba", "au", "la") [3 interpretations: aba(1,2,1), au(1,21), la(12,1)] Input: {9, 1, 8} Output: {"iah", "ir"} [2 interpretations: iah(9,1,8), ir(9,18)] Please note we cannot change order of array. That means {1,2,1} cannot become {2,1,1} On first look it looks like a problem of permutation/combination. But on closer look you will figure out that this is an interesting tree problem. The idea here is string can take at-most two paths: 1. Process single digit 2. Process two digits That means we can use binary tree here. Processing with single digit will be left child and two digits will be right child. If value two digits is greater than 26 then our right child will be null as we don’t have alphabet for greater than 26.Let’s understand with an example .Array a = {1,2,1}. Below diagram shows that how our tree grows. “” {1,2,1} Codes used in tree / \ "a" --> 1 / \ "b" --> 2 "a"{2,1} "l"{1} "l" --> 12 / \ / \ / \ / \ "ab"{1} "au" "la" null / \ / \ "aba" null Braces {} contain array still pending for processing. Note that with every level, our array size decreases. If you will see carefully, it is not hard to find that tree height is always n (array size) How to print all strings (interpretations)? Output strings are leaf node of tree. i.e for {1,2,1}, output is {aba au la}. We can conclude that there are mainly two steps to print all interpretations of given integer array. Step 1: Create a binary tree with all possible interpretations in leaf nodes.Step 2: Print all leaf nodes from the binary tree created in step 1.Following is Java implementation of above algorithm. Java // A Java program to print all interpretations of an integer arrayimport java.util.Arrays; // A Binary Tree nodeclass Node { String dataString; Node left; Node right; Node(String dataString) { this.dataString = dataString; //Be default left and right child are null. } public String getDataString() { return dataString; }} public class arrayToAllInterpretations { // Method to create a binary tree which stores all interpretations // of arr[] in lead nodes public static Node createTree(int data, String pString, int[] arr) { // Invalid input as alphabets maps from 1 to 26 if (data > 26) return null; // Parent String + String for this node String dataToStr = pString + alphabet[data]; Node root = new Node(dataToStr); // if arr.length is 0 means we are done if (arr.length != 0) { data = arr[0]; // new array will be from index 1 to end as we are consuming // first index with this node int newArr[] = Arrays.copyOfRange(arr, 1, arr.length); // left child root.left = createTree(data, dataToStr, newArr); // right child will be null if size of array is 0 or 1 if (arr.length > 1) { data = arr[0] * 10 + arr[1]; // new array will be from index 2 to end as we // are consuming first two index with this node newArr = Arrays.copyOfRange(arr, 2, arr.length); root.right = createTree(data, dataToStr, newArr); } } return root; } // To print out leaf nodes public static void printleaf(Node root) { if (root == null) return; if (root.left == null && root.right == null) System.out.print(root.getDataString() + " "); printleaf(root.left); printleaf(root.right); } // The main function that prints all interpretations of array static void printAllInterpretations(int[] arr) { // Step 1: Create Tree Node root = createTree(0, "", arr); // Step 2: Print Leaf nodes printleaf(root); System.out.println(); // Print new line } // For simplicity I am taking it as string array. Char Array will save space private static final String[] alphabet = {"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "v", "z"}; // Driver method to test above methods public static void main(String args[]) { // aacd(1,1,3,4) amd(1,13,4) kcd(11,3,4) // Note : 1,1,34 is not valid as we don't have values corresponding // to 34 in alphabet int[] arr = {1, 1, 3, 4}; printAllInterpretations(arr); // aaa(1,1,1) ak(1,11) ka(11,1) int[] arr2 = {1, 1, 1}; printAllInterpretations(arr2); // bf(2,6) z(26) int[] arr3 = {2, 6}; printAllInterpretations(arr3); // ab(1,2), l(12) int[] arr4 = {1, 2}; printAllInterpretations(arr4); // a(1,0} j(10) int[] arr5 = {1, 0}; printAllInterpretations(arr5); // "" empty string output as array is empty int[] arr6 = {}; printAllInterpretations(arr6); // abba abu ava lba lu int[] arr7 = {1, 2, 2, 1}; printAllInterpretations(arr7); }} Output: aacd amd kcd aaa ak ka bf z ab l a j abba abu ava lba lu Exercise: 1. What is the time complexity of this solution? [Hint : size of tree + finding leaf nodes] 2. Can we store leaf nodes at the time of tree creation so that no need to run loop again for leaf node fetching? 3. How can we reduce extra space? This article is compiled by Varun Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Method 2 : ( using backtracking ) This problem can be solved using backtracking . One of the basic intuition is that all the numbers we are going to generate using digits of the input array must lie in between the range of [ 1 , 26 ] both inclusive . So in a bruteforce way we try all the possible combinations and if the number generated so far lies in between the range of [ 1 , 26 ] we append the corresponding alphabet and recur for the remaining string and we pop the appended character ( backtrack ) to find all the valid interpretations . In this process if we reach the end of the string that means we have found 1 possible interpretation . But at any point of time if we find the number generated so far is greater than 26 we need not to proceed further because that is not a valid number to interpret , so in that case we backtrack and try for the rest of the combinations . Below is the C++ implementation C++ #include<bits/stdc++.h>using namespace std; string dup;// function which returns all the valid interpretationsvoid compute(int arr[],int n,vector<string> &vect,int s){ //cout << "ex" << endl; /* if we reach the end of the string than we have found 1 valid interpretation */ if(s == n) { // store it in the vector vect.push_back(dup); /* since we have reached the end of the string there is no string to recur so return */ return ; } // initialize the num with zero int num = 0; for(int i=s;i<n;i++) { // generate the number num = num*10 + arr[i]; /* validate the number generated so far */ if(num >= 1 and num <= 26) { // append the corresponding alphabet dup += ('a' + (num - 1)); // recur for the remaining string compute(arr,n,vect,i+1); // backtrack to find rest of the combinations dup.pop_back(); } // if the number generated so far if greater // than 26 we need not to proceed further // as it cannot be used to make a valid // interpretation else break; } return ;} vector<string> findAllInterpretations(int n,int arr[]){ // vector to store all the valid interpretations vector<string> vect; dup = ""; compute(arr,n,vect,0); // return all valid interpretations return vect;}int main(){ int n; cin >> n; int *arr = new int[n]; for(int i=0;i<n;i++) { cin >> arr[i]; } vector<string> res; res = findAllInterpretations(n,arr); int m = res.size(); for(int i=0;i<m;i++) { cout << res[i] << " "; } return 0;} Input : 5 1 1 2 1 2 Output : aabab aabl aaub alab all kbab kbl kub Akanksha_Rai anveshkarra1234 Facebook number-digits Advanced Data Structure Facebook Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Proof that Dominant Set of a Graph is NP-Complete Extendible Hashing (Dynamic approach to DBMS) 2-3 Trees | (Search, Insert and Deletion) Trie | (Delete) Advantages of Trie Data Structure Quad Tree Ternary Search Tree Cartesian Tree Suffix Array | Set 1 (Introduction) Skip List | Set 2 (Insertion)
[ { "code": null, "e": 24486, "s": 24458, "text": "\n17 Feb, 2022" }, { "code": null, "e": 24717, "s": 24486, "text": "Consider a coding system for alphabets to integers where ‘a’ is represented as 1, ‘b’ as 2, .. ‘z’ as 26. Given an array of digits (1 to 9) as input, write a function that prints all valid interpretations of input array. Examples " }, { "code": null, "e": 24971, "s": 24717, "text": "Input: {1, 1}\nOutput: (\"aa\", 'k\") \n[2 interpretations: aa(1, 1), k(11)]\n\nInput: {1, 2, 1}\nOutput: (\"aba\", \"au\", \"la\") \n[3 interpretations: aba(1,2,1), au(1,21), la(12,1)]\n\nInput: {9, 1, 8}\nOutput: {\"iah\", \"ir\"} \n[2 interpretations: iah(9,1,8), ir(9,18)]" }, { "code": null, "e": 25647, "s": 24973, "text": "Please note we cannot change order of array. That means {1,2,1} cannot become {2,1,1} On first look it looks like a problem of permutation/combination. But on closer look you will figure out that this is an interesting tree problem. The idea here is string can take at-most two paths: 1. Process single digit 2. Process two digits That means we can use binary tree here. Processing with single digit will be left child and two digits will be right child. If value two digits is greater than 26 then our right child will be null as we don’t have alphabet for greater than 26.Let’s understand with an example .Array a = {1,2,1}. Below diagram shows that how our tree grows. " }, { "code": null, "e": 26113, "s": 25647, "text": " “” {1,2,1} Codes used in tree\n / \\ \"a\" --> 1\n / \\ \"b\" --> 2 \n \"a\"{2,1} \"l\"{1} \"l\" --> 12\n / \\ / \\\n / \\ / \\\n \"ab\"{1} \"au\" \"la\" null\n / \\\n / \\\n \"aba\" null" }, { "code": null, "e": 26735, "s": 26113, "text": "Braces {} contain array still pending for processing. Note that with every level, our array size decreases. If you will see carefully, it is not hard to find that tree height is always n (array size) How to print all strings (interpretations)? Output strings are leaf node of tree. i.e for {1,2,1}, output is {aba au la}. We can conclude that there are mainly two steps to print all interpretations of given integer array. Step 1: Create a binary tree with all possible interpretations in leaf nodes.Step 2: Print all leaf nodes from the binary tree created in step 1.Following is Java implementation of above algorithm. " }, { "code": null, "e": 26740, "s": 26735, "text": "Java" }, { "code": "// A Java program to print all interpretations of an integer arrayimport java.util.Arrays; // A Binary Tree nodeclass Node { String dataString; Node left; Node right; Node(String dataString) { this.dataString = dataString; //Be default left and right child are null. } public String getDataString() { return dataString; }} public class arrayToAllInterpretations { // Method to create a binary tree which stores all interpretations // of arr[] in lead nodes public static Node createTree(int data, String pString, int[] arr) { // Invalid input as alphabets maps from 1 to 26 if (data > 26) return null; // Parent String + String for this node String dataToStr = pString + alphabet[data]; Node root = new Node(dataToStr); // if arr.length is 0 means we are done if (arr.length != 0) { data = arr[0]; // new array will be from index 1 to end as we are consuming // first index with this node int newArr[] = Arrays.copyOfRange(arr, 1, arr.length); // left child root.left = createTree(data, dataToStr, newArr); // right child will be null if size of array is 0 or 1 if (arr.length > 1) { data = arr[0] * 10 + arr[1]; // new array will be from index 2 to end as we // are consuming first two index with this node newArr = Arrays.copyOfRange(arr, 2, arr.length); root.right = createTree(data, dataToStr, newArr); } } return root; } // To print out leaf nodes public static void printleaf(Node root) { if (root == null) return; if (root.left == null && root.right == null) System.out.print(root.getDataString() + \" \"); printleaf(root.left); printleaf(root.right); } // The main function that prints all interpretations of array static void printAllInterpretations(int[] arr) { // Step 1: Create Tree Node root = createTree(0, \"\", arr); // Step 2: Print Leaf nodes printleaf(root); System.out.println(); // Print new line } // For simplicity I am taking it as string array. Char Array will save space private static final String[] alphabet = {\"\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"v\", \"z\"}; // Driver method to test above methods public static void main(String args[]) { // aacd(1,1,3,4) amd(1,13,4) kcd(11,3,4) // Note : 1,1,34 is not valid as we don't have values corresponding // to 34 in alphabet int[] arr = {1, 1, 3, 4}; printAllInterpretations(arr); // aaa(1,1,1) ak(1,11) ka(11,1) int[] arr2 = {1, 1, 1}; printAllInterpretations(arr2); // bf(2,6) z(26) int[] arr3 = {2, 6}; printAllInterpretations(arr3); // ab(1,2), l(12) int[] arr4 = {1, 2}; printAllInterpretations(arr4); // a(1,0} j(10) int[] arr5 = {1, 0}; printAllInterpretations(arr5); // \"\" empty string output as array is empty int[] arr6 = {}; printAllInterpretations(arr6); // abba abu ava lba lu int[] arr7 = {1, 2, 2, 1}; printAllInterpretations(arr7); }}", "e": 30183, "s": 26740, "text": null }, { "code": null, "e": 30192, "s": 30183, "text": "Output: " }, { "code": null, "e": 30275, "s": 30192, "text": "aacd amd kcd \naaa ak ka \nbf z \nab l \na j \n \nabba abu ava lba lu " }, { "code": null, "e": 30690, "s": 30275, "text": "Exercise: 1. What is the time complexity of this solution? [Hint : size of tree + finding leaf nodes] 2. Can we store leaf nodes at the time of tree creation so that no need to run loop again for leaf node fetching? 3. How can we reduce extra space? This article is compiled by Varun Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 30724, "s": 30690, "text": "Method 2 : ( using backtracking )" }, { "code": null, "e": 31576, "s": 30724, "text": "This problem can be solved using backtracking . One of the basic intuition is that all the numbers we are going to generate using digits of the input array must lie in between the range of [ 1 , 26 ] both inclusive . So in a bruteforce way we try all the possible combinations and if the number generated so far lies in between the range of [ 1 , 26 ] we append the corresponding alphabet and recur for the remaining string and we pop the appended character ( backtrack ) to find all the valid interpretations . In this process if we reach the end of the string that means we have found 1 possible interpretation . But at any point of time if we find the number generated so far is greater than 26 we need not to proceed further because that is not a valid number to interpret , so in that case we backtrack and try for the rest of the combinations ." }, { "code": null, "e": 31609, "s": 31576, "text": "Below is the C++ implementation " }, { "code": null, "e": 31613, "s": 31609, "text": "C++" }, { "code": "#include<bits/stdc++.h>using namespace std; string dup;// function which returns all the valid interpretationsvoid compute(int arr[],int n,vector<string> &vect,int s){ //cout << \"ex\" << endl; /* if we reach the end of the string than we have found 1 valid interpretation */ if(s == n) { // store it in the vector vect.push_back(dup); /* since we have reached the end of the string there is no string to recur so return */ return ; } // initialize the num with zero int num = 0; for(int i=s;i<n;i++) { // generate the number num = num*10 + arr[i]; /* validate the number generated so far */ if(num >= 1 and num <= 26) { // append the corresponding alphabet dup += ('a' + (num - 1)); // recur for the remaining string compute(arr,n,vect,i+1); // backtrack to find rest of the combinations dup.pop_back(); } // if the number generated so far if greater // than 26 we need not to proceed further // as it cannot be used to make a valid // interpretation else break; } return ;} vector<string> findAllInterpretations(int n,int arr[]){ // vector to store all the valid interpretations vector<string> vect; dup = \"\"; compute(arr,n,vect,0); // return all valid interpretations return vect;}int main(){ int n; cin >> n; int *arr = new int[n]; for(int i=0;i<n;i++) { cin >> arr[i]; } vector<string> res; res = findAllInterpretations(n,arr); int m = res.size(); for(int i=0;i<m;i++) { cout << res[i] << \" \"; } return 0;}", "e": 33380, "s": 31613, "text": null }, { "code": null, "e": 33401, "s": 33380, "text": "Input : \n5\n1 1 2 1 2" }, { "code": null, "e": 33449, "s": 33401, "text": "Output : \naabab aabl aaub alab all kbab kbl kub" }, { "code": null, "e": 33462, "s": 33449, "text": "Akanksha_Rai" }, { "code": null, "e": 33478, "s": 33462, "text": "anveshkarra1234" }, { "code": null, "e": 33487, "s": 33478, "text": "Facebook" }, { "code": null, "e": 33501, "s": 33487, "text": "number-digits" }, { "code": null, "e": 33525, "s": 33501, "text": "Advanced Data Structure" }, { "code": null, "e": 33534, "s": 33525, "text": "Facebook" }, { "code": null, "e": 33632, "s": 33534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33641, "s": 33632, "text": "Comments" }, { "code": null, "e": 33654, "s": 33641, "text": "Old Comments" }, { "code": null, "e": 33704, "s": 33654, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 33750, "s": 33704, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 33792, "s": 33750, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 33808, "s": 33792, "text": "Trie | (Delete)" }, { "code": null, "e": 33842, "s": 33808, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 33852, "s": 33842, "text": "Quad Tree" }, { "code": null, "e": 33872, "s": 33852, "text": "Ternary Search Tree" }, { "code": null, "e": 33887, "s": 33872, "text": "Cartesian Tree" }, { "code": null, "e": 33923, "s": 33887, "text": "Suffix Array | Set 1 (Introduction)" } ]
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks
30 Sep, 2021 Consider two processors P1 and P2 executing the same instruction set. Assume that under identical conditions, for the same input, a program running on P2 takes 25% less time but incurs 20% more CPI (clock cycles per instruction) as compared to the program running on P1. If the clock frequency of P1 is 1GHz, then the clock frequency of P2 (in GHz) is _________.(A) 1.6(B) 3.2(C) 1.2(D) 0.8Answer: (A)Explanation: For P1 clock period = 1ns Let clock period for P2 be t. Now consider following equation based on specification 7.5 ns = 12*t ns We get t and inverse of t will be 1.6GHz YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch 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:0035:15 / 40:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h-14CfDEprU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(Set-1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE CS 2011 | Question 7
[ { "code": null, "e": 24522, "s": 24494, "text": "\n30 Sep, 2021" }, { "code": null, "e": 24936, "s": 24522, "text": "Consider two processors P1 and P2 executing the same instruction set. Assume that under identical conditions, for the same input, a program running on P2 takes 25% less time but incurs 20% more CPI (clock cycles per instruction) as compared to the program running on P1. If the clock frequency of P1 is 1GHz, then the clock frequency of P2 (in GHz) is _________.(A) 1.6(B) 3.2(C) 1.2(D) 0.8Answer: (A)Explanation:" }, { "code": null, "e": 25110, "s": 24936, "text": "For P1 clock period = 1ns \n\nLet clock period for P2 be t.\n\nNow consider following equation based on specification\n7.5 ns = 12*t ns\n\nWe get t and inverse of t will be 1.6GHz " }, { "code": null, "e": 26024, "s": 25110, "text": "YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch 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:0035:15 / 40:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=h-14CfDEprU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 26045, "s": 26024, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 26071, "s": 26045, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 26076, "s": 26071, "text": "GATE" }, { "code": null, "e": 26174, "s": 26076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26208, "s": 26174, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26250, "s": 26208, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26292, "s": 26250, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26326, "s": 26292, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26359, "s": 26326, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26393, "s": 26359, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26427, "s": 26393, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26461, "s": 26427, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26503, "s": 26461, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" } ]
Subarray Product Less Than K in C++
Suppose we have given an array of positive integers nums. We have to count and print the number of (contiguous) subarrays where the product of each the elements in the subarray is less than k. So if the input is like [10,5,2,6] and k := 100, then the output will be 8. So the subarrays will be [[10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]] To solve this, we will follow these steps − temp := 1, j := 0 and ans := 0 for i in range 0 to size of the arraytemp := temp * nums[i]while temp >= k and j <= i, dotemp := temp / nums[j]increase j by 1ans := ans + (i – j + 1) temp := temp * nums[i] while temp >= k and j <= i, dotemp := temp / nums[j]increase j by 1 temp := temp / nums[j] increase j by 1 ans := ans + (i – j + 1) return ans Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { lli temp = 1; int j = 0; int ans = 0; for(int i = 0; i < nums.size(); i++){ temp *= nums[i]; while(temp >= k && j <= i) { temp /= nums[j]; j++; } ans += (i - j + 1); } return ans; } }; main(){ Solution ob; vector<int> v = {10,5,2,6}; cout << (ob.numSubarrayProductLessThanK(v, 100)); } [10,5,2,6] 100 8
[ { "code": null, "e": 1417, "s": 1062, "text": "Suppose we have given an array of positive integers nums. We have to count and print the number of (contiguous) subarrays where the product of each the elements in the subarray is less than k. So if the input is like [10,5,2,6] and k := 100, then the output will be 8. So the subarrays will be [[10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]]" }, { "code": null, "e": 1461, "s": 1417, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1492, "s": 1461, "text": "temp := 1, j := 0 and ans := 0" }, { "code": null, "e": 1643, "s": 1492, "text": "for i in range 0 to size of the arraytemp := temp * nums[i]while temp >= k and j <= i, dotemp := temp / nums[j]increase j by 1ans := ans + (i – j + 1)" }, { "code": null, "e": 1666, "s": 1643, "text": "temp := temp * nums[i]" }, { "code": null, "e": 1734, "s": 1666, "text": "while temp >= k and j <= i, dotemp := temp / nums[j]increase j by 1" }, { "code": null, "e": 1757, "s": 1734, "text": "temp := temp / nums[j]" }, { "code": null, "e": 1773, "s": 1757, "text": "increase j by 1" }, { "code": null, "e": 1798, "s": 1773, "text": "ans := ans + (i – j + 1)" }, { "code": null, "e": 1809, "s": 1798, "text": "return ans" }, { "code": null, "e": 1881, "s": 1809, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1892, "s": 1881, "text": " Live Demo" }, { "code": null, "e": 2447, "s": 1892, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\npublic:\n int numSubarrayProductLessThanK(vector<int>& nums, int k) {\n lli temp = 1;\n int j = 0;\n int ans = 0;\n for(int i = 0; i < nums.size(); i++){\n temp *= nums[i];\n while(temp >= k && j <= i) {\n temp /= nums[j];\n j++;\n }\n ans += (i - j + 1);\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {10,5,2,6};\n cout << (ob.numSubarrayProductLessThanK(v, 100));\n}" }, { "code": null, "e": 2462, "s": 2447, "text": "[10,5,2,6]\n100" }, { "code": null, "e": 2464, "s": 2462, "text": "8" } ]
How An Online Judge Works And How To Avoid Time Limit Exceeded Problem? - GeeksforGeeks
10 Jun, 2020 In this article, you will get consent on how an online judge works and this article discusses very frustrating error Time Limit Exceed error that coders get at some point in time while solving the questions at online platforms. The article primarily discusses three things: How does an online judge work? Why do we get TLE? How to avoid TLE? There are various online judges Hackerrank, HackerEarth, Codechef. All of the have their respective algorithms and systems of evaluating submissions. Let’s consider an online judge who is accepting the submission for a given problem. For this submission, the judge has some input and some output files loaded in it already. The judge passes the submission to the processor and this processor has some processing limits. Let’s say in 1 sec the processor is able to perform 10^8 operations. Now, what happens internally when you submit your program is that your program executes and it gets the input from the processor and verifies the output with already loaded test cases in it. If it matches then it is a case of a correct answer but sometimes during the execution, if the program takes more time than the required time limit then it prompts the user time limit exceeded error. For example, if the required limit was 1 second and your program were taking more than 1 second for execution, then your judge will issue a kill command and your output will be killed and in the output, you will get Time Limit Exceeded (Optimize Your Code). This is how an online judge works. When your algorithm doesn’t have the required efficiency you get TLE so the idea is to complete the processing in a finite amount of time. Let’s assume you are calculating whether a number is prime or not and the number is of the order 10^18. If you are using the O(n) algorithm you are bound to get TLE and if you use the O(log N) algorithm you won’t get TLE. Below are some common reasons for TLE error... Online judges put some restrictions on time and it doesn’t allow you to process your instruction after that time limit. If you take more time than the time limit which is specified than you will get the TLE error. TLE error also depends on the server architecture, operating system, and the complexity of an algorithm. For different platform server architectures are different and the speed of the execution for the code varies on each server. If the programmer is using a slow method of reading and writing the input in the code then it will give you a TLE error. 1. Analyze the constraints: If the time limit is 1 sec, your processor is able to execute 10^8 operations. 2. Choose faster input and output method. For example: Use buffer reader in java, do not use Scanner In C++ use scanf/printf instead of cin/cout, Use these two statements in python for speeding up your execution import psycopsyco.full() 3. Your program must not contain 4 nested loops if N<=100. 4. Sometimes too many nested loops can make your program slower. So it’s better to optimize your code and reduce the number of loops according to the instruction of input bound already specified in the question. So read the bounds in your code carefully and according to that write your program. 5. Optimize your algorithm or try to find a different solution for the problem statement using another data structure. As the saying goes, the experience is the best teacher. The more you code the algorithms, the more efficient the geek you become in the coding. Important Link: How to overcome Time Limit Exceed(TLE)? Competitive Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments String hashing using Polynomial rolling hash function Runtime Errors Check if a number is perfect square without finding square root Graph implementation using STL for competitive programming | Set 2 (Weighted graph) Breadth First Traversal ( BFS ) on a 2D array Sub-string that contains all lowercase alphabets after performing the given operation Find all the possible remainders when N is divided by all positive integers from 1 to N+1 Find the minimum dominating set of a Binary tree Problem of 8 Neighbours of an element in a 2-D Matrix Remove all occurrences of a character in a string | Recursive approach
[ { "code": null, "e": 24633, "s": 24605, "text": "\n10 Jun, 2020" }, { "code": null, "e": 24907, "s": 24633, "text": "In this article, you will get consent on how an online judge works and this article discusses very frustrating error Time Limit Exceed error that coders get at some point in time while solving the questions at online platforms. The article primarily discusses three things:" }, { "code": null, "e": 24938, "s": 24907, "text": "How does an online judge work?" }, { "code": null, "e": 24957, "s": 24938, "text": "Why do we get TLE?" }, { "code": null, "e": 24975, "s": 24957, "text": "How to avoid TLE?" }, { "code": null, "e": 26148, "s": 24975, "text": "There are various online judges Hackerrank, HackerEarth, Codechef. All of the have their respective algorithms and systems of evaluating submissions. Let’s consider an online judge who is accepting the submission for a given problem. For this submission, the judge has some input and some output files loaded in it already. The judge passes the submission to the processor and this processor has some processing limits. Let’s say in 1 sec the processor is able to perform 10^8 operations. Now, what happens internally when you submit your program is that your program executes and it gets the input from the processor and verifies the output with already loaded test cases in it. If it matches then it is a case of a correct answer but sometimes during the execution, if the program takes more time than the required time limit then it prompts the user time limit exceeded error. For example, if the required limit was 1 second and your program were taking more than 1 second for execution, then your judge will issue a kill command and your output will be killed and in the output, you will get Time Limit Exceeded (Optimize Your Code). This is how an online judge works." }, { "code": null, "e": 26556, "s": 26148, "text": "When your algorithm doesn’t have the required efficiency you get TLE so the idea is to complete the processing in a finite amount of time. Let’s assume you are calculating whether a number is prime or not and the number is of the order 10^18. If you are using the O(n) algorithm you are bound to get TLE and if you use the O(log N) algorithm you won’t get TLE. Below are some common reasons for TLE error..." }, { "code": null, "e": 26770, "s": 26556, "text": "Online judges put some restrictions on time and it doesn’t allow you to process your instruction after that time limit. If you take more time than the time limit which is specified than you will get the TLE error." }, { "code": null, "e": 27000, "s": 26770, "text": "TLE error also depends on the server architecture, operating system, and the complexity of an algorithm. For different platform server architectures are different and the speed of the execution for the code varies on each server." }, { "code": null, "e": 27121, "s": 27000, "text": "If the programmer is using a slow method of reading and writing the input in the code then it will give you a TLE error." }, { "code": null, "e": 27228, "s": 27121, "text": "1. Analyze the constraints: If the time limit is 1 sec, your processor is able to execute 10^8 operations." }, { "code": null, "e": 27283, "s": 27228, "text": "2. Choose faster input and output method. For example:" }, { "code": null, "e": 27329, "s": 27283, "text": "Use buffer reader in java, do not use Scanner" }, { "code": null, "e": 27374, "s": 27329, "text": "In C++ use scanf/printf instead of cin/cout," }, { "code": null, "e": 27440, "s": 27374, "text": "Use these two statements in python for speeding up your execution" }, { "code": "import psycopsyco.full()", "e": 27465, "s": 27440, "text": null }, { "code": null, "e": 27524, "s": 27465, "text": "3. Your program must not contain 4 nested loops if N<=100." }, { "code": null, "e": 27820, "s": 27524, "text": "4. Sometimes too many nested loops can make your program slower. So it’s better to optimize your code and reduce the number of loops according to the instruction of input bound already specified in the question. So read the bounds in your code carefully and according to that write your program." }, { "code": null, "e": 27939, "s": 27820, "text": "5. Optimize your algorithm or try to find a different solution for the problem statement using another data structure." }, { "code": null, "e": 28083, "s": 27939, "text": "As the saying goes, the experience is the best teacher. The more you code the algorithms, the more efficient the geek you become in the coding." }, { "code": null, "e": 28139, "s": 28083, "text": "Important Link: How to overcome Time Limit Exceed(TLE)?" }, { "code": null, "e": 28163, "s": 28139, "text": "Competitive Programming" }, { "code": null, "e": 28261, "s": 28163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28270, "s": 28261, "text": "Comments" }, { "code": null, "e": 28283, "s": 28270, "text": "Old Comments" }, { "code": null, "e": 28337, "s": 28283, "text": "String hashing using Polynomial rolling hash function" }, { "code": null, "e": 28352, "s": 28337, "text": "Runtime Errors" }, { "code": null, "e": 28416, "s": 28352, "text": "Check if a number is perfect square without finding square root" }, { "code": null, "e": 28500, "s": 28416, "text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)" }, { "code": null, "e": 28546, "s": 28500, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 28632, "s": 28546, "text": "Sub-string that contains all lowercase alphabets after performing the given operation" }, { "code": null, "e": 28722, "s": 28632, "text": "Find all the possible remainders when N is divided by all positive integers from 1 to N+1" }, { "code": null, "e": 28771, "s": 28722, "text": "Find the minimum dominating set of a Binary tree" }, { "code": null, "e": 28825, "s": 28771, "text": "Problem of 8 Neighbours of an element in a 2-D Matrix" } ]
Python program for the permutation of a given string inbuilt function in python
String is given. Our task is to display permutation of given string. Here solve this problem in python using inbuilt function permutations (iterable). Input : string = 'XYZ' Output : XYZ XZY YXZ YZX ZXY ZYX Step 1: given string. Step 2: Get all permutations of string. Step 3: print all permutations. from itertools import permutations def allPermutations(str1): # Get all permutations of string 'ABC' per = permutations(str1) # print all permutations print("Permutation Of this String ::>") for i in list(per): print (''.join(i)) # Driver program if __name__ == "__main__": str1 = input("Enter the string ::>") allPermutations(str1) Enter the string ::> abc Permutation Of this String ::> abc acb bac bca cab cba
[ { "code": null, "e": 1213, "s": 1062, "text": "String is given. Our task is to display permutation of given string. Here solve this problem in python using inbuilt function permutations (iterable)." }, { "code": null, "e": 1269, "s": 1213, "text": "Input : string = 'XYZ'\nOutput : XYZ\nXZY\nYXZ\nYZX\nZXY\nZYX" }, { "code": null, "e": 1363, "s": 1269, "text": "Step 1: given string.\nStep 2: Get all permutations of string.\nStep 3: print all permutations." }, { "code": null, "e": 1717, "s": 1363, "text": "from itertools import permutations\ndef allPermutations(str1):\n # Get all permutations of string 'ABC'\n per = permutations(str1)\n # print all permutations\n print(\"Permutation Of this String ::>\")\n for i in list(per):\n print (''.join(i))\n# Driver program\nif __name__ == \"__main__\":\n str1 = input(\"Enter the string ::>\")\nallPermutations(str1)" }, { "code": null, "e": 1797, "s": 1717, "text": "Enter the string ::> abc\nPermutation Of this String ::>\nabc\nacb\nbac\nbca\ncab\ncba" } ]
Ratio and Proportion - GeeksforGeeks
21 Apr, 2016 Then (3x+5) / (4x+5) = 7 / 9 ∴ 9(3x + 5) = 7(4x + 5) ∴ 27x + 45 = 28x + 35 ∴ x = 10 ∴ Ashok’s present age = 4x = 40 years Let the present age of Ram and Shyam be 6x years and 5x years respectively. Then 5x + 7 = 32 ∴ 5x = 25 ∴ x = 5 ∴ Present age of Ram = 6x = 30 years Then (4x-9) + (5x-9) + (9x-9) =45 ∴ 18x – 27 = 45 ∴ 18x = 72 ∴ x = 4 Let the numbers be 2X and 9X Then their H.C.F. is X, so X = 19 ∴ Numbers are (2x19 and 9x19) i.e. 38 and 171 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies How to Update Multiple Columns in Single Update Statement in SQL? Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples SQLAlchemy Core - Creating Table How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File How to Replace Values in a List in Python? Spring - REST Controller
[ { "code": null, "e": 27530, "s": 27502, "text": "\n21 Apr, 2016" }, { "code": null, "e": 27656, "s": 27530, "text": "Then (3x+5) / (4x+5) = 7 / 9 \n\n∴ 9(3x + 5) = 7(4x + 5)\n∴ 27x + 45 = 28x + 35\n∴ x = 10\n∴ Ashok’s present age = 4x = 40 years " }, { "code": null, "e": 27817, "s": 27656, "text": "Let the present age of Ram and Shyam be 6x years and 5x years respectively.\n\nThen 5x + 7 = 32\n∴ 5x = 25\n∴ x = 5\n∴ Present age of Ram = 6x = 30 years" }, { "code": null, "e": 27886, "s": 27817, "text": "Then (4x-9) + (5x-9) + (9x-9) =45\n∴ 18x – 27 = 45\n∴ 18x = 72\n∴ x = 4" }, { "code": null, "e": 27995, "s": 27886, "text": "Let the numbers be 2X and 9X\nThen their H.C.F. is X, so X = 19\n∴ Numbers are (2x19 and 9x19) i.e. 38 and 171" }, { "code": null, "e": 28093, "s": 27995, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 28102, "s": 28093, "text": "Comments" }, { "code": null, "e": 28115, "s": 28102, "text": "Old Comments" }, { "code": null, "e": 28168, "s": 28115, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28234, "s": 28168, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28295, "s": 28234, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28333, "s": 28295, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28366, "s": 28333, "text": "SQLAlchemy Core - Creating Table" }, { "code": null, "e": 28428, "s": 28366, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28508, "s": 28428, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 28549, "s": 28508, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28592, "s": 28549, "text": "How to Replace Values in a List in Python?" } ]
C++ Data Types - GeeksforGeeks
28 Jan, 2022 All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data-type with which it is declared. Every data type requires a different amount of memory. Data types in C++ is mainly divided into three types: Primitive Data Types: These data types are built-in or predefined data types and can be used directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C++ are: IntegerCharacterBooleanFloating PointDouble Floating PointValueless or VoidWide CharacterDerived Data Types: The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely: FunctionArrayPointerReferenceAbstract or User-Defined Data Types: These data types are defined by user itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined datatypes: ClassStructureUnionEnumerationTypedef defined DataType Primitive Data Types: These data types are built-in or predefined data types and can be used directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C++ are: IntegerCharacterBooleanFloating PointDouble Floating PointValueless or VoidWide Character Integer Character Boolean Floating Point Double Floating Point Valueless or Void Wide Character Derived Data Types: The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely: FunctionArrayPointerReference Function Array Pointer Reference Abstract or User-Defined Data Types: These data types are defined by user itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined datatypes: ClassStructureUnionEnumerationTypedef defined DataType Class Structure Union Enumeration Typedef defined DataType This article discusses primitive data types available in C++. Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of memory space and ranges from -2147483648 to 2147483647. Character: Character data type is used for storing characters. Keyword used for character data type is char. Characters typically requires 1 byte of memory space and ranges from -128 to 127 or 0 to 255. Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can store either true or false. Keyword used for boolean data type is bool. Floating Point: Floating Point data type is used for storing single precision floating point values or decimal values. Keyword used for floating point data type is float. Float variables typically requires 4 byte of memory space. Double Floating Point: Double Floating Point data type is used for storing double precision floating point values or decimal values. Keyword used for double floating point data type is double. Double variables typically requires 8 byte of memory space. void: Void means without any value. void datatype represents a valueless entity. Void data type is used for those function which does not returns a value. Wide Character: Wide character data type is also a character data type but this data type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes long. Datatype Modifiers As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold. Data type modifiers available in C++ are: Signed Unsigned Short Long Below table summarizes the modified size and range of built-in datatypes when combined with the type modifiers: Note : Above values may vary from compiler to compiler. In the above example, we have considered GCC 32 bit.We can display the size of all the data types by using the sizeof() operator and passing the keyword of the datatype as argument to this function as shown below: CPP // C++ program to sizes of data types#include<iostream>using namespace std; int main(){ cout << "Size of char : " << sizeof(char) << " byte" << endl; cout << "Size of int : " << sizeof(int) << " bytes" << endl; cout << "Size of short int : " << sizeof(short int) << " bytes" << endl; cout << "Size of long int : " << sizeof(long int) << " bytes" << endl; cout << "Size of signed long int : " << sizeof(signed long int) << " bytes" << endl; cout << "Size of unsigned long int : " << sizeof(unsigned long int) << " bytes" << endl; cout << "Size of float : " << sizeof(float) << " bytes" <<endl; cout << "Size of double : " << sizeof(double) << " bytes" << endl; cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes" <<endl; return 0;} Output: Size of char : 1 byte Size of int : 4 bytes Size of short int : 2 bytes Size of long int : 8 bytes Size of signed long int : 8 bytes Size of unsigned long int : 8 bytes Size of float : 4 bytes Size of double : 8 bytes Size of wchar_t : 4 bytes This article is contributed by Harsh 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Naman-Bhalla Abhi rex adityamalik8087 glitch_09 whysodarkbro tusharmalhotra494 tonima2003 C Basics CBSE - Class 11 CPP-Basics Data Type school-programming C++ Mathematical School Programming Strings Strings Mathematical Data Type CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Socket Programming in C/C++ Program for Fibonacci numbers Write a program to print all permutations of a given string Coin Change | DP-7 Merge two sorted arrays Program to find GCD or HCF of two numbers
[ { "code": null, "e": 26648, "s": 26620, "text": "\n28 Jan, 2022" }, { "code": null, "e": 27036, "s": 26648, "text": "All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data-type with which it is declared. Every data type requires a different amount of memory. " }, { "code": null, "e": 27092, "s": 27036, "text": "Data types in C++ is mainly divided into three types: " }, { "code": null, "e": 27828, "s": 27092, "text": "Primitive Data Types: These data types are built-in or predefined data types and can be used directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C++ are: IntegerCharacterBooleanFloating PointDouble Floating PointValueless or VoidWide CharacterDerived Data Types: The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely: FunctionArrayPointerReferenceAbstract or User-Defined Data Types: These data types are defined by user itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined datatypes: ClassStructureUnionEnumerationTypedef defined DataType" }, { "code": null, "e": 28135, "s": 27828, "text": "Primitive Data Types: These data types are built-in or predefined data types and can be used directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C++ are: IntegerCharacterBooleanFloating PointDouble Floating PointValueless or VoidWide Character" }, { "code": null, "e": 28143, "s": 28135, "text": "Integer" }, { "code": null, "e": 28153, "s": 28143, "text": "Character" }, { "code": null, "e": 28161, "s": 28153, "text": "Boolean" }, { "code": null, "e": 28176, "s": 28161, "text": "Floating Point" }, { "code": null, "e": 28198, "s": 28176, "text": "Double Floating Point" }, { "code": null, "e": 28216, "s": 28198, "text": "Valueless or Void" }, { "code": null, "e": 28231, "s": 28216, "text": "Wide Character" }, { "code": null, "e": 28428, "s": 28231, "text": "Derived Data Types: The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely: FunctionArrayPointerReference" }, { "code": null, "e": 28437, "s": 28428, "text": "Function" }, { "code": null, "e": 28443, "s": 28437, "text": "Array" }, { "code": null, "e": 28451, "s": 28443, "text": "Pointer" }, { "code": null, "e": 28461, "s": 28451, "text": "Reference" }, { "code": null, "e": 28695, "s": 28461, "text": "Abstract or User-Defined Data Types: These data types are defined by user itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined datatypes: ClassStructureUnionEnumerationTypedef defined DataType" }, { "code": null, "e": 28701, "s": 28695, "text": "Class" }, { "code": null, "e": 28711, "s": 28701, "text": "Structure" }, { "code": null, "e": 28717, "s": 28711, "text": "Union" }, { "code": null, "e": 28729, "s": 28717, "text": "Enumeration" }, { "code": null, "e": 28754, "s": 28729, "text": "Typedef defined DataType" }, { "code": null, "e": 28818, "s": 28754, "text": "This article discusses primitive data types available in C++. " }, { "code": null, "e": 28968, "s": 28818, "text": "Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of memory space and ranges from -2147483648 to 2147483647. " }, { "code": null, "e": 29173, "s": 28968, "text": "Character: Character data type is used for storing characters. Keyword used for character data type is char. Characters typically requires 1 byte of memory space and ranges from -128 to 127 or 0 to 255. " }, { "code": null, "e": 29344, "s": 29173, "text": "Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can store either true or false. Keyword used for boolean data type is bool. " }, { "code": null, "e": 29576, "s": 29344, "text": "Floating Point: Floating Point data type is used for storing single precision floating point values or decimal values. Keyword used for floating point data type is float. Float variables typically requires 4 byte of memory space. " }, { "code": null, "e": 29831, "s": 29576, "text": "Double Floating Point: Double Floating Point data type is used for storing double precision floating point values or decimal values. Keyword used for double floating point data type is double. Double variables typically requires 8 byte of memory space. " }, { "code": null, "e": 29988, "s": 29831, "text": "void: Void means without any value. void datatype represents a valueless entity. Void data type is used for those function which does not returns a value. " }, { "code": null, "e": 30188, "s": 29988, "text": "Wide Character: Wide character data type is also a character data type but this data type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes long. " }, { "code": null, "e": 30209, "s": 30190, "text": "Datatype Modifiers" }, { "code": null, "e": 30356, "s": 30209, "text": "As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold. " }, { "code": null, "e": 30400, "s": 30356, "text": "Data type modifiers available in C++ are: " }, { "code": null, "e": 30407, "s": 30400, "text": "Signed" }, { "code": null, "e": 30416, "s": 30407, "text": "Unsigned" }, { "code": null, "e": 30422, "s": 30416, "text": "Short" }, { "code": null, "e": 30427, "s": 30422, "text": "Long" }, { "code": null, "e": 30540, "s": 30427, "text": "Below table summarizes the modified size and range of built-in datatypes when combined with the type modifiers: " }, { "code": null, "e": 30812, "s": 30540, "text": "Note : Above values may vary from compiler to compiler. In the above example, we have considered GCC 32 bit.We can display the size of all the data types by using the sizeof() operator and passing the keyword of the datatype as argument to this function as shown below: " }, { "code": null, "e": 30816, "s": 30812, "text": "CPP" }, { "code": "// C++ program to sizes of data types#include<iostream>using namespace std; int main(){ cout << \"Size of char : \" << sizeof(char) << \" byte\" << endl; cout << \"Size of int : \" << sizeof(int) << \" bytes\" << endl; cout << \"Size of short int : \" << sizeof(short int) << \" bytes\" << endl; cout << \"Size of long int : \" << sizeof(long int) << \" bytes\" << endl; cout << \"Size of signed long int : \" << sizeof(signed long int) << \" bytes\" << endl; cout << \"Size of unsigned long int : \" << sizeof(unsigned long int) << \" bytes\" << endl; cout << \"Size of float : \" << sizeof(float) << \" bytes\" <<endl; cout << \"Size of double : \" << sizeof(double) << \" bytes\" << endl; cout << \"Size of wchar_t : \" << sizeof(wchar_t) << \" bytes\" <<endl; return 0;}", "e": 31641, "s": 30816, "text": null }, { "code": null, "e": 31651, "s": 31641, "text": "Output: " }, { "code": null, "e": 31895, "s": 31651, "text": "Size of char : 1 byte\nSize of int : 4 bytes\nSize of short int : 2 bytes\nSize of long int : 8 bytes\nSize of signed long int : 8 bytes\nSize of unsigned long int : 8 bytes\nSize of float : 4 bytes\nSize of double : 8 bytes\nSize of wchar_t : 4 bytes" }, { "code": null, "e": 32317, "s": 31895, "text": "This article is contributed by Harsh 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32330, "s": 32317, "text": "Naman-Bhalla" }, { "code": null, "e": 32339, "s": 32330, "text": "Abhi rex" }, { "code": null, "e": 32355, "s": 32339, "text": "adityamalik8087" }, { "code": null, "e": 32365, "s": 32355, "text": "glitch_09" }, { "code": null, "e": 32378, "s": 32365, "text": "whysodarkbro" }, { "code": null, "e": 32396, "s": 32378, "text": "tusharmalhotra494" }, { "code": null, "e": 32407, "s": 32396, "text": "tonima2003" }, { "code": null, "e": 32416, "s": 32407, "text": "C Basics" }, { "code": null, "e": 32432, "s": 32416, "text": "CBSE - Class 11" }, { "code": null, "e": 32443, "s": 32432, "text": "CPP-Basics" }, { "code": null, "e": 32453, "s": 32443, "text": "Data Type" }, { "code": null, "e": 32472, "s": 32453, "text": "school-programming" }, { "code": null, "e": 32476, "s": 32472, "text": "C++" }, { "code": null, "e": 32489, "s": 32476, "text": "Mathematical" }, { "code": null, "e": 32508, "s": 32489, "text": "School Programming" }, { "code": null, "e": 32516, "s": 32508, "text": "Strings" }, { "code": null, "e": 32524, "s": 32516, "text": "Strings" }, { "code": null, "e": 32537, "s": 32524, "text": "Mathematical" }, { "code": null, "e": 32547, "s": 32537, "text": "Data Type" }, { "code": null, "e": 32551, "s": 32547, "text": "CPP" }, { "code": null, "e": 32649, "s": 32551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32658, "s": 32649, "text": "Comments" }, { "code": null, "e": 32671, "s": 32658, "text": "Old Comments" }, { "code": null, "e": 32689, "s": 32671, "text": "Vector in C++ STL" }, { "code": null, "e": 32735, "s": 32689, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 32758, "s": 32735, "text": "std::sort() in C++ STL" }, { "code": null, "e": 32785, "s": 32758, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 32813, "s": 32785, "text": "Socket Programming in C/C++" }, { "code": null, "e": 32843, "s": 32813, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32903, "s": 32843, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32922, "s": 32903, "text": "Coin Change | DP-7" }, { "code": null, "e": 32946, "s": 32922, "text": "Merge two sorted arrays" } ]
Presenting Python code using RISE | by Tanu N Prabhu | Towards Data Science
Your boss/professor tells you to find the largest number in a Python list and present the result in front of the whole employees/classmates. Now there are some rules that you need to follow to impress your boss/professor. They should be able to see both the documentation and code in this presentation. You should execute the code too. You may use any presentation tool of your choice. Now, how would you be able to present your code and ace it at the same time? The above scenario can be easily tackled with the help of RISE — a Jupyter Notebook plugin, which can convert your .ipynb notebooks into a presentation (slideshow). The entire code of this article can be found on my GitHub Repository below: github.com Below are the six steps to present your python code using RISE Write the python code/logic for the presentation.Install Python — later the better.Install Jupyter Notebook using the command prompt.Install RISE from the command prompt.After installing, open the Jupyter Notebook and check for the RISE button on the toggle bar.For creating a slide show, click on “View — Cell Toolbar — Slideshow”. Write the python code/logic for the presentation. Install Python — later the better. Install Jupyter Notebook using the command prompt. Install RISE from the command prompt. After installing, open the Jupyter Notebook and check for the RISE button on the toggle bar. For creating a slide show, click on “View — Cell Toolbar — Slideshow”. Don’t worry, I won’t let you go or leave confused without explaining these steps in a detailed manner. Stay tuned! Let’s write the logic of “find the largest number in a Python list”. The logic for this will be really minimalistic and easy to understand. Let’s use the below-given algorithm to write the logic: Create a list of values. Sort the list using sort(). Print the last element after it is being sorted. # Create a list of valueslistValues = [-1, 10, -100, -50, 2]# Sorting the listlistValues.sort()# Printing the last elementprint("Largest element in the list is:", listValues[-1]) When you execute the above code you will be prompted by the largest number in the list Largest element in the list is: 10 In this step, you need to download and install Python, but keep in mind the latest version is always the best version. It would be associated with all the additional features and plug-ins, let’s get not very specific here. For Windows: www.python.org Video Installation Remember: There might be a billion of ways to install all the below software, one might use docker, anaconda or, etc. But I wouldn’t be using any of those. Rather, I would follow the traditional methods which would be easy to understand and ace it. Also, in this tutorial, I would provide the installation commands for windows only, if you want to add any commands for other operating systems, comment section is all yours. After downloading Python, navigate to the “Scripts” folder as shown below: If you don’t know where to find “Scripts” use the below path, you will get it: C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts There are two things that you need to take care of: The username, in this case, differs. Please double-check this.Sometimes, you won’t be able to find AppData, so in this case go to the top and click on View, and check the box which says hidden items. The username, in this case, differs. Please double-check this. Sometimes, you won’t be able to find AppData, so in this case go to the top and click on View, and check the box which says hidden items. After navigating to the Scripts folder. Open the path on your command prompt, or just press Ctrl+A and then type cmd and then press Enter, you will be directly navigated to the command prompt from the “Scripts” path. Use the following command to install Jupyter Notebook from your command prompt. pip install jupyter notebook Wait till it is successfully installed. By the way, the next time you want to open Jupyter Notebook, please type jupyter notebook to launch it. After opening the Jupyter Notebook to create a new Python notebook, on the right-hand top corner, click on the drop-down menu and then select Python 3 Notebook. Video Example After you have installed the Jupyter Notebook, the time has now come to install RISE. Just navigate to your command prompt and type in the below command to install it: pip install RISE If you need to read furthermore about RISE then there is no better place than the official docs given below: rise.readthedocs.io Installing RISE will automatically enable the option on the toggle bar as shown below, which clearly says “Enter/Exit RISE Slideshow”. This indicates that you have successfully installed RISE on your device. Lastly, when your Python code and the documentation is ready, it’s time to present it. To present it click on the same RISE button it will automatically open your code in a presentation mode, meaning like a slide show as shown below: Now if you need to edit your slides, or change their “Slide Type”, you need to navigate to “View — Cell Toolbar — Slideshow”. If you want to come out of this mode, select “None” from the same dropdown. Currently, there are 5 different types of slides as shown below, you can choose from them, go ahead and try it out. Note: You can independently choose a different slide type for every cell. Thanks to RISE. Video Example You have reached the end of this article “Presenting Python code using RISE”. I hope you guys have learned a thing or two from this tutorial. Suggestions are always welcomed here. If you have/facing any issues during installations, comment down below. I will respond ASAP. Until then, nail your Python code presentations, show them who is the boss in presentations. Stay tuned for more updates. Have a nice day!
[ { "code": null, "e": 635, "s": 172, "text": "Your boss/professor tells you to find the largest number in a Python list and present the result in front of the whole employees/classmates. Now there are some rules that you need to follow to impress your boss/professor. They should be able to see both the documentation and code in this presentation. You should execute the code too. You may use any presentation tool of your choice. Now, how would you be able to present your code and ace it at the same time?" }, { "code": null, "e": 876, "s": 635, "text": "The above scenario can be easily tackled with the help of RISE — a Jupyter Notebook plugin, which can convert your .ipynb notebooks into a presentation (slideshow). The entire code of this article can be found on my GitHub Repository below:" }, { "code": null, "e": 887, "s": 876, "text": "github.com" }, { "code": null, "e": 950, "s": 887, "text": "Below are the six steps to present your python code using RISE" }, { "code": null, "e": 1283, "s": 950, "text": "Write the python code/logic for the presentation.Install Python — later the better.Install Jupyter Notebook using the command prompt.Install RISE from the command prompt.After installing, open the Jupyter Notebook and check for the RISE button on the toggle bar.For creating a slide show, click on “View — Cell Toolbar — Slideshow”." }, { "code": null, "e": 1333, "s": 1283, "text": "Write the python code/logic for the presentation." }, { "code": null, "e": 1368, "s": 1333, "text": "Install Python — later the better." }, { "code": null, "e": 1419, "s": 1368, "text": "Install Jupyter Notebook using the command prompt." }, { "code": null, "e": 1457, "s": 1419, "text": "Install RISE from the command prompt." }, { "code": null, "e": 1550, "s": 1457, "text": "After installing, open the Jupyter Notebook and check for the RISE button on the toggle bar." }, { "code": null, "e": 1621, "s": 1550, "text": "For creating a slide show, click on “View — Cell Toolbar — Slideshow”." }, { "code": null, "e": 1736, "s": 1621, "text": "Don’t worry, I won’t let you go or leave confused without explaining these steps in a detailed manner. Stay tuned!" }, { "code": null, "e": 1932, "s": 1736, "text": "Let’s write the logic of “find the largest number in a Python list”. The logic for this will be really minimalistic and easy to understand. Let’s use the below-given algorithm to write the logic:" }, { "code": null, "e": 1957, "s": 1932, "text": "Create a list of values." }, { "code": null, "e": 1985, "s": 1957, "text": "Sort the list using sort()." }, { "code": null, "e": 2034, "s": 1985, "text": "Print the last element after it is being sorted." }, { "code": null, "e": 2213, "s": 2034, "text": "# Create a list of valueslistValues = [-1, 10, -100, -50, 2]# Sorting the listlistValues.sort()# Printing the last elementprint(\"Largest element in the list is:\", listValues[-1])" }, { "code": null, "e": 2300, "s": 2213, "text": "When you execute the above code you will be prompted by the largest number in the list" }, { "code": null, "e": 2335, "s": 2300, "text": "Largest element in the list is: 10" }, { "code": null, "e": 2558, "s": 2335, "text": "In this step, you need to download and install Python, but keep in mind the latest version is always the best version. It would be associated with all the additional features and plug-ins, let’s get not very specific here." }, { "code": null, "e": 2571, "s": 2558, "text": "For Windows:" }, { "code": null, "e": 2586, "s": 2571, "text": "www.python.org" }, { "code": null, "e": 2605, "s": 2586, "text": "Video Installation" }, { "code": null, "e": 3029, "s": 2605, "text": "Remember: There might be a billion of ways to install all the below software, one might use docker, anaconda or, etc. But I wouldn’t be using any of those. Rather, I would follow the traditional methods which would be easy to understand and ace it. Also, in this tutorial, I would provide the installation commands for windows only, if you want to add any commands for other operating systems, comment section is all yours." }, { "code": null, "e": 3104, "s": 3029, "text": "After downloading Python, navigate to the “Scripts” folder as shown below:" }, { "code": null, "e": 3183, "s": 3104, "text": "If you don’t know where to find “Scripts” use the below path, you will get it:" }, { "code": null, "e": 3248, "s": 3183, "text": "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\Scripts" }, { "code": null, "e": 3300, "s": 3248, "text": "There are two things that you need to take care of:" }, { "code": null, "e": 3500, "s": 3300, "text": "The username, in this case, differs. Please double-check this.Sometimes, you won’t be able to find AppData, so in this case go to the top and click on View, and check the box which says hidden items." }, { "code": null, "e": 3563, "s": 3500, "text": "The username, in this case, differs. Please double-check this." }, { "code": null, "e": 3701, "s": 3563, "text": "Sometimes, you won’t be able to find AppData, so in this case go to the top and click on View, and check the box which says hidden items." }, { "code": null, "e": 3998, "s": 3701, "text": "After navigating to the Scripts folder. Open the path on your command prompt, or just press Ctrl+A and then type cmd and then press Enter, you will be directly navigated to the command prompt from the “Scripts” path. Use the following command to install Jupyter Notebook from your command prompt." }, { "code": null, "e": 4027, "s": 3998, "text": "pip install jupyter notebook" }, { "code": null, "e": 4332, "s": 4027, "text": "Wait till it is successfully installed. By the way, the next time you want to open Jupyter Notebook, please type jupyter notebook to launch it. After opening the Jupyter Notebook to create a new Python notebook, on the right-hand top corner, click on the drop-down menu and then select Python 3 Notebook." }, { "code": null, "e": 4346, "s": 4332, "text": "Video Example" }, { "code": null, "e": 4514, "s": 4346, "text": "After you have installed the Jupyter Notebook, the time has now come to install RISE. Just navigate to your command prompt and type in the below command to install it:" }, { "code": null, "e": 4531, "s": 4514, "text": "pip install RISE" }, { "code": null, "e": 4640, "s": 4531, "text": "If you need to read furthermore about RISE then there is no better place than the official docs given below:" }, { "code": null, "e": 4660, "s": 4640, "text": "rise.readthedocs.io" }, { "code": null, "e": 4868, "s": 4660, "text": "Installing RISE will automatically enable the option on the toggle bar as shown below, which clearly says “Enter/Exit RISE Slideshow”. This indicates that you have successfully installed RISE on your device." }, { "code": null, "e": 5102, "s": 4868, "text": "Lastly, when your Python code and the documentation is ready, it’s time to present it. To present it click on the same RISE button it will automatically open your code in a presentation mode, meaning like a slide show as shown below:" }, { "code": null, "e": 5304, "s": 5102, "text": "Now if you need to edit your slides, or change their “Slide Type”, you need to navigate to “View — Cell Toolbar — Slideshow”. If you want to come out of this mode, select “None” from the same dropdown." }, { "code": null, "e": 5420, "s": 5304, "text": "Currently, there are 5 different types of slides as shown below, you can choose from them, go ahead and try it out." }, { "code": null, "e": 5510, "s": 5420, "text": "Note: You can independently choose a different slide type for every cell. Thanks to RISE." }, { "code": null, "e": 5524, "s": 5510, "text": "Video Example" } ]
Maximize array elements upto given number - GeeksforGeeks
04 May, 2021 Given an array of integers, a number and a maximum value, task is to compute the maximum value that can be obtained from the array elements. Every value on the array traversing from the beginning can be either added to or subtracted from the result obtained from previous index such that at any point the result is not less than 0 and not greater than the given maximum value. For index 0 take previous result equal to given number. In case of no possible answer print -1. Examples : Input : arr[] = {2, 1, 7} Number = 3 Maximum value = 7 Output : 7 The order of addition and subtraction is: 3(given number) - 2(arr[0]) - 1(arr[1]) + 7(arr[2]). Input : arr[] = {3, 10, 6, 4, 5} Number = 1 Maximum value = 15 Output : 9 The order of addition and subtraction is: 1 + 3 + 10 - 6 - 4 + 5 Prerequisite : Dynamic Programming | Recursion.Naive Approach : Use recursion to find maximum value. At every index position there are two choices, either add current array element to value obtained so far from previous elements or subtract current array element from value obtained so far from previous elements. Start from index 0, add or subtract arr[0] from given number and recursively call for next index along with updated number. When entire array is traversed, compare the updated number with overall maximum value of number obtained so far. Below is the implementation of above approach : C++ Java Python3 C# PHP Javascript // CPP code to find maximum// value of number obtained by// using array elements recursively.#include <bits/stdc++.h>using namespace std; // Utility function to find maximum possible valuevoid findMaxValUtil(int arr[], int n, int num, int maxLimit, int ind, int& ans){ // If entire array is traversed, then compare // current value in num to overall maximum // obtained so far. if (ind == n) { ans = max(ans, num); return; } // Case 1: Subtract current element from value so // far if result is greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1, ans); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1, ans); }} // Function to find maximum possible// value that can be obtained using// array elements and given number.int findMaxVal(int arr[], int n, int num, int maxLimit){ // variable to store maximum value // that can be obtained. int ans = 0; // variable to store current index position. int ind = 0; // call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind, ans); return ans;} // Driver codeint main(){ int num = 1; int arr[] = { 3, 10, 6, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int maxLimit = 15; cout << findMaxVal(arr, n, num, maxLimit); return 0;} // Java code to find maximum// value of number obtained by// using array elements recursively.import java.io.*;import java.lang.*; public class GFG { // variable to store maximum value // that can be obtained. static int ans; // Utility function to find maximum // possible value static void findMaxValUtil(int []arr, int n, int num, int maxLimit, int ind) { // If entire array is traversed, then compare // current value in num to overall maximum // obtained so far. if (ind == n) { ans = Math.max(ans, num); return; } // Case 1: Subtract current element from value so // far if result is greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1); } } // Function to find maximum possible // value that can be obtained using // array elements and given number. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // variable to store current index position. int ind = 0; // call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind); return ans; } // Driver code public static void main(String args[]) { int num = 1; int []arr = { 3, 10, 6, 4, 5 }; int n = arr.length; int maxLimit = 15; System.out.print(findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed by Manish Shaw// (manishshaw1) # Python3 code to find maximum# value of number obtained by# using array elements recursively. # Utility def to find# maximum possible value # variable to store maximum value# that can be obtained.ans = 0;def findMaxValUtil(arr, n, num, maxLimit, ind): global ans # If entire array is traversed, # then compare current value # in num to overall maximum # obtained so far. if (ind == n) : ans = max(ans, num) return # Case 1: Subtract current element # from value so far if result is # greater than or equal to zero. if (num - arr[ind] >= 0) : findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1) # Case 2 : Add current element to # value so far if result is less # than or equal to maxLimit. if (num + arr[ind] <= maxLimit) : findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1) # def to find maximum possible# value that can be obtained using# array elements and given number.def findMaxVal(arr, n, num, maxLimit) : global ans # variable to store # current index position. ind = 0 # call to utility def to # find maximum possible value # that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind) return ans # Driver codenum = 1arr = [3, 10, 6, 4, 5]n = len(arr)maxLimit = 15 print (findMaxVal(arr, n, num, maxLimit)) # This code is contributed by Manish Shaw# (manishshaw1) // C# code to find maximum// value of number obtained by// using array elements recursively.using System;using System.Collections.Generic; class GFG { // Utility function to find maximum // possible value static void findMaxValUtil(int []arr, int n, int num, int maxLimit, int ind, ref int ans) { // If entire array is traversed, then compare // current value in num to overall maximum // obtained so far. if (ind == n) { ans = Math.Max(ans, num); return; } // Case 1: Subtract current element from value so // far if result is greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1, ref ans); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1, ref ans); } } // Function to find maximum possible // value that can be obtained using // array elements and given number. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // variable to store maximum value // that can be obtained. int ans = 0; // variable to store current index position. int ind = 0; // call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind, ref ans); return ans; } // Driver code public static void Main() { int num = 1; int []arr = { 3, 10, 6, 4, 5 }; int n = arr.Length; int maxLimit = 15; Console.Write(findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed by Manish Shaw// (manishshaw1) <?php// PHP code to find maximum// value of number obtained by// using array elements recursively. // Utility function to find// maximum possible valuefunction findMaxValUtil($arr, $n, $num, $maxLimit, $ind, &$ans){ // If entire array is traversed, // then compare current value // in num to overall maximum // obtained so far. if ($ind == $n) { $ans = max($ans, $num); return; } // Case 1: Subtract current element // from value so far if result is // greater than or equal to zero. if ($num - $arr[$ind] >= 0) { findMaxValUtil($arr, $n, $num - $arr[$ind], $maxLimit, $ind + 1, $ans); } // Case 2 : Add current element to // value so far if result is less // than or equal to maxLimit. if ($num + $arr[$ind] <= $maxLimit) { findMaxValUtil($arr, $n, $num + $arr[$ind], $maxLimit, $ind + 1, $ans); }} // Function to find maximum possible// value that can be obtained using// array elements and given number.function findMaxVal($arr, $n, $num, $maxLimit){ // variable to store maximum value // that can be obtained. $ans = 0; // variable to store // current index position. $ind = 0; // call to utility function to // find maximum possible value // that can be obtained. findMaxValUtil($arr, $n, $num, $maxLimit, $ind, $ans); return $ans;} // Driver code$num = 1;$arr = array(3, 10, 6, 4, 5);$n = count($arr);$maxLimit = 15; echo (findMaxVal($arr, $n, $num, $maxLimit)); //This code is contributed by Manish Shaw//(manishshaw1)?> <script> // Javascript code to find maximum// value of number obtained by// using array elements recursively. // variable to store maximum value// that can be obtained.let ans = 0; // Utility function to find maximum// possible valuefunction findMaxValUtil(arr, n, num, maxLimit, ind){ // If entire array is traversed, then // compare current value in num to // overall maximum obtained so far. if (ind == n) { ans = Math.max(ans, num); return; } // Case 1: Subtract current element // from value so far if result is // greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1); }} // Function to find maximum possible// value that can be obtained using// array elements and given number.function findMaxVal(arr, n, num, maxLimit){ // Variable to store current index position. let ind = 0; // Call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind); return ans;} // Driver codelet num = 1;let arr = [ 3, 10, 6, 4, 5 ];let n = arr.length;let maxLimit = 15; document.write(findMaxVal(arr, n, num, maxLimit)); // This code is contributed by mukesh07 </script> 9 Time Complexity : O(2^n). Note : For small values of n <= 20, this solution will work. But as array size increases, this will not be an optimal solution. An efficient solution is to use Dynamic Programming. Observe that the value at every step is constrained between 0 and maxLimit and hence, the required maximum value will also lie in this range. At every index position, after arr[i] is added to or subtracted from result, the new value of result will also lie in this range. Lets try to build the solution backwards. Suppose the required maximum possible value is x, where 0 ≤ x ≤ maxLimit. This value x is obtained by either adding or subtracting arr[n-1] to/from the value obtained until index position n-2. The same reason can be given for value obtained at index position n-2 that it depends on value at index position n-3 and so on. The resulting recurrence relation can be given as : Check can x be obtained from arr[0..n-1]: Check can x - arr[n-1] be obtained from arr[0..n-2] || Check can x + arr[n-1] be obtained from arr[0..n-2] A boolean DP table can be created in which dp[i][j] is 1 if value j can be obtained using arr[0..i] and 0 if not. For each index position, start from j = 0 and move to value maxLimit, and set dp[i][j] either 0 or 1 as described above. Find the maximum possible value that can be obtained at index position n-1 by finding maximum j when i = n-1 and dp[n-1][j] = 1. C++ Java Python3 C# PHP Javascript // C++ program to find maximum value of// number obtained by using array// elements by using dynamic programming.#include <bits/stdc++.h>using namespace std; // Function to find maximum possible// value of number that can be// obtained using array elements.int findMaxVal(int arr[], int n, int num, int maxLimit){ // Variable to represent current index. int ind; // Variable to show value between // 0 and maxLimit. int val; // Table to store whether a value can // be obtained or not upto a certain index. // 1. dp[i][j] = 1 if value j can be // obtained upto index i. // 2. dp[i][j] = 0 if value j cannot be // obtained upto index i. int dp[n][maxLimit+1]; for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given value // val can be obtained by either adding // to or subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind][val] = 1; } else { dp[ind][val] = 0; } } else { // 1. If arr[ind] is added to // obtain given val then val- // arr[ind] should be obtainable // from index ind-1. // 2. If arr[ind] is subtracted to // obtain given val then val+arr[ind] // should be obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition is true, // then val is obtainable at index ind. dp[ind][val] = dp[ind-1][val-arr[ind]] || dp[ind-1][val+arr[ind]]; } else if(val - arr[ind] >= 0) { dp[ind][val] = dp[ind-1][val-arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind][val] = dp[ind-1][val+arr[ind]]; } else { dp[ind][val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n-1][val]) { return val; } } // If no solution exists return -1. return -1;} // Driver Codeint main(){ int num = 1; int arr[] = {3, 10, 6, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int maxLimit = 15; cout << findMaxVal(arr, n, num, maxLimit); return 0;} // Java program to find maximum// value of number obtained by// using array elements by using// dynamic programming.import java.io.*; class GFG{ // Function to find maximum // possible value of number // that can be obtained // using array elements. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // Variable to represent // current index. int ind; // Variable to show value // between 0 and maxLimit. int val; // Table to store whether // a value can be obtained // or not upto a certain // index 1. dp[i,j] = 1 if // value j can be obtained // upto index i. // 2. dp[i,j] = 0 if value j // cannot be obtained upto index i. int [][]dp = new int[n][maxLimit + 1]; for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given // value val can be obtained // by either adding to or // subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind][val] = 1; } else { dp[ind][val] = 0; } } else { // 1. If arr[ind] is added // to obtain given val then // val- arr[ind] should be // obtainable from index // ind-1. // 2. If arr[ind] is subtracted // to obtain given val then // val+arr[ind] should be // obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition // is true, then val is // obtainable at index ind. if(dp[ind - 1][val - arr[ind]] == 1 || dp[ind - 1][val + arr[ind]] == 1) dp[ind][val] = 1; } else if(val - arr[ind] >= 0) { dp[ind][val] = dp[ind - 1][val - arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind][val] = dp[ind - 1][val + arr[ind]]; } else { dp[ind][val] = 0; } } } } // Find maximum value that // is obtained at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n - 1][val] == 1) { return val; } } // If no solution // exists return -1. return -1; } // Driver Code public static void main(String args[]) { int num = 1; int []arr = new int[]{3, 10, 6, 4, 5}; int n = arr.length; int maxLimit = 15; System.out.print(findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed// by Manish Shaw(manishshaw1) # Python3 program to find maximum# value of number obtained by# using array elements by using# dynamic programming. # Function to find maximum# possible value of number# that can be obtained# using array elements.def findMaxVal(arr, n, num, maxLimit): # Variable to represent # current index. ind = -1; # Variable to show value # between 0 and maxLimit. val = -1; # Table to store whether # a value can be obtained # or not upto a certain # index 1. dp[i,j] = 1 if # value j can be obtained # upto index i. # 2. dp[i,j] = 0 if value j # cannot be obtained upto index i. dp = [[0 for i in range(maxLimit + 1)] for j in range(n)]; for ind in range(n): for val in range(maxLimit + 1): # Check for index 0 if given # value val can be obtained # by either adding to or # subtracting arr[0] from num. if (ind == 0): if (num - arr[ind] == val or num + arr[ind] == val): dp[ind][val] = 1; else: dp[ind][val] = 0; else: # 1. If arr[ind] is added # to obtain given val then # val- arr[ind] should be # obtainable from index # ind-1. # 2. If arr[ind] is subtracted # to obtain given val then # val+arr[ind] should be # obtainable from index ind-1. # Check for both the conditions. if (val - arr[ind] >= 0 and val + arr[ind] <= maxLimit): # If either of one condition # is True, then val is # obtainable at index ind. if (dp[ind - 1][val - arr[ind]] == 1 or dp[ind - 1][val + arr[ind]] == 1): dp[ind][val] = 1; elif (val - arr[ind] >= 0): dp[ind][val] = dp[ind - 1][val - arr[ind]]; elif (val + arr[ind] <= maxLimit): dp[ind][val] = dp[ind - 1][val + arr[ind]]; else: dp[ind][val] = 0; # Find maximum value that # is obtained at index n-1. for val in range(maxLimit, -1, -1): if (dp[n - 1][val] == 1): return val; # If no solution # exists return -1. return -1; # Driver Codeif __name__ == '__main__': num = 1; arr = [3, 10, 6, 4, 5]; n = len(arr); maxLimit = 15; print(findMaxVal(arr, n, num, maxLimit)); # This code is contributed by 29AjayKumar // C# program to find maximum value of// number obtained by using array// elements by using dynamic programming.using System; class GFG { // Function to find maximum possible // value of number that can be // obtained using array elements. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // Variable to represent current index. int ind; // Variable to show value between // 0 and maxLimit. int val; // Table to store whether a value can // be obtained or not upto a certain // index 1. dp[i,j] = 1 if value j // can be obtained upto index i. // 2. dp[i,j] = 0 if value j cannot be // obtained upto index i. int [,]dp = new int[n,maxLimit+1]; for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given // value val can be obtained // by either adding to or // subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind,val] = 1; } else { dp[ind,val] = 0; } } else { // 1. If arr[ind] is added // to obtain given val then // val- arr[ind] should be // obtainable from index // ind-1. // 2. If arr[ind] is subtracted // to obtain given val then // val+arr[ind] should be // obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition // is true, then val is // obtainable at index ind. if(dp[ind-1,val-arr[ind]] == 1 || dp[ind-1,val+arr[ind]] == 1) dp[ind,val] = 1; } else if(val - arr[ind] >= 0) { dp[ind,val] = dp[ind-1,val-arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind,val] = dp[ind-1,val+arr[ind]]; } else { dp[ind,val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n-1,val] == 1) { return val; } } // If no solution exists return -1. return -1; } // Driver Code static void Main() { int num = 1; int []arr = new int[]{3, 10, 6, 4, 5}; int n = arr.Length; int maxLimit = 15; Console.Write( findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed by Manish Shaw// (manishshaw1) <?php// PHP program to find maximum value of// number obtained by using array// elements by using dynamic programming. // Function to find maximum possible// value of number that can be// obtained using array elements.function findMaxVal($arr, $n, $num, $maxLimit){ // Variable to represent // current index. $ind; // Variable to show value between // 0 and maxLimit. $val; // Table to store whether a value can // be obtained or not upto a certain index. // 1. dp[i][j] = 1 if value j can be // obtained upto index i. // 2. dp[i][j] = 0 if value j cannot be // obtained upto index i. $dp[$n][$maxLimit + 1] = array(); for($ind = 0; $ind < $n; $ind++) { for($val = 0; $val <= $maxLimit; $val++) { // Check for index 0 if given value // val can be obtained by either adding // to or subtracting arr[0] from num. if($ind == 0) { if($num - $arr[$ind] == $val || $num + $arr[$ind] == $val) { $dp[$ind][$val] = 1; } else { $dp[$ind][$val] = 0; } } else { // 1. If arr[ind] is added to // obtain given val then val- // arr[ind] should be obtainable // from index ind-1. // 2. If arr[ind] is subtracted to // obtain given val then val+arr[ind] // should be obtainable from index ind-1. // Check for both the conditions. if($val - $arr[$ind] >= 0 && $val + $arr[$ind] <= $maxLimit) { // If either of one condition is true, // then val is obtainable at index ind. $dp[$ind][$val] = $dp[$ind - 1][$val - $arr[$ind]] || $dp[$ind - 1][$val + $arr[$ind]]; } else if($val - $arr[$ind] >= 0) { $dp[$ind][$val] = $dp[$ind - 1][$val - $arr[$ind]]; } else if($val + $arr[$ind] <= $maxLimit) { $dp[$ind][$val] = $dp[$ind - 1][$val + $arr[$ind]]; } else { $dp[$ind][$val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for($val = $maxLimit; $val >= 0; $val--) { if($dp[$n - 1][$val]) { return $val; } } // If no solution exists return -1. return -1;} // Driver Code$num = 1;$arr = array(3, 10, 6, 4, 5);$n = sizeof($arr);$maxLimit = 15; echo findMaxVal($arr, $n, $num, $maxLimit); // This code is contributed by ajit.?> <script> // Javascript program to find maximum value of// number obtained by using array// elements by using dynamic programming. // Function to find maximum possible// value of number that can be// obtained using array elements.function findMaxVal(arr, n, num, maxLimit){ // Variable to represent current index. var ind; // Variable to show value between // 0 and maxLimit. var val; // Table to store whether a value can // be obtained or not upto a certain index. // 1. dp[i][j] = 1 if value j can be // obtained upto index i. // 2. dp[i][j] = 0 if value j cannot be // obtained upto index i. var dp = Array.from( Array(n), () => Array(maxLimit+1)); for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given value // val can be obtained by either adding // to or subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind][val] = 1; } else { dp[ind][val] = 0; } } else { // 1. If arr[ind] is added to // obtain given val then val- // arr[ind] should be obtainable // from index ind-1. // 2. If arr[ind] is subtracted to // obtain given val then val+arr[ind] // should be obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition is true, // then val is obtainable at index ind. dp[ind][val] = dp[ind-1][val-arr[ind]] || dp[ind-1][val+arr[ind]]; } else if(val - arr[ind] >= 0) { dp[ind][val] = dp[ind-1][val-arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind][val] = dp[ind-1][val+arr[ind]]; } else { dp[ind][val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n-1][val]) { return val; } } // If no solution exists return -1. return -1;} // Driver Codevar num = 1;var arr = [3, 10, 6, 4, 5];var n = arr.length;var maxLimit = 15; document.write( findMaxVal(arr, n, num, maxLimit)); // This code is contributed by rutvik_56.</script> 9 Time Complexity : O(n*maxLimit), where n is the size of array and maxLimit is the given max value. Auxiliary Space : O(n*maxLimit), n is the size of array and maxLimit is the given max value.Optimization : The space required can be reduced to O(2*maxLimit). Note that at every index position, we are only using values from previous row. So we can create a table with two rows, in which one of the rows store result for previous iteration and other for the current iteration. manishshaw1 jit_t 29AjayKumar rutvik_56 mukesh07 cpp-array Arrays Dynamic Programming Recursion Arrays Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Linear Search Multidimensional Arrays in Java Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 25254, "s": 25226, "text": "\n04 May, 2021" }, { "code": null, "e": 25727, "s": 25254, "text": "Given an array of integers, a number and a maximum value, task is to compute the maximum value that can be obtained from the array elements. Every value on the array traversing from the beginning can be either added to or subtracted from the result obtained from previous index such that at any point the result is not less than 0 and not greater than the given maximum value. For index 0 take previous result equal to given number. In case of no possible answer print -1." }, { "code": null, "e": 25739, "s": 25727, "text": "Examples : " }, { "code": null, "e": 26073, "s": 25739, "text": "Input : arr[] = {2, 1, 7}\n Number = 3\n Maximum value = 7\nOutput : 7\nThe order of addition and subtraction\nis: 3(given number) - 2(arr[0]) - \n1(arr[1]) + 7(arr[2]).\n\nInput : arr[] = {3, 10, 6, 4, 5}\n Number = 1\n Maximum value = 15\nOutput : 9\nThe order of addition and subtraction\nis: 1 + 3 + 10 - 6 - 4 + 5" }, { "code": null, "e": 26624, "s": 26073, "text": "Prerequisite : Dynamic Programming | Recursion.Naive Approach : Use recursion to find maximum value. At every index position there are two choices, either add current array element to value obtained so far from previous elements or subtract current array element from value obtained so far from previous elements. Start from index 0, add or subtract arr[0] from given number and recursively call for next index along with updated number. When entire array is traversed, compare the updated number with overall maximum value of number obtained so far." }, { "code": null, "e": 26673, "s": 26624, "text": "Below is the implementation of above approach : " }, { "code": null, "e": 26677, "s": 26673, "text": "C++" }, { "code": null, "e": 26682, "s": 26677, "text": "Java" }, { "code": null, "e": 26690, "s": 26682, "text": "Python3" }, { "code": null, "e": 26693, "s": 26690, "text": "C#" }, { "code": null, "e": 26697, "s": 26693, "text": "PHP" }, { "code": null, "e": 26708, "s": 26697, "text": "Javascript" }, { "code": "// CPP code to find maximum// value of number obtained by// using array elements recursively.#include <bits/stdc++.h>using namespace std; // Utility function to find maximum possible valuevoid findMaxValUtil(int arr[], int n, int num, int maxLimit, int ind, int& ans){ // If entire array is traversed, then compare // current value in num to overall maximum // obtained so far. if (ind == n) { ans = max(ans, num); return; } // Case 1: Subtract current element from value so // far if result is greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1, ans); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1, ans); }} // Function to find maximum possible// value that can be obtained using// array elements and given number.int findMaxVal(int arr[], int n, int num, int maxLimit){ // variable to store maximum value // that can be obtained. int ans = 0; // variable to store current index position. int ind = 0; // call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind, ans); return ans;} // Driver codeint main(){ int num = 1; int arr[] = { 3, 10, 6, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int maxLimit = 15; cout << findMaxVal(arr, n, num, maxLimit); return 0;}", "e": 28347, "s": 26708, "text": null }, { "code": "// Java code to find maximum// value of number obtained by// using array elements recursively.import java.io.*;import java.lang.*; public class GFG { // variable to store maximum value // that can be obtained. static int ans; // Utility function to find maximum // possible value static void findMaxValUtil(int []arr, int n, int num, int maxLimit, int ind) { // If entire array is traversed, then compare // current value in num to overall maximum // obtained so far. if (ind == n) { ans = Math.max(ans, num); return; } // Case 1: Subtract current element from value so // far if result is greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1); } } // Function to find maximum possible // value that can be obtained using // array elements and given number. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // variable to store current index position. int ind = 0; // call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind); return ans; } // Driver code public static void main(String args[]) { int num = 1; int []arr = { 3, 10, 6, 4, 5 }; int n = arr.length; int maxLimit = 15; System.out.print(findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 30390, "s": 28347, "text": null }, { "code": "# Python3 code to find maximum# value of number obtained by# using array elements recursively. # Utility def to find# maximum possible value # variable to store maximum value# that can be obtained.ans = 0;def findMaxValUtil(arr, n, num, maxLimit, ind): global ans # If entire array is traversed, # then compare current value # in num to overall maximum # obtained so far. if (ind == n) : ans = max(ans, num) return # Case 1: Subtract current element # from value so far if result is # greater than or equal to zero. if (num - arr[ind] >= 0) : findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1) # Case 2 : Add current element to # value so far if result is less # than or equal to maxLimit. if (num + arr[ind] <= maxLimit) : findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1) # def to find maximum possible# value that can be obtained using# array elements and given number.def findMaxVal(arr, n, num, maxLimit) : global ans # variable to store # current index position. ind = 0 # call to utility def to # find maximum possible value # that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind) return ans # Driver codenum = 1arr = [3, 10, 6, 4, 5]n = len(arr)maxLimit = 15 print (findMaxVal(arr, n, num, maxLimit)) # This code is contributed by Manish Shaw# (manishshaw1)", "e": 31842, "s": 30390, "text": null }, { "code": "// C# code to find maximum// value of number obtained by// using array elements recursively.using System;using System.Collections.Generic; class GFG { // Utility function to find maximum // possible value static void findMaxValUtil(int []arr, int n, int num, int maxLimit, int ind, ref int ans) { // If entire array is traversed, then compare // current value in num to overall maximum // obtained so far. if (ind == n) { ans = Math.Max(ans, num); return; } // Case 1: Subtract current element from value so // far if result is greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1, ref ans); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1, ref ans); } } // Function to find maximum possible // value that can be obtained using // array elements and given number. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // variable to store maximum value // that can be obtained. int ans = 0; // variable to store current index position. int ind = 0; // call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind, ref ans); return ans; } // Driver code public static void Main() { int num = 1; int []arr = { 3, 10, 6, 4, 5 }; int n = arr.Length; int maxLimit = 15; Console.Write(findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 33932, "s": 31842, "text": null }, { "code": "<?php// PHP code to find maximum// value of number obtained by// using array elements recursively. // Utility function to find// maximum possible valuefunction findMaxValUtil($arr, $n, $num, $maxLimit, $ind, &$ans){ // If entire array is traversed, // then compare current value // in num to overall maximum // obtained so far. if ($ind == $n) { $ans = max($ans, $num); return; } // Case 1: Subtract current element // from value so far if result is // greater than or equal to zero. if ($num - $arr[$ind] >= 0) { findMaxValUtil($arr, $n, $num - $arr[$ind], $maxLimit, $ind + 1, $ans); } // Case 2 : Add current element to // value so far if result is less // than or equal to maxLimit. if ($num + $arr[$ind] <= $maxLimit) { findMaxValUtil($arr, $n, $num + $arr[$ind], $maxLimit, $ind + 1, $ans); }} // Function to find maximum possible// value that can be obtained using// array elements and given number.function findMaxVal($arr, $n, $num, $maxLimit){ // variable to store maximum value // that can be obtained. $ans = 0; // variable to store // current index position. $ind = 0; // call to utility function to // find maximum possible value // that can be obtained. findMaxValUtil($arr, $n, $num, $maxLimit, $ind, $ans); return $ans;} // Driver code$num = 1;$arr = array(3, 10, 6, 4, 5);$n = count($arr);$maxLimit = 15; echo (findMaxVal($arr, $n, $num, $maxLimit)); //This code is contributed by Manish Shaw//(manishshaw1)?>", "e": 35698, "s": 33932, "text": null }, { "code": "<script> // Javascript code to find maximum// value of number obtained by// using array elements recursively. // variable to store maximum value// that can be obtained.let ans = 0; // Utility function to find maximum// possible valuefunction findMaxValUtil(arr, n, num, maxLimit, ind){ // If entire array is traversed, then // compare current value in num to // overall maximum obtained so far. if (ind == n) { ans = Math.max(ans, num); return; } // Case 1: Subtract current element // from value so far if result is // greater than or equal to zero. if (num - arr[ind] >= 0) { findMaxValUtil(arr, n, num - arr[ind], maxLimit, ind + 1); } // Case 2 : Add current element to value so far // if result is less than or equal to maxLimit. if (num + arr[ind] <= maxLimit) { findMaxValUtil(arr, n, num + arr[ind], maxLimit, ind + 1); }} // Function to find maximum possible// value that can be obtained using// array elements and given number.function findMaxVal(arr, n, num, maxLimit){ // Variable to store current index position. let ind = 0; // Call to utility function to find maximum // possible value that can be obtained. findMaxValUtil(arr, n, num, maxLimit, ind); return ans;} // Driver codelet num = 1;let arr = [ 3, 10, 6, 4, 5 ];let n = arr.length;let maxLimit = 15; document.write(findMaxVal(arr, n, num, maxLimit)); // This code is contributed by mukesh07 </script>", "e": 37289, "s": 35698, "text": null }, { "code": null, "e": 37291, "s": 37289, "text": "9" }, { "code": null, "e": 37319, "s": 37293, "text": "Time Complexity : O(2^n)." }, { "code": null, "e": 37448, "s": 37319, "text": "Note : For small values of n <= 20, this solution will work. But as array size increases, this will not be an optimal solution. " }, { "code": null, "e": 38189, "s": 37448, "text": "An efficient solution is to use Dynamic Programming. Observe that the value at every step is constrained between 0 and maxLimit and hence, the required maximum value will also lie in this range. At every index position, after arr[i] is added to or subtracted from result, the new value of result will also lie in this range. Lets try to build the solution backwards. Suppose the required maximum possible value is x, where 0 ≤ x ≤ maxLimit. This value x is obtained by either adding or subtracting arr[n-1] to/from the value obtained until index position n-2. The same reason can be given for value obtained at index position n-2 that it depends on value at index position n-3 and so on. The resulting recurrence relation can be given as : " }, { "code": null, "e": 38345, "s": 38189, "text": "Check can x be obtained from arr[0..n-1]:\n Check can x - arr[n-1] be obtained from arr[0..n-2] \n || Check can x + arr[n-1] be obtained from arr[0..n-2]" }, { "code": null, "e": 38710, "s": 38345, "text": "A boolean DP table can be created in which dp[i][j] is 1 if value j can be obtained using arr[0..i] and 0 if not. For each index position, start from j = 0 and move to value maxLimit, and set dp[i][j] either 0 or 1 as described above. Find the maximum possible value that can be obtained at index position n-1 by finding maximum j when i = n-1 and dp[n-1][j] = 1. " }, { "code": null, "e": 38714, "s": 38710, "text": "C++" }, { "code": null, "e": 38719, "s": 38714, "text": "Java" }, { "code": null, "e": 38727, "s": 38719, "text": "Python3" }, { "code": null, "e": 38730, "s": 38727, "text": "C#" }, { "code": null, "e": 38734, "s": 38730, "text": "PHP" }, { "code": null, "e": 38745, "s": 38734, "text": "Javascript" }, { "code": "// C++ program to find maximum value of// number obtained by using array// elements by using dynamic programming.#include <bits/stdc++.h>using namespace std; // Function to find maximum possible// value of number that can be// obtained using array elements.int findMaxVal(int arr[], int n, int num, int maxLimit){ // Variable to represent current index. int ind; // Variable to show value between // 0 and maxLimit. int val; // Table to store whether a value can // be obtained or not upto a certain index. // 1. dp[i][j] = 1 if value j can be // obtained upto index i. // 2. dp[i][j] = 0 if value j cannot be // obtained upto index i. int dp[n][maxLimit+1]; for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given value // val can be obtained by either adding // to or subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind][val] = 1; } else { dp[ind][val] = 0; } } else { // 1. If arr[ind] is added to // obtain given val then val- // arr[ind] should be obtainable // from index ind-1. // 2. If arr[ind] is subtracted to // obtain given val then val+arr[ind] // should be obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition is true, // then val is obtainable at index ind. dp[ind][val] = dp[ind-1][val-arr[ind]] || dp[ind-1][val+arr[ind]]; } else if(val - arr[ind] >= 0) { dp[ind][val] = dp[ind-1][val-arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind][val] = dp[ind-1][val+arr[ind]]; } else { dp[ind][val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n-1][val]) { return val; } } // If no solution exists return -1. return -1;} // Driver Codeint main(){ int num = 1; int arr[] = {3, 10, 6, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int maxLimit = 15; cout << findMaxVal(arr, n, num, maxLimit); return 0;}", "e": 41634, "s": 38745, "text": null }, { "code": "// Java program to find maximum// value of number obtained by// using array elements by using// dynamic programming.import java.io.*; class GFG{ // Function to find maximum // possible value of number // that can be obtained // using array elements. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // Variable to represent // current index. int ind; // Variable to show value // between 0 and maxLimit. int val; // Table to store whether // a value can be obtained // or not upto a certain // index 1. dp[i,j] = 1 if // value j can be obtained // upto index i. // 2. dp[i,j] = 0 if value j // cannot be obtained upto index i. int [][]dp = new int[n][maxLimit + 1]; for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given // value val can be obtained // by either adding to or // subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind][val] = 1; } else { dp[ind][val] = 0; } } else { // 1. If arr[ind] is added // to obtain given val then // val- arr[ind] should be // obtainable from index // ind-1. // 2. If arr[ind] is subtracted // to obtain given val then // val+arr[ind] should be // obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition // is true, then val is // obtainable at index ind. if(dp[ind - 1][val - arr[ind]] == 1 || dp[ind - 1][val + arr[ind]] == 1) dp[ind][val] = 1; } else if(val - arr[ind] >= 0) { dp[ind][val] = dp[ind - 1][val - arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind][val] = dp[ind - 1][val + arr[ind]]; } else { dp[ind][val] = 0; } } } } // Find maximum value that // is obtained at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n - 1][val] == 1) { return val; } } // If no solution // exists return -1. return -1; } // Driver Code public static void main(String args[]) { int num = 1; int []arr = new int[]{3, 10, 6, 4, 5}; int n = arr.length; int maxLimit = 15; System.out.print(findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed// by Manish Shaw(manishshaw1)", "e": 45373, "s": 41634, "text": null }, { "code": "# Python3 program to find maximum# value of number obtained by# using array elements by using# dynamic programming. # Function to find maximum# possible value of number# that can be obtained# using array elements.def findMaxVal(arr, n, num, maxLimit): # Variable to represent # current index. ind = -1; # Variable to show value # between 0 and maxLimit. val = -1; # Table to store whether # a value can be obtained # or not upto a certain # index 1. dp[i,j] = 1 if # value j can be obtained # upto index i. # 2. dp[i,j] = 0 if value j # cannot be obtained upto index i. dp = [[0 for i in range(maxLimit + 1)] for j in range(n)]; for ind in range(n): for val in range(maxLimit + 1): # Check for index 0 if given # value val can be obtained # by either adding to or # subtracting arr[0] from num. if (ind == 0): if (num - arr[ind] == val or num + arr[ind] == val): dp[ind][val] = 1; else: dp[ind][val] = 0; else: # 1. If arr[ind] is added # to obtain given val then # val- arr[ind] should be # obtainable from index # ind-1. # 2. If arr[ind] is subtracted # to obtain given val then # val+arr[ind] should be # obtainable from index ind-1. # Check for both the conditions. if (val - arr[ind] >= 0 and val + arr[ind] <= maxLimit): # If either of one condition # is True, then val is # obtainable at index ind. if (dp[ind - 1][val - arr[ind]] == 1 or dp[ind - 1][val + arr[ind]] == 1): dp[ind][val] = 1; elif (val - arr[ind] >= 0): dp[ind][val] = dp[ind - 1][val - arr[ind]]; elif (val + arr[ind] <= maxLimit): dp[ind][val] = dp[ind - 1][val + arr[ind]]; else: dp[ind][val] = 0; # Find maximum value that # is obtained at index n-1. for val in range(maxLimit, -1, -1): if (dp[n - 1][val] == 1): return val; # If no solution # exists return -1. return -1; # Driver Codeif __name__ == '__main__': num = 1; arr = [3, 10, 6, 4, 5]; n = len(arr); maxLimit = 15; print(findMaxVal(arr, n, num, maxLimit)); # This code is contributed by 29AjayKumar", "e": 47967, "s": 45373, "text": null }, { "code": "// C# program to find maximum value of// number obtained by using array// elements by using dynamic programming.using System; class GFG { // Function to find maximum possible // value of number that can be // obtained using array elements. static int findMaxVal(int []arr, int n, int num, int maxLimit) { // Variable to represent current index. int ind; // Variable to show value between // 0 and maxLimit. int val; // Table to store whether a value can // be obtained or not upto a certain // index 1. dp[i,j] = 1 if value j // can be obtained upto index i. // 2. dp[i,j] = 0 if value j cannot be // obtained upto index i. int [,]dp = new int[n,maxLimit+1]; for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given // value val can be obtained // by either adding to or // subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind,val] = 1; } else { dp[ind,val] = 0; } } else { // 1. If arr[ind] is added // to obtain given val then // val- arr[ind] should be // obtainable from index // ind-1. // 2. If arr[ind] is subtracted // to obtain given val then // val+arr[ind] should be // obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition // is true, then val is // obtainable at index ind. if(dp[ind-1,val-arr[ind]] == 1 || dp[ind-1,val+arr[ind]] == 1) dp[ind,val] = 1; } else if(val - arr[ind] >= 0) { dp[ind,val] = dp[ind-1,val-arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind,val] = dp[ind-1,val+arr[ind]]; } else { dp[ind,val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n-1,val] == 1) { return val; } } // If no solution exists return -1. return -1; } // Driver Code static void Main() { int num = 1; int []arr = new int[]{3, 10, 6, 4, 5}; int n = arr.Length; int maxLimit = 15; Console.Write( findMaxVal(arr, n, num, maxLimit)); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 51472, "s": 47967, "text": null }, { "code": "<?php// PHP program to find maximum value of// number obtained by using array// elements by using dynamic programming. // Function to find maximum possible// value of number that can be// obtained using array elements.function findMaxVal($arr, $n, $num, $maxLimit){ // Variable to represent // current index. $ind; // Variable to show value between // 0 and maxLimit. $val; // Table to store whether a value can // be obtained or not upto a certain index. // 1. dp[i][j] = 1 if value j can be // obtained upto index i. // 2. dp[i][j] = 0 if value j cannot be // obtained upto index i. $dp[$n][$maxLimit + 1] = array(); for($ind = 0; $ind < $n; $ind++) { for($val = 0; $val <= $maxLimit; $val++) { // Check for index 0 if given value // val can be obtained by either adding // to or subtracting arr[0] from num. if($ind == 0) { if($num - $arr[$ind] == $val || $num + $arr[$ind] == $val) { $dp[$ind][$val] = 1; } else { $dp[$ind][$val] = 0; } } else { // 1. If arr[ind] is added to // obtain given val then val- // arr[ind] should be obtainable // from index ind-1. // 2. If arr[ind] is subtracted to // obtain given val then val+arr[ind] // should be obtainable from index ind-1. // Check for both the conditions. if($val - $arr[$ind] >= 0 && $val + $arr[$ind] <= $maxLimit) { // If either of one condition is true, // then val is obtainable at index ind. $dp[$ind][$val] = $dp[$ind - 1][$val - $arr[$ind]] || $dp[$ind - 1][$val + $arr[$ind]]; } else if($val - $arr[$ind] >= 0) { $dp[$ind][$val] = $dp[$ind - 1][$val - $arr[$ind]]; } else if($val + $arr[$ind] <= $maxLimit) { $dp[$ind][$val] = $dp[$ind - 1][$val + $arr[$ind]]; } else { $dp[$ind][$val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for($val = $maxLimit; $val >= 0; $val--) { if($dp[$n - 1][$val]) { return $val; } } // If no solution exists return -1. return -1;} // Driver Code$num = 1;$arr = array(3, 10, 6, 4, 5);$n = sizeof($arr);$maxLimit = 15; echo findMaxVal($arr, $n, $num, $maxLimit); // This code is contributed by ajit.?>", "e": 54421, "s": 51472, "text": null }, { "code": "<script> // Javascript program to find maximum value of// number obtained by using array// elements by using dynamic programming. // Function to find maximum possible// value of number that can be// obtained using array elements.function findMaxVal(arr, n, num, maxLimit){ // Variable to represent current index. var ind; // Variable to show value between // 0 and maxLimit. var val; // Table to store whether a value can // be obtained or not upto a certain index. // 1. dp[i][j] = 1 if value j can be // obtained upto index i. // 2. dp[i][j] = 0 if value j cannot be // obtained upto index i. var dp = Array.from( Array(n), () => Array(maxLimit+1)); for(ind = 0; ind < n; ind++) { for(val = 0; val <= maxLimit; val++) { // Check for index 0 if given value // val can be obtained by either adding // to or subtracting arr[0] from num. if(ind == 0) { if(num - arr[ind] == val || num + arr[ind] == val) { dp[ind][val] = 1; } else { dp[ind][val] = 0; } } else { // 1. If arr[ind] is added to // obtain given val then val- // arr[ind] should be obtainable // from index ind-1. // 2. If arr[ind] is subtracted to // obtain given val then val+arr[ind] // should be obtainable from index ind-1. // Check for both the conditions. if(val - arr[ind] >= 0 && val + arr[ind] <= maxLimit) { // If either of one condition is true, // then val is obtainable at index ind. dp[ind][val] = dp[ind-1][val-arr[ind]] || dp[ind-1][val+arr[ind]]; } else if(val - arr[ind] >= 0) { dp[ind][val] = dp[ind-1][val-arr[ind]]; } else if(val + arr[ind] <= maxLimit) { dp[ind][val] = dp[ind-1][val+arr[ind]]; } else { dp[ind][val] = 0; } } } } // Find maximum value that is obtained // at index n-1. for(val = maxLimit; val >= 0; val--) { if(dp[n-1][val]) { return val; } } // If no solution exists return -1. return -1;} // Driver Codevar num = 1;var arr = [3, 10, 6, 4, 5];var n = arr.length;var maxLimit = 15; document.write( findMaxVal(arr, n, num, maxLimit)); // This code is contributed by rutvik_56.</script>", "e": 57280, "s": 54421, "text": null }, { "code": null, "e": 57282, "s": 57280, "text": "9" }, { "code": null, "e": 57760, "s": 57284, "text": "Time Complexity : O(n*maxLimit), where n is the size of array and maxLimit is the given max value. Auxiliary Space : O(n*maxLimit), n is the size of array and maxLimit is the given max value.Optimization : The space required can be reduced to O(2*maxLimit). Note that at every index position, we are only using values from previous row. So we can create a table with two rows, in which one of the rows store result for previous iteration and other for the current iteration. " }, { "code": null, "e": 57772, "s": 57760, "text": "manishshaw1" }, { "code": null, "e": 57778, "s": 57772, "text": "jit_t" }, { "code": null, "e": 57790, "s": 57778, "text": "29AjayKumar" }, { "code": null, "e": 57800, "s": 57790, "text": "rutvik_56" }, { "code": null, "e": 57809, "s": 57800, "text": "mukesh07" }, { "code": null, "e": 57819, "s": 57809, "text": "cpp-array" }, { "code": null, "e": 57826, "s": 57819, "text": "Arrays" }, { "code": null, "e": 57846, "s": 57826, "text": "Dynamic Programming" }, { "code": null, "e": 57856, "s": 57846, "text": "Recursion" }, { "code": null, "e": 57863, "s": 57856, "text": "Arrays" }, { "code": null, "e": 57883, "s": 57863, "text": "Dynamic Programming" }, { "code": null, "e": 57893, "s": 57883, "text": "Recursion" }, { "code": null, "e": 57991, "s": 57893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 58000, "s": 57991, "text": "Comments" }, { "code": null, "e": 58013, "s": 58000, "text": "Old Comments" }, { "code": null, "e": 58036, "s": 58013, "text": "Introduction to Arrays" }, { "code": null, "e": 58050, "s": 58036, "text": "Linear Search" }, { "code": null, "e": 58082, "s": 58050, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 58150, "s": 58082, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 58195, "s": 58150, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 58224, "s": 58195, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 58254, "s": 58224, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 58288, "s": 58254, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 58319, "s": 58288, "text": "Bellman–Ford Algorithm | DP-23" } ]
C# Strings
Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes: Create a variable of type string and assign it a value: string greeting = "Hello"; Run example » A string in C# is actually an object, which contain properties and methods that can perform certain operations on strings. For example, the length of a string can be found with the Length property: string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Console.WriteLine("The length of the txt string is: " + txt.Length); Run example » There are many string methods available, for example ToUpper() and ToLower(), which returns a copy of the string converted to uppercase or lowercase: string txt = "Hello World"; Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD" Console.WriteLine(txt.ToLower()); // Outputs "hello world" Run example » The + operator can be used between strings to combine them. This is called concatenation: string firstName = "John "; string lastName = "Doe"; string name = firstName + lastName; Console.WriteLine(name); Run example » Note that we have added a space after "John" to create a space between firstName and lastName on print. You can also use the string.Concat() method to concatenate two strings: string firstName = "John "; string lastName = "Doe"; string name = string.Concat(firstName, lastName); Console.WriteLine(name); Run example » Another option of string concatenation, is string interpolation, which substitutes values of variables into placeholders in a string. Note that you do not have to worry about spaces, like with concatenation: string firstName = "John"; string lastName = "Doe"; string name = $"My full name is: {firstName} {lastName}"; Console.WriteLine(name); Run example » Also note that you have to use the dollar sign ($) when using the string interpolation method. String interpolation was introduced in C# version 6. You can access the characters in a string by referring to its index number inside square brackets []. This example prints the first character in myString: string myString = "Hello"; Console.WriteLine(myString[0]); // Outputs "H" Run example » Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc. This example prints the second character (1) in myString: string myString = "Hello"; Console.WriteLine(myString[1]); // Outputs "e" Run example » You can also find the index position of a specific character in a string, by using the IndexOf() method: string myString = "Hello"; Console.WriteLine(myString.IndexOf("e")); // Outputs "1" Run example » Another useful method is Substring(), which extracts the characters from a string, starting from the specified character position/index, and returns a new string. This method is often used together with IndexOf() to get the specific character position: // Full name string name = "John Doe"; // Location of the letter D int charPos = name.IndexOf("D"); // Get last name string lastName = name.Substring(charPos); // Print the result Console.WriteLine(lastName); Run example » Because strings must be written within quotes, C# will misunderstand this string, and generate an error: string txt = "We are the so-called "Vikings" from the north."; The solution to avoid this problem, is to use the backslash escape character. The backslash (\) escape character turns special characters into string characters: The sequence \" inserts a double quote in a string: string txt = "We are the so-called \"Vikings\" from the north."; Try it Yourself » The sequence \' inserts a single quote in a string: string txt = "It\'s alright."; Try it Yourself » The sequence \\ inserts a single backslash in a string: string txt = "The character \\ is called backslash."; Try it Yourself » Other useful escape characters in C# are: WARNING! C# uses the + operator for both addition and concatenation. Remember: Numbers are added. Strings are concatenated. If you add two numbers, the result will be a number: int x = 10; int y = 20; int z = x + y; // z will be 30 (an integer/number) Run example » If you add two strings, the result will be a string concatenation: string x = "10"; string y = "20"; string z = x + y; // z will be 1020 (a string) Run example » Fill in the missing part to create a greeting variable of type string and assign it the value Hello. = ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 35, "s": 0, "text": "Strings are used for storing text." }, { "code": null, "e": 118, "s": 35, "text": "A string variable contains a collection of characters surrounded by double quotes:" }, { "code": null, "e": 174, "s": 118, "text": "Create a variable of type string and assign it a value:" }, { "code": null, "e": 202, "s": 174, "text": "string greeting = \"Hello\";\n" }, { "code": null, "e": 218, "s": 202, "text": "\nRun example »\n" }, { "code": null, "e": 416, "s": 218, "text": "A string in C# is actually an object, which contain properties and methods that can perform certain operations on strings. For example, the length of a string can be found with the Length property:" }, { "code": null, "e": 529, "s": 416, "text": "string txt = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nConsole.WriteLine(\"The length of the txt string is: \" + txt.Length);\n" }, { "code": null, "e": 545, "s": 529, "text": "\nRun example »\n" }, { "code": null, "e": 695, "s": 545, "text": "There are many string methods available, for example ToUpper() and ToLower(), which returns a copy of the string converted to uppercase or lowercase:" }, { "code": null, "e": 846, "s": 695, "text": "string txt = \"Hello World\";\nConsole.WriteLine(txt.ToUpper()); // Outputs \"HELLO WORLD\"\nConsole.WriteLine(txt.ToLower()); // Outputs \"hello world\"\n" }, { "code": null, "e": 862, "s": 846, "text": "\nRun example »\n" }, { "code": null, "e": 952, "s": 862, "text": "The + operator can be used between strings to combine them. This is called concatenation:" }, { "code": null, "e": 1067, "s": 952, "text": "string firstName = \"John \";\nstring lastName = \"Doe\";\nstring name = firstName + lastName;\nConsole.WriteLine(name);\n" }, { "code": null, "e": 1083, "s": 1067, "text": "\nRun example »\n" }, { "code": null, "e": 1187, "s": 1083, "text": "Note that we have added a space after \"John\" to create a space between firstName and lastName on print." }, { "code": null, "e": 1259, "s": 1187, "text": "You can also use the string.Concat() method to concatenate two strings:" }, { "code": null, "e": 1388, "s": 1259, "text": "string firstName = \"John \";\nstring lastName = \"Doe\";\nstring name = string.Concat(firstName, lastName);\nConsole.WriteLine(name);\n" }, { "code": null, "e": 1404, "s": 1388, "text": "\nRun example »\n" }, { "code": null, "e": 1614, "s": 1404, "text": "Another option of string concatenation, is string interpolation, \nwhich substitutes values of variables into placeholders in a string. Note that \nyou do not have to worry about spaces, like with concatenation:" }, { "code": null, "e": 1750, "s": 1614, "text": "string firstName = \"John\";\nstring lastName = \"Doe\";\nstring name = $\"My full name is: {firstName} {lastName}\";\nConsole.WriteLine(name);\n" }, { "code": null, "e": 1766, "s": 1750, "text": "\nRun example »\n" }, { "code": null, "e": 1861, "s": 1766, "text": "Also note that you have to use the dollar sign ($) when using the string interpolation method." }, { "code": null, "e": 1914, "s": 1861, "text": "String interpolation was introduced in C# version 6." }, { "code": null, "e": 2017, "s": 1914, "text": "You can access the characters in a string by referring to its index number \ninside square brackets []." }, { "code": null, "e": 2071, "s": 2017, "text": "This example prints the first character in \nmyString:" }, { "code": null, "e": 2147, "s": 2071, "text": "string myString = \"Hello\";\nConsole.WriteLine(myString[0]); // Outputs \"H\"\n" }, { "code": null, "e": 2163, "s": 2147, "text": "\nRun example »\n" }, { "code": null, "e": 2261, "s": 2163, "text": "Note: String indexes start with 0: [0] is the first character. [1] is the second \ncharacter, etc." }, { "code": null, "e": 2320, "s": 2261, "text": "This example prints the second character (1) in \nmyString:" }, { "code": null, "e": 2396, "s": 2320, "text": "string myString = \"Hello\";\nConsole.WriteLine(myString[1]); // Outputs \"e\"\n" }, { "code": null, "e": 2412, "s": 2396, "text": "\nRun example »\n" }, { "code": null, "e": 2517, "s": 2412, "text": "You can also find the index position of a specific character in a string, by using the IndexOf() method:" }, { "code": null, "e": 2603, "s": 2517, "text": "string myString = \"Hello\";\nConsole.WriteLine(myString.IndexOf(\"e\")); // Outputs \"1\"\n" }, { "code": null, "e": 2619, "s": 2603, "text": "\nRun example »\n" }, { "code": null, "e": 2873, "s": 2619, "text": "Another useful method is Substring(), which extracts the characters from a string, \nstarting from the specified character position/index, and returns a new string. This method is often used together with IndexOf() to get the specific character position:" }, { "code": null, "e": 3086, "s": 2873, "text": "// Full name\nstring name = \"John Doe\";\n\n// Location of the letter D\nint charPos = name.IndexOf(\"D\");\n\n// Get last name\nstring lastName = name.Substring(charPos);\n\n// Print the result\nConsole.WriteLine(lastName);\n" }, { "code": null, "e": 3102, "s": 3086, "text": "\nRun example »\n" }, { "code": null, "e": 3208, "s": 3102, "text": "Because strings must be written within quotes, C# will misunderstand this string, \nand generate an error:" }, { "code": null, "e": 3272, "s": 3208, "text": "string txt = \"We are the so-called \"Vikings\" from the north.\";\n" }, { "code": null, "e": 3350, "s": 3272, "text": "The solution to avoid this problem, is to use the backslash escape character." }, { "code": null, "e": 3434, "s": 3350, "text": "The backslash (\\) escape character turns special characters into string characters:" }, { "code": null, "e": 3487, "s": 3434, "text": "The sequence \\\" inserts a double quote in a string:" }, { "code": null, "e": 3555, "s": 3489, "text": "string txt = \"We are the so-called \\\"Vikings\\\" from the north.\";\n" }, { "code": null, "e": 3575, "s": 3555, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3628, "s": 3575, "text": "The sequence \\' inserts a single quote in a string:" }, { "code": null, "e": 3662, "s": 3630, "text": "string txt = \"It\\'s alright.\";\n" }, { "code": null, "e": 3682, "s": 3662, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3739, "s": 3682, "text": "The sequence \\\\ inserts a single backslash in a string:" }, { "code": null, "e": 3796, "s": 3741, "text": "string txt = \"The character \\\\ is called backslash.\";\n" }, { "code": null, "e": 3816, "s": 3796, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3858, "s": 3816, "text": "Other useful escape characters in C# are:" }, { "code": null, "e": 3867, "s": 3858, "text": "WARNING!" }, { "code": null, "e": 3927, "s": 3867, "text": "C# uses the + operator for both addition and concatenation." }, { "code": null, "e": 3982, "s": 3927, "text": "Remember: Numbers are added. Strings are concatenated." }, { "code": null, "e": 4035, "s": 3982, "text": "If you add two numbers, the result will be a number:" }, { "code": null, "e": 4112, "s": 4035, "text": "int x = 10;\nint y = 20;\nint z = x + y; // z will be 30 (an integer/number)\n" }, { "code": null, "e": 4128, "s": 4112, "text": "\nRun example »\n" }, { "code": null, "e": 4195, "s": 4128, "text": "If you add two strings, the result will be a string concatenation:" }, { "code": null, "e": 4278, "s": 4195, "text": "string x = \"10\";\nstring y = \"20\";\nstring z = x + y; // z will be 1020 (a string)\n" }, { "code": null, "e": 4294, "s": 4278, "text": "\nRun example »\n" }, { "code": null, "e": 4395, "s": 4294, "text": "Fill in the missing part to create a greeting variable of type string and assign it the value Hello." }, { "code": null, "e": 4402, "s": 4395, "text": " = ;\n" }, { "code": null, "e": 4421, "s": 4402, "text": "Start the Exercise" }, { "code": null, "e": 4454, "s": 4421, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 4496, "s": 4454, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 4603, "s": 4496, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4622, "s": 4603, "text": "help@w3schools.com" } ]
COVID-19 Outbreak Prediction using Machine Learning Algorithm | by Wie Kiang H. | Towards Data Science
Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional health advice. However, this article will be focus on how machine learning can be used to predict the spread of the pandemic. Our society is in the era of unbelievable attempts to struggle upon the spread of this life-threatening condition in terms of infrastructure, finance, business, manufacturing, and several other resources. Artificial Intelligence (AI) researchers strengthen their proficiency in developing mathematical paradigms for investigating this pandemic using nationwide distributed data. This article intends to apply the machine learning models simultaneously with the forecast of expected reachability of the COVID-19 over the nations by using the real-time data from the Johns Hopkins dashboard. Coronavirus spreads are categorized into four stages. The first stage starts with the cases recorded for the people who traveled to or from affected countries or cities, whereas in the second stage, cases are reported regionally among family, friends, and groups who came into contact with the person coming from the affected countries. Therefore, the affected people are identifiable. Next, the third stage causes the circumstance severely as the infected person becomes undetectable and flattens across the individuals who neither have any travel records nor came in connection with the affected person. This condition obliges immediate lockdown across the nation to reduce the social contacts between individuals to measure the movement of the virus. Finally, stage four starts when the transmission converts to endemic and uncontrollable. China is the first country that felt under stage four of the COVID-19 transmission, while most of the developed countries are now in this stage of the transmission and bearing a further number of epidemics and losses compared to China. Machine learning algorithms play an essential role in the pandemic investigation and forecasting. Furthermore, machine learning techniques help to expose the epidemic patterns. As a result, an immediate response might be prepared to prevent the spread of the virus (Kalipe, Gautham & Behera, 20181; Singh, Singh & Bhatia, 20182). Moreover, machine learning models are utilized to recognize collective behavior together with the prediction of the expected spread of the COVID-19 across the society by employing the real-time data from the Johns Hopkins dashboard. The dataset retrieved from the official repository of Johns Hopkins University3. This data consists of daily case reports and daily time series summary tables. In the study, we have selected time-series summary tables in CSV format having three tables for confirmed, death, and recovered cases of COVID-19 with six properties. For example, province/state, country/region, last update, confirmed, death, and recovered cases. The CSV data are available in Github4 repositories. Coronavirus spread has conducted the society under the edge of loss in social lives. Additionally, it is crucial to investigate the transmission growth ahead and predict the future occurrences of the transmission. In concurrent, state-of-the-art mathematical models are chosen based on machine learning for a computational process to predict the spread of the virus, for instance: Support Vector Regression5 (SVR) Polynomial Regression6 (PR) Deep Learning regression models It is also involving: Artificial Neural Network7 (ANN) Recurrent Neural Networks8 (RNN) using Long Short-Term Memory9 (LSTM) cells. Machine learning and deep learning strategies are performed using the python library to predict the total number of confirmed, recovered, and death cases extensively. This prediction will allow undertaking specific determinations based on transmission growth, such as expanding the lockdown phase, performing the sanitation plan, and providing daily support and supplies. Regression analysis is a section of machine learning algorithms. It is the leading machine learning algorithm. Think of straight equation line combining any two variables X and Y, which can be declared algebraically as: Where b is declared the intercept on the y-axis, and a is called the slope of the line. Here, a and b are also called the parameters of regression analysis. These parameters should learn throughout proper learning methods. Regression analysis contains a set of machine learning methods that enable us to predict a continuous result variable (Y) based on the value of one or multiple predictor variables (X). It pretends a continuing connection between the result and the predictor variables. The correlation coefficient interpreted as the strength of a linear relationship between two variables. Karl Pearson emphasizes that the coefficient of correlation is a weight or degree of the linear correlation between two variables. He also has been generated a formula known as Correlation Coefficient. The correlation coefficient between two random variables X and Y, generally indicated by a numerical measure of the linear dependence between those variables and is defined as: Where, i = 1, 2, 3, 4, ...N, is the collection of input and output variables. Some prediction is given below: If the value of the correlation coefficient is equal to zero, it indicates no correlation between input variables X and output variable Y.If the value of the correlation coefficient is equal to positive one, it indicates there is a strong relationship between the input variable and the output variable. In other words, if the input variable is increased then the output variable is also increased.If the value of the correlation coefficient is equal to negative, it indicates the input variable is increased then the output variable is also decreased and so on. If the value of the correlation coefficient is equal to zero, it indicates no correlation between input variables X and output variable Y. If the value of the correlation coefficient is equal to positive one, it indicates there is a strong relationship between the input variable and the output variable. In other words, if the input variable is increased then the output variable is also increased. If the value of the correlation coefficient is equal to negative, it indicates the input variable is increased then the output variable is also decreased and so on. Those variables that have a small or no linear correlation might have a strong nonlinear relationship. On the other hand, estimating linear correlation before fitting a model is a valuable way to recognize variables with a simple relationship. In this proposed study, we have measured the correlation coefficient between date and number of confirmed cases of COVID-2019 spread nationwide. Our environment is under the control of the COVID-19 virus. This article intended to employ the machine learning models for pandemic analysis through a dataset from Johns Hopkins. In conclusion, the method of Polynomial Regression (PR) generated a minimum Root Mean Square Error (RMSE) amount over other methods in projecting the COVID-19 transmission. However, if the spread mimics the prognosticated trend of the PR model, then it would lead to extensive loss of lives as it presents the incredible growth of the transmission globally. As perceived in China, the increased case of COVID-19 can be degraded by lessening the number of sensitive individuals from infected people. This new normal is obtainable by becoming unsocial and supporting the lockdown regulation with control. References#1 Predicting Malarial Outbreak using Machine Learning and Deep Learning Approach: A Review and Analysis#2 Sentiment analysis using machine learning techniques to predict outbreaks and epidemics#3 Johns Hopkins University#4 Johns Hopkins University: COVID-19 Data Repository#5 Support Vector Regression#6 Polynomial Regression#7 Artificial Neural Network#8 Recurrent Neural Networks#9 Long Short-Term MemoryDisclaimerThis is for education and information purposes only, additional research in the machine learning algorithm needed to give the exact amount of prediction data from the real-time dataset. The source code of the experiment can be access here on GitHub.
[ { "code": null, "e": 560, "s": 172, "text": "Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional health advice. However, this article will be focus on how machine learning can be used to predict the spread of the pandemic." }, { "code": null, "e": 1150, "s": 560, "text": "Our society is in the era of unbelievable attempts to struggle upon the spread of this life-threatening condition in terms of infrastructure, finance, business, manufacturing, and several other resources. Artificial Intelligence (AI) researchers strengthen their proficiency in developing mathematical paradigms for investigating this pandemic using nationwide distributed data. This article intends to apply the machine learning models simultaneously with the forecast of expected reachability of the COVID-19 over the nations by using the real-time data from the Johns Hopkins dashboard." }, { "code": null, "e": 2229, "s": 1150, "text": "Coronavirus spreads are categorized into four stages. The first stage starts with the cases recorded for the people who traveled to or from affected countries or cities, whereas in the second stage, cases are reported regionally among family, friends, and groups who came into contact with the person coming from the affected countries. Therefore, the affected people are identifiable. Next, the third stage causes the circumstance severely as the infected person becomes undetectable and flattens across the individuals who neither have any travel records nor came in connection with the affected person. This condition obliges immediate lockdown across the nation to reduce the social contacts between individuals to measure the movement of the virus. Finally, stage four starts when the transmission converts to endemic and uncontrollable. China is the first country that felt under stage four of the COVID-19 transmission, while most of the developed countries are now in this stage of the transmission and bearing a further number of epidemics and losses compared to China." }, { "code": null, "e": 2792, "s": 2229, "text": "Machine learning algorithms play an essential role in the pandemic investigation and forecasting. Furthermore, machine learning techniques help to expose the epidemic patterns. As a result, an immediate response might be prepared to prevent the spread of the virus (Kalipe, Gautham & Behera, 20181; Singh, Singh & Bhatia, 20182). Moreover, machine learning models are utilized to recognize collective behavior together with the prediction of the expected spread of the COVID-19 across the society by employing the real-time data from the Johns Hopkins dashboard." }, { "code": null, "e": 3268, "s": 2792, "text": "The dataset retrieved from the official repository of Johns Hopkins University3. This data consists of daily case reports and daily time series summary tables. In the study, we have selected time-series summary tables in CSV format having three tables for confirmed, death, and recovered cases of COVID-19 with six properties. For example, province/state, country/region, last update, confirmed, death, and recovered cases. The CSV data are available in Github4 repositories." }, { "code": null, "e": 3649, "s": 3268, "text": "Coronavirus spread has conducted the society under the edge of loss in social lives. Additionally, it is crucial to investigate the transmission growth ahead and predict the future occurrences of the transmission. In concurrent, state-of-the-art mathematical models are chosen based on machine learning for a computational process to predict the spread of the virus, for instance:" }, { "code": null, "e": 3682, "s": 3649, "text": "Support Vector Regression5 (SVR)" }, { "code": null, "e": 3710, "s": 3682, "text": "Polynomial Regression6 (PR)" }, { "code": null, "e": 3742, "s": 3710, "text": "Deep Learning regression models" }, { "code": null, "e": 3764, "s": 3742, "text": "It is also involving:" }, { "code": null, "e": 3797, "s": 3764, "text": "Artificial Neural Network7 (ANN)" }, { "code": null, "e": 3874, "s": 3797, "text": "Recurrent Neural Networks8 (RNN) using Long Short-Term Memory9 (LSTM) cells." }, { "code": null, "e": 4246, "s": 3874, "text": "Machine learning and deep learning strategies are performed using the python library to predict the total number of confirmed, recovered, and death cases extensively. This prediction will allow undertaking specific determinations based on transmission growth, such as expanding the lockdown phase, performing the sanitation plan, and providing daily support and supplies." }, { "code": null, "e": 4466, "s": 4246, "text": "Regression analysis is a section of machine learning algorithms. It is the leading machine learning algorithm. Think of straight equation line combining any two variables X and Y, which can be declared algebraically as:" }, { "code": null, "e": 4689, "s": 4466, "text": "Where b is declared the intercept on the y-axis, and a is called the slope of the line. Here, a and b are also called the parameters of regression analysis. These parameters should learn throughout proper learning methods." }, { "code": null, "e": 4958, "s": 4689, "text": "Regression analysis contains a set of machine learning methods that enable us to predict a continuous result variable (Y) based on the value of one or multiple predictor variables (X). It pretends a continuing connection between the result and the predictor variables." }, { "code": null, "e": 5441, "s": 4958, "text": "The correlation coefficient interpreted as the strength of a linear relationship between two variables. Karl Pearson emphasizes that the coefficient of correlation is a weight or degree of the linear correlation between two variables. He also has been generated a formula known as Correlation Coefficient. The correlation coefficient between two random variables X and Y, generally indicated by a numerical measure of the linear dependence between those variables and is defined as:" }, { "code": null, "e": 5551, "s": 5441, "text": "Where, i = 1, 2, 3, 4, ...N, is the collection of input and output variables. Some prediction is given below:" }, { "code": null, "e": 6114, "s": 5551, "text": "If the value of the correlation coefficient is equal to zero, it indicates no correlation between input variables X and output variable Y.If the value of the correlation coefficient is equal to positive one, it indicates there is a strong relationship between the input variable and the output variable. In other words, if the input variable is increased then the output variable is also increased.If the value of the correlation coefficient is equal to negative, it indicates the input variable is increased then the output variable is also decreased and so on." }, { "code": null, "e": 6253, "s": 6114, "text": "If the value of the correlation coefficient is equal to zero, it indicates no correlation between input variables X and output variable Y." }, { "code": null, "e": 6514, "s": 6253, "text": "If the value of the correlation coefficient is equal to positive one, it indicates there is a strong relationship between the input variable and the output variable. In other words, if the input variable is increased then the output variable is also increased." }, { "code": null, "e": 6679, "s": 6514, "text": "If the value of the correlation coefficient is equal to negative, it indicates the input variable is increased then the output variable is also decreased and so on." }, { "code": null, "e": 7068, "s": 6679, "text": "Those variables that have a small or no linear correlation might have a strong nonlinear relationship. On the other hand, estimating linear correlation before fitting a model is a valuable way to recognize variables with a simple relationship. In this proposed study, we have measured the correlation coefficient between date and number of confirmed cases of COVID-2019 spread nationwide." }, { "code": null, "e": 7851, "s": 7068, "text": "Our environment is under the control of the COVID-19 virus. This article intended to employ the machine learning models for pandemic analysis through a dataset from Johns Hopkins. In conclusion, the method of Polynomial Regression (PR) generated a minimum Root Mean Square Error (RMSE) amount over other methods in projecting the COVID-19 transmission. However, if the spread mimics the prognosticated trend of the PR model, then it would lead to extensive loss of lives as it presents the incredible growth of the transmission globally. As perceived in China, the increased case of COVID-19 can be degraded by lessening the number of sensitive individuals from infected people. This new normal is obtainable by becoming unsocial and supporting the lockdown regulation with control." } ]
Display a percentage in Java
To display a percentage in Java, use the following DecimalFormat. DecimalFormat decFormat = new DecimalFormat("#%"); Since, we have used the DecimalFormat class, therefore do not forget to import the following package − import java.text.DecimalFormat; Now, let us learn how to display percentage − decFormat.format(0.80) decFormat.format(-0.19) decFormat.format(1.88) The above will be displayed as − 80% -19% 188% The following is the complete example − Live Demo import java.text.DecimalFormat; public class Demo { public static void main(String[] argv) throws Exception { DecimalFormat decFormat = new DecimalFormat("#%"); System.out.println(decFormat.format(0.80)); System.out.println(decFormat.format(-0.19)); System.out.println(decFormat.format(1.88)); System.out.println(decFormat.format(0.9099)); System.out.println(decFormat.format(12.788)); System.out.println(decFormat.format(-9.678)); } } 80% -19% 188% 91% 1279% -968%
[ { "code": null, "e": 1128, "s": 1062, "text": "To display a percentage in Java, use the following DecimalFormat." }, { "code": null, "e": 1179, "s": 1128, "text": "DecimalFormat decFormat = new DecimalFormat(\"#%\");" }, { "code": null, "e": 1282, "s": 1179, "text": "Since, we have used the DecimalFormat class, therefore do not forget to import the following package −" }, { "code": null, "e": 1314, "s": 1282, "text": "import java.text.DecimalFormat;" }, { "code": null, "e": 1360, "s": 1314, "text": "Now, let us learn how to display percentage −" }, { "code": null, "e": 1430, "s": 1360, "text": "decFormat.format(0.80)\ndecFormat.format(-0.19)\ndecFormat.format(1.88)" }, { "code": null, "e": 1463, "s": 1430, "text": "The above will be displayed as −" }, { "code": null, "e": 1477, "s": 1463, "text": "80%\n-19%\n188%" }, { "code": null, "e": 1517, "s": 1477, "text": "The following is the complete example −" }, { "code": null, "e": 1528, "s": 1517, "text": " Live Demo" }, { "code": null, "e": 2012, "s": 1528, "text": "import java.text.DecimalFormat;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n DecimalFormat decFormat = new DecimalFormat(\"#%\");\n System.out.println(decFormat.format(0.80));\n System.out.println(decFormat.format(-0.19));\n System.out.println(decFormat.format(1.88));\n System.out.println(decFormat.format(0.9099));\n System.out.println(decFormat.format(12.788));\n System.out.println(decFormat.format(-9.678));\n }\n}" }, { "code": null, "e": 2042, "s": 2012, "text": "80%\n-19%\n188%\n91%\n1279%\n-968%" } ]
How to create a Ripple Effect on Click the Button ? - GeeksforGeeks
24 Apr, 2020 Ripple effect is a part of the modern design trend. You have seen it on many websites specially on Google’s material design language. It gives a button pressing effect. We can make a ripple effect by adding and animating a child element to the button. We can also position it according to the position of the cursor on the button using Javascript. Basic styling: Add basic styling to the button with a position:relative attribute to position the inner span tag and overflow:hidden to prevent span going outside of button.<!DOCTYPE html><html> <head> <title> Button Ripple Effect - GFG </title> <style> /* Adding styles to button */ .btn { padding: 12px 50px; border: none; border-radius: 5px; background-color: #1abc9c; color: #fff; font-size: 18px; outline: none; cursor: pointer; /* We need this to position span inside button */ position: relative; overflow: hidden; box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2); } </style></head> <body> <button class="btn"> Enter GeeksforGeeks </button></body> </html>Output:Add styling to the span element: Now adding the style for the span element that will show up on the click of a button.<style> .btn span { position: absolute; border-radius: 50%; /* To make it round */ background-color: rgba(0, 0, 0, 0.3); width: 100px; height: 100px; margin-top: -50px; /* for positioning */ margin-left: -50px; animation: ripple 1s; opacity: 0; } /* Add animation */ @keyframes ripple { from { opacity: 1; transform: scale(0); } to { opacity: 0; transform: scale(10); } }</style>Adding JavaScript: Now we’ll add the span element on button click with position according to the mouse click. On button click we have to do the following:Create span element and add ripple class to it.Get the clicked position of cursor using event variable.Set the position of the span element.Remove the span element to avoid spamming of span elements in button.<script> const btn = document.querySelector(".btn"); // Listen for click event btn.onclick = function (e) { // Create span element let ripple = document.createElement("span"); // Add ripple class to span ripple.classList.add("ripple"); // Add span to the button this.appendChild(ripple); // Get position of X let x = e.clientX - e.target.offsetLeft; // Get position of Y let y = e.clientY - e.target.offsetTop; // Position the span element ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; // Remove span after 0.3s setTimeout(() => { ripple.remove(); }, 300); };</script> Basic styling: Add basic styling to the button with a position:relative attribute to position the inner span tag and overflow:hidden to prevent span going outside of button.<!DOCTYPE html><html> <head> <title> Button Ripple Effect - GFG </title> <style> /* Adding styles to button */ .btn { padding: 12px 50px; border: none; border-radius: 5px; background-color: #1abc9c; color: #fff; font-size: 18px; outline: none; cursor: pointer; /* We need this to position span inside button */ position: relative; overflow: hidden; box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2); } </style></head> <body> <button class="btn"> Enter GeeksforGeeks </button></body> </html>Output: <!DOCTYPE html><html> <head> <title> Button Ripple Effect - GFG </title> <style> /* Adding styles to button */ .btn { padding: 12px 50px; border: none; border-radius: 5px; background-color: #1abc9c; color: #fff; font-size: 18px; outline: none; cursor: pointer; /* We need this to position span inside button */ position: relative; overflow: hidden; box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2); } </style></head> <body> <button class="btn"> Enter GeeksforGeeks </button></body> </html> Output: Add styling to the span element: Now adding the style for the span element that will show up on the click of a button.<style> .btn span { position: absolute; border-radius: 50%; /* To make it round */ background-color: rgba(0, 0, 0, 0.3); width: 100px; height: 100px; margin-top: -50px; /* for positioning */ margin-left: -50px; animation: ripple 1s; opacity: 0; } /* Add animation */ @keyframes ripple { from { opacity: 1; transform: scale(0); } to { opacity: 0; transform: scale(10); } }</style> <style> .btn span { position: absolute; border-radius: 50%; /* To make it round */ background-color: rgba(0, 0, 0, 0.3); width: 100px; height: 100px; margin-top: -50px; /* for positioning */ margin-left: -50px; animation: ripple 1s; opacity: 0; } /* Add animation */ @keyframes ripple { from { opacity: 1; transform: scale(0); } to { opacity: 0; transform: scale(10); } }</style> Adding JavaScript: Now we’ll add the span element on button click with position according to the mouse click. On button click we have to do the following:Create span element and add ripple class to it.Get the clicked position of cursor using event variable.Set the position of the span element.Remove the span element to avoid spamming of span elements in button.<script> const btn = document.querySelector(".btn"); // Listen for click event btn.onclick = function (e) { // Create span element let ripple = document.createElement("span"); // Add ripple class to span ripple.classList.add("ripple"); // Add span to the button this.appendChild(ripple); // Get position of X let x = e.clientX - e.target.offsetLeft; // Get position of Y let y = e.clientY - e.target.offsetTop; // Position the span element ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; // Remove span after 0.3s setTimeout(() => { ripple.remove(); }, 300); };</script> Create span element and add ripple class to it.Get the clicked position of cursor using event variable.Set the position of the span element.Remove the span element to avoid spamming of span elements in button. Create span element and add ripple class to it. Get the clicked position of cursor using event variable. Set the position of the span element. Remove the span element to avoid spamming of span elements in button. <script> const btn = document.querySelector(".btn"); // Listen for click event btn.onclick = function (e) { // Create span element let ripple = document.createElement("span"); // Add ripple class to span ripple.classList.add("ripple"); // Add span to the button this.appendChild(ripple); // Get position of X let x = e.clientX - e.target.offsetLeft; // Get position of Y let y = e.clientY - e.target.offsetTop; // Position the span element ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; // Remove span after 0.3s setTimeout(() => { ripple.remove(); }, 300); };</script> The final output will be look something like below: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? CSS | :not(:last-child):after Selector How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24879, "s": 24851, "text": "\n24 Apr, 2020" }, { "code": null, "e": 25227, "s": 24879, "text": "Ripple effect is a part of the modern design trend. You have seen it on many websites specially on Google’s material design language. It gives a button pressing effect. We can make a ripple effect by adding and animating a child element to the button. We can also position it according to the position of the cursor on the button using Javascript." }, { "code": null, "e": 27895, "s": 25227, "text": "Basic styling: Add basic styling to the button with a position:relative attribute to position the inner span tag and overflow:hidden to prevent span going outside of button.<!DOCTYPE html><html> <head> <title> Button Ripple Effect - GFG </title> <style> /* Adding styles to button */ .btn { padding: 12px 50px; border: none; border-radius: 5px; background-color: #1abc9c; color: #fff; font-size: 18px; outline: none; cursor: pointer; /* We need this to position span inside button */ position: relative; overflow: hidden; box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2); } </style></head> <body> <button class=\"btn\"> Enter GeeksforGeeks </button></body> </html>Output:Add styling to the span element: Now adding the style for the span element that will show up on the click of a button.<style> .btn span { position: absolute; border-radius: 50%; /* To make it round */ background-color: rgba(0, 0, 0, 0.3); width: 100px; height: 100px; margin-top: -50px; /* for positioning */ margin-left: -50px; animation: ripple 1s; opacity: 0; } /* Add animation */ @keyframes ripple { from { opacity: 1; transform: scale(0); } to { opacity: 0; transform: scale(10); } }</style>Adding JavaScript: Now we’ll add the span element on button click with position according to the mouse click. On button click we have to do the following:Create span element and add ripple class to it.Get the clicked position of cursor using event variable.Set the position of the span element.Remove the span element to avoid spamming of span elements in button.<script> const btn = document.querySelector(\".btn\"); // Listen for click event btn.onclick = function (e) { // Create span element let ripple = document.createElement(\"span\"); // Add ripple class to span ripple.classList.add(\"ripple\"); // Add span to the button this.appendChild(ripple); // Get position of X let x = e.clientX - e.target.offsetLeft; // Get position of Y let y = e.clientY - e.target.offsetTop; // Position the span element ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; // Remove span after 0.3s setTimeout(() => { ripple.remove(); }, 300); };</script>" }, { "code": null, "e": 28795, "s": 27895, "text": "Basic styling: Add basic styling to the button with a position:relative attribute to position the inner span tag and overflow:hidden to prevent span going outside of button.<!DOCTYPE html><html> <head> <title> Button Ripple Effect - GFG </title> <style> /* Adding styles to button */ .btn { padding: 12px 50px; border: none; border-radius: 5px; background-color: #1abc9c; color: #fff; font-size: 18px; outline: none; cursor: pointer; /* We need this to position span inside button */ position: relative; overflow: hidden; box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2); } </style></head> <body> <button class=\"btn\"> Enter GeeksforGeeks </button></body> </html>Output:" }, { "code": "<!DOCTYPE html><html> <head> <title> Button Ripple Effect - GFG </title> <style> /* Adding styles to button */ .btn { padding: 12px 50px; border: none; border-radius: 5px; background-color: #1abc9c; color: #fff; font-size: 18px; outline: none; cursor: pointer; /* We need this to position span inside button */ position: relative; overflow: hidden; box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2); } </style></head> <body> <button class=\"btn\"> Enter GeeksforGeeks </button></body> </html>", "e": 29515, "s": 28795, "text": null }, { "code": null, "e": 29523, "s": 29515, "text": "Output:" }, { "code": null, "e": 30193, "s": 29523, "text": "Add styling to the span element: Now adding the style for the span element that will show up on the click of a button.<style> .btn span { position: absolute; border-radius: 50%; /* To make it round */ background-color: rgba(0, 0, 0, 0.3); width: 100px; height: 100px; margin-top: -50px; /* for positioning */ margin-left: -50px; animation: ripple 1s; opacity: 0; } /* Add animation */ @keyframes ripple { from { opacity: 1; transform: scale(0); } to { opacity: 0; transform: scale(10); } }</style>" }, { "code": "<style> .btn span { position: absolute; border-radius: 50%; /* To make it round */ background-color: rgba(0, 0, 0, 0.3); width: 100px; height: 100px; margin-top: -50px; /* for positioning */ margin-left: -50px; animation: ripple 1s; opacity: 0; } /* Add animation */ @keyframes ripple { from { opacity: 1; transform: scale(0); } to { opacity: 0; transform: scale(10); } }</style>", "e": 30745, "s": 30193, "text": null }, { "code": null, "e": 31845, "s": 30745, "text": "Adding JavaScript: Now we’ll add the span element on button click with position according to the mouse click. On button click we have to do the following:Create span element and add ripple class to it.Get the clicked position of cursor using event variable.Set the position of the span element.Remove the span element to avoid spamming of span elements in button.<script> const btn = document.querySelector(\".btn\"); // Listen for click event btn.onclick = function (e) { // Create span element let ripple = document.createElement(\"span\"); // Add ripple class to span ripple.classList.add(\"ripple\"); // Add span to the button this.appendChild(ripple); // Get position of X let x = e.clientX - e.target.offsetLeft; // Get position of Y let y = e.clientY - e.target.offsetTop; // Position the span element ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; // Remove span after 0.3s setTimeout(() => { ripple.remove(); }, 300); };</script>" }, { "code": null, "e": 32055, "s": 31845, "text": "Create span element and add ripple class to it.Get the clicked position of cursor using event variable.Set the position of the span element.Remove the span element to avoid spamming of span elements in button." }, { "code": null, "e": 32103, "s": 32055, "text": "Create span element and add ripple class to it." }, { "code": null, "e": 32160, "s": 32103, "text": "Get the clicked position of cursor using event variable." }, { "code": null, "e": 32198, "s": 32160, "text": "Set the position of the span element." }, { "code": null, "e": 32268, "s": 32198, "text": "Remove the span element to avoid spamming of span elements in button." }, { "code": "<script> const btn = document.querySelector(\".btn\"); // Listen for click event btn.onclick = function (e) { // Create span element let ripple = document.createElement(\"span\"); // Add ripple class to span ripple.classList.add(\"ripple\"); // Add span to the button this.appendChild(ripple); // Get position of X let x = e.clientX - e.target.offsetLeft; // Get position of Y let y = e.clientY - e.target.offsetTop; // Position the span element ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; // Remove span after 0.3s setTimeout(() => { ripple.remove(); }, 300); };</script>", "e": 33005, "s": 32268, "text": null }, { "code": null, "e": 33057, "s": 33005, "text": "The final output will be look something like below:" }, { "code": null, "e": 33066, "s": 33057, "text": "CSS-Misc" }, { "code": null, "e": 33076, "s": 33066, "text": "HTML-Misc" }, { "code": null, "e": 33092, "s": 33076, "text": "JavaScript-Misc" }, { "code": null, "e": 33099, "s": 33092, "text": "Picked" }, { "code": null, "e": 33103, "s": 33099, "text": "CSS" }, { "code": null, "e": 33108, "s": 33103, "text": "HTML" }, { "code": null, "e": 33119, "s": 33108, "text": "JavaScript" }, { "code": null, "e": 33136, "s": 33119, "text": "Web Technologies" }, { "code": null, "e": 33163, "s": 33136, "text": "Web technologies Questions" }, { "code": null, "e": 33179, "s": 33163, "text": "Write From Home" }, { "code": null, "e": 33184, "s": 33179, "text": "HTML" }, { "code": null, "e": 33282, "s": 33184, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33346, "s": 33282, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 33387, "s": 33346, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 33424, "s": 33387, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33485, "s": 33424, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 33524, "s": 33485, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 33584, "s": 33524, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33645, "s": 33584, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33698, "s": 33645, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33748, "s": 33698, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to create an array of integers in JavaScript?
To create an array of integers in JavaScript, try the following − var rank = [1, 2, 3, 4]; You can also use the new keyword to create array of integers in JavaScript − var rank = new Array(1, 2, 3, 4); The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295. Let’s see an example to create an array of integers in JavaScript − Live Demo <html> <body> <script> var arr1 = [50,60,65,90]; var arr2 = [25,35,50,90]; for (i = 0; i < arr1.length; i++) { for (z = 0; z < arr1.length; z++) { if (arr1[i] === arr2[z]) { document.write("<br>Matched element: "+arr2[z]); } } } </script> </body> </html> Matched element: 50 Matched element: 90
[ { "code": null, "e": 1128, "s": 1062, "text": "To create an array of integers in JavaScript, try the following −" }, { "code": null, "e": 1153, "s": 1128, "text": "var rank = [1, 2, 3, 4];" }, { "code": null, "e": 1230, "s": 1153, "text": "You can also use the new keyword to create array of integers in JavaScript −" }, { "code": null, "e": 1264, "s": 1230, "text": "var rank = new Array(1, 2, 3, 4);" }, { "code": null, "e": 1493, "s": 1264, "text": "The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295." }, { "code": null, "e": 1561, "s": 1493, "text": "Let’s see an example to create an array of integers in JavaScript −" }, { "code": null, "e": 1571, "s": 1561, "text": "Live Demo" }, { "code": null, "e": 1968, "s": 1571, "text": "<html> \n <body> \n <script>\n var arr1 = [50,60,65,90];\n var arr2 = [25,35,50,90]; \n for (i = 0; i < arr1.length; i++) { \n for (z = 0; z < arr1.length; z++) {\n if (arr1[i] === arr2[z]) {\n document.write(\"<br>Matched element: \"+arr2[z]);\n } \n } \n } \n </script>\n </body>\n</html>" }, { "code": null, "e": 2008, "s": 1968, "text": "Matched element: 50\nMatched element: 90" } ]
How to Override toString Method for ArrayList in Java? - GeeksforGeeks
04 Dec, 2020 Every class in java is a child of Object class either directly or indirectly. toString() is present in Object class. The toString method returns a string representation of an object. The toString() can be overridden as part of a class to cater to the customized needs of the user. Whenever we try to print the Object reference then internally toString() method is invoked. If we did not define the toString() method in your class then the Object class toString() method is invoked otherwise our implemented/Overridden toString() method will be called. Syntax of Object class toString() Method: public String toString() { return getClass().getName()+"@"+Integer.toHexString(hashCode()); } Returns: The method returns a string. Example: Java // Java program to demonstrate// how to override toString // method for ArrayList import java.util.ArrayList; // define a classclass Employee { // attributes of an Employee private String EmployeeName; private int EmployeeId; private double EmployeeSalary; // Create Constructor that accept // name id and salary as // an argument Employee(String name, int id, double salary) { this.EmployeeSalary = salary; this.EmployeeName = name; this.EmployeeId = id; } // Override toString() // provide your own implementation public String toString() { return " Employee Name = " + this.EmployeeName + " Employee Id = " + this.EmployeeId + " Employee Salary = " + this.EmployeeSalary; }} public class GFG { public static void main(String[] args) { // Create a ArrayList of Employee Class Type ArrayList<Employee> ArrList = new ArrayList<Employee>(); ArrList.add(new Employee("Mukul", 1001, 52000.0)); ArrList.add(new Employee("Robin", 1002, 65000.0)); ArrList.add(new Employee("Rahul", 1003, 53000.0)); ArrList.add(new Employee("Suraj", 1004, 45000.0)); ArrList.add(new Employee("Akash", 1005, 38000.0)); // When an object is tried to print // toString() method is called for (Employee t : ArrList) { System.out.println(t); } }} Employee Name = Mukul Employee Id = 1001 Employee Salary = 52000.0 Employee Name = Robin Employee Id = 1002 Employee Salary = 65000.0 Employee Name = Rahul Employee Id = 1003 Employee Salary = 53000.0 Employee Name = Suraj Employee Id = 1004 Employee Salary = 45000.0 Employee Name = Akash Employee Id = 1005 Employee Salary = 38000.0 Explanation: When we try to print Employee instance, toString() method which is overridden is called and the string value is printed. Java-ArrayList Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25373, "s": 25345, "text": "\n04 Dec, 2020" }, { "code": null, "e": 25925, "s": 25373, "text": "Every class in java is a child of Object class either directly or indirectly. toString() is present in Object class. The toString method returns a string representation of an object. The toString() can be overridden as part of a class to cater to the customized needs of the user. Whenever we try to print the Object reference then internally toString() method is invoked. If we did not define the toString() method in your class then the Object class toString() method is invoked otherwise our implemented/Overridden toString() method will be called." }, { "code": null, "e": 25967, "s": 25925, "text": "Syntax of Object class toString() Method:" }, { "code": null, "e": 26065, "s": 25967, "text": "public String toString()\n{\n return getClass().getName()+\"@\"+Integer.toHexString(hashCode());\n}" }, { "code": null, "e": 26103, "s": 26065, "text": "Returns: The method returns a string." }, { "code": null, "e": 26112, "s": 26103, "text": "Example:" }, { "code": null, "e": 26117, "s": 26112, "text": "Java" }, { "code": "// Java program to demonstrate// how to override toString // method for ArrayList import java.util.ArrayList; // define a classclass Employee { // attributes of an Employee private String EmployeeName; private int EmployeeId; private double EmployeeSalary; // Create Constructor that accept // name id and salary as // an argument Employee(String name, int id, double salary) { this.EmployeeSalary = salary; this.EmployeeName = name; this.EmployeeId = id; } // Override toString() // provide your own implementation public String toString() { return \" Employee Name = \" + this.EmployeeName + \" Employee Id = \" + this.EmployeeId + \" Employee Salary = \" + this.EmployeeSalary; }} public class GFG { public static void main(String[] args) { // Create a ArrayList of Employee Class Type ArrayList<Employee> ArrList = new ArrayList<Employee>(); ArrList.add(new Employee(\"Mukul\", 1001, 52000.0)); ArrList.add(new Employee(\"Robin\", 1002, 65000.0)); ArrList.add(new Employee(\"Rahul\", 1003, 53000.0)); ArrList.add(new Employee(\"Suraj\", 1004, 45000.0)); ArrList.add(new Employee(\"Akash\", 1005, 38000.0)); // When an object is tried to print // toString() method is called for (Employee t : ArrList) { System.out.println(t); } }}", "e": 27569, "s": 26117, "text": null }, { "code": null, "e": 27949, "s": 27569, "text": " Employee Name = Mukul Employee Id = 1001 Employee Salary = 52000.0\n Employee Name = Robin Employee Id = 1002 Employee Salary = 65000.0\n Employee Name = Rahul Employee Id = 1003 Employee Salary = 53000.0\n Employee Name = Suraj Employee Id = 1004 Employee Salary = 45000.0\n Employee Name = Akash Employee Id = 1005 Employee Salary = 38000.0" }, { "code": null, "e": 28083, "s": 27949, "text": "Explanation: When we try to print Employee instance, toString() method which is overridden is called and the string value is printed." }, { "code": null, "e": 28098, "s": 28083, "text": "Java-ArrayList" }, { "code": null, "e": 28105, "s": 28098, "text": "Picked" }, { "code": null, "e": 28110, "s": 28105, "text": "Java" }, { "code": null, "e": 28124, "s": 28110, "text": "Java Programs" }, { "code": null, "e": 28129, "s": 28124, "text": "Java" }, { "code": null, "e": 28227, "s": 28129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28242, "s": 28227, "text": "Stream In Java" }, { "code": null, "e": 28261, "s": 28242, "text": "Exceptions in Java" }, { "code": null, "e": 28282, "s": 28261, "text": "Constructors in Java" }, { "code": null, "e": 28312, "s": 28282, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28358, "s": 28312, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28384, "s": 28358, "text": "Java Programming Examples" }, { "code": null, "e": 28418, "s": 28384, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28465, "s": 28418, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28497, "s": 28465, "text": "How to Iterate HashMap in Java?" } ]
KNN visualization in just 13 lines of code | by Deepthi A R | Towards Data Science
Yes! It’s that simple. Let’s play around with datasets to visualize how the decision boundary changes as ‘k’ changes. Let’s have a quick review... K Nearest Neighbor(KNN) algorithm is a very simple, easy to understand, versatile and one of the topmost machine learning algorithms. In k-NN classification, the output is a class membership. An object is classified by a plurality vote of its neighbours, with the object being assigned to the class most common among its k nearest neighbours (k is a positive integer, typically small). If k = 1, then the object is simply assigned to the class of that single nearest neighbour. In KNN, K is the number of nearest neighbours. The number of neighbours is the core deciding factor. K is generally an odd number if the number of classes is 2. When K=1, then the algorithm is known as the nearest neighbour algorithm. This is the simplest case. Suppose P1 is the point, for which label needs to be predicted. KNN has three basic steps.1. Calculate the distance.2. Find the k nearest neighbours.3. Vote for classes You can’t pick any random value for k. The whole algorithm is based on the k value. Even small changes to k may result in big changes. Like most machine learning algorithms, the K in KNN is a hyperparameter. You can think of K as a controlling variable for the prediction model. In this blog, we’ll see how decision boundary changes with k. For this, I’ll be using different types of toy datasets. You can easily download all these datasets from the given link below. www.kaggle.com U — Shaped U — Shaped In this dataset, we can observe that the classes are in the form of an interlocked U. This is a non-linear dataset. The blue points belong to class 0 and the orange points belong to class 1. 2. Two set concentric circles In this dataset, we can see that the points form two sets of concentric circles. This is a non-linear dataset.The blue points belong to class 0 and the orange points belong to class 1. 3. XOR This dataset resembles the 2 variable XOR k-map. This is a non-linear linear dataset. The blue points belong to class -1 and the orange points belong to class 1. 4. Linearly separable This is a linear dataset in which the points can be linearly separated. The blue points belong to class 0 and the orange points belong to class 1. 5. Outliers In this dataset, we can observe that there are outlier points from both the classes. We’ll see how the presence of outliers can affect the decision boundary. This is a linear dataset.The blue points belong to class 0 and the orange points belong to class 1. Now that we know how our looks we will now go ahead with and see how the decision boundary changes with the value of k. here I’m taking 1,5,20,30,40 and 60 as k values. You can try with any set of value To start off, let’s import the libraries. import matplotlib.pyplot as pltimport pandas as pdfrom sklearn import datasets, neighborsfrom mlxtend.plotting import plot_decision_regions The following core function required. def knn_comparison(data, k): x = data[[‘X’,’Y’]].values y = data[‘class’].astype(int).values clf = neighbors.KNeighborsClassifier(n_neighbors=k) clf.fit(x, y)# Plotting decision region plot_decision_regions(x, y, clf=clf, legend=2)# Adding axes annotations plt.xlabel(‘X’) plt.ylabel(‘Y’) plt.title(‘Knn with K=’+ str(k)) plt.show() You can observe that its just one line of code that is doing ever everything — clf = neighbors.KNeighborsClassifier(n_neighbors=k) It’s that simple and elegant. Now we just have to load our CSV file and pass it to this function along with k. We’ll do this for all the datasets one by one. Let’s dive in... data1 = pd.read_csv(‘ushape.csv’)for i in [1,5,20,30,40,80]: knn_comparison(data1, i) data2 = pd.read_csv(‘concertriccir2.csv’)for i in [1,5,20,30,40,60]: knn_comparison(data2, i) data3 = pd.read_csv(‘xor.csv’)for i in [1,5,20,30,40,60]: knn_comparison(data3, i) data4 = pd.read_csv(‘linearsep.csv’)for i in [1,5,20,30,40,60]: knn_comparison(data4, i) data5 = pd.read_csv(‘outlier.csv’)for i in [1, 5,20,30,40,60]: knn_comparison(data5, i) In all the datasets we can observe that when k=1, we are overfitting the model. That is, each point is classified correctly, you might think that it is a good thing, well as the saying goes “ too much is too bad”, overfitting essentially means that our model is training way too well to an extent that it negatively impacts the model. In all the datasets we can observe that when k = 60 (a large number), we are underfitting the model. Underfitting refers to a model that can neither model the training data nor generalize to new data. An underfit machine learning model is not a suitable model. In the case of outlier dataset, for k=60, our model did a pretty good job. How can we tell this? Because we know that those points are outliers and the data is linearly separable, but that’s not the case every time, we cannot be sure. Also in the XOR dataset, the value of k is not affecting the model to a great extent, unlike other models. Research has shown that there is no optimal value of hyperparameter(k ) that suits all kind of data sets. Each dataset has it’s own requirements. In the case of a small k, the noise will have a higher influence on the result, and a large k will make it computationally expensive. Research has also shown that a small k is most flexible fit which will have low bias but the high variance and a large k will have a smoother decision boundary which means lower variance but higher bias. Overfitting and underfitting are the two biggest causes for the poor performance of machine learning algorithms. When K is small, we are restraining the region of a given prediction and forcing our classifier to be “blind” to the overall distribution. A small value for K provides the most flexible fit, which will have low bias but high variance. Graphically, our decision boundary will be more jagged as we observed above. On the other hand, a higher K averages more points in each prediction and hence is more resilient to outliers. Larger values of K will have smoother decision boundaries which mean lower variance but increased bias. www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learnscott.fortmann-roe.com/docs/BiasVariance.htmlrasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/#references www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn scott.fortmann-roe.com/docs/BiasVariance.html rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/#references What are you waiting for? Go ahead and play around with the datasets !!
[ { "code": null, "e": 290, "s": 172, "text": "Yes! It’s that simple. Let’s play around with datasets to visualize how the decision boundary changes as ‘k’ changes." }, { "code": null, "e": 319, "s": 290, "text": "Let’s have a quick review..." }, { "code": null, "e": 797, "s": 319, "text": "K Nearest Neighbor(KNN) algorithm is a very simple, easy to understand, versatile and one of the topmost machine learning algorithms. In k-NN classification, the output is a class membership. An object is classified by a plurality vote of its neighbours, with the object being assigned to the class most common among its k nearest neighbours (k is a positive integer, typically small). If k = 1, then the object is simply assigned to the class of that single nearest neighbour." }, { "code": null, "e": 1123, "s": 797, "text": "In KNN, K is the number of nearest neighbours. The number of neighbours is the core deciding factor. K is generally an odd number if the number of classes is 2. When K=1, then the algorithm is known as the nearest neighbour algorithm. This is the simplest case. Suppose P1 is the point, for which label needs to be predicted." }, { "code": null, "e": 1228, "s": 1123, "text": "KNN has three basic steps.1. Calculate the distance.2. Find the k nearest neighbours.3. Vote for classes" }, { "code": null, "e": 1507, "s": 1228, "text": "You can’t pick any random value for k. The whole algorithm is based on the k value. Even small changes to k may result in big changes. Like most machine learning algorithms, the K in KNN is a hyperparameter. You can think of K as a controlling variable for the prediction model." }, { "code": null, "e": 1696, "s": 1507, "text": "In this blog, we’ll see how decision boundary changes with k. For this, I’ll be using different types of toy datasets. You can easily download all these datasets from the given link below." }, { "code": null, "e": 1711, "s": 1696, "text": "www.kaggle.com" }, { "code": null, "e": 1722, "s": 1711, "text": "U — Shaped" }, { "code": null, "e": 1733, "s": 1722, "text": "U — Shaped" }, { "code": null, "e": 1924, "s": 1733, "text": "In this dataset, we can observe that the classes are in the form of an interlocked U. This is a non-linear dataset. The blue points belong to class 0 and the orange points belong to class 1." }, { "code": null, "e": 1954, "s": 1924, "text": "2. Two set concentric circles" }, { "code": null, "e": 2139, "s": 1954, "text": "In this dataset, we can see that the points form two sets of concentric circles. This is a non-linear dataset.The blue points belong to class 0 and the orange points belong to class 1." }, { "code": null, "e": 2146, "s": 2139, "text": "3. XOR" }, { "code": null, "e": 2232, "s": 2146, "text": "This dataset resembles the 2 variable XOR k-map. This is a non-linear linear dataset." }, { "code": null, "e": 2308, "s": 2232, "text": "The blue points belong to class -1 and the orange points belong to class 1." }, { "code": null, "e": 2330, "s": 2308, "text": "4. Linearly separable" }, { "code": null, "e": 2402, "s": 2330, "text": "This is a linear dataset in which the points can be linearly separated." }, { "code": null, "e": 2477, "s": 2402, "text": "The blue points belong to class 0 and the orange points belong to class 1." }, { "code": null, "e": 2489, "s": 2477, "text": "5. Outliers" }, { "code": null, "e": 2747, "s": 2489, "text": "In this dataset, we can observe that there are outlier points from both the classes. We’ll see how the presence of outliers can affect the decision boundary. This is a linear dataset.The blue points belong to class 0 and the orange points belong to class 1." }, { "code": null, "e": 2950, "s": 2747, "text": "Now that we know how our looks we will now go ahead with and see how the decision boundary changes with the value of k. here I’m taking 1,5,20,30,40 and 60 as k values. You can try with any set of value" }, { "code": null, "e": 2992, "s": 2950, "text": "To start off, let’s import the libraries." }, { "code": null, "e": 3132, "s": 2992, "text": "import matplotlib.pyplot as pltimport pandas as pdfrom sklearn import datasets, neighborsfrom mlxtend.plotting import plot_decision_regions" }, { "code": null, "e": 3170, "s": 3132, "text": "The following core function required." }, { "code": null, "e": 3503, "s": 3170, "text": "def knn_comparison(data, k): x = data[[‘X’,’Y’]].values y = data[‘class’].astype(int).values clf = neighbors.KNeighborsClassifier(n_neighbors=k) clf.fit(x, y)# Plotting decision region plot_decision_regions(x, y, clf=clf, legend=2)# Adding axes annotations plt.xlabel(‘X’) plt.ylabel(‘Y’) plt.title(‘Knn with K=’+ str(k)) plt.show()" }, { "code": null, "e": 3634, "s": 3503, "text": "You can observe that its just one line of code that is doing ever everything — clf = neighbors.KNeighborsClassifier(n_neighbors=k)" }, { "code": null, "e": 3792, "s": 3634, "text": "It’s that simple and elegant. Now we just have to load our CSV file and pass it to this function along with k. We’ll do this for all the datasets one by one." }, { "code": null, "e": 3809, "s": 3792, "text": "Let’s dive in..." }, { "code": null, "e": 3898, "s": 3809, "text": "data1 = pd.read_csv(‘ushape.csv’)for i in [1,5,20,30,40,80]: knn_comparison(data1, i)" }, { "code": null, "e": 3995, "s": 3898, "text": "data2 = pd.read_csv(‘concertriccir2.csv’)for i in [1,5,20,30,40,60]: knn_comparison(data2, i)" }, { "code": null, "e": 4080, "s": 3995, "text": "data3 = pd.read_csv(‘xor.csv’)for i in [1,5,20,30,40,60]: knn_comparison(data3, i)" }, { "code": null, "e": 4172, "s": 4080, "text": "data4 = pd.read_csv(‘linearsep.csv’)for i in [1,5,20,30,40,60]: knn_comparison(data4, i)" }, { "code": null, "e": 4263, "s": 4172, "text": "data5 = pd.read_csv(‘outlier.csv’)for i in [1, 5,20,30,40,60]: knn_comparison(data5, i)" }, { "code": null, "e": 4598, "s": 4263, "text": "In all the datasets we can observe that when k=1, we are overfitting the model. That is, each point is classified correctly, you might think that it is a good thing, well as the saying goes “ too much is too bad”, overfitting essentially means that our model is training way too well to an extent that it negatively impacts the model." }, { "code": null, "e": 5201, "s": 4598, "text": "In all the datasets we can observe that when k = 60 (a large number), we are underfitting the model. Underfitting refers to a model that can neither model the training data nor generalize to new data. An underfit machine learning model is not a suitable model. In the case of outlier dataset, for k=60, our model did a pretty good job. How can we tell this? Because we know that those points are outliers and the data is linearly separable, but that’s not the case every time, we cannot be sure. Also in the XOR dataset, the value of k is not affecting the model to a great extent, unlike other models." }, { "code": null, "e": 5685, "s": 5201, "text": "Research has shown that there is no optimal value of hyperparameter(k ) that suits all kind of data sets. Each dataset has it’s own requirements. In the case of a small k, the noise will have a higher influence on the result, and a large k will make it computationally expensive. Research has also shown that a small k is most flexible fit which will have low bias but the high variance and a large k will have a smoother decision boundary which means lower variance but higher bias." }, { "code": null, "e": 5798, "s": 5685, "text": "Overfitting and underfitting are the two biggest causes for the poor performance of machine learning algorithms." }, { "code": null, "e": 6325, "s": 5798, "text": "When K is small, we are restraining the region of a given prediction and forcing our classifier to be “blind” to the overall distribution. A small value for K provides the most flexible fit, which will have low bias but high variance. Graphically, our decision boundary will be more jagged as we observed above. On the other hand, a higher K averages more points in each prediction and hence is more resilient to outliers. Larger values of K will have smoother decision boundaries which mean lower variance but increased bias." }, { "code": null, "e": 6531, "s": 6325, "text": "www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learnscott.fortmann-roe.com/docs/BiasVariance.htmlrasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/#references" }, { "code": null, "e": 6615, "s": 6531, "text": "www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn" }, { "code": null, "e": 6661, "s": 6615, "text": "scott.fortmann-roe.com/docs/BiasVariance.html" }, { "code": null, "e": 6739, "s": 6661, "text": "rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/#references" } ]
Use of explicit keyword in C++ - GeeksforGeeks
02 May, 2022 Explicit Keyword in C++ is used to mark constructors to not implicitly convert types in C++. It is optional for constructors that take exactly one argument and work on constructors(with a single argument) since those are the only constructors that can be used in typecasting. Let’s understand explicit keyword through an example. Predict the output of the following C++ Program CPP // C++ program to illustrate default// constructor without 'explicit'// keyword#include <iostream>using namespace std; class Complex {private: double real; double imag; public: // Default constructor Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } // A method to compare two // Complex numbers bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag); }}; // Driver Codeint main(){ // a Complex object Complex com1(3.0, 0.0); if (com1 == 3.0) cout << "Same"; else cout << "Not Same"; return 0;} Same As discussed in this article, in C++, if a class has a constructor which can be called with a single argument, then this constructor becomes a conversion constructor because such a constructor allows conversion of the single argument to the class being constructed. We can avoid such implicit conversions as these may lead to unexpected results. We can make the constructor explicit with the help of an explicit keyword. For example, if we try the following program that uses explicit keywords with a constructor, we get a compilation error. CPP // C++ program to illustrate// default constructor with// 'explicit' keyword#include <iostream>using namespace std; class Complex {private: double real; double imag; public: // Default constructor explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } // A method to compare two // Complex numbers bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag); }}; // Driver Codeint main(){ // a Complex object Complex com1(3.0, 0.0); if (com1 == 3.0) cout << "Same"; else cout << "Not Same"; return 0;} Output Compiler Error : no match for 'operator==' in 'com1 == 3.0e+0' We can still typecast the double values to Complex, but now we have to explicitly typecast it. For example, the following program works fine. CPP // C++ program to illustrate// default constructor with// 'explicit' keyword#include <iostream>using namespace std; class Complex {private: double real; double imag; public: // Default constructor explicit Complex(double r = 0.0, double i = 0.0): real(r) , imag(i) { } // A method to compare two // Complex numbers bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag); }}; // Driver Codeint main(){ // a Complex object Complex com1(3.0, 0.0); if (com1 == (Complex)3.0) cout << "Same"; else cout << "Not Same"; return 0;} Same Note: The explicit specifier can be used with a constant expression. However, if that constant expression evaluates to true, then only the function is explicit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 jayeshtpatel C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Function Pointer in C Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24620, "s": 24592, "text": "\n02 May, 2022" }, { "code": null, "e": 24896, "s": 24620, "text": "Explicit Keyword in C++ is used to mark constructors to not implicitly convert types in C++. It is optional for constructors that take exactly one argument and work on constructors(with a single argument) since those are the only constructors that can be used in typecasting." }, { "code": null, "e": 24951, "s": 24896, "text": "Let’s understand explicit keyword through an example. " }, { "code": null, "e": 24999, "s": 24951, "text": "Predict the output of the following C++ Program" }, { "code": null, "e": 25003, "s": 24999, "text": "CPP" }, { "code": "// C++ program to illustrate default// constructor without 'explicit'// keyword#include <iostream>using namespace std; class Complex {private: double real; double imag; public: // Default constructor Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } // A method to compare two // Complex numbers bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag); }}; // Driver Codeint main(){ // a Complex object Complex com1(3.0, 0.0); if (com1 == 3.0) cout << \"Same\"; else cout << \"Not Same\"; return 0;}", "e": 25664, "s": 25003, "text": null }, { "code": null, "e": 25669, "s": 25664, "text": "Same" }, { "code": null, "e": 26211, "s": 25669, "text": "As discussed in this article, in C++, if a class has a constructor which can be called with a single argument, then this constructor becomes a conversion constructor because such a constructor allows conversion of the single argument to the class being constructed. We can avoid such implicit conversions as these may lead to unexpected results. We can make the constructor explicit with the help of an explicit keyword. For example, if we try the following program that uses explicit keywords with a constructor, we get a compilation error." }, { "code": null, "e": 26215, "s": 26211, "text": "CPP" }, { "code": "// C++ program to illustrate// default constructor with// 'explicit' keyword#include <iostream>using namespace std; class Complex {private: double real; double imag; public: // Default constructor explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } // A method to compare two // Complex numbers bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag); }}; // Driver Codeint main(){ // a Complex object Complex com1(3.0, 0.0); if (com1 == 3.0) cout << \"Same\"; else cout << \"Not Same\"; return 0;}", "e": 26879, "s": 26215, "text": null }, { "code": null, "e": 26886, "s": 26879, "text": "Output" }, { "code": null, "e": 26949, "s": 26886, "text": "Compiler Error : no match for 'operator==' in 'com1 == 3.0e+0'" }, { "code": null, "e": 27091, "s": 26949, "text": "We can still typecast the double values to Complex, but now we have to explicitly typecast it. For example, the following program works fine." }, { "code": null, "e": 27095, "s": 27091, "text": "CPP" }, { "code": "// C++ program to illustrate// default constructor with// 'explicit' keyword#include <iostream>using namespace std; class Complex {private: double real; double imag; public: // Default constructor explicit Complex(double r = 0.0, double i = 0.0): real(r) , imag(i) { } // A method to compare two // Complex numbers bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag); }}; // Driver Codeint main(){ // a Complex object Complex com1(3.0, 0.0); if (com1 == (Complex)3.0) cout << \"Same\"; else cout << \"Not Same\"; return 0;}", "e": 27771, "s": 27095, "text": null }, { "code": null, "e": 27776, "s": 27771, "text": "Same" }, { "code": null, "e": 27937, "s": 27776, "text": "Note: The explicit specifier can be used with a constant expression. However, if that constant expression evaluates to true, then only the function is explicit." }, { "code": null, "e": 28062, "s": 27937, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28076, "s": 28062, "text": "anshikajain26" }, { "code": null, "e": 28089, "s": 28076, "text": "jayeshtpatel" }, { "code": null, "e": 28100, "s": 28089, "text": "C Language" }, { "code": null, "e": 28104, "s": 28100, "text": "C++" }, { "code": null, "e": 28108, "s": 28104, "text": "CPP" }, { "code": null, "e": 28206, "s": 28108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28241, "s": 28206, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28287, "s": 28241, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 28299, "s": 28287, "text": "fork() in C" }, { "code": null, "e": 28339, "s": 28299, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 28361, "s": 28339, "text": "Function Pointer in C" }, { "code": null, "e": 28379, "s": 28361, "text": "Vector in C++ STL" }, { "code": null, "e": 28398, "s": 28379, "text": "Inheritance in C++" }, { "code": null, "e": 28444, "s": 28398, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28487, "s": 28444, "text": "Map in C++ Standard Template Library (STL)" } ]
Java 8 - Functional Interfaces
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package. BiConsumer<T,U> Represents an operation that accepts two input arguments, and returns no result. BiFunction<T,U,R> Represents a function that accepts two arguments and produces a result. BinaryOperator<T> Represents an operation upon two operands of the same type, producing a result of the same type as the operands. BiPredicate<T,U> Represents a predicate (Boolean-valued function) of two arguments. BooleanSupplier Represents a supplier of Boolean-valued results. Consumer<T> Represents an operation that accepts a single input argument and returns no result. DoubleBinaryOperator Represents an operation upon two double-valued operands and producing a double-valued result. DoubleConsumer Represents an operation that accepts a single double-valued argument and returns no result. DoubleFunction<R> Represents a function that accepts a double-valued argument and produces a result. DoublePredicate Represents a predicate (Boolean-valued function) of one double-valued argument. DoubleSupplier Represents a supplier of double-valued results. DoubleToIntFunction Represents a function that accepts a double-valued argument and produces an int-valued result. DoubleToLongFunction Represents a function that accepts a double-valued argument and produces a long-valued result. DoubleUnaryOperator Represents an operation on a single double-valued operand that produces a double-valued result. Function<T,R> Represents a function that accepts one argument and produces a result. IntBinaryOperator Represents an operation upon two int-valued operands and produces an int-valued result. IntConsumer Represents an operation that accepts a single int-valued argument and returns no result. IntFunction<R> Represents a function that accepts an int-valued argument and produces a result. IntPredicate Represents a predicate (Boolean-valued function) of one int-valued argument. IntSupplier Represents a supplier of int-valued results. IntToDoubleFunction Represents a function that accepts an int-valued argument and produces a double-valued result. IntToLongFunction Represents a function that accepts an int-valued argument and produces a long-valued result. IntUnaryOperator Represents an operation on a single int-valued operand that produces an int-valued result. LongBinaryOperator Represents an operation upon two long-valued operands and produces a long-valued result. LongConsumer Represents an operation that accepts a single long-valued argument and returns no result. LongFunction<R> Represents a function that accepts a long-valued argument and produces a result. LongPredicate Represents a predicate (Boolean-valued function) of one long-valued argument. LongSupplier Represents a supplier of long-valued results. LongToDoubleFunction Represents a function that accepts a long-valued argument and produces a double-valued result. LongToIntFunction Represents a function that accepts a long-valued argument and produces an int-valued result. LongUnaryOperator Represents an operation on a single long-valued operand that produces a long-valued result. ObjDoubleConsumer<T> Represents an operation that accepts an object-valued and a double-valued argument, and returns no result. ObjIntConsumer<T> Represents an operation that accepts an object-valued and an int-valued argument, and returns no result. ObjLongConsumer<T> Represents an operation that accepts an object-valued and a long-valued argument, and returns no result. Predicate<T> Represents a predicate (Boolean-valued function) of one argument. Supplier<T> Represents a supplier of results. ToDoubleBiFunction<T,U> Represents a function that accepts two arguments and produces a double-valued result. ToDoubleFunction<T> Represents a function that produces a double-valued result. ToIntBiFunction<T,U> Represents a function that accepts two arguments and produces an int-valued result. ToIntFunction<T> Represents a function that produces an int-valued result. ToLongBiFunction<T,U> Represents a function that accepts two arguments and produces a long-valued result. ToLongFunction<T> Represents a function that produces a long-valued result. UnaryOperator<T> Represents an operation on a single operand that produces a result of the same type as its operand. Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false. Create the following Java program using any editor of your choice in, say, C:\> JAVA. import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class Java8Tester { public static void main(String args[]) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); // Predicate<Integer> predicate = n -> true // n is passed as parameter to test method of Predicate interface // test method will always return true no matter what value n has. System.out.println("Print all numbers:"); //pass n as parameter eval(list, n->true); // Predicate<Integer> predicate1 = n -> n%2 == 0 // n is passed as parameter to test method of Predicate interface // test method will return true if n%2 comes to be zero System.out.println("Print even numbers:"); eval(list, n-> n%2 == 0 ); // Predicate<Integer> predicate2 = n -> n > 3 // n is passed as parameter to test method of Predicate interface // test method will return true if n is greater than 3. System.out.println("Print numbers greater than 3:"); eval(list, n-> n > 3 ); } public static void eval(List<Integer> list, Predicate<Integer> predicate) { for(Integer n: list) { if(predicate.test(n)) { System.out.println(n + " "); } } } } Here we've passed Predicate interface, which takes a single input and returns Boolean. Compile the class using javac compiler as follows − C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:\JAVA>java Java8Tester It should produce the following output − Print all numbers: 1 2 3 4 5 6 7 8 9 Print even numbers: 2 4 6 8 Print numbers greater than 3: 4 5 6 7 8 9 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2219, "s": 1874, "text": "Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package." }, { "code": null, "e": 2235, "s": 2219, "text": "BiConsumer<T,U>" }, { "code": null, "e": 2316, "s": 2235, "text": "Represents an operation that accepts two input arguments, and returns no result." }, { "code": null, "e": 2334, "s": 2316, "text": "BiFunction<T,U,R>" }, { "code": null, "e": 2406, "s": 2334, "text": "Represents a function that accepts two arguments and produces a result." }, { "code": null, "e": 2424, "s": 2406, "text": "BinaryOperator<T>" }, { "code": null, "e": 2537, "s": 2424, "text": "Represents an operation upon two operands of the same type, producing a result of the same type as the operands." }, { "code": null, "e": 2554, "s": 2537, "text": "BiPredicate<T,U>" }, { "code": null, "e": 2621, "s": 2554, "text": "Represents a predicate (Boolean-valued function) of two arguments." }, { "code": null, "e": 2637, "s": 2621, "text": "BooleanSupplier" }, { "code": null, "e": 2686, "s": 2637, "text": "Represents a supplier of Boolean-valued results." }, { "code": null, "e": 2698, "s": 2686, "text": "Consumer<T>" }, { "code": null, "e": 2782, "s": 2698, "text": "Represents an operation that accepts a single input argument and returns no result." }, { "code": null, "e": 2803, "s": 2782, "text": "DoubleBinaryOperator" }, { "code": null, "e": 2897, "s": 2803, "text": "Represents an operation upon two double-valued operands and producing a double-valued result." }, { "code": null, "e": 2912, "s": 2897, "text": "DoubleConsumer" }, { "code": null, "e": 3004, "s": 2912, "text": "Represents an operation that accepts a single double-valued argument and returns no result." }, { "code": null, "e": 3022, "s": 3004, "text": "DoubleFunction<R>" }, { "code": null, "e": 3105, "s": 3022, "text": "Represents a function that accepts a double-valued argument and produces a result." }, { "code": null, "e": 3121, "s": 3105, "text": "DoublePredicate" }, { "code": null, "e": 3201, "s": 3121, "text": "Represents a predicate (Boolean-valued function) of one double-valued argument." }, { "code": null, "e": 3216, "s": 3201, "text": "DoubleSupplier" }, { "code": null, "e": 3264, "s": 3216, "text": "Represents a supplier of double-valued results." }, { "code": null, "e": 3284, "s": 3264, "text": "DoubleToIntFunction" }, { "code": null, "e": 3379, "s": 3284, "text": "Represents a function that accepts a double-valued argument and produces an int-valued result." }, { "code": null, "e": 3400, "s": 3379, "text": "DoubleToLongFunction" }, { "code": null, "e": 3495, "s": 3400, "text": "Represents a function that accepts a double-valued argument and produces a long-valued result." }, { "code": null, "e": 3515, "s": 3495, "text": "DoubleUnaryOperator" }, { "code": null, "e": 3611, "s": 3515, "text": "Represents an operation on a single double-valued operand that produces a double-valued result." }, { "code": null, "e": 3625, "s": 3611, "text": "Function<T,R>" }, { "code": null, "e": 3696, "s": 3625, "text": "Represents a function that accepts one argument and produces a result." }, { "code": null, "e": 3714, "s": 3696, "text": "IntBinaryOperator" }, { "code": null, "e": 3802, "s": 3714, "text": "Represents an operation upon two int-valued operands and produces an int-valued result." }, { "code": null, "e": 3814, "s": 3802, "text": "IntConsumer" }, { "code": null, "e": 3903, "s": 3814, "text": "Represents an operation that accepts a single int-valued argument and returns no result." }, { "code": null, "e": 3918, "s": 3903, "text": "IntFunction<R>" }, { "code": null, "e": 3999, "s": 3918, "text": "Represents a function that accepts an int-valued argument and produces a result." }, { "code": null, "e": 4012, "s": 3999, "text": "IntPredicate" }, { "code": null, "e": 4089, "s": 4012, "text": "Represents a predicate (Boolean-valued function) of one int-valued argument." }, { "code": null, "e": 4101, "s": 4089, "text": "IntSupplier" }, { "code": null, "e": 4146, "s": 4101, "text": "Represents a supplier of int-valued results." }, { "code": null, "e": 4166, "s": 4146, "text": "IntToDoubleFunction" }, { "code": null, "e": 4261, "s": 4166, "text": "Represents a function that accepts an int-valued argument and produces a double-valued result." }, { "code": null, "e": 4279, "s": 4261, "text": "IntToLongFunction" }, { "code": null, "e": 4372, "s": 4279, "text": "Represents a function that accepts an int-valued argument and produces a long-valued result." }, { "code": null, "e": 4389, "s": 4372, "text": "IntUnaryOperator" }, { "code": null, "e": 4480, "s": 4389, "text": "Represents an operation on a single int-valued operand that produces an int-valued result." }, { "code": null, "e": 4499, "s": 4480, "text": "LongBinaryOperator" }, { "code": null, "e": 4588, "s": 4499, "text": "Represents an operation upon two long-valued operands and produces a long-valued result." }, { "code": null, "e": 4601, "s": 4588, "text": "LongConsumer" }, { "code": null, "e": 4691, "s": 4601, "text": "Represents an operation that accepts a single long-valued argument and returns no result." }, { "code": null, "e": 4707, "s": 4691, "text": "LongFunction<R>" }, { "code": null, "e": 4788, "s": 4707, "text": "Represents a function that accepts a long-valued argument and produces a result." }, { "code": null, "e": 4802, "s": 4788, "text": "LongPredicate" }, { "code": null, "e": 4880, "s": 4802, "text": "Represents a predicate (Boolean-valued function) of one long-valued argument." }, { "code": null, "e": 4893, "s": 4880, "text": "LongSupplier" }, { "code": null, "e": 4939, "s": 4893, "text": "Represents a supplier of long-valued results." }, { "code": null, "e": 4960, "s": 4939, "text": "LongToDoubleFunction" }, { "code": null, "e": 5055, "s": 4960, "text": "Represents a function that accepts a long-valued argument and produces a double-valued result." }, { "code": null, "e": 5073, "s": 5055, "text": "LongToIntFunction" }, { "code": null, "e": 5166, "s": 5073, "text": "Represents a function that accepts a long-valued argument and produces an int-valued result." }, { "code": null, "e": 5184, "s": 5166, "text": "LongUnaryOperator" }, { "code": null, "e": 5276, "s": 5184, "text": "Represents an operation on a single long-valued operand that produces a long-valued result." }, { "code": null, "e": 5297, "s": 5276, "text": "ObjDoubleConsumer<T>" }, { "code": null, "e": 5404, "s": 5297, "text": "Represents an operation that accepts an object-valued and a double-valued argument, and returns no result." }, { "code": null, "e": 5422, "s": 5404, "text": "ObjIntConsumer<T>" }, { "code": null, "e": 5527, "s": 5422, "text": "Represents an operation that accepts an object-valued and an int-valued argument, and returns no result." }, { "code": null, "e": 5546, "s": 5527, "text": "ObjLongConsumer<T>" }, { "code": null, "e": 5651, "s": 5546, "text": "Represents an operation that accepts an object-valued and a long-valued argument, and returns no result." }, { "code": null, "e": 5664, "s": 5651, "text": "Predicate<T>" }, { "code": null, "e": 5730, "s": 5664, "text": "Represents a predicate (Boolean-valued function) of one argument." }, { "code": null, "e": 5742, "s": 5730, "text": "Supplier<T>" }, { "code": null, "e": 5776, "s": 5742, "text": "Represents a supplier of results." }, { "code": null, "e": 5800, "s": 5776, "text": "ToDoubleBiFunction<T,U>" }, { "code": null, "e": 5886, "s": 5800, "text": "Represents a function that accepts two arguments and produces a double-valued result." }, { "code": null, "e": 5906, "s": 5886, "text": "ToDoubleFunction<T>" }, { "code": null, "e": 5966, "s": 5906, "text": "Represents a function that produces a double-valued result." }, { "code": null, "e": 5987, "s": 5966, "text": "ToIntBiFunction<T,U>" }, { "code": null, "e": 6071, "s": 5987, "text": "Represents a function that accepts two arguments and produces an int-valued result." }, { "code": null, "e": 6088, "s": 6071, "text": "ToIntFunction<T>" }, { "code": null, "e": 6146, "s": 6088, "text": "Represents a function that produces an int-valued result." }, { "code": null, "e": 6168, "s": 6146, "text": "ToLongBiFunction<T,U>" }, { "code": null, "e": 6252, "s": 6168, "text": "Represents a function that accepts two arguments and produces a long-valued result." }, { "code": null, "e": 6270, "s": 6252, "text": "ToLongFunction<T>" }, { "code": null, "e": 6328, "s": 6270, "text": "Represents a function that produces a long-valued result." }, { "code": null, "e": 6345, "s": 6328, "text": "UnaryOperator<T>" }, { "code": null, "e": 6445, "s": 6345, "text": "Represents an operation on a single operand that produces a result of the same type as its operand." }, { "code": null, "e": 6620, "s": 6445, "text": "Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false." }, { "code": null, "e": 6706, "s": 6620, "text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA." }, { "code": null, "e": 8015, "s": 6706, "text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.function.Predicate;\n\npublic class Java8Tester {\n\n public static void main(String args[]) {\n List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);\n\t\t\n // Predicate<Integer> predicate = n -> true\n // n is passed as parameter to test method of Predicate interface\n // test method will always return true no matter what value n has.\n\t\t\n System.out.println(\"Print all numbers:\");\n\t\t\n //pass n as parameter\n eval(list, n->true);\n\t\t\n // Predicate<Integer> predicate1 = n -> n%2 == 0\n // n is passed as parameter to test method of Predicate interface\n // test method will return true if n%2 comes to be zero\n\t\t\n System.out.println(\"Print even numbers:\");\n eval(list, n-> n%2 == 0 );\n\t\t\n // Predicate<Integer> predicate2 = n -> n > 3\n // n is passed as parameter to test method of Predicate interface\n // test method will return true if n is greater than 3.\n\t\t\n System.out.println(\"Print numbers greater than 3:\");\n eval(list, n-> n > 3 );\n }\n\t\n public static void eval(List<Integer> list, Predicate<Integer> predicate) {\n\n for(Integer n: list) {\n\n if(predicate.test(n)) {\n System.out.println(n + \" \");\n }\n }\n }\n}" }, { "code": null, "e": 8102, "s": 8015, "text": "Here we've passed Predicate interface, which takes a single input and returns Boolean." }, { "code": null, "e": 8154, "s": 8102, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 8186, "s": 8154, "text": "C:\\JAVA>javac Java8Tester.java\n" }, { "code": null, "e": 8223, "s": 8186, "text": "Now run the Java8Tester as follows −" }, { "code": null, "e": 8249, "s": 8223, "text": "C:\\JAVA>java Java8Tester\n" }, { "code": null, "e": 8290, "s": 8249, "text": "It should produce the following output −" }, { "code": null, "e": 8398, "s": 8290, "text": "Print all numbers:\n1\n2\n3\n4\n5\n6\n7\n8\n9\nPrint even numbers:\n2\n4\n6\n8\nPrint numbers greater than 3:\n4\n5\n6\n7\n8\n9\n" }, { "code": null, "e": 8431, "s": 8398, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8447, "s": 8431, "text": " Malhar Lathkar" }, { "code": null, "e": 8480, "s": 8447, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8496, "s": 8480, "text": " Malhar Lathkar" }, { "code": null, "e": 8531, "s": 8496, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8545, "s": 8531, "text": " Anadi Sharma" }, { "code": null, "e": 8579, "s": 8545, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 8593, "s": 8579, "text": " Tushar Kale" }, { "code": null, "e": 8630, "s": 8593, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8645, "s": 8630, "text": " Monica Mittal" }, { "code": null, "e": 8678, "s": 8645, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 8697, "s": 8678, "text": " Arnab Chakraborty" }, { "code": null, "e": 8704, "s": 8697, "text": " Print" }, { "code": null, "e": 8715, "s": 8704, "text": " Add Notes" } ]
Animation using clip-path property in CSS - GeeksforGeeks
24 Aug, 2020 The clip-path CSS property is used to clip the region in such a way that element in the clipped regions are shown. In this article, we will see how we can use the clip-path and @keyframes together to create an image animation. Step 1: Create a div with a class container that should include <img> tag. <!DOCTYPE html><html> <head> <title>Clip-Path Animation</title></head> <body> <h2>Welcome to GFG</h2> <!--div with class container contains img tag --> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200717172614/authPreLogo.png" alt="logo"> </div></body> </html> Step 2: Including CSS properties – We will clip the image to polygon initially.Then, bind an animation to img tag.The animation is set for three seconds in an infinite loop.Now, we will specify CSS style inside the @keyframes which will change the clip-path property from one value to another. We will clip the image to polygon initially. Then, bind an animation to img tag. The animation is set for three seconds in an infinite loop. Now, we will specify CSS style inside the @keyframes which will change the clip-path property from one value to another. <!DOCTYPE html><html> <head> <title>Clip-Path Animation</title> <style> .container { /* Aligning all container elements to center using flex */ display: flex; justify-content: center; align-items: center; } img { width: 600px; /* Cliping img into polygon shape*/ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); /* Setting animation for 3s in an infinite loop */ animation: clipPath 3s infinite; } /* Creating animation name clipPath */ @keyframes clipPath { 0% { /* clip-path property initially */ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); } 50% { /* clip-path property at 50% */ clip-path: polygon(50% 50%, 90% 88%, 80% 10%, 20% 10%, 8% 90%); } 100% { /* clip-path property finally */ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); } } </style></head> <body> <h2>Welcome To GFG</h2> <!--div with class container which contain img tag --> <div class="container"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200717172614/authPreLogo.png" alt="Travel"> </div></body> </html> Output: CSS-Misc HTML-Misc CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n24 Aug, 2020" }, { "code": null, "e": 26736, "s": 26621, "text": "The clip-path CSS property is used to clip the region in such a way that element in the clipped regions are shown." }, { "code": null, "e": 26848, "s": 26736, "text": "In this article, we will see how we can use the clip-path and @keyframes together to create an image animation." }, { "code": null, "e": 26923, "s": 26848, "text": "Step 1: Create a div with a class container that should include <img> tag." }, { "code": "<!DOCTYPE html><html> <head> <title>Clip-Path Animation</title></head> <body> <h2>Welcome to GFG</h2> <!--div with class container contains img tag --> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200717172614/authPreLogo.png\" alt=\"logo\"> </div></body> </html>", "e": 27267, "s": 26923, "text": null }, { "code": null, "e": 27302, "s": 27267, "text": "Step 2: Including CSS properties –" }, { "code": null, "e": 27562, "s": 27302, "text": "We will clip the image to polygon initially.Then, bind an animation to img tag.The animation is set for three seconds in an infinite loop.Now, we will specify CSS style inside the @keyframes which will change the clip-path property from one value to another. " }, { "code": null, "e": 27607, "s": 27562, "text": "We will clip the image to polygon initially." }, { "code": null, "e": 27643, "s": 27607, "text": "Then, bind an animation to img tag." }, { "code": null, "e": 27703, "s": 27643, "text": "The animation is set for three seconds in an infinite loop." }, { "code": null, "e": 27825, "s": 27703, "text": "Now, we will specify CSS style inside the @keyframes which will change the clip-path property from one value to another. " }, { "code": "<!DOCTYPE html><html> <head> <title>Clip-Path Animation</title> <style> .container { /* Aligning all container elements to center using flex */ display: flex; justify-content: center; align-items: center; } img { width: 600px; /* Cliping img into polygon shape*/ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); /* Setting animation for 3s in an infinite loop */ animation: clipPath 3s infinite; } /* Creating animation name clipPath */ @keyframes clipPath { 0% { /* clip-path property initially */ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); } 50% { /* clip-path property at 50% */ clip-path: polygon(50% 50%, 90% 88%, 80% 10%, 20% 10%, 8% 90%); } 100% { /* clip-path property finally */ clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); } } </style></head> <body> <h2>Welcome To GFG</h2> <!--div with class container which contain img tag --> <div class=\"container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200717172614/authPreLogo.png\" alt=\"Travel\"> </div></body> </html>", "e": 29363, "s": 27825, "text": null }, { "code": null, "e": 29371, "s": 29363, "text": "Output:" }, { "code": null, "e": 29380, "s": 29371, "text": "CSS-Misc" }, { "code": null, "e": 29390, "s": 29380, "text": "HTML-Misc" }, { "code": null, "e": 29394, "s": 29390, "text": "CSS" }, { "code": null, "e": 29411, "s": 29394, "text": "Web Technologies" }, { "code": null, "e": 29438, "s": 29411, "text": "Web technologies Questions" }, { "code": null, "e": 29536, "s": 29438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29575, "s": 29536, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29612, "s": 29575, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29641, "s": 29612, "text": "Form validation using jQuery" }, { "code": null, "e": 29676, "s": 29641, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29718, "s": 29676, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29758, "s": 29718, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29791, "s": 29758, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29836, "s": 29791, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29879, "s": 29836, "text": "How to fetch data from an API in ReactJS ?" } ]