title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
HTML | input readonly Attribute
16 Apr, 2019 The readonly attribute of <input> element in HTML is used to specify that the input field is read-only. If an input is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute. Syntax: <input readonly> Example: This example uses HTML <input> readonly Attribute. <!DOCTYPE html> <html> <head> <title>HTML Input readonly Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML Input readonly Attribute </h2> <label>Input: <!--A readonly input--> <input type="text" name="value" value = "This input field is readonly" readonly> </label> </body> </html> Output: Supported Browsers: The browser supported by <input> readonly attribute are listed below: Apple Safari 1.0 Google Chrome 1.0 Firefox 1.0 Opera 1.0 Internet Explorer 6.0 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2019" }, { "code": null, "e": 255, "s": 28, "text": "The readonly attribute of <input> element in HTML is used to specify that the input field is read-only. If an input is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute." }, { "code": null, "e": 263, "s": 255, "text": "Syntax:" }, { "code": null, "e": 280, "s": 263, "text": "<input readonly>" }, { "code": null, "e": 340, "s": 280, "text": "Example: This example uses HTML <input> readonly Attribute." }, { "code": "<!DOCTYPE html> <html> <head> <title>HTML Input readonly Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML Input readonly Attribute </h2> <label>Input: <!--A readonly input--> <input type=\"text\" name=\"value\" value = \"This input field is readonly\" readonly> </label> </body> </html> ", "e": 807, "s": 340, "text": null }, { "code": null, "e": 815, "s": 807, "text": "Output:" }, { "code": null, "e": 905, "s": 815, "text": "Supported Browsers: The browser supported by <input> readonly attribute are listed below:" }, { "code": null, "e": 922, "s": 905, "text": "Apple Safari 1.0" }, { "code": null, "e": 940, "s": 922, "text": "Google Chrome 1.0" }, { "code": null, "e": 952, "s": 940, "text": "Firefox 1.0" }, { "code": null, "e": 962, "s": 952, "text": "Opera 1.0" }, { "code": null, "e": 984, "s": 962, "text": "Internet Explorer 6.0" }, { "code": null, "e": 1000, "s": 984, "text": "HTML-Attributes" }, { "code": null, "e": 1005, "s": 1000, "text": "HTML" }, { "code": null, "e": 1022, "s": 1005, "text": "Web Technologies" }, { "code": null, "e": 1027, "s": 1022, "text": "HTML" } ]
Evaluate an array expression with numbers, + and –
15 Jun, 2022 Given an array arr[] of string type which consists of strings “+”, “-” and Numbers. Find the sum of the given array. Examples : Input : arr[] = {"3", "+", "4", "-", "7", "+", "13"} Output : Value = 13 The value of expression 3+4-7+13 is 13. Input : arr[] = { "2", "+", "1", "-8", "+", "13"} Output : Value = 8 Approach : 1) First of all, initialize the sum i.e, sum = 0. 2) Start traversing the array. 3) As there is string of numbers at every even position of the array, so convert this string into integer and store in a variable value by using stoi function in C++. 4) As there is operator at every odd position, check if the operator is ‘+’ or ‘-‘. If it is ‘+’, then add the value to the sum, else subtract from the sum. 5) Finally, return the sum obtained.Below is the implementation of the above approach : C++ Java Python 3 C# PHP Javascript // C++ program to find sum of given array of// string type in integer form#include <bits/stdc++.h>using namespace std; // Function to find the sum of given arrayint calculateSum(string arr[], int n){ // if string is empty if (n == 0) return 0; string s = arr[0]; // stoi function to convert // string into integer int value = stoi(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // stoi function to convert // string into integer int value = stoi(s); // Find operator char operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum;} // Driver Functionint main(){ string arr[] = { "3", "+", "4", "-", "7", "+", "13" }; int n = sizeof(arr) / sizeof(arr[0]); cout << calculateSum(arr, n); return 0;} // Java program to find sum of given array of// string type in integer formimport java.io.*; class GFG { // Function to find the sum of given array public static int calculateSum(String arr[], int n) { // if string is empty if (n == 0) return 0; String s = arr[0]; // parseInt function to convert // string into integer int value = Integer.parseInt(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // parseInt function to convert // string into integer value = Integer.parseInt(s); // Find operator char operation = arr[i - 1].charAt(0); // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } // Driver code public static void main (String[] args) { String arr[] = { "3", "+", "4", "-", "7", "+", "13" }; int n = arr.length; System.out.println( calculateSum(arr, n)); }} // This code in contributed by Upendra bartwal # Python3 program to find sum of given# array of string type in integer form # Function to find the sum of given arraydef calculateSum(arr, n): # if string is empty if (n == 0): return 0 s = arr[0] # stoi function to convert # string into integer value = int(s) sum = value for i in range(2 , n, 2): s = arr[i] # stoi function to convert # string into integer value = int(s) # Find operator operation = arr[i - 1][0] # If operator is equal to '+', # add value in sum variable # else subtract if (operation == '+'): sum += value else: sum -= value return sum # Driver Functionarr = ["3", "+", "4", "-","7", "+", "13"]n = len(arr)print(calculateSum(arr, n)) # This code is contributed by Smitha // C# program to find sum of given array of// string type in integer formusing System; class GFG { // Function to find the sum of given array public static int calculateSum(string []arr, int n) { // if string is empty if (n == 0) return 0; string s = arr[0]; // parseInt function to convert // string into integer int value = int.Parse(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // parseInt function to convert // string into integer value = int.Parse(s); // Find operator char operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } // Driver code public static void Main () { string []arr = { "3", "+", "4", "-", "7", "+", "13" }; int n = arr.Length; Console.Write(calculateSum(arr, n)); }} // This code in contributed by nitin mittal. <?php// php program to find sum of given// array of string type in integer form // Function to find the// sum of given arrayfunction calculateSum($arr,$n){ // if string is empty if ($n == 0) return 0; $s = $arr[0]; // stoi function to convert // string into integer $value = (int)$s; $sum = $value; for ($i = 2; $i < $n; $i = $i + 2) { $s = $arr[$i]; // cast to convert // string into integer $value = (int)$s; // Find operator $operation = $arr[$i - 1]; // If operator is equal to '+', // add value in sum variable // else subtract if ($operation == '+') $sum += $value; else if ($operation == '-') $sum -= $value; } return $sum;} // Driver code $arr = array("3", "+", "4", "-", "7", "+", "13" ); $n = sizeof($arr) / sizeof($arr[0]); echo calculateSum($arr, $n); // This code is contributed by mits?> <script> // Javascript program to find sum of given array of // string type in integer form // Function to find the sum of given array function calculateSum(arr, n) { // if string is empty if (n == 0) return 0; let s = arr[0]; // parseInt function to convert // string into integer let value = parseInt(s); let sum = value; for (let i = 2; i < n; i = i + 2) { s = arr[i]; // parseInt function to convert // string into integer value = parseInt(s); // Find operator let operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } let arr = [ "3", "+", "4", "-", "7", "+", "13" ]; let n = arr.length; document.write(calculateSum(arr, n)); // This code is contributed by vaibhavrabadiya117.</script> Output : 13 Time Complexity: O(n)Auxiliary Space: O(1) Evaluate an array expression with numbers, + and – | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersEvaluate an array expression with numbers, + and – | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:12•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oVW1_g7AnIg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Mithun Kumar nitin mittal Smitha Dinesh Semwal vaibhavrabadiya117 geekygirl2001 expression-evaluation Arrays Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jun, 2022" }, { "code": null, "e": 183, "s": 53, "text": "Given an array arr[] of string type which consists of strings “+”, “-” and Numbers. Find the sum of the given array. Examples : " }, { "code": null, "e": 366, "s": 183, "text": "Input : arr[] = {\"3\", \"+\", \"4\", \"-\", \"7\", \"+\", \"13\"}\nOutput : Value = 13\nThe value of expression 3+4-7+13 is 13.\n\nInput : arr[] = { \"2\", \"+\", \"1\", \"-8\", \"+\", \"13\"}\nOutput : Value = 8" }, { "code": null, "e": 873, "s": 368, "text": "Approach : 1) First of all, initialize the sum i.e, sum = 0. 2) Start traversing the array. 3) As there is string of numbers at every even position of the array, so convert this string into integer and store in a variable value by using stoi function in C++. 4) As there is operator at every odd position, check if the operator is ‘+’ or ‘-‘. If it is ‘+’, then add the value to the sum, else subtract from the sum. 5) Finally, return the sum obtained.Below is the implementation of the above approach : " }, { "code": null, "e": 877, "s": 873, "text": "C++" }, { "code": null, "e": 882, "s": 877, "text": "Java" }, { "code": null, "e": 891, "s": 882, "text": "Python 3" }, { "code": null, "e": 894, "s": 891, "text": "C#" }, { "code": null, "e": 898, "s": 894, "text": "PHP" }, { "code": null, "e": 909, "s": 898, "text": "Javascript" }, { "code": "// C++ program to find sum of given array of// string type in integer form#include <bits/stdc++.h>using namespace std; // Function to find the sum of given arrayint calculateSum(string arr[], int n){ // if string is empty if (n == 0) return 0; string s = arr[0]; // stoi function to convert // string into integer int value = stoi(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // stoi function to convert // string into integer int value = stoi(s); // Find operator char operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum;} // Driver Functionint main(){ string arr[] = { \"3\", \"+\", \"4\", \"-\", \"7\", \"+\", \"13\" }; int n = sizeof(arr) / sizeof(arr[0]); cout << calculateSum(arr, n); return 0;}", "e": 1924, "s": 909, "text": null }, { "code": "// Java program to find sum of given array of// string type in integer formimport java.io.*; class GFG { // Function to find the sum of given array public static int calculateSum(String arr[], int n) { // if string is empty if (n == 0) return 0; String s = arr[0]; // parseInt function to convert // string into integer int value = Integer.parseInt(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // parseInt function to convert // string into integer value = Integer.parseInt(s); // Find operator char operation = arr[i - 1].charAt(0); // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } // Driver code public static void main (String[] args) { String arr[] = { \"3\", \"+\", \"4\", \"-\", \"7\", \"+\", \"13\" }; int n = arr.length; System.out.println( calculateSum(arr, n)); }} // This code in contributed by Upendra bartwal", "e": 3194, "s": 1924, "text": null }, { "code": "# Python3 program to find sum of given# array of string type in integer form # Function to find the sum of given arraydef calculateSum(arr, n): # if string is empty if (n == 0): return 0 s = arr[0] # stoi function to convert # string into integer value = int(s) sum = value for i in range(2 , n, 2): s = arr[i] # stoi function to convert # string into integer value = int(s) # Find operator operation = arr[i - 1][0] # If operator is equal to '+', # add value in sum variable # else subtract if (operation == '+'): sum += value else: sum -= value return sum # Driver Functionarr = [\"3\", \"+\", \"4\", \"-\",\"7\", \"+\", \"13\"]n = len(arr)print(calculateSum(arr, n)) # This code is contributed by Smitha", "e": 4037, "s": 3194, "text": null }, { "code": "// C# program to find sum of given array of// string type in integer formusing System; class GFG { // Function to find the sum of given array public static int calculateSum(string []arr, int n) { // if string is empty if (n == 0) return 0; string s = arr[0]; // parseInt function to convert // string into integer int value = int.Parse(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // parseInt function to convert // string into integer value = int.Parse(s); // Find operator char operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } // Driver code public static void Main () { string []arr = { \"3\", \"+\", \"4\", \"-\", \"7\", \"+\", \"13\" }; int n = arr.Length; Console.Write(calculateSum(arr, n)); }} // This code in contributed by nitin mittal.", "e": 5334, "s": 4037, "text": null }, { "code": "<?php// php program to find sum of given// array of string type in integer form // Function to find the// sum of given arrayfunction calculateSum($arr,$n){ // if string is empty if ($n == 0) return 0; $s = $arr[0]; // stoi function to convert // string into integer $value = (int)$s; $sum = $value; for ($i = 2; $i < $n; $i = $i + 2) { $s = $arr[$i]; // cast to convert // string into integer $value = (int)$s; // Find operator $operation = $arr[$i - 1]; // If operator is equal to '+', // add value in sum variable // else subtract if ($operation == '+') $sum += $value; else if ($operation == '-') $sum -= $value; } return $sum;} // Driver code $arr = array(\"3\", \"+\", \"4\", \"-\", \"7\", \"+\", \"13\" ); $n = sizeof($arr) / sizeof($arr[0]); echo calculateSum($arr, $n); // This code is contributed by mits?>", "e": 6318, "s": 5334, "text": null }, { "code": "<script> // Javascript program to find sum of given array of // string type in integer form // Function to find the sum of given array function calculateSum(arr, n) { // if string is empty if (n == 0) return 0; let s = arr[0]; // parseInt function to convert // string into integer let value = parseInt(s); let sum = value; for (let i = 2; i < n; i = i + 2) { s = arr[i]; // parseInt function to convert // string into integer value = parseInt(s); // Find operator let operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } let arr = [ \"3\", \"+\", \"4\", \"-\", \"7\", \"+\", \"13\" ]; let n = arr.length; document.write(calculateSum(arr, n)); // This code is contributed by vaibhavrabadiya117.</script>", "e": 7480, "s": 6318, "text": null }, { "code": null, "e": 7491, "s": 7480, "text": "Output : " }, { "code": null, "e": 7495, "s": 7491, "text": "13 " }, { "code": null, "e": 7538, "s": 7495, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 8456, "s": 7538, "text": "Evaluate an array expression with numbers, + and – | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersEvaluate an array expression with numbers, + and – | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:12•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oVW1_g7AnIg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 8471, "s": 8458, "text": "Mithun Kumar" }, { "code": null, "e": 8484, "s": 8471, "text": "nitin mittal" }, { "code": null, "e": 8505, "s": 8484, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 8524, "s": 8505, "text": "vaibhavrabadiya117" }, { "code": null, "e": 8538, "s": 8524, "text": "geekygirl2001" }, { "code": null, "e": 8560, "s": 8538, "text": "expression-evaluation" }, { "code": null, "e": 8567, "s": 8560, "text": "Arrays" }, { "code": null, "e": 8575, "s": 8567, "text": "Strings" }, { "code": null, "e": 8582, "s": 8575, "text": "Arrays" }, { "code": null, "e": 8590, "s": 8582, "text": "Strings" } ]
Unix / Linux - Shell Quoting Mechanisms
In this chapter, we will discuss in detail about the Shell quoting mechanisms. We will start by discussing the metacharacters. Unix Shell provides various metacharacters which have special meaning while using them in any Shell Script and causes termination of a word unless quoted. For example, ? matches with a single character while listing files in a directory and an * matches more than one character. Here is a list of most of the shell special characters (also called metacharacters) − * ? [ ] ' " \ $ ; & ( ) | ^ < > new-line space tab A character may be quoted (i.e., made to stand for itself) by preceding it with a \. Following example shows how to print a * or a ? − #!/bin/sh echo Hello; Word Upon execution, you will receive the following result − Hello ./test.sh: line 2: Word: command not found shell returned 127 Let us now try using a quoted character − #!/bin/sh echo Hello\; Word Upon execution, you will receive the following result − Hello; Word The $ sign is one of the metacharacters, so it must be quoted to avoid special handling by the shell − #!/bin/sh echo "I have \$1200" Upon execution, you will receive the following result − I have $1200 The following table lists the four forms of quoting − Single quote All special characters between these quotes lose their special meaning. Double quote Most special characters between these quotes lose their special meaning with these exceptions − $ ` \$ \' \" \\ Backslash Any character immediately following the backslash loses its special meaning. Back quote Anything in between back quotes would be treated as a command and would be executed. Consider an echo command that contains many special shell characters − echo <-$1500.**>; (update?) [y|n] Putting a backslash in front of each special character is tedious and makes the line difficult to read − echo \<-\$1500.\*\*\>\; \(update\?\) \[y\|n\] There is an easy way to quote a large group of characters. Put a single quote (') at the beginning and at the end of the string − echo '<-$1500.**>; (update?) [y|n]' Characters within single quotes are quoted just as if a backslash is in front of each character. With this, the echo command displays in a proper way. If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash (\) as follows − echo 'It\'s Shell Programming Try to execute the following shell script. This shell script makes use of single quote − VAR=ZARA echo '$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]' Upon execution, you will receive the following result − $VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ] This is not what had to be displayed. It is obvious that single quotes prevent variable substitution. If you want to substitute variable values and to make inverted commas work as expected, then you would need to put your commands in double quotes as follows − VAR=ZARA echo "$VAR owes <-\$1500.**>; [ as of (`date +%m/%d`) ]" Upon execution, you will receive the following result − ZARA owes <-$1500.**>; [ as of (07/02) ] Double quotes take away the special meaning of all characters except the following − $ for parameter substitution $ for parameter substitution Backquotes for command substitution Backquotes for command substitution \$ to enable literal dollar signs \$ to enable literal dollar signs \` to enable literal backquotes \` to enable literal backquotes \" to enable embedded double quotes \" to enable embedded double quotes \\ to enable embedded backslashes \\ to enable embedded backslashes All other \ characters are literal (not special) All other \ characters are literal (not special) Characters within single quotes are quoted just as if a backslash is in front of each character. This helps the echo command display properly. If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash (\) as follows − echo 'It\'s Shell Programming' Putting any Shell command in between backquotes executes the command. Here is the simple syntax to put any Shell command in between backquotes − var=`command` The date command is executed in the following example and the produced result is stored in DATA variable. DATE=`date` echo "Current Date: $DATE" Upon execution, you will receive the following result − Current Date: Thu Jul 2 05:28:45 MST 2009 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2874, "s": 2747, "text": "In this chapter, we will discuss in detail about the Shell quoting mechanisms. We will start by discussing the metacharacters." }, { "code": null, "e": 3029, "s": 2874, "text": "Unix Shell provides various metacharacters which have special meaning while using them in any Shell Script and causes termination of a word unless quoted." }, { "code": null, "e": 3239, "s": 3029, "text": "For example, ? matches with a single character while listing files in a directory and an * matches more than one character. Here is a list of most of the shell special characters (also called metacharacters) −" }, { "code": null, "e": 3291, "s": 3239, "text": "* ? [ ] ' \" \\ $ ; & ( ) | ^ < > new-line space tab\n" }, { "code": null, "e": 3376, "s": 3291, "text": "A character may be quoted (i.e., made to stand for itself) by preceding it with a \\." }, { "code": null, "e": 3426, "s": 3376, "text": "Following example shows how to print a * or a ? −" }, { "code": null, "e": 3454, "s": 3426, "text": "#!/bin/sh\n\necho Hello; Word" }, { "code": null, "e": 3510, "s": 3454, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 3580, "s": 3510, "text": "Hello\n./test.sh: line 2: Word: command not found\n\nshell returned 127\n" }, { "code": null, "e": 3622, "s": 3580, "text": "Let us now try using a quoted character −" }, { "code": null, "e": 3651, "s": 3622, "text": "#!/bin/sh\n\necho Hello\\; Word" }, { "code": null, "e": 3707, "s": 3651, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 3720, "s": 3707, "text": "Hello; Word\n" }, { "code": null, "e": 3823, "s": 3720, "text": "The $ sign is one of the metacharacters, so it must be quoted to avoid special handling by the shell −" }, { "code": null, "e": 3855, "s": 3823, "text": "#!/bin/sh\n\necho \"I have \\$1200\"" }, { "code": null, "e": 3911, "s": 3855, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 3925, "s": 3911, "text": "I have $1200\n" }, { "code": null, "e": 3979, "s": 3925, "text": "The following table lists the four forms of quoting −" }, { "code": null, "e": 3992, "s": 3979, "text": "Single quote" }, { "code": null, "e": 4064, "s": 3992, "text": "All special characters between these quotes lose their special meaning." }, { "code": null, "e": 4077, "s": 4064, "text": "Double quote" }, { "code": null, "e": 4173, "s": 4077, "text": "Most special characters between these quotes lose their special meaning with these exceptions −" }, { "code": null, "e": 4175, "s": 4173, "text": "$" }, { "code": null, "e": 4177, "s": 4175, "text": "`" }, { "code": null, "e": 4180, "s": 4177, "text": "\\$" }, { "code": null, "e": 4183, "s": 4180, "text": "\\'" }, { "code": null, "e": 4186, "s": 4183, "text": "\\\"" }, { "code": null, "e": 4189, "s": 4186, "text": "\\\\" }, { "code": null, "e": 4199, "s": 4189, "text": "Backslash" }, { "code": null, "e": 4276, "s": 4199, "text": "Any character immediately following the backslash loses its special meaning." }, { "code": null, "e": 4287, "s": 4276, "text": "Back quote" }, { "code": null, "e": 4372, "s": 4287, "text": "Anything in between back quotes would be treated as a command and would be executed." }, { "code": null, "e": 4443, "s": 4372, "text": "Consider an echo command that contains many special shell characters −" }, { "code": null, "e": 4478, "s": 4443, "text": "echo <-$1500.**>; (update?) [y|n]\n" }, { "code": null, "e": 4583, "s": 4478, "text": "Putting a backslash in front of each special character is tedious and makes the line difficult to read −" }, { "code": null, "e": 4630, "s": 4583, "text": "echo \\<-\\$1500.\\*\\*\\>\\; \\(update\\?\\) \\[y\\|n\\]\n" }, { "code": null, "e": 4760, "s": 4630, "text": "There is an easy way to quote a large group of characters. Put a single quote (') at the beginning and at the end of the string −" }, { "code": null, "e": 4797, "s": 4760, "text": "echo '<-$1500.**>; (update?) [y|n]'\n" }, { "code": null, "e": 4948, "s": 4797, "text": "Characters within single quotes are quoted just as if a backslash is in front of each character. With this, the echo command displays in a proper way." }, { "code": null, "e": 5128, "s": 4948, "text": "If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash (\\) as follows −" }, { "code": null, "e": 5159, "s": 5128, "text": "echo 'It\\'s Shell Programming\n" }, { "code": null, "e": 5248, "s": 5159, "text": "Try to execute the following shell script. This shell script makes use of single quote −" }, { "code": null, "e": 5313, "s": 5248, "text": "VAR=ZARA\necho '$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]'" }, { "code": null, "e": 5369, "s": 5313, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 5419, "s": 5369, "text": "$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]\n" }, { "code": null, "e": 5680, "s": 5419, "text": "This is not what had to be displayed. It is obvious that single quotes prevent variable substitution. If you want to substitute variable values and to make inverted commas work as expected, then you would need to put your commands in double quotes as follows −" }, { "code": null, "e": 5746, "s": 5680, "text": "VAR=ZARA\necho \"$VAR owes <-\\$1500.**>; [ as of (`date +%m/%d`) ]\"" }, { "code": null, "e": 5802, "s": 5746, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 5844, "s": 5802, "text": "ZARA owes <-$1500.**>; [ as of (07/02) ]\n" }, { "code": null, "e": 5929, "s": 5844, "text": "Double quotes take away the special meaning of all characters except the following −" }, { "code": null, "e": 5958, "s": 5929, "text": "$ for parameter substitution" }, { "code": null, "e": 5987, "s": 5958, "text": "$ for parameter substitution" }, { "code": null, "e": 6023, "s": 5987, "text": "Backquotes for command substitution" }, { "code": null, "e": 6059, "s": 6023, "text": "Backquotes for command substitution" }, { "code": null, "e": 6093, "s": 6059, "text": "\\$ to enable literal dollar signs" }, { "code": null, "e": 6127, "s": 6093, "text": "\\$ to enable literal dollar signs" }, { "code": null, "e": 6159, "s": 6127, "text": "\\` to enable literal backquotes" }, { "code": null, "e": 6191, "s": 6159, "text": "\\` to enable literal backquotes" }, { "code": null, "e": 6227, "s": 6191, "text": "\\\" to enable embedded double quotes" }, { "code": null, "e": 6263, "s": 6227, "text": "\\\" to enable embedded double quotes" }, { "code": null, "e": 6297, "s": 6263, "text": "\\\\ to enable embedded backslashes" }, { "code": null, "e": 6331, "s": 6297, "text": "\\\\ to enable embedded backslashes" }, { "code": null, "e": 6380, "s": 6331, "text": "All other \\ characters are literal (not special)" }, { "code": null, "e": 6429, "s": 6380, "text": "All other \\ characters are literal (not special)" }, { "code": null, "e": 6572, "s": 6429, "text": "Characters within single quotes are quoted just as if a backslash is in front of each character. This helps the echo command display properly." }, { "code": null, "e": 6752, "s": 6572, "text": "If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash (\\) as follows −" }, { "code": null, "e": 6784, "s": 6752, "text": "echo 'It\\'s Shell Programming'\n" }, { "code": null, "e": 6854, "s": 6784, "text": "Putting any Shell command in between backquotes executes the command." }, { "code": null, "e": 6929, "s": 6854, "text": "Here is the simple syntax to put any Shell command in between backquotes −" }, { "code": null, "e": 6944, "s": 6929, "text": "var=`command`\n" }, { "code": null, "e": 7050, "s": 6944, "text": "The date command is executed in the following example and the produced result is stored in DATA variable." }, { "code": null, "e": 7090, "s": 7050, "text": "DATE=`date`\n\necho \"Current Date: $DATE\"" }, { "code": null, "e": 7146, "s": 7090, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 7190, "s": 7146, "text": "Current Date: Thu Jul 2 05:28:45 MST 2009\n" }, { "code": null, "e": 7225, "s": 7190, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 7253, "s": 7225, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7287, "s": 7253, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7304, "s": 7287, "text": " Frahaan Hussain" }, { "code": null, "e": 7337, "s": 7304, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 7348, "s": 7337, "text": " Pradeep D" }, { "code": null, "e": 7383, "s": 7348, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7399, "s": 7383, "text": " Musab Zayadneh" }, { "code": null, "e": 7432, "s": 7399, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 7444, "s": 7432, "text": " GUHARAJANM" }, { "code": null, "e": 7476, "s": 7444, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 7484, "s": 7476, "text": " Uplatz" }, { "code": null, "e": 7491, "s": 7484, "text": " Print" }, { "code": null, "e": 7502, "s": 7491, "text": " Add Notes" } ]
What is the importance of SwingUtilities class in Java?
In Java, after swing components displayed on the screen, they can be operated by only one thread called Event Handling Thread. We can write our code in a separate block and can give this block reference to Event Handling thread. The SwingUtilities class has two important static methods, invokeAndWait() and invokeLater() to use to put references to blocks of code onto the event queue. public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException public static void invokeLater(Runnable doRun) The parameter doRun is a reference to an instance of Runnable interface. In this case, the Runnable interface will not be passed to the constructor of a Thread. The Runnable interface is simply being used as a means to identify the entry point for the event thread. Just as a newly spawned thread will invoke run(), the event thread will invoke run() method when it has processed all the other events pending in the queue. An InterruptedException is thrown if the thread that called invokeAndWait() or invokeLater() is interrupted before the block of code referred to by target completes. An InvocationTargetException is thrown if an uncaught exception is thrown by the code inside the run() method. import javax.swing.*; import java.lang.reflect.InvocationTargetException; public class SwingUtilitiesTest { public static void main(String[] args) { final JButton button = new JButton("Not Changed"); JPanel panel = new JPanel(); panel.add(button); JFrame f = new JFrame("InvokeAndWaitMain"); f.setContentPane(panel); f.setSize(300, 100); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println(Thread.currentThread().getName()+" is going into sleep for 3 seconds"); try { Thread.sleep(3000); } catch(Exception e){ } //Preparing code for label change Runnable r = new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"is going into sleep for 10 seconds"); try { Thread.sleep(10000); } catch(Exception e){ } button.setText("Button Text Changed by "+ Thread.currentThread().getName()); System.out.println("Button changes ended"); } }; System.out.println("Component changes put on the event thread by main thread"); try { SwingUtilities.invokeAndWait(r); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } System.out.println("Main thread reached end"); } }
[ { "code": null, "e": 1449, "s": 1062, "text": "In Java, after swing components displayed on the screen, they can be operated by only one thread called Event Handling Thread. We can write our code in a separate block and can give this block reference to Event Handling thread. The SwingUtilities class has two important static methods, invokeAndWait() and invokeLater() to use to put references to blocks of code onto the event queue." }, { "code": null, "e": 1600, "s": 1449, "text": "public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException\npublic static void invokeLater(Runnable doRun)" }, { "code": null, "e": 2300, "s": 1600, "text": "The parameter doRun is a reference to an instance of Runnable interface. In this case, the Runnable interface will not be passed to the constructor of a Thread. The Runnable interface is simply being used as a means to identify the entry point for the event thread. Just as a newly spawned thread will invoke run(), the event thread will invoke run() method when it has processed all the other events pending in the queue. An InterruptedException is thrown if the thread that called invokeAndWait() or invokeLater() is interrupted before the block of code referred to by target completes. An InvocationTargetException is thrown if an uncaught exception is thrown by the code inside the run() method." }, { "code": null, "e": 3723, "s": 2300, "text": "import javax.swing.*;\nimport java.lang.reflect.InvocationTargetException;\npublic class SwingUtilitiesTest {\n public static void main(String[] args) {\n final JButton button = new JButton(\"Not Changed\");\n JPanel panel = new JPanel();\n panel.add(button);\n JFrame f = new JFrame(\"InvokeAndWaitMain\");\n f.setContentPane(panel);\n f.setSize(300, 100);\n f.setVisible(true);\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n System.out.println(Thread.currentThread().getName()+\" is going into sleep for 3 seconds\");\n try {\n Thread.sleep(3000);\n } catch(Exception e){ }\n //Preparing code for label change\n Runnable r = new Runnable() {\n @Override\n public void run() {\n System.out.println(Thread.currentThread().getName()+\"is going into sleep for 10 seconds\");\n try {\n Thread.sleep(10000);\n } catch(Exception e){ }\n button.setText(\"Button Text Changed by \"+ Thread.currentThread().getName());\n System.out.println(\"Button changes ended\");\n }\n };\n System.out.println(\"Component changes put on the event thread by main thread\");\n try {\n SwingUtilities.invokeAndWait(r);\n } catch (InvocationTargetException | InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"Main thread reached end\");\n }\n}" } ]
Deploy a machine learning application with Streamlit and Docker on AWS | by Kostas Stathoulopoulos | Towards Data Science
In the previous blog, we discussed how to build a semantic search engine with sentence transformers and Faiss. Here, we will create a Streamlit application and deploy the search engine both locally and on AWS Elastic Beanstalk. If you want to jump straight into the code, check out the GitHub repo! Streamlit is an open-source Python library that makes it easy to create applications for machine learning and data science. With Streamlit, you don’t need to learn Flask or any frontend development and you can focus solely on your application. Our app will help users search for academic articles. Users will type text queries in a search box and retrieve the most relevant publications and their metadata. They will also be able to choose the number of returned results and filter them by the number of paper citations and the publication year. Behind the scenes, we will vectorise the search query with a sentence-DistilBERT model and pass it onto a pre-built Faiss index for similarity matching. Faiss will measure the L2 distance between the query vector and the indexed paper vectors and return a list of paper IDs that are closest to the query. Let’s see how the app will look like and then dive into the code. Let’s import the required Python packages. Next, we will write a few functions to load the data, transformer model and Faiss index. We will cache them with Streamlit’s @st.cache decorator to speed up our application. Finally, we will create the main body of the application. Let’s examine the code line by line: Lines 4–6: Call the functions shown above to load and cache the data and models. Line 8: Set the title of our application. Line 11: Create a multi-line text input widget on the main body of the page. That’s our search box! Lines 14–17: Create the search engine filters and place them on a sidebar. Line 22: Do a semantic search for a given text query and return the paper IDs of the most relevant results. These will be ordered based on their similarity to the text query. Lines 24–28: Filter the data by publication year and the number of papers’ citations. Lines 30–34: For each paper ID retrieved in Line 22, fetch its metadata from the filtered dataset. Lines 36–43: Print the paper’s metadata, namely the title, citations, publication year and abstract. We will package the application with all of its dependencies in a container using Docker. We will create a Dockerfile which is a text document containing the commands (i.e. instructions) to assemble an image. If you are not familiar with Docker, this guide offers an in-depth introduction. FROM python:3.8-slim-busterCOPY . /appWORKDIR /appRUN pip install -r requirements.txtEXPOSE 8501ENTRYPOINT ["streamlit","run"]CMD ["app.py"] Let’s explain line by line what this Dockerfile will do: Line 1: Fetch a Python base image. Line 2: Copy the contents of this GitHub repo into a directory called /app Line 3: Change the working directory to /app Line 4: Pip install the requirements.txtfile. Line 5: Make the container listen on the 8501 port at runtime. Line 6: Execute the command streamlit runwhen starting the container. Line 7: Specify the arguments that will be fed to the ENTRYPOINT, in our case, the file name of our app. Now, assuming that Docker is running on your machine, we can build the image with the following command: $ docker build -t <USERNAME>/<YOUR_IMAGE_NAME> . The build command will create an image with the Dockerfile’s spec. Now, we are ready to deploy our application! Deploying our semantic search engine locally is straightforward. Having built the image, we will use the run command to spin our application in a container. We will also add the -p argument to publish the container’s port at 8501. $ docker run -p 8501:8501 <USERNAME>/<YOUR_IMAGE_NAME> You can access the application at the following address: http://localhost:8501/ To deploy our application on AWS, we need to publish our image on a registry which can be accessed by the cloud provider. For convenience, let’s go with Docker Hub. If you haven’t pushed an image before, the client might ask you to login. Provide the same credentials that you used for logging into Docker Hub. Note that this step might take a while as our image is fairly large! $ docker push <USERNAME>/<YOUR_IMAGE_NAME> . Publishing your image on a public registry is not compulsory, however, it simplifies the deployment by skipping few configuration steps. Now, we are almost ready to deploy our image on AWS Elastic Beanstalk (EB). Let’s list the steps: Login to AWS Console and search for Elastic Beanstalk. Click on the Create Application button and name your application. Choose Docker as the platform. Now, we need to upload our code from a local file. Since our application is dockerized, we only need to provide the details of the container. We will do this by clicking on the Choose file button and uploading the Dockerrun.aws.json file. This is an AWS-specific file that share with EB our application’s details and the docker configuration. Before uploading it, make sure you have changed the image name in the Dockerrun.aws.json from kstathou/vector_engine to the <USERNAME>/<YOUR_IMAGE_NAME> you used previously. Once you upload the file, click on Configure more options. Edit Instances and Capacity. Starting with Instances, change the Root volume type to General Purpose (SSD) and the Size to 8GB. Scroll to the bottom of the page and click on Save. Next, choose Capacity and change the Instance type from t2.micro to t3.medium. Note that the EC2 instance we selected is not in the free tier and you will be charged for using it. Make sure you shut down your application once you are done with it! Click on Create app. EB will take a few minutes to deploy our application. Once it’s done, you will be able to access and share the semantic search engine via its URL! In this tutorial, I showed you how to prototype an application with Streamlit and deploy with Docker both locally and on AWS Elastic Beanstalk. Let me know in the comments if you have any questions. The code is available on GitHub!
[ { "code": null, "e": 399, "s": 171, "text": "In the previous blog, we discussed how to build a semantic search engine with sentence transformers and Faiss. Here, we will create a Streamlit application and deploy the search engine both locally and on AWS Elastic Beanstalk." }, { "code": null, "e": 470, "s": 399, "text": "If you want to jump straight into the code, check out the GitHub repo!" }, { "code": null, "e": 714, "s": 470, "text": "Streamlit is an open-source Python library that makes it easy to create applications for machine learning and data science. With Streamlit, you don’t need to learn Flask or any frontend development and you can focus solely on your application." }, { "code": null, "e": 1016, "s": 714, "text": "Our app will help users search for academic articles. Users will type text queries in a search box and retrieve the most relevant publications and their metadata. They will also be able to choose the number of returned results and filter them by the number of paper citations and the publication year." }, { "code": null, "e": 1321, "s": 1016, "text": "Behind the scenes, we will vectorise the search query with a sentence-DistilBERT model and pass it onto a pre-built Faiss index for similarity matching. Faiss will measure the L2 distance between the query vector and the indexed paper vectors and return a list of paper IDs that are closest to the query." }, { "code": null, "e": 1387, "s": 1321, "text": "Let’s see how the app will look like and then dive into the code." }, { "code": null, "e": 1430, "s": 1387, "text": "Let’s import the required Python packages." }, { "code": null, "e": 1604, "s": 1430, "text": "Next, we will write a few functions to load the data, transformer model and Faiss index. We will cache them with Streamlit’s @st.cache decorator to speed up our application." }, { "code": null, "e": 1662, "s": 1604, "text": "Finally, we will create the main body of the application." }, { "code": null, "e": 1699, "s": 1662, "text": "Let’s examine the code line by line:" }, { "code": null, "e": 1780, "s": 1699, "text": "Lines 4–6: Call the functions shown above to load and cache the data and models." }, { "code": null, "e": 1822, "s": 1780, "text": "Line 8: Set the title of our application." }, { "code": null, "e": 1922, "s": 1822, "text": "Line 11: Create a multi-line text input widget on the main body of the page. That’s our search box!" }, { "code": null, "e": 1997, "s": 1922, "text": "Lines 14–17: Create the search engine filters and place them on a sidebar." }, { "code": null, "e": 2172, "s": 1997, "text": "Line 22: Do a semantic search for a given text query and return the paper IDs of the most relevant results. These will be ordered based on their similarity to the text query." }, { "code": null, "e": 2258, "s": 2172, "text": "Lines 24–28: Filter the data by publication year and the number of papers’ citations." }, { "code": null, "e": 2357, "s": 2258, "text": "Lines 30–34: For each paper ID retrieved in Line 22, fetch its metadata from the filtered dataset." }, { "code": null, "e": 2458, "s": 2357, "text": "Lines 36–43: Print the paper’s metadata, namely the title, citations, publication year and abstract." }, { "code": null, "e": 2748, "s": 2458, "text": "We will package the application with all of its dependencies in a container using Docker. We will create a Dockerfile which is a text document containing the commands (i.e. instructions) to assemble an image. If you are not familiar with Docker, this guide offers an in-depth introduction." }, { "code": null, "e": 2889, "s": 2748, "text": "FROM python:3.8-slim-busterCOPY . /appWORKDIR /appRUN pip install -r requirements.txtEXPOSE 8501ENTRYPOINT [\"streamlit\",\"run\"]CMD [\"app.py\"]" }, { "code": null, "e": 2946, "s": 2889, "text": "Let’s explain line by line what this Dockerfile will do:" }, { "code": null, "e": 2981, "s": 2946, "text": "Line 1: Fetch a Python base image." }, { "code": null, "e": 3056, "s": 2981, "text": "Line 2: Copy the contents of this GitHub repo into a directory called /app" }, { "code": null, "e": 3101, "s": 3056, "text": "Line 3: Change the working directory to /app" }, { "code": null, "e": 3147, "s": 3101, "text": "Line 4: Pip install the requirements.txtfile." }, { "code": null, "e": 3210, "s": 3147, "text": "Line 5: Make the container listen on the 8501 port at runtime." }, { "code": null, "e": 3280, "s": 3210, "text": "Line 6: Execute the command streamlit runwhen starting the container." }, { "code": null, "e": 3385, "s": 3280, "text": "Line 7: Specify the arguments that will be fed to the ENTRYPOINT, in our case, the file name of our app." }, { "code": null, "e": 3490, "s": 3385, "text": "Now, assuming that Docker is running on your machine, we can build the image with the following command:" }, { "code": null, "e": 3539, "s": 3490, "text": "$ docker build -t <USERNAME>/<YOUR_IMAGE_NAME> ." }, { "code": null, "e": 3651, "s": 3539, "text": "The build command will create an image with the Dockerfile’s spec. Now, we are ready to deploy our application!" }, { "code": null, "e": 3882, "s": 3651, "text": "Deploying our semantic search engine locally is straightforward. Having built the image, we will use the run command to spin our application in a container. We will also add the -p argument to publish the container’s port at 8501." }, { "code": null, "e": 3937, "s": 3882, "text": "$ docker run -p 8501:8501 <USERNAME>/<YOUR_IMAGE_NAME>" }, { "code": null, "e": 3994, "s": 3937, "text": "You can access the application at the following address:" }, { "code": null, "e": 4017, "s": 3994, "text": "http://localhost:8501/" }, { "code": null, "e": 4397, "s": 4017, "text": "To deploy our application on AWS, we need to publish our image on a registry which can be accessed by the cloud provider. For convenience, let’s go with Docker Hub. If you haven’t pushed an image before, the client might ask you to login. Provide the same credentials that you used for logging into Docker Hub. Note that this step might take a while as our image is fairly large!" }, { "code": null, "e": 4442, "s": 4397, "text": "$ docker push <USERNAME>/<YOUR_IMAGE_NAME> ." }, { "code": null, "e": 4579, "s": 4442, "text": "Publishing your image on a public registry is not compulsory, however, it simplifies the deployment by skipping few configuration steps." }, { "code": null, "e": 4677, "s": 4579, "text": "Now, we are almost ready to deploy our image on AWS Elastic Beanstalk (EB). Let’s list the steps:" }, { "code": null, "e": 4732, "s": 4677, "text": "Login to AWS Console and search for Elastic Beanstalk." }, { "code": null, "e": 4798, "s": 4732, "text": "Click on the Create Application button and name your application." }, { "code": null, "e": 5405, "s": 4798, "text": "Choose Docker as the platform. Now, we need to upload our code from a local file. Since our application is dockerized, we only need to provide the details of the container. We will do this by clicking on the Choose file button and uploading the Dockerrun.aws.json file. This is an AWS-specific file that share with EB our application’s details and the docker configuration. Before uploading it, make sure you have changed the image name in the Dockerrun.aws.json from kstathou/vector_engine to the <USERNAME>/<YOUR_IMAGE_NAME> you used previously. Once you upload the file, click on Configure more options." }, { "code": null, "e": 5833, "s": 5405, "text": "Edit Instances and Capacity. Starting with Instances, change the Root volume type to General Purpose (SSD) and the Size to 8GB. Scroll to the bottom of the page and click on Save. Next, choose Capacity and change the Instance type from t2.micro to t3.medium. Note that the EC2 instance we selected is not in the free tier and you will be charged for using it. Make sure you shut down your application once you are done with it!" }, { "code": null, "e": 6001, "s": 5833, "text": "Click on Create app. EB will take a few minutes to deploy our application. Once it’s done, you will be able to access and share the semantic search engine via its URL!" }, { "code": null, "e": 6200, "s": 6001, "text": "In this tutorial, I showed you how to prototype an application with Streamlit and deploy with Docker both locally and on AWS Elastic Beanstalk. Let me know in the comments if you have any questions." } ]
jQuery load() with Examples
The load() method in jQuery is used to load data from a server and puts the returned data into the selected element The syntax is as follows − $(selector).load(url,data,function(response,status,xhr)) Above, URL is the URL to be loaded. The data parameter is the data to send to the server, whereas the callback function runs when the load() completes. Let us now see an example to implement the jQuery load() method − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").load("new.txt"); }); }); </script> </head> <body> <div> <p>Demo text...</p> </div> <button>Load Content from server</button> </body> </html> This will produce the following output − Click the above button to load content from “new.txt” − The content visible above is the new.txt file.
[ { "code": null, "e": 1178, "s": 1062, "text": "The load() method in jQuery is used to load data from a server and puts the returned data into the selected element" }, { "code": null, "e": 1205, "s": 1178, "text": "The syntax is as follows −" }, { "code": null, "e": 1262, "s": 1205, "text": "$(selector).load(url,data,function(response,status,xhr))" }, { "code": null, "e": 1414, "s": 1262, "text": "Above, URL is the URL to be loaded. The data parameter is the data to send to the server, whereas the callback function runs when the load() completes." }, { "code": null, "e": 1480, "s": 1414, "text": "Let us now see an example to implement the jQuery load() method −" }, { "code": null, "e": 1491, "s": 1480, "text": " Live Demo" }, { "code": null, "e": 1856, "s": 1491, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $(\"div\").load(\"new.txt\");\n });\n });\n</script>\n</head>\n<body>\n<div>\n<p>Demo text...</p>\n</div>\n<button>Load Content from server</button>\n</body>\n</html>" }, { "code": null, "e": 1897, "s": 1856, "text": "This will produce the following output −" }, { "code": null, "e": 1953, "s": 1897, "text": "Click the above button to load content from “new.txt” −" }, { "code": null, "e": 2000, "s": 1953, "text": "The content visible above is the new.txt file." } ]
__file__ (A Special variable) in Python - GeeksforGeeks
08 Aug, 2021 A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a “Special way”. This Special way depends on the variable that is being used. Note: For more information, refer to Dunder or magic methods in Python __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system. The import system can choose to leave the variable empty when there is no semantic meaning, that is when the module/file is imported from the database. This attribute is a String. This can be used to know the path of the module you are using. To understand the usage of __file__ consider the following example. Example: Let’s create a module named HelloWorld and store it as a .py file. python # Creating a module named# HelloWorld def hello(): print("This is imported from HelloWorld") # This code is improved by gherson283 Now let’s create another file named GFG.py that imports the above-created module to show the use of __file__ variable. python # Importing the above# created moduleimport HelloWorld # Calling the method# created inside the moduleHelloWorld.hello() # printing the __file__# variableprint(HelloWorld.__file__) Output: gherson283 python-utility Python Technical Scripter 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() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23926, "s": 23898, "text": "\n08 Aug, 2021" }, { "code": null, "e": 24161, "s": 23926, "text": "A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a “Special way”. This Special way depends on the variable that is being used. " }, { "code": null, "e": 24233, "s": 24161, "text": "Note: For more information, refer to Dunder or magic methods in Python " }, { "code": null, "e": 24812, "s": 24233, "text": "__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system. The import system can choose to leave the variable empty when there is no semantic meaning, that is when the module/file is imported from the database. This attribute is a String. This can be used to know the path of the module you are using. To understand the usage of __file__ consider the following example. " }, { "code": null, "e": 24889, "s": 24812, "text": "Example: Let’s create a module named HelloWorld and store it as a .py file. " }, { "code": null, "e": 24896, "s": 24889, "text": "python" }, { "code": "# Creating a module named# HelloWorld def hello(): print(\"This is imported from HelloWorld\") # This code is improved by gherson283", "e": 25034, "s": 24896, "text": null }, { "code": null, "e": 25154, "s": 25034, "text": "Now let’s create another file named GFG.py that imports the above-created module to show the use of __file__ variable. " }, { "code": null, "e": 25161, "s": 25154, "text": "python" }, { "code": "# Importing the above# created moduleimport HelloWorld # Calling the method# created inside the moduleHelloWorld.hello() # printing the __file__# variableprint(HelloWorld.__file__)", "e": 25343, "s": 25161, "text": null }, { "code": null, "e": 25352, "s": 25343, "text": "Output: " }, { "code": null, "e": 25365, "s": 25354, "text": "gherson283" }, { "code": null, "e": 25380, "s": 25365, "text": "python-utility" }, { "code": null, "e": 25387, "s": 25380, "text": "Python" }, { "code": null, "e": 25406, "s": 25387, "text": "Technical Scripter" }, { "code": null, "e": 25504, "s": 25406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25513, "s": 25504, "text": "Comments" }, { "code": null, "e": 25526, "s": 25513, "text": "Old Comments" }, { "code": null, "e": 25558, "s": 25526, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25614, "s": 25558, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25656, "s": 25614, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25698, "s": 25656, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25734, "s": 25698, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25773, "s": 25734, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25795, "s": 25773, "text": "Defaultdict in Python" }, { "code": null, "e": 25826, "s": 25795, "text": "Python | os.path.join() method" }, { "code": null, "e": 25853, "s": 25826, "text": "Python Classes and Objects" } ]
Step-by-Step Guide — Building a Prediction Model in Python | by Behic Guven | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. In this post, I will show you how to build a program that can predict the price of a specific stock. This is a great project of using machine learning in finance. If we want a machine to make predictions for us, we should definitely train it well with some data. First, for those who are new to python, I will introduce it to you. Then, we will start working on our prediction model. As mentioned in the subtitle, we will be using Apple Stock Data. If you are wondering is it free to get that data, the answer is absolutely yes. The stock data is available on NASDAQ official website. The NASDAQ (National Association of Securities Dealers Automated Quotations) is an electronic stock exchange with more than 3,300 company listings. The Apple stock data can be downloaded from here. On this website, you can also find stock data for different companies and practice your skills using different datasets. I can’t wait to see our prediction accuracy results, let’s get started! Python Libraries Understanding the Apple Stock Data Data Manipulation Data Visualization LSTM Prediction Model Python is a general-purpose programming language that is becoming ever more popular for analyzing data. Python also lets you work quickly and integrate systems more effectively. Companies from all around the world are utilizing Python to gather bits of knowledge from their data. The official Python page if you want to learn more. towardsdatascience.com First things first, we have to install some libraries so that our program works. Here is a list of the libraries we will install: pandas, numpy, keras, and tensorflow. Tensorflow has to be installed so that keras can work. Keras is an API designed for human beings, not machines. Keras follows best practices for reducing cognitive load: it offers consistent & simple APIs, it minimizes the number of user actions required for common use cases, and it provides clear & actionable error messages. It also has extensive documentation and developer guides. Reference: https://keras.io We can install these libraries using Pip library manager: pip install pandas numpy keras tensorflow After the installation is completed, let’s import them into our code editor. Matplotlib is already included in Python that’s why we can import it without installing it. import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom matplotlib.pylab import rcParamsrcParams['figure.figsize']=20,10from keras.models import Sequentialfrom keras.layers import LSTM,Dropout,Densefrom sklearn.preprocessing import MinMaxScaler Secondly, we will start loading the data into a dataframe, it is a good practice to take a look at it before we start manipulating it. This helps us to understand that we have the right data and to get some insights about it. As mentioned earlier, for this exercise we will be using historical data of Apple. I thought Apple would be a good one to go with. After walking through with me on this project, you will learn some skills that will give you the ability to practice yourself using different datasets. The dataframe that we will be using contains the closing prices of Apple stock of the last one year (Sept 16, 2019 — Sept 15, 2020). import pandas as pddf = pd.read_csv('aapl_stock_1yr.csv') The first thing we’ll do to get some understanding of the data is using the head method. When you call the head method on the dataframe, it displays the first five rows of the dataframe. After running this method, we can also see that our data is sorted by the date index. df.head() Another helpful method we will call is the tail method. It displays the last five rows of the dataframe. Let’s say if you want to see the last seven rows, you can input the value 7 as an integer between the parentheses. df.tail(7) Now we have an idea of the data. Let’s move to the next step which is data manipulation and making it ready for prediction. As you can see from the screenshots earlier, our dataframe has 6 columns. Do we need all of them? Of course not. For our prediction project, we will just need “Date” and “Close/Last” columns. Let’s get rid of the other columns then. df = df[['Date', 'Close']]df.head() Now, let’s check the data types of the columns. Since we have a “$” sign in the closing price values, it might not be a float data type. When training the data, string datatype will not work with our model, so we have to convert it to float or integer type. Before we convert it to float, let’s get rid of the “$” sign. Otherwise, conversion method will give us an error. df = df.replace({'\$':''}, regex = True) Great! Now, we can convert the “Closing price” data type to float. And we will also convert the “Date” data to datetime type. df = df.astype({"Close": float})df["Date"] = pd.to_datetime(df.Date, format="%m/%d/%Y")df.dtypes This will be a short step. We will just define the dataframe’s index value as the date column. This will be helpful in the data visualization step. df.index = df['Date'] I will share a simple line chart with you just to give an idea of the stock price change in the last one year. We will also use the visualization method at the end to compare our prediction and reality. plt.plot(df["Close"],label='Close Price history') In this step, we will do most of the programming. First, we need to do a couple of basic adjustments on the data. When our data is ready, we will use itto train our model. As a neural network model, we will use LSTM(Long Short-Term Memory) model. LSTM models work great when making predictions based on time-series datasets. df = df.sort_index(ascending=True,axis=0)data = pd.DataFrame(index=range(0,len(df)),columns=['Date','Close'])for i in range(0,len(data)): data["Date"][i]=df['Date'][i] data["Close"][i]=df["Close"][i]data.head() scaler=MinMaxScaler(feature_range=(0,1))data.index=data.Datedata.drop(“Date”,axis=1,inplace=True)final_data = data.valuestrain_data=final_data[0:200,:]valid_data=final_data[200:,:]scaler=MinMaxScaler(feature_range=(0,1))scaled_data=scaler.fit_transform(final_data)x_train_data,y_train_data=[],[]for i in range(60,len(train_data)): x_train_data.append(scaled_data[i-60:i,0]) y_train_data.append(scaled_data[i,0]) In this step, we are defining the Long Short-Term Memory model. lstm_model=Sequential()lstm_model.add(LSTM(units=50,return_sequences=True,input_shape=(np.shape(x_train_data)[1],1)))lstm_model.add(LSTM(units=50))lstm_model.add(Dense(1))model_data=data[len(data)-len(valid_data)-60:].valuesmodel_data=model_data.reshape(-1,1)model_data=scaler.transform(model_data) This step covers the preparation of the train data and the test data. lstm_model.compile(loss=’mean_squared_error’,optimizer=’adam’)lstm_model.fit(x_train_data,y_train_data,epochs=1,batch_size=1,verbose=2)X_test=[]for i in range(60,model_data.shape[0]): X_test.append(model_data[i-60:i,0])X_test=np.array(X_test)X_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1)) In this step, we are running the model using the test data we defined in the previous step. predicted_stock_price=lstm_model.predict(X_test)predicted_stock_price=scaler.inverse_transform(predicted_stock_price) Almost there, let’s check the accuracy of our model. We have around 250 rows, so I used 80% as train data and 20% as test data. train_data=data[:200]valid_data=data[200:]valid_data['Predictions']=predicted_stock_priceplt.plot(train_data["Close"])plt.plot(valid_data[['Close',"Predictions"]]) lifexplorer.medium.com Congrats!! You have created a Python program that predicts the stock closing price of a company. Now, you have some idea of how to use machine learning in finance, you should try it with different stocks. Hoping that you enjoyed reading my article. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. I am so glad if you learned something new today. Feel free to contact me if you have any questions while implementing the code. 😊 I am Behic Guven, and I love sharing stories on programming, education, and life. Subscribe to my content to stay inspired. Ty,
[ { "code": null, "e": 472, "s": 172, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 1205, "s": 472, "text": "In this post, I will show you how to build a program that can predict the price of a specific stock. This is a great project of using machine learning in finance. If we want a machine to make predictions for us, we should definitely train it well with some data. First, for those who are new to python, I will introduce it to you. Then, we will start working on our prediction model. As mentioned in the subtitle, we will be using Apple Stock Data. If you are wondering is it free to get that data, the answer is absolutely yes. The stock data is available on NASDAQ official website. The NASDAQ (National Association of Securities Dealers Automated Quotations) is an electronic stock exchange with more than 3,300 company listings." }, { "code": null, "e": 1448, "s": 1205, "text": "The Apple stock data can be downloaded from here. On this website, you can also find stock data for different companies and practice your skills using different datasets. I can’t wait to see our prediction accuracy results, let’s get started!" }, { "code": null, "e": 1455, "s": 1448, "text": "Python" }, { "code": null, "e": 1465, "s": 1455, "text": "Libraries" }, { "code": null, "e": 1500, "s": 1465, "text": "Understanding the Apple Stock Data" }, { "code": null, "e": 1518, "s": 1500, "text": "Data Manipulation" }, { "code": null, "e": 1537, "s": 1518, "text": "Data Visualization" }, { "code": null, "e": 1559, "s": 1537, "text": "LSTM Prediction Model" }, { "code": null, "e": 1891, "s": 1559, "text": "Python is a general-purpose programming language that is becoming ever more popular for analyzing data. Python also lets you work quickly and integrate systems more effectively. Companies from all around the world are utilizing Python to gather bits of knowledge from their data. The official Python page if you want to learn more." }, { "code": null, "e": 1914, "s": 1891, "text": "towardsdatascience.com" }, { "code": null, "e": 2137, "s": 1914, "text": "First things first, we have to install some libraries so that our program works. Here is a list of the libraries we will install: pandas, numpy, keras, and tensorflow. Tensorflow has to be installed so that keras can work." }, { "code": null, "e": 2468, "s": 2137, "text": "Keras is an API designed for human beings, not machines. Keras follows best practices for reducing cognitive load: it offers consistent & simple APIs, it minimizes the number of user actions required for common use cases, and it provides clear & actionable error messages. It also has extensive documentation and developer guides." }, { "code": null, "e": 2496, "s": 2468, "text": "Reference: https://keras.io" }, { "code": null, "e": 2554, "s": 2496, "text": "We can install these libraries using Pip library manager:" }, { "code": null, "e": 2596, "s": 2554, "text": "pip install pandas numpy keras tensorflow" }, { "code": null, "e": 2765, "s": 2596, "text": "After the installation is completed, let’s import them into our code editor. Matplotlib is already included in Python that’s why we can import it without installing it." }, { "code": null, "e": 3045, "s": 2765, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom matplotlib.pylab import rcParamsrcParams['figure.figsize']=20,10from keras.models import Sequentialfrom keras.layers import LSTM,Dropout,Densefrom sklearn.preprocessing import MinMaxScaler" }, { "code": null, "e": 3271, "s": 3045, "text": "Secondly, we will start loading the data into a dataframe, it is a good practice to take a look at it before we start manipulating it. This helps us to understand that we have the right data and to get some insights about it." }, { "code": null, "e": 3554, "s": 3271, "text": "As mentioned earlier, for this exercise we will be using historical data of Apple. I thought Apple would be a good one to go with. After walking through with me on this project, you will learn some skills that will give you the ability to practice yourself using different datasets." }, { "code": null, "e": 3687, "s": 3554, "text": "The dataframe that we will be using contains the closing prices of Apple stock of the last one year (Sept 16, 2019 — Sept 15, 2020)." }, { "code": null, "e": 3745, "s": 3687, "text": "import pandas as pddf = pd.read_csv('aapl_stock_1yr.csv')" }, { "code": null, "e": 4018, "s": 3745, "text": "The first thing we’ll do to get some understanding of the data is using the head method. When you call the head method on the dataframe, it displays the first five rows of the dataframe. After running this method, we can also see that our data is sorted by the date index." }, { "code": null, "e": 4028, "s": 4018, "text": "df.head()" }, { "code": null, "e": 4248, "s": 4028, "text": "Another helpful method we will call is the tail method. It displays the last five rows of the dataframe. Let’s say if you want to see the last seven rows, you can input the value 7 as an integer between the parentheses." }, { "code": null, "e": 4259, "s": 4248, "text": "df.tail(7)" }, { "code": null, "e": 4383, "s": 4259, "text": "Now we have an idea of the data. Let’s move to the next step which is data manipulation and making it ready for prediction." }, { "code": null, "e": 4616, "s": 4383, "text": "As you can see from the screenshots earlier, our dataframe has 6 columns. Do we need all of them? Of course not. For our prediction project, we will just need “Date” and “Close/Last” columns. Let’s get rid of the other columns then." }, { "code": null, "e": 4652, "s": 4616, "text": "df = df[['Date', 'Close']]df.head()" }, { "code": null, "e": 4910, "s": 4652, "text": "Now, let’s check the data types of the columns. Since we have a “$” sign in the closing price values, it might not be a float data type. When training the data, string datatype will not work with our model, so we have to convert it to float or integer type." }, { "code": null, "e": 5024, "s": 4910, "text": "Before we convert it to float, let’s get rid of the “$” sign. Otherwise, conversion method will give us an error." }, { "code": null, "e": 5065, "s": 5024, "text": "df = df.replace({'\\$':''}, regex = True)" }, { "code": null, "e": 5191, "s": 5065, "text": "Great! Now, we can convert the “Closing price” data type to float. And we will also convert the “Date” data to datetime type." }, { "code": null, "e": 5288, "s": 5191, "text": "df = df.astype({\"Close\": float})df[\"Date\"] = pd.to_datetime(df.Date, format=\"%m/%d/%Y\")df.dtypes" }, { "code": null, "e": 5436, "s": 5288, "text": "This will be a short step. We will just define the dataframe’s index value as the date column. This will be helpful in the data visualization step." }, { "code": null, "e": 5458, "s": 5436, "text": "df.index = df['Date']" }, { "code": null, "e": 5661, "s": 5458, "text": "I will share a simple line chart with you just to give an idea of the stock price change in the last one year. We will also use the visualization method at the end to compare our prediction and reality." }, { "code": null, "e": 5711, "s": 5661, "text": "plt.plot(df[\"Close\"],label='Close Price history')" }, { "code": null, "e": 6036, "s": 5711, "text": "In this step, we will do most of the programming. First, we need to do a couple of basic adjustments on the data. When our data is ready, we will use itto train our model. As a neural network model, we will use LSTM(Long Short-Term Memory) model. LSTM models work great when making predictions based on time-series datasets." }, { "code": null, "e": 6253, "s": 6036, "text": "df = df.sort_index(ascending=True,axis=0)data = pd.DataFrame(index=range(0,len(df)),columns=['Date','Close'])for i in range(0,len(data)): data[\"Date\"][i]=df['Date'][i] data[\"Close\"][i]=df[\"Close\"][i]data.head()" }, { "code": null, "e": 6671, "s": 6253, "text": "scaler=MinMaxScaler(feature_range=(0,1))data.index=data.Datedata.drop(“Date”,axis=1,inplace=True)final_data = data.valuestrain_data=final_data[0:200,:]valid_data=final_data[200:,:]scaler=MinMaxScaler(feature_range=(0,1))scaled_data=scaler.fit_transform(final_data)x_train_data,y_train_data=[],[]for i in range(60,len(train_data)): x_train_data.append(scaled_data[i-60:i,0]) y_train_data.append(scaled_data[i,0])" }, { "code": null, "e": 6735, "s": 6671, "text": "In this step, we are defining the Long Short-Term Memory model." }, { "code": null, "e": 7034, "s": 6735, "text": "lstm_model=Sequential()lstm_model.add(LSTM(units=50,return_sequences=True,input_shape=(np.shape(x_train_data)[1],1)))lstm_model.add(LSTM(units=50))lstm_model.add(Dense(1))model_data=data[len(data)-len(valid_data)-60:].valuesmodel_data=model_data.reshape(-1,1)model_data=scaler.transform(model_data)" }, { "code": null, "e": 7104, "s": 7034, "text": "This step covers the preparation of the train data and the test data." }, { "code": null, "e": 7411, "s": 7104, "text": "lstm_model.compile(loss=’mean_squared_error’,optimizer=’adam’)lstm_model.fit(x_train_data,y_train_data,epochs=1,batch_size=1,verbose=2)X_test=[]for i in range(60,model_data.shape[0]): X_test.append(model_data[i-60:i,0])X_test=np.array(X_test)X_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))" }, { "code": null, "e": 7503, "s": 7411, "text": "In this step, we are running the model using the test data we defined in the previous step." }, { "code": null, "e": 7621, "s": 7503, "text": "predicted_stock_price=lstm_model.predict(X_test)predicted_stock_price=scaler.inverse_transform(predicted_stock_price)" }, { "code": null, "e": 7749, "s": 7621, "text": "Almost there, let’s check the accuracy of our model. We have around 250 rows, so I used 80% as train data and 20% as test data." }, { "code": null, "e": 7913, "s": 7749, "text": "train_data=data[:200]valid_data=data[200:]valid_data['Predictions']=predicted_stock_priceplt.plot(train_data[\"Close\"])plt.plot(valid_data[['Close',\"Predictions\"]])" }, { "code": null, "e": 7936, "s": 7913, "text": "lifexplorer.medium.com" }, { "code": null, "e": 8287, "s": 7936, "text": "Congrats!! You have created a Python program that predicts the stock closing price of a company. Now, you have some idea of how to use machine learning in finance, you should try it with different stocks. Hoping that you enjoyed reading my article. Working on hands-on programming projects like this one is the best way to sharpen your coding skills." }, { "code": null, "e": 8417, "s": 8287, "text": "I am so glad if you learned something new today. Feel free to contact me if you have any questions while implementing the code. 😊" } ]
Program to calculate area of Circumcircle of an Equilateral Triangle
A circumcircle is a circle that inscribes a regular polygon inside it. The triangle that is inscribed inside a circle is an equilateral triangle. Area of circumcircle of can be found using the following formula, Area of circumcircle = “(a * a * (丌 / 3))” Code Logic, The area of circumcircle of an equilateral triangle is found using the mathematical formula (a*a*(丌/3)). The value of 丌 in this code is coded as 3.14. The expression is evaluated into a float value. Live Demo #include <stdio.h> #include <math.h> int main(){ int a = 5; float area; float pie = 3.14; printf("Program to calculate area of Circumcircle of an Equilateral Triangle\n"); printf("The side of the triangle is %d \n", a); area = ((pie/3)*a*a); printf("The area of of Circumcircle of an Equilateral Triangle is %f \n", area); return 0; } Program to calculate area of Circumcircle of an Equilateral Triangle The side of the triangle is 5 The area of circle inscribed inside a square is 19.625000
[ { "code": null, "e": 1274, "s": 1062, "text": "A circumcircle is a circle that inscribes a regular polygon inside it. The triangle that is inscribed inside a circle is an equilateral triangle. Area of circumcircle of can be found using the following formula," }, { "code": null, "e": 1317, "s": 1274, "text": "Area of circumcircle = “(a * a * (丌 / 3))”" }, { "code": null, "e": 1528, "s": 1317, "text": "Code Logic, The area of circumcircle of an equilateral triangle is found using the mathematical formula (a*a*(丌/3)). The value of 丌 in this code is coded as 3.14. The expression is evaluated into a float value." }, { "code": null, "e": 1539, "s": 1528, "text": " Live Demo" }, { "code": null, "e": 1898, "s": 1539, "text": "#include <stdio.h>\n#include <math.h>\nint main(){\n int a = 5;\n float area;\n float pie = 3.14;\n printf(\"Program to calculate area of Circumcircle of an Equilateral Triangle\\n\");\n printf(\"The side of the triangle is %d \\n\", a);\n area = ((pie/3)*a*a);\n printf(\"The area of of Circumcircle of an Equilateral Triangle is %f \\n\", area);\n return 0;\n}" }, { "code": null, "e": 2055, "s": 1898, "text": "Program to calculate area of Circumcircle of an Equilateral Triangle\nThe side of the triangle is 5\nThe area of circle inscribed inside a square is 19.625000" } ]
How to echo print statements while executing an SQL script?
To perform echo print statements while executing SQL scripts, use the following syntax. The syntax is as follows − SELECT ‘anyStringValue as’ ‘; The query is as follows − mysql> select 'This is a SQL Script' AS' '; The following is the output − +----------------------+ | | +----------------------+ | This is a SQL Script | +----------------------+ 1 row in set, 1 warning (0.00 sec) You can add dynamic data to your status like insert, update and delete with the help of concat() function. The query is as follows − mysql> select concat ("Inserted ", row_count(), " rows successfully") AS ''; The following is the output − +-------------------------------+ | | +-------------------------------+ | Inserted -1 rows successfully | +-------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1150, "s": 1062, "text": "To perform echo print statements while executing SQL scripts, use the following syntax." }, { "code": null, "e": 1177, "s": 1150, "text": "The syntax is as follows −" }, { "code": null, "e": 1207, "s": 1177, "text": "SELECT ‘anyStringValue as’ ‘;" }, { "code": null, "e": 1233, "s": 1207, "text": "The query is as follows −" }, { "code": null, "e": 1277, "s": 1233, "text": "mysql> select 'This is a SQL Script' AS' ';" }, { "code": null, "e": 1307, "s": 1277, "text": "The following is the output −" }, { "code": null, "e": 1467, "s": 1307, "text": "+----------------------+\n| |\n+----------------------+\n| This is a SQL Script |\n+----------------------+\n1 row in set, 1 warning (0.00 sec)" }, { "code": null, "e": 1600, "s": 1467, "text": "You can add dynamic data to your status like insert, update and delete with the help of concat() function. The query is as follows −" }, { "code": null, "e": 1677, "s": 1600, "text": "mysql> select concat (\"Inserted \", row_count(), \" rows successfully\") AS '';" }, { "code": null, "e": 1707, "s": 1677, "text": "The following is the output −" }, { "code": null, "e": 1901, "s": 1707, "text": "+-------------------------------+\n| |\n+-------------------------------+\n| Inserted -1 rows successfully |\n+-------------------------------+\n1 row in set (0.00 sec)" } ]
How to enable wifi in android?
This example demonstrate about How to enable wifi in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:textSize="30sp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> In the above code, we have taken a text view to enable wifi. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); textView.setText("enable wifi"); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); wifiManager.setWifiEnabled(true); } }); } } Step 4 − Add the following code to AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1124, "s": 1062, "text": "This example demonstrate about How to enable wifi in android." }, { "code": null, "e": 1253, "s": 1124, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1318, "s": 1253, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1852, "s": 1318, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1913, "s": 1852, "text": "In the above code, we have taken a text view to enable wifi." }, { "code": null, "e": 1970, "s": 1913, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2912, "s": 1970, "text": "package com.example.myapplication;\n\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n textView.setText(\"enable wifi\");\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n wifiManager.setWifiEnabled(true);\n }\n });\n }\n}" }, { "code": null, "e": 2967, "s": 2912, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 3879, "s": 2967, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.myapplication\">\n <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />\n <uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4226, "s": 3879, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4266, "s": 4226, "text": "Click here to download the project code" } ]
React Native - Text Input
In this chapter, we will show you how to work with TextInput elements in React Native. The Home component will import and render inputs. import React from 'react'; import Inputs from './inputs.js' const App = () => { return ( <Inputs /> ) } export default App We will define the initial state. After defining the initial state, we will create the handleEmail and the handlePassword functions. These functions are used for updating state. The login() function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. import React, { Component } from 'react' import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native' class Inputs extends Component { state = { email: '', password: '' } handleEmail = (text) => { this.setState({ email: text }) } handlePassword = (text) => { this.setState({ password: text }) } login = (email, pass) => { alert('email: ' + email + ' password: ' + pass) } render() { return ( <View style = {styles.container}> <TextInput style = {styles.input} underlineColorAndroid = "transparent" placeholder = "Email" placeholderTextColor = "#9a73ef" autoCapitalize = "none" onChangeText = {this.handleEmail}/> <TextInput style = {styles.input} underlineColorAndroid = "transparent" placeholder = "Password" placeholderTextColor = "#9a73ef" autoCapitalize = "none" onChangeText = {this.handlePassword}/> <TouchableOpacity style = {styles.submitButton} onPress = { () => this.login(this.state.email, this.state.password) }> <Text style = {styles.submitButtonText}> Submit </Text> </TouchableOpacity> </View> ) } } export default Inputs const styles = StyleSheet.create({ container: { paddingTop: 23 }, input: { margin: 15, height: 40, borderColor: '#7a42f4', borderWidth: 1 }, submitButton: { backgroundColor: '#7a42f4', padding: 10, margin: 15, height: 40, }, submitButtonText:{ color: 'white' } }) Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box. Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box. 20 Lectures 1.5 hours Anadi Sharma 61 Lectures 6.5 hours A To Z Mentor 40 Lectures 4.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2431, "s": 2344, "text": "In this chapter, we will show you how to work with TextInput elements in React Native." }, { "code": null, "e": 2481, "s": 2431, "text": "The Home component will import and render inputs." }, { "code": null, "e": 2617, "s": 2481, "text": "import React from 'react';\nimport Inputs from './inputs.js'\n\nconst App = () => {\n return (\n <Inputs />\n )\n}\nexport default App" }, { "code": null, "e": 2651, "s": 2617, "text": "We will define the initial state." }, { "code": null, "e": 2795, "s": 2651, "text": "After defining the initial state, we will create the handleEmail and the handlePassword functions. These functions are used for updating state." }, { "code": null, "e": 2864, "s": 2795, "text": "The login() function will just alert the current value of the state." }, { "code": null, "e": 3017, "s": 2864, "text": "We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder." }, { "code": null, "e": 4818, "s": 3017, "text": "import React, { Component } from 'react'\nimport { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'\n\nclass Inputs extends Component {\n state = {\n email: '',\n password: ''\n }\n handleEmail = (text) => {\n this.setState({ email: text })\n }\n handlePassword = (text) => {\n this.setState({ password: text })\n }\n login = (email, pass) => {\n alert('email: ' + email + ' password: ' + pass)\n }\n render() {\n return (\n <View style = {styles.container}>\n <TextInput style = {styles.input}\n underlineColorAndroid = \"transparent\"\n placeholder = \"Email\"\n placeholderTextColor = \"#9a73ef\"\n autoCapitalize = \"none\"\n onChangeText = {this.handleEmail}/>\n \n <TextInput style = {styles.input}\n underlineColorAndroid = \"transparent\"\n placeholder = \"Password\"\n placeholderTextColor = \"#9a73ef\"\n autoCapitalize = \"none\"\n onChangeText = {this.handlePassword}/>\n \n <TouchableOpacity\n style = {styles.submitButton}\n onPress = {\n () => this.login(this.state.email, this.state.password)\n }>\n <Text style = {styles.submitButtonText}> Submit </Text>\n </TouchableOpacity>\n </View>\n )\n }\n}\nexport default Inputs\n\nconst styles = StyleSheet.create({\n container: {\n paddingTop: 23\n },\n input: {\n margin: 15,\n height: 40,\n borderColor: '#7a42f4',\n borderWidth: 1\n },\n submitButton: {\n backgroundColor: '#7a42f4',\n padding: 10,\n margin: 15,\n height: 40,\n },\n submitButtonText:{\n color: 'white'\n }\n})" }, { "code": null, "e": 4980, "s": 4818, "text": "Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box." }, { "code": null, "e": 5142, "s": 4980, "text": "Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box." }, { "code": null, "e": 5177, "s": 5142, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5191, "s": 5177, "text": " Anadi Sharma" }, { "code": null, "e": 5226, "s": 5191, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5241, "s": 5226, "text": " A To Z Mentor" }, { "code": null, "e": 5276, "s": 5241, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5304, "s": 5276, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5340, "s": 5304, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5368, "s": 5340, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5403, "s": 5368, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5415, "s": 5403, "text": " Senol Atac" }, { "code": null, "e": 5450, "s": 5415, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5462, "s": 5450, "text": " Senol Atac" }, { "code": null, "e": 5469, "s": 5462, "text": " Print" }, { "code": null, "e": 5480, "s": 5469, "text": " Add Notes" } ]
Python Desktop News Notifier in 20 lines - GeeksforGeeks
03 Sep, 2021 To get started with the Desktop News Notifier, we require two libraries: feedparser and notify2. Give following command to to install feedparser: sudo pip3 install feedparser For installing notify2 in your terminal: sudo pip3 install notify2 Feedparser will parse the feed that we will get from the URL. We will use notify2 for the desktop notification purpose. Other than these two libraries, we will use OS and time lib. Once you are done with the installation import both libraries in the program. Here, in this example I have parsed the news from the BBC UK, you can use any news feedparser URL. Let’s have a look at the program: Python # Python program to illustrate# desktop news notifierimport feedparserimport notify2import osimport timedef parseFeed(): f = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml") ICON_PATH = os.getcwd() + "/icon.ico" notify2.init('News Notify') for newsitem in f['items']: n = notify2.Notification(newsitem['title'], newsitem['summary'], icon=ICON_PATH ) n.set_urgency(notify2.URGENCY_NORMAL) n.show() n.set_timeout(15000) time.sleep(1200) if __name__ == '__main__': parseFeed() Screenshot of the news notification popup Step by step Explanation of Code: f = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml") Here feedparser will parse the news data from the feed URL. The parsed data will be in the form of dictionary. ICON_PATH = os.getcwd() + "/icon.ico" If you want to set any icon in the notification then here we are setting the Icon path. This is optional. notify2.init('News Notify') Here we are initializing the notify2 using the init method of notify2. Initialize the D-Bus connection. Must be called before you send any notifications, or retrieve server info or capabilities. for newsitem in f['items']: n = notify2.Notification(newsitem['title'], newsitem['summary'], icon=ICON_PATH ) Looping from the parsed data to get the relevant information like news title, short summary and setting the notification icon using the Notification method of the notify2 lib. n.set_urgency(notify2.URGENCY_NORMAL) Set the urgency level to one of URGENCY_LOW, URGENCY_NORMAL or URGENCY_CRITICAL n.show() This method will show the notification on the Desktop n.set_timeout(15000) Setting the time to keep the notification on the desktop (in milliseconds). I have set here as 15 seconds. time.sleep(1200) This will usually display the news notification every 20 mins. You can set the time as per your requirement. You can find the full source code that is hosted on GitHub This article is contributed by Srce Cde. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mayurkadam clintra Python-projects python-utility GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar Top 10 Angular Libraries For Web Developers Top 10 System Design Interview Questions and Answers XML parsing in Python 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": 24938, "s": 24910, "text": "\n03 Sep, 2021" }, { "code": null, "e": 25085, "s": 24938, "text": "To get started with the Desktop News Notifier, we require two libraries: feedparser and notify2. Give following command to to install feedparser: " }, { "code": null, "e": 25114, "s": 25085, "text": "sudo pip3 install feedparser" }, { "code": null, "e": 25155, "s": 25114, "text": "For installing notify2 in your terminal:" }, { "code": null, "e": 25181, "s": 25155, "text": "sudo pip3 install notify2" }, { "code": null, "e": 25575, "s": 25181, "text": "Feedparser will parse the feed that we will get from the URL. We will use notify2 for the desktop notification purpose. Other than these two libraries, we will use OS and time lib. Once you are done with the installation import both libraries in the program. Here, in this example I have parsed the news from the BBC UK, you can use any news feedparser URL. Let’s have a look at the program: " }, { "code": null, "e": 25582, "s": 25575, "text": "Python" }, { "code": "# Python program to illustrate# desktop news notifierimport feedparserimport notify2import osimport timedef parseFeed(): f = feedparser.parse(\"http://feeds.bbci.co.uk/news/rss.xml\") ICON_PATH = os.getcwd() + \"/icon.ico\" notify2.init('News Notify') for newsitem in f['items']: n = notify2.Notification(newsitem['title'], newsitem['summary'], icon=ICON_PATH ) n.set_urgency(notify2.URGENCY_NORMAL) n.show() n.set_timeout(15000) time.sleep(1200) if __name__ == '__main__': parseFeed()", "e": 26198, "s": 25582, "text": null }, { "code": null, "e": 26240, "s": 26198, "text": "Screenshot of the news notification popup" }, { "code": null, "e": 26275, "s": 26240, "text": "Step by step Explanation of Code: " }, { "code": null, "e": 26336, "s": 26275, "text": "f = feedparser.parse(\"http://feeds.bbci.co.uk/news/rss.xml\")" }, { "code": null, "e": 26448, "s": 26336, "text": "Here feedparser will parse the news data from the feed URL. The parsed data will be in the form of dictionary. " }, { "code": null, "e": 26486, "s": 26448, "text": "ICON_PATH = os.getcwd() + \"/icon.ico\"" }, { "code": null, "e": 26592, "s": 26486, "text": "If you want to set any icon in the notification then here we are setting the Icon path. This is optional." }, { "code": null, "e": 26620, "s": 26592, "text": "notify2.init('News Notify')" }, { "code": null, "e": 26815, "s": 26620, "text": "Here we are initializing the notify2 using the init method of notify2. Initialize the D-Bus connection. Must be called before you send any notifications, or retrieve server info or capabilities." }, { "code": null, "e": 27037, "s": 26815, "text": " for newsitem in f['items']: \n n = notify2.Notification(newsitem['title'], \n newsitem['summary'], \n icon=ICON_PATH \n )" }, { "code": null, "e": 27213, "s": 27037, "text": "Looping from the parsed data to get the relevant information like news title, short summary and setting the notification icon using the Notification method of the notify2 lib." }, { "code": null, "e": 27251, "s": 27213, "text": "n.set_urgency(notify2.URGENCY_NORMAL)" }, { "code": null, "e": 27331, "s": 27251, "text": "Set the urgency level to one of URGENCY_LOW, URGENCY_NORMAL or URGENCY_CRITICAL" }, { "code": null, "e": 27340, "s": 27331, "text": "n.show()" }, { "code": null, "e": 27394, "s": 27340, "text": "This method will show the notification on the Desktop" }, { "code": null, "e": 27415, "s": 27394, "text": "n.set_timeout(15000)" }, { "code": null, "e": 27523, "s": 27415, "text": "Setting the time to keep the notification on the desktop (in milliseconds). I have set here as 15 seconds. " }, { "code": null, "e": 27540, "s": 27523, "text": "time.sleep(1200)" }, { "code": null, "e": 27708, "s": 27540, "text": "This will usually display the news notification every 20 mins. You can set the time as per your requirement. You can find the full source code that is hosted on GitHub" }, { "code": null, "e": 28124, "s": 27708, "text": "This article is contributed by Srce Cde. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28135, "s": 28124, "text": "Mayurkadam" }, { "code": null, "e": 28143, "s": 28135, "text": "clintra" }, { "code": null, "e": 28159, "s": 28143, "text": "Python-projects" }, { "code": null, "e": 28174, "s": 28159, "text": "python-utility" }, { "code": null, "e": 28180, "s": 28174, "text": "GBlog" }, { "code": null, "e": 28187, "s": 28180, "text": "Python" }, { "code": null, "e": 28285, "s": 28187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28294, "s": 28285, "text": "Comments" }, { "code": null, "e": 28307, "s": 28294, "text": "Old Comments" }, { "code": null, "e": 28349, "s": 28307, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28374, "s": 28349, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 28418, "s": 28374, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28471, "s": 28418, "text": "Top 10 System Design Interview Questions and Answers" }, { "code": null, "e": 28493, "s": 28471, "text": "XML parsing in Python" }, { "code": null, "e": 28521, "s": 28493, "text": "Read JSON file using Python" }, { "code": null, "e": 28571, "s": 28521, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28593, "s": 28571, "text": "Python map() function" } ]
Why We Need Indexes for Database Tables | by Christopher Tao | Towards Data Science
If you are not a DBA or a Database Developer, you may not know the mechanisms of the database index. But as long as you can write some SQL queries, you must have been heard of database indexes and know that indexes can improve the performance of the SQL queries. In this article, I’ll try to use the simplest language and diagrams to illustrate how the B+tree index can improve the performance of your SQL queries. The reason why I use the B+tree index as the example is that It is used by most Relational Database Management Systems such as MySQL, SQL Server and Oracle It can improve the performance of most types of SQL queries, rather than specific types Let’s keep this instruction simple, here is a simplified diagram illustrating the structure of the B+tree index. In the above B+Tree example, each rectangle stands for a block in the hard disk, while the blue filled dot stands for a pointer that links the blocks together. Please be noted that this diagram has extremely simplified the B+Tree for demonstration purposes, as it assumes that each hard disk block can only contain 2 keys. In practice, this will be much larger. It is important to understand how a B+tree index is constructed. We need to know that the “Leaf Nodes” level is supposed to have all the values of the field that this index was created on. In the above example, it is apparent that we have only 9 rows in this table column, and their values are from 1 to 9. If you’re interested in how the above B+Tree was built, please refer to another article of mine: How B+Tree Indexes Are Built In A Database? towardsdatascience.com B+tree can help most of the database query scenarios, and this is also the reason why it is useful. Let’s suppose that our SQL query is retrieving on “equal” where condition, for example: SELECT *FROM TABLEWHERE ID = 3 To find the ID equals 3, the B+tree is used as follows. Starts from the top level of the tree, 3 is less than 5, so we need to use the pointer on the left of the number 5 On the next level, 3 is in between 2 and 4, so we need to use the pointer in the middle We’ve got the block on the leaf node, 3 is in here What if our SQL query is searching in a range? For example, here is the SQL query: SELECT *FROM TABLEWHERE ID BETWEEN 3 AND 7 Here is the demonstration of the process. Starts from the top level of the tree, 3 is less than 5, so we need to use the pointer on the left of the number 5 On the next level, 3 is in between 2 and 4, so we need to use the pointer in the middle We’ve got the block on the leaf node, 3 is in here Since we’re querying on the comparison, so the cursor will keep fetching in this block, so we can get the number 4 We haven’t got to 7 yet, so the cursor will keep going to the next (right) leaf node block We reached the next block, so we’ve got the numbers 5 and 6. But it has not finished yet, similar mechanism as the previous step will be used to get to the next block We reached the next block which contains the number 7 We have reached the upper bound of the range, so the query finished The most important characteristic of B+Tree indexes is that it consists of leaf node level and search key level of the tree. All the values of this indexed column appear in the leaf nodes.The non-leaf nodes are only used for searching purposes, so there are only pointers to the lower level. In other words, they can’t lead to the actual data entries.Every key in the leaf nodes have an extra pointer to the data entry, so it can lead the cursor to find/fetch the data rows. All the values of this indexed column appear in the leaf nodes. The non-leaf nodes are only used for searching purposes, so there are only pointers to the lower level. In other words, they can’t lead to the actual data entries. Every key in the leaf nodes have an extra pointer to the data entry, so it can lead the cursor to find/fetch the data rows. As shown in the above examples, B+Tree works for both “equal” and comparison conditions. It can be seen that the query only need to go through the search keys on the non-leaf nodes to find the expected values. Therefore, when the SQL query is retrieving on the column on which the B+Tree index was created, only a few levels of non-leaf nodes need to go through. You must be thinking that the non-leaf nodes must be kind of overheads, and when there are a lot of data rows it will be slow down because there might be numerous non-leaf levels. Partially correct. Yes, the non-leaf nodes need to be scanned to get the expected value. In fact, the number of scanned times exactly equals the number of non-leaf levels. However, in practice, the block on our hard disk will be much larger than the above examples. Typically, a table with 10 million entries can be put in a B+Tree with only 3 non-leaf levels. Even though the table is extremely big such as billions scaled, normally the number of non-leaf levels of the B+Tree is usually 4 or 5. Hence, using B+Tree indexes can dramatically reduce the number of hard disk blocks scanned in a SQL query. I suppose the audience of this article might not have a computer science background, so I guess a simple explanation of the “block” might be necessary for a better understanding of the problem. In our hard disk, the data is stored not always in sequence. A single file might be split and stored into different blocks. So, when we are reading a file/dataset/table, in order to scan the whole file, it will be necessary to jump between different blocks. Typically, for a mechanical hard drive, there is a magnetic head that can only move up and down. When it is necessary to read data from a different location, the whole hard drive disk will rotate the location to where the magnetic head is so that the head can read the data. Imagine that we are scanning 1000 blocks. The worst case is that the disk will need to be rotated 1000 times. If we’re using indexes, this number will be reduced to 4–5 times. That’s why an index can help to the performance. In this article, I’ve shared how B+tree looks like and how it works and facilitate a SQL query, typically with equal and comparing conditions. It turns out B+Tree is not the most advanced database index anymore, but I believe as probably the most classic index which is still pervasively used in most RDBMS, it is still the best example to demonstrate why we need indexes for a database table and how it works. Hope this is interesting enough for you. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 435, "s": 172, "text": "If you are not a DBA or a Database Developer, you may not know the mechanisms of the database index. But as long as you can write some SQL queries, you must have been heard of database indexes and know that indexes can improve the performance of the SQL queries." }, { "code": null, "e": 648, "s": 435, "text": "In this article, I’ll try to use the simplest language and diagrams to illustrate how the B+tree index can improve the performance of your SQL queries. The reason why I use the B+tree index as the example is that" }, { "code": null, "e": 743, "s": 648, "text": "It is used by most Relational Database Management Systems such as MySQL, SQL Server and Oracle" }, { "code": null, "e": 831, "s": 743, "text": "It can improve the performance of most types of SQL queries, rather than specific types" }, { "code": null, "e": 944, "s": 831, "text": "Let’s keep this instruction simple, here is a simplified diagram illustrating the structure of the B+tree index." }, { "code": null, "e": 1104, "s": 944, "text": "In the above B+Tree example, each rectangle stands for a block in the hard disk, while the blue filled dot stands for a pointer that links the blocks together." }, { "code": null, "e": 1306, "s": 1104, "text": "Please be noted that this diagram has extremely simplified the B+Tree for demonstration purposes, as it assumes that each hard disk block can only contain 2 keys. In practice, this will be much larger." }, { "code": null, "e": 1613, "s": 1306, "text": "It is important to understand how a B+tree index is constructed. We need to know that the “Leaf Nodes” level is supposed to have all the values of the field that this index was created on. In the above example, it is apparent that we have only 9 rows in this table column, and their values are from 1 to 9." }, { "code": null, "e": 1754, "s": 1613, "text": "If you’re interested in how the above B+Tree was built, please refer to another article of mine: How B+Tree Indexes Are Built In A Database?" }, { "code": null, "e": 1777, "s": 1754, "text": "towardsdatascience.com" }, { "code": null, "e": 1877, "s": 1777, "text": "B+tree can help most of the database query scenarios, and this is also the reason why it is useful." }, { "code": null, "e": 1965, "s": 1877, "text": "Let’s suppose that our SQL query is retrieving on “equal” where condition, for example:" }, { "code": null, "e": 1996, "s": 1965, "text": "SELECT *FROM TABLEWHERE ID = 3" }, { "code": null, "e": 2052, "s": 1996, "text": "To find the ID equals 3, the B+tree is used as follows." }, { "code": null, "e": 2167, "s": 2052, "text": "Starts from the top level of the tree, 3 is less than 5, so we need to use the pointer on the left of the number 5" }, { "code": null, "e": 2255, "s": 2167, "text": "On the next level, 3 is in between 2 and 4, so we need to use the pointer in the middle" }, { "code": null, "e": 2306, "s": 2255, "text": "We’ve got the block on the leaf node, 3 is in here" }, { "code": null, "e": 2389, "s": 2306, "text": "What if our SQL query is searching in a range? For example, here is the SQL query:" }, { "code": null, "e": 2432, "s": 2389, "text": "SELECT *FROM TABLEWHERE ID BETWEEN 3 AND 7" }, { "code": null, "e": 2474, "s": 2432, "text": "Here is the demonstration of the process." }, { "code": null, "e": 2589, "s": 2474, "text": "Starts from the top level of the tree, 3 is less than 5, so we need to use the pointer on the left of the number 5" }, { "code": null, "e": 2677, "s": 2589, "text": "On the next level, 3 is in between 2 and 4, so we need to use the pointer in the middle" }, { "code": null, "e": 2728, "s": 2677, "text": "We’ve got the block on the leaf node, 3 is in here" }, { "code": null, "e": 2843, "s": 2728, "text": "Since we’re querying on the comparison, so the cursor will keep fetching in this block, so we can get the number 4" }, { "code": null, "e": 2934, "s": 2843, "text": "We haven’t got to 7 yet, so the cursor will keep going to the next (right) leaf node block" }, { "code": null, "e": 3101, "s": 2934, "text": "We reached the next block, so we’ve got the numbers 5 and 6. But it has not finished yet, similar mechanism as the previous step will be used to get to the next block" }, { "code": null, "e": 3155, "s": 3101, "text": "We reached the next block which contains the number 7" }, { "code": null, "e": 3223, "s": 3155, "text": "We have reached the upper bound of the range, so the query finished" }, { "code": null, "e": 3348, "s": 3223, "text": "The most important characteristic of B+Tree indexes is that it consists of leaf node level and search key level of the tree." }, { "code": null, "e": 3698, "s": 3348, "text": "All the values of this indexed column appear in the leaf nodes.The non-leaf nodes are only used for searching purposes, so there are only pointers to the lower level. In other words, they can’t lead to the actual data entries.Every key in the leaf nodes have an extra pointer to the data entry, so it can lead the cursor to find/fetch the data rows." }, { "code": null, "e": 3762, "s": 3698, "text": "All the values of this indexed column appear in the leaf nodes." }, { "code": null, "e": 3926, "s": 3762, "text": "The non-leaf nodes are only used for searching purposes, so there are only pointers to the lower level. In other words, they can’t lead to the actual data entries." }, { "code": null, "e": 4050, "s": 3926, "text": "Every key in the leaf nodes have an extra pointer to the data entry, so it can lead the cursor to find/fetch the data rows." }, { "code": null, "e": 4139, "s": 4050, "text": "As shown in the above examples, B+Tree works for both “equal” and comparison conditions." }, { "code": null, "e": 4413, "s": 4139, "text": "It can be seen that the query only need to go through the search keys on the non-leaf nodes to find the expected values. Therefore, when the SQL query is retrieving on the column on which the B+Tree index was created, only a few levels of non-leaf nodes need to go through." }, { "code": null, "e": 4593, "s": 4413, "text": "You must be thinking that the non-leaf nodes must be kind of overheads, and when there are a lot of data rows it will be slow down because there might be numerous non-leaf levels." }, { "code": null, "e": 5090, "s": 4593, "text": "Partially correct. Yes, the non-leaf nodes need to be scanned to get the expected value. In fact, the number of scanned times exactly equals the number of non-leaf levels. However, in practice, the block on our hard disk will be much larger than the above examples. Typically, a table with 10 million entries can be put in a B+Tree with only 3 non-leaf levels. Even though the table is extremely big such as billions scaled, normally the number of non-leaf levels of the B+Tree is usually 4 or 5." }, { "code": null, "e": 5197, "s": 5090, "text": "Hence, using B+Tree indexes can dramatically reduce the number of hard disk blocks scanned in a SQL query." }, { "code": null, "e": 5391, "s": 5197, "text": "I suppose the audience of this article might not have a computer science background, so I guess a simple explanation of the “block” might be necessary for a better understanding of the problem." }, { "code": null, "e": 5649, "s": 5391, "text": "In our hard disk, the data is stored not always in sequence. A single file might be split and stored into different blocks. So, when we are reading a file/dataset/table, in order to scan the whole file, it will be necessary to jump between different blocks." }, { "code": null, "e": 5924, "s": 5649, "text": "Typically, for a mechanical hard drive, there is a magnetic head that can only move up and down. When it is necessary to read data from a different location, the whole hard drive disk will rotate the location to where the magnetic head is so that the head can read the data." }, { "code": null, "e": 6149, "s": 5924, "text": "Imagine that we are scanning 1000 blocks. The worst case is that the disk will need to be rotated 1000 times. If we’re using indexes, this number will be reduced to 4–5 times. That’s why an index can help to the performance." }, { "code": null, "e": 6292, "s": 6149, "text": "In this article, I’ve shared how B+tree looks like and how it works and facilitate a SQL query, typically with equal and comparing conditions." }, { "code": null, "e": 6601, "s": 6292, "text": "It turns out B+Tree is not the most advanced database index anymore, but I believe as probably the most classic index which is still pervasively used in most RDBMS, it is still the best example to demonstrate why we need indexes for a database table and how it works. Hope this is interesting enough for you." }, { "code": null, "e": 6612, "s": 6601, "text": "medium.com" } ]
Predicate.not() Method in Java with Examples - GeeksforGeeks
05 Feb, 2021 In order to negate an existing predicate, the Predicate.not() static method added to Java 11. The Predicate class is present in java.util.function package. Syntax: negate = Predicate.not( positivePredicate ); Parameters: Predicate whose negate is required Return Type: Return type not() method is Predicate. Approach: Create one predicate and initialize the conditions to it.Create another predicate to create negate and assign it with the not() method. Create one predicate and initialize the conditions to it. Create another predicate to create negate and assign it with the not() method. Below is the implementation of the above approach: Java // Implementation of Predicate.not() method in Javaimport java.util.Arrays;import java.util.List;import java.util.function.Predicate;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // creating a predicate for negation Predicate<Integer> even = i -> i % 2 == 0; // creating a predicate object which // is negation os supplied predicate Predicate<Integer> odd = Predicate.not(even); // filtering the even number using even predicate List<Integer> evenNumbers = list.stream().filter(even).collect( Collectors.toList()); // filtering the odd number using odd predicate List<Integer> oddNumbers = list.stream().filter(odd).collect( Collectors.toList()); // Print the Lists System.out.println(evenNumbers); System.out.println(oddNumbers); }} Output: [2, 4, 6, 8, 10] [1, 3, 5, 7, 9] Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23868, "s": 23840, "text": "\n05 Feb, 2021" }, { "code": null, "e": 24024, "s": 23868, "text": "In order to negate an existing predicate, the Predicate.not() static method added to Java 11. The Predicate class is present in java.util.function package." }, { "code": null, "e": 24032, "s": 24024, "text": "Syntax:" }, { "code": null, "e": 24077, "s": 24032, "text": "negate = Predicate.not( positivePredicate );" }, { "code": null, "e": 24089, "s": 24077, "text": "Parameters:" }, { "code": null, "e": 24124, "s": 24089, "text": "Predicate whose negate is required" }, { "code": null, "e": 24176, "s": 24124, "text": "Return Type: Return type not() method is Predicate." }, { "code": null, "e": 24186, "s": 24176, "text": "Approach:" }, { "code": null, "e": 24322, "s": 24186, "text": "Create one predicate and initialize the conditions to it.Create another predicate to create negate and assign it with the not() method." }, { "code": null, "e": 24380, "s": 24322, "text": "Create one predicate and initialize the conditions to it." }, { "code": null, "e": 24459, "s": 24380, "text": "Create another predicate to create negate and assign it with the not() method." }, { "code": null, "e": 24510, "s": 24459, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24515, "s": 24510, "text": "Java" }, { "code": "// Implementation of Predicate.not() method in Javaimport java.util.Arrays;import java.util.List;import java.util.function.Predicate;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // creating a predicate for negation Predicate<Integer> even = i -> i % 2 == 0; // creating a predicate object which // is negation os supplied predicate Predicate<Integer> odd = Predicate.not(even); // filtering the even number using even predicate List<Integer> evenNumbers = list.stream().filter(even).collect( Collectors.toList()); // filtering the odd number using odd predicate List<Integer> oddNumbers = list.stream().filter(odd).collect( Collectors.toList()); // Print the Lists System.out.println(evenNumbers); System.out.println(oddNumbers); }}", "e": 25538, "s": 24515, "text": null }, { "code": null, "e": 25546, "s": 25538, "text": "Output:" }, { "code": null, "e": 25579, "s": 25546, "text": "[2, 4, 6, 8, 10]\n[1, 3, 5, 7, 9]" }, { "code": null, "e": 25586, "s": 25579, "text": "Picked" }, { "code": null, "e": 25591, "s": 25586, "text": "Java" }, { "code": null, "e": 25605, "s": 25591, "text": "Java Programs" }, { "code": null, "e": 25610, "s": 25605, "text": "Java" }, { "code": null, "e": 25708, "s": 25610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25717, "s": 25708, "text": "Comments" }, { "code": null, "e": 25730, "s": 25717, "text": "Old Comments" }, { "code": null, "e": 25751, "s": 25730, "text": "Constructors in Java" }, { "code": null, "e": 25766, "s": 25751, "text": "Stream In Java" }, { "code": null, "e": 25785, "s": 25766, "text": "Exceptions in Java" }, { "code": null, "e": 25815, "s": 25785, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25861, "s": 25815, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25905, "s": 25861, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 25931, "s": 25905, "text": "Java Programming Examples" }, { "code": null, "e": 25965, "s": 25931, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26012, "s": 25965, "text": "Implementing a Linked List in Java using Class" } ]
Summarize whole paragraph to one sentence by Extractive Approach | by Edward Ma | Towards Data Science
To catch a quick idea of long document, we will always to do a summarization when we read a article or book. In English, the first (or first two) sentence(s) of each article has a very high chance of representing the whole article. Of course, the topic sentence can be the last sentence in sometimes. In NLP, there are two approaches to do the text summarization. The first one, extractive approach, is a simple approach which is extracting key words or sentences from article. There are some limitations and proved that the performance is not very good. The second one, abstractive approach, is generating a new sentences base on given article. It needs more advanced technique. After read this article: Understand PageRank algorithmUnderstand TextRank algorithmHow can we use TextRank algorithm to have a summarization Understand PageRank algorithm Understand TextRank algorithm How can we use TextRank algorithm to have a summarization PageRank algorithm is developed by Google for searching the most importance of website so that Google search result is relevant to query. In PageRank, it is a directed graph. At the beginning, all node have equal score (1 / total number of node). The algorithm The first formula is the simplified version of PageRank and we will use this one for demo. The second one is a little bit complicated as it involved one more parameter which is damping factor, “d”. By default d is 0.85 Let take a look in the simplified version. In iteration 1, here is how PageRank calculate: A: (1/4)/3. As only C is pointing to A, so we use previous C score (iteration 0) divided by number of node (i.e. 3) that C is pointing B: (1/4)/2 + (1/4)/3. Both A and C are pointing to B, so previous A score (iteration 0) divided by number of node (i.e. 2) that A is pointing. For C, it is same as previous one which is (1/4)/3. For detail, you may checkout the video for full explantation. Question: When should we stop the iteration? According to theory, it should calculate until no big update on score. Why we need to introduce PageRank before TextRank? Because the idea of TextRank comes from PageRank and using similar algorithm (graph concept) to calculate the importance. Difference: TextRank graph is undirected. Meaning that all edge are bidirectionalThe weight of edge is difference while it is 1 in PageRank. There are different way to calculate such as BM25, TF-IDF. TextRank graph is undirected. Meaning that all edge are bidirectional The weight of edge is difference while it is 1 in PageRank. There are different way to calculate such as BM25, TF-IDF. There are a lot of different document similarity implementation such as BM25, cosine similarity, IDF-modified-cosine. You may choose the best fit for your problem. If you do not have idea about those algorithm, please let us know and we will include it in later sharing. gensim provides a simple API to calculate TextRank by using BM25 (Best Match 25). Step 1: Environment Setup pip install gensim==3.4.0 Step 2: Import library import gensim print('gensim Version: %s' % (gensim.__version__)) Result: gensim Version: 3.4.0 Step 3: Initial testing content # Capture from https://www.cnbc.com/2018/06/01/microsoft--github-acquisition-talks-resume.htmlcontent = "Microsoft held talks in the past few weeks " + \ "to acquire software developer platform GitHub, Business " + \ "Insider reports. One person familiar with the discussions " + \ "between the companies told CNBC that they had been " + \ "considering a joint marketing partnership valued around " + \ "$35 million, and that those discussions had progressed to " + \ "a possible investment or outright acquisition. It is " + \ "unclear whether talks are still ongoing, but this " + \ "person said that GitHub's price for a full acquisition " + \ "was more than Microsoft currently wanted to pay. GitHub " + \ "was last valued at $2 billion in its last funding round " + \ "2015, but the price tag for an acquisition could be $5 " + \ "billion or more, based on a price that was floated " + \ "last year. GitHub's tools have become essential to " + \ "software developers, who use it to store code, " + \ "keep track of updates and discuss issues. The privately " + \ "held company has more than 23 million individual users in " + \ "more than 1.5 million organizations. It was on track to " + \ "book more than $200 million in subscription revenue, " + \ "including more than $110 million from companies using its " + \ "enterprise product, GitHub told CNBC last fall.Microsoft " + \ "has reportedly flirted with buying GitHub in the past, " + \ "including in 2016, although GitHub denied those " + \ "reports. A partnership would give Microsoft another " + \ "connection point to the developers it needs to court to " + \ "build applications on its various platforms, including " + \ "the Azure cloud. Microsoft could also use data from " + \ "GitHub to improve its artificial intelligence " + \ "producs. The talks come amid GitHub's struggle to " + \ "replace CEO and founder Chris Wanstrath, who stepped " + \ "down 10 months ago. Business Insider reported that " + \ "Microsoft exec Nat Friedman -- who previously " + \ "ran Xamarin, a developer tools start-up that Microsoft " + \ "acquired in 2016 -- may take that CEO role. Google's " + \ "senior VP of ads and commerce, Sridhar Ramaswamy, has " + \ "also been in discussions for the job, says the report. " + \ "Microsoft declined to comment on the report. " + \ "GitHub did not immediately return a request for comment." Step 4: Try different ratio Ratio parameter use for decide number of import sentences are returned. Original Content:Microsoft held talks in the past few weeks to acquire software developer platform GitHub, Business Insider reports. One person familiar with the discussions between the companies told CNBC that they had been considering a joint marketing partnership valued around $35 million, and that those discussions had progressed to a possible investment or outright acquisition. It is unclear whether talks are still ongoing, but this person said that GitHub's price for a full acquisition was more than Microsoft currently wanted to pay. GitHub was last valued at $2 billion in its last funding round 2015, but the price tag for an acquisition could be $5 billion or more, based on a price that was floated last year. GitHub's tools have become essential to software developers, who use it to store code, keep track of updates and discuss issues. The privately held company has more than 23 million individual users in more than 1.5 million organizations. It was on track to book more than $200 million in subscription revenue, including more than $110 million from companies using its enterprise product, GitHub told CNBC last fall.Microsoft has reportedly flirted with buying GitHub in the past, including in 2016, although GitHub denied those reports. A partnership would give Microsoft another connection point to the developers it needs to court to build applications on its various platforms, including the Azure cloud. Microsoft could also use data from GitHub to improve its artificial intelligence producs. The talks come amid GitHub's struggle to replace CEO and founder Chris Wanstrath, who stepped down 10 months ago. Business Insider reported that Microsoft exec Nat Friedman -- who previously ran Xamarin, a developer tools start-up that Microsoft acquired in 2016 -- may take that CEO role. Google's senior VP of ads and commerce, Sridhar Ramaswamy, has also been in discussions for the job, says the report. Microsoft declined to comment on the report. GitHub did not immediately return a request for comment.---> Summarized Content (Ratio is 0.3):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.5):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.7):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.From there, anyone from all over the world can download those projects and submit their own improvements.development world. Result Original Content:On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users. It's not immediately clear what will come of these talks. Microsoft declined to comment, but you can read the full Business Insider report here. While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup. If the stars align, and GitHub is integrated intelligently into Microsoft's products, it could give the company a big edge against Amazon Web Services, the leading player in the fast-growing cloud market. Just to catch you up: GitHub is an online service that allows developers to host their software projects. From there, anyone from all over the world can download those projects and submit their own improvements. That functionality has made GitHub the center of the open source software. development world.---> Summarized Content (Ratio is 0.3):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.5):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.7):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.From there, anyone from all over the world can download those projects and submit their own improvements.development world. Step 5: Try different word count Word count parameter is another variable to control the result. If both word_count and ratio are entered. Ratio will be ignored. print('Original Content:')print(content)for word_count in [10, 30, 50]: summarized_content = gensim.summarization.summarize(body, word_count=word_count) print() print('---> Summarized Content (Word Count is %d):' % word_count) print(summarized_content) Result riginal Content:Microsoft held talks in the past few weeks to acquire software developer platform GitHub, Business Insider reports. One person familiar with the discussions between the companies told CNBC that they had been considering a joint marketing partnership valued around $35 million, and that those discussions had progressed to a possible investment or outright acquisition. It is unclear whether talks are still ongoing, but this person said that GitHub's price for a full acquisition was more than Microsoft currently wanted to pay. GitHub was last valued at $2 billion in its last funding round 2015, but the price tag for an acquisition could be $5 billion or more, based on a price that was floated last year. GitHub's tools have become essential to software developers, who use it to store code, keep track of updates and discuss issues. The privately held company has more than 23 million individual users in more than 1.5 million organizations. It was on track to book more than $200 million in subscription revenue, including more than $110 million from companies using its enterprise product, GitHub told CNBC last fall.Microsoft has reportedly flirted with buying GitHub in the past, including in 2016, although GitHub denied those reports. A partnership would give Microsoft another connection point to the developers it needs to court to build applications on its various platforms, including the Azure cloud. Microsoft could also use data from GitHub to improve its artificial intelligence producs. The talks come amid GitHub's struggle to replace CEO and founder Chris Wanstrath, who stepped down 10 months ago. Business Insider reported that Microsoft exec Nat Friedman -- who previously ran Xamarin, a developer tools start-up that Microsoft acquired in 2016 -- may take that CEO role. Google's senior VP of ads and commerce, Sridhar Ramaswamy, has also been in discussions for the job, says the report. Microsoft declined to comment on the report. GitHub did not immediately return a request for comment.---> Summarized Content (Word Count is 10):---> Summarized Content (Word Count is 30):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.---> Summarized Content (Word Count is 50):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Just to catch you up: GitHub is an online service that allows developers to host their software projects. For entire code, you may check out from github. Let us know if you also want to understand about abstractive approach. Will arrange an article later on According to gensim source code, at least 10 sentences is recommend for the input No training data or model building is required. It fits not only English but also any other a bag of input (Symbol, Japanese etc). You may also read TextRank research paper for detail understanding. From my experience, the result is not good in most of the time. It may due to variety of words and the result is only a subset of input. I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. Visit my blog from ttp://medium.com/@makcedward/ Get connection from https://www.linkedin.com/in/edwardma1026 Explore my code from https://github.com/makcedward Check my kernal from https://www.kaggle.com/makcedward
[ { "code": null, "e": 473, "s": 172, "text": "To catch a quick idea of long document, we will always to do a summarization when we read a article or book. In English, the first (or first two) sentence(s) of each article has a very high chance of representing the whole article. Of course, the topic sentence can be the last sentence in sometimes." }, { "code": null, "e": 852, "s": 473, "text": "In NLP, there are two approaches to do the text summarization. The first one, extractive approach, is a simple approach which is extracting key words or sentences from article. There are some limitations and proved that the performance is not very good. The second one, abstractive approach, is generating a new sentences base on given article. It needs more advanced technique." }, { "code": null, "e": 877, "s": 852, "text": "After read this article:" }, { "code": null, "e": 993, "s": 877, "text": "Understand PageRank algorithmUnderstand TextRank algorithmHow can we use TextRank algorithm to have a summarization" }, { "code": null, "e": 1023, "s": 993, "text": "Understand PageRank algorithm" }, { "code": null, "e": 1053, "s": 1023, "text": "Understand TextRank algorithm" }, { "code": null, "e": 1111, "s": 1053, "text": "How can we use TextRank algorithm to have a summarization" }, { "code": null, "e": 1249, "s": 1111, "text": "PageRank algorithm is developed by Google for searching the most importance of website so that Google search result is relevant to query." }, { "code": null, "e": 1358, "s": 1249, "text": "In PageRank, it is a directed graph. At the beginning, all node have equal score (1 / total number of node)." }, { "code": null, "e": 1372, "s": 1358, "text": "The algorithm" }, { "code": null, "e": 1591, "s": 1372, "text": "The first formula is the simplified version of PageRank and we will use this one for demo. The second one is a little bit complicated as it involved one more parameter which is damping factor, “d”. By default d is 0.85" }, { "code": null, "e": 1682, "s": 1591, "text": "Let take a look in the simplified version. In iteration 1, here is how PageRank calculate:" }, { "code": null, "e": 1817, "s": 1682, "text": "A: (1/4)/3. As only C is pointing to A, so we use previous C score (iteration 0) divided by number of node (i.e. 3) that C is pointing" }, { "code": null, "e": 2012, "s": 1817, "text": "B: (1/4)/2 + (1/4)/3. Both A and C are pointing to B, so previous A score (iteration 0) divided by number of node (i.e. 2) that A is pointing. For C, it is same as previous one which is (1/4)/3." }, { "code": null, "e": 2074, "s": 2012, "text": "For detail, you may checkout the video for full explantation." }, { "code": null, "e": 2119, "s": 2074, "text": "Question: When should we stop the iteration?" }, { "code": null, "e": 2190, "s": 2119, "text": "According to theory, it should calculate until no big update on score." }, { "code": null, "e": 2363, "s": 2190, "text": "Why we need to introduce PageRank before TextRank? Because the idea of TextRank comes from PageRank and using similar algorithm (graph concept) to calculate the importance." }, { "code": null, "e": 2375, "s": 2363, "text": "Difference:" }, { "code": null, "e": 2563, "s": 2375, "text": "TextRank graph is undirected. Meaning that all edge are bidirectionalThe weight of edge is difference while it is 1 in PageRank. There are different way to calculate such as BM25, TF-IDF." }, { "code": null, "e": 2633, "s": 2563, "text": "TextRank graph is undirected. Meaning that all edge are bidirectional" }, { "code": null, "e": 2752, "s": 2633, "text": "The weight of edge is difference while it is 1 in PageRank. There are different way to calculate such as BM25, TF-IDF." }, { "code": null, "e": 3023, "s": 2752, "text": "There are a lot of different document similarity implementation such as BM25, cosine similarity, IDF-modified-cosine. You may choose the best fit for your problem. If you do not have idea about those algorithm, please let us know and we will include it in later sharing." }, { "code": null, "e": 3105, "s": 3023, "text": "gensim provides a simple API to calculate TextRank by using BM25 (Best Match 25)." }, { "code": null, "e": 3131, "s": 3105, "text": "Step 1: Environment Setup" }, { "code": null, "e": 3157, "s": 3131, "text": "pip install gensim==3.4.0" }, { "code": null, "e": 3180, "s": 3157, "text": "Step 2: Import library" }, { "code": null, "e": 3245, "s": 3180, "text": "import gensim print('gensim Version: %s' % (gensim.__version__))" }, { "code": null, "e": 3253, "s": 3245, "text": "Result:" }, { "code": null, "e": 3275, "s": 3253, "text": "gensim Version: 3.4.0" }, { "code": null, "e": 3307, "s": 3275, "text": "Step 3: Initial testing content" }, { "code": null, "e": 5800, "s": 3307, "text": "# Capture from https://www.cnbc.com/2018/06/01/microsoft--github-acquisition-talks-resume.htmlcontent = \"Microsoft held talks in the past few weeks \" + \\ \"to acquire software developer platform GitHub, Business \" + \\ \"Insider reports. One person familiar with the discussions \" + \\ \"between the companies told CNBC that they had been \" + \\ \"considering a joint marketing partnership valued around \" + \\ \"$35 million, and that those discussions had progressed to \" + \\ \"a possible investment or outright acquisition. It is \" + \\ \"unclear whether talks are still ongoing, but this \" + \\ \"person said that GitHub's price for a full acquisition \" + \\ \"was more than Microsoft currently wanted to pay. GitHub \" + \\ \"was last valued at $2 billion in its last funding round \" + \\ \"2015, but the price tag for an acquisition could be $5 \" + \\ \"billion or more, based on a price that was floated \" + \\ \"last year. GitHub's tools have become essential to \" + \\ \"software developers, who use it to store code, \" + \\ \"keep track of updates and discuss issues. The privately \" + \\ \"held company has more than 23 million individual users in \" + \\ \"more than 1.5 million organizations. It was on track to \" + \\ \"book more than $200 million in subscription revenue, \" + \\ \"including more than $110 million from companies using its \" + \\ \"enterprise product, GitHub told CNBC last fall.Microsoft \" + \\ \"has reportedly flirted with buying GitHub in the past, \" + \\ \"including in 2016, although GitHub denied those \" + \\ \"reports. A partnership would give Microsoft another \" + \\ \"connection point to the developers it needs to court to \" + \\ \"build applications on its various platforms, including \" + \\ \"the Azure cloud. Microsoft could also use data from \" + \\ \"GitHub to improve its artificial intelligence \" + \\ \"producs. The talks come amid GitHub's struggle to \" + \\ \"replace CEO and founder Chris Wanstrath, who stepped \" + \\ \"down 10 months ago. Business Insider reported that \" + \\ \"Microsoft exec Nat Friedman -- who previously \" + \\ \"ran Xamarin, a developer tools start-up that Microsoft \" + \\ \"acquired in 2016 -- may take that CEO role. Google's \" + \\ \"senior VP of ads and commerce, Sridhar Ramaswamy, has \" + \\ \"also been in discussions for the job, says the report. \" + \\ \"Microsoft declined to comment on the report. \" + \\ \"GitHub did not immediately return a request for comment.\"" }, { "code": null, "e": 5828, "s": 5800, "text": "Step 4: Try different ratio" }, { "code": null, "e": 5900, "s": 5828, "text": "Ratio parameter use for decide number of import sentences are returned." }, { "code": null, "e": 9413, "s": 5900, "text": "Original Content:Microsoft held talks in the past few weeks to acquire software developer platform GitHub, Business Insider reports. One person familiar with the discussions between the companies told CNBC that they had been considering a joint marketing partnership valued around $35 million, and that those discussions had progressed to a possible investment or outright acquisition. It is unclear whether talks are still ongoing, but this person said that GitHub's price for a full acquisition was more than Microsoft currently wanted to pay. GitHub was last valued at $2 billion in its last funding round 2015, but the price tag for an acquisition could be $5 billion or more, based on a price that was floated last year. GitHub's tools have become essential to software developers, who use it to store code, keep track of updates and discuss issues. The privately held company has more than 23 million individual users in more than 1.5 million organizations. It was on track to book more than $200 million in subscription revenue, including more than $110 million from companies using its enterprise product, GitHub told CNBC last fall.Microsoft has reportedly flirted with buying GitHub in the past, including in 2016, although GitHub denied those reports. A partnership would give Microsoft another connection point to the developers it needs to court to build applications on its various platforms, including the Azure cloud. Microsoft could also use data from GitHub to improve its artificial intelligence producs. The talks come amid GitHub's struggle to replace CEO and founder Chris Wanstrath, who stepped down 10 months ago. Business Insider reported that Microsoft exec Nat Friedman -- who previously ran Xamarin, a developer tools start-up that Microsoft acquired in 2016 -- may take that CEO role. Google's senior VP of ads and commerce, Sridhar Ramaswamy, has also been in discussions for the job, says the report. Microsoft declined to comment on the report. GitHub did not immediately return a request for comment.---> Summarized Content (Ratio is 0.3):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.5):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.7):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.From there, anyone from all over the world can download those projects and submit their own improvements.development world." }, { "code": null, "e": 9420, "s": 9413, "text": "Result" }, { "code": null, "e": 11872, "s": 9420, "text": "Original Content:On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users. It's not immediately clear what will come of these talks. Microsoft declined to comment, but you can read the full Business Insider report here. While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup. If the stars align, and GitHub is integrated intelligently into Microsoft's products, it could give the company a big edge against Amazon Web Services, the leading player in the fast-growing cloud market. Just to catch you up: GitHub is an online service that allows developers to host their software projects. From there, anyone from all over the world can download those projects and submit their own improvements. That functionality has made GitHub the center of the open source software. development world.---> Summarized Content (Ratio is 0.3):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.5):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.---> Summarized Content (Ratio is 0.7):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Microsoft declined to comment, but you can read the full Business Insider report here.While we wait for further word on the future of GitHub, one thing is very clear: It would make perfect sense for Microsoft to buy the startup.Just to catch you up: GitHub is an online service that allows developers to host their software projects.From there, anyone from all over the world can download those projects and submit their own improvements.development world." }, { "code": null, "e": 11905, "s": 11872, "text": "Step 5: Try different word count" }, { "code": null, "e": 12034, "s": 11905, "text": "Word count parameter is another variable to control the result. If both word_count and ratio are entered. Ratio will be ignored." }, { "code": null, "e": 12299, "s": 12034, "text": "print('Original Content:')print(content)for word_count in [10, 30, 50]: summarized_content = gensim.summarization.summarize(body, word_count=word_count) print() print('---> Summarized Content (Word Count is %d):' % word_count) print(summarized_content)" }, { "code": null, "e": 12306, "s": 12299, "text": "Result" }, { "code": null, "e": 14885, "s": 12306, "text": "riginal Content:Microsoft held talks in the past few weeks to acquire software developer platform GitHub, Business Insider reports. One person familiar with the discussions between the companies told CNBC that they had been considering a joint marketing partnership valued around $35 million, and that those discussions had progressed to a possible investment or outright acquisition. It is unclear whether talks are still ongoing, but this person said that GitHub's price for a full acquisition was more than Microsoft currently wanted to pay. GitHub was last valued at $2 billion in its last funding round 2015, but the price tag for an acquisition could be $5 billion or more, based on a price that was floated last year. GitHub's tools have become essential to software developers, who use it to store code, keep track of updates and discuss issues. The privately held company has more than 23 million individual users in more than 1.5 million organizations. It was on track to book more than $200 million in subscription revenue, including more than $110 million from companies using its enterprise product, GitHub told CNBC last fall.Microsoft has reportedly flirted with buying GitHub in the past, including in 2016, although GitHub denied those reports. A partnership would give Microsoft another connection point to the developers it needs to court to build applications on its various platforms, including the Azure cloud. Microsoft could also use data from GitHub to improve its artificial intelligence producs. The talks come amid GitHub's struggle to replace CEO and founder Chris Wanstrath, who stepped down 10 months ago. Business Insider reported that Microsoft exec Nat Friedman -- who previously ran Xamarin, a developer tools start-up that Microsoft acquired in 2016 -- may take that CEO role. Google's senior VP of ads and commerce, Sridhar Ramaswamy, has also been in discussions for the job, says the report. Microsoft declined to comment on the report. GitHub did not immediately return a request for comment.---> Summarized Content (Word Count is 10):---> Summarized Content (Word Count is 30):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.---> Summarized Content (Word Count is 50):On Friday, Business Insider reported that Microsoft has held talks to buy GitHub — a $2 billion startup that claims 24 million software developers as users.Just to catch you up: GitHub is an online service that allows developers to host their software projects." }, { "code": null, "e": 15037, "s": 14885, "text": "For entire code, you may check out from github. Let us know if you also want to understand about abstractive approach. Will arrange an article later on" }, { "code": null, "e": 15119, "s": 15037, "text": "According to gensim source code, at least 10 sentences is recommend for the input" }, { "code": null, "e": 15167, "s": 15119, "text": "No training data or model building is required." }, { "code": null, "e": 15318, "s": 15167, "text": "It fits not only English but also any other a bag of input (Symbol, Japanese etc). You may also read TextRank research paper for detail understanding." }, { "code": null, "e": 15455, "s": 15318, "text": "From my experience, the result is not good in most of the time. It may due to variety of words and the result is only a subset of input." }, { "code": null, "e": 15600, "s": 15455, "text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related." }, { "code": null, "e": 15649, "s": 15600, "text": "Visit my blog from ttp://medium.com/@makcedward/" }, { "code": null, "e": 15710, "s": 15649, "text": "Get connection from https://www.linkedin.com/in/edwardma1026" }, { "code": null, "e": 15761, "s": 15710, "text": "Explore my code from https://github.com/makcedward" } ]
What is the correct way of using <br>, <br/>, or <br /> in HTML?
In HTML, the <br> tag is used for line break. It is an empty tag i.e. no need to add an end tag. Writing <br> tag is perfectly fine. Let’s see the usage of other br tags i.e. <br/> or <br />, In HTML, use <br> tag. In XHTML, the valid way is to use <br/> or <br></br> as mentioned in the XHTML guidelines. According to w3 guidelines, a space should be included before the trailing / and > of empty elements, for example, <br />. These guidelines are for XHTML documents to render on existing HTML user agents. You can try to run the following code to learn the perfect usage of <br> tag Live Demo <!DOCTYPE html> <html> <head> <title>HTML br Tag</title> </head> <body> <p>This is before the line break<br> and this after the line break. </p> </body> </html>
[ { "code": null, "e": 1195, "s": 1062, "text": "In HTML, the <br> tag is used for line break. It is an empty tag i.e. no need to add an end tag. Writing <br> tag is perfectly fine." }, { "code": null, "e": 1254, "s": 1195, "text": "Let’s see the usage of other br tags i.e. <br/> or <br />," }, { "code": null, "e": 1277, "s": 1254, "text": "In HTML, use <br> tag." }, { "code": null, "e": 1368, "s": 1277, "text": "In XHTML, the valid way is to use <br/> or <br></br> as mentioned in the XHTML guidelines." }, { "code": null, "e": 1572, "s": 1368, "text": "According to w3 guidelines, a space should be included before the trailing / and > of empty elements, for example, <br />. These guidelines are for XHTML documents to render on existing HTML user agents." }, { "code": null, "e": 1649, "s": 1572, "text": "You can try to run the following code to learn the perfect usage of <br> tag" }, { "code": null, "e": 1659, "s": 1649, "text": "Live Demo" }, { "code": null, "e": 1859, "s": 1659, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML br Tag</title>\n </head>\n <body>\n <p>This is before the line break<br>\n and this after the line break.\n </p>\n </body>\n</html>" } ]
What is the difference between checked and unchecked exceptions in Java?
A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions. If you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. import java.io.File; import java.io.FileReader; public class FilenotFound_Demo { public static void main(String args[]) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } } C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error
[ { "code": null, "e": 1313, "s": 1062, "text": "A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions." }, { "code": null, "e": 1541, "s": 1313, "text": "If you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception." }, { "code": null, "e": 1762, "s": 1541, "text": "import java.io.File;\nimport java.io.FileReader;\n\npublic class FilenotFound_Demo {\n public static void main(String args[]) {\n File file = new File(\"E://file.txt\");\n FileReader fr = new FileReader(file);\n }\n}" }, { "code": null, "e": 1984, "s": 1762, "text": "C:\\>javac FilenotFound_Demo.java\nFilenotFound_Demo.java:8: error: unreported exception\nFileNotFoundException; must be caught or declared to be thrown\n FileReader fr = new FileReader(file);\n ^\n1 error" } ]
1 quick tip for pulling data from a Pandas dataframe using SQL queries | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 The Pandas library is awesome for anyone that uses Python to analyse their data. It’s very easy to use, quite fast when applied properly, and flexible in its capabilities. With Pandas, a lot of the functions that would have normally required more work, for example retrieving some basic statistics about your data, are just a single function call away! Still, sometimes we’re more comfortable with one tool over another. If you’re used to looking through your data on Excel, Tableau, or SQL, then switching to Pandas is still a bit of a jump. There’s a great Python library for helping smooth over that transition if you’re coming from a background of SQL: Pandasql. Pandasql allows you to write SQL queries for querying your data from a pandas dataframe. This allows you to get around the normal requirement of having to learn a lot of Python in Pandas. Instead, you can simply write your regular SQL query within a function call and run it on a Pandas dataframe to retrieve your data! We can install the Pandasql with a quick pip: pip install pandasql Let’s start working with an actual dataset. We’ll load in the iris flowers dataset using the seaborn library: import pandasqlimport seaborn as snsdata = sns.load_dataset('iris') Normally, if we wanted to retrieve the first 20 items in our dataframe, we’d do something like this with pandas: data.head(20) With pandasql we can write out our standard SQL query in the exact same way we normally do when running it on an SQL database. Just pass the name of the pandas dataframe as the name of the table you are parsing and the data will be retrieved: sub_data = pandasql.sqldf("SELECT * FROM data LIMIT 20;", globals())print(sub_data) The regular filtering operations that we can do with WHERE in SQL are also applicable. Let’s pull all the data where petal_length is greater than 5 using pandas first: sub_data = data[data["petal_length"] > 5.0] To do it in SQL, wecertain rows simply add our WHERE call to do the same filtering: sub_data = pandasql.sqldf("SELECT * FROM data WHERE petal_length > 5.0;", globals()) We can of course, always select only the columns we want as well: sub_data = pandasql.sqldf("SELECT petal_width, petal_length FROM data WHERE petal_length > 5.0;", globals()) And that’s how you can use SQL queries to retrieve data from a pandas dataframe. Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
[ { "code": null, "e": 233, "s": 172, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 314, "s": 233, "text": "The Pandas library is awesome for anyone that uses Python to analyse their data." }, { "code": null, "e": 586, "s": 314, "text": "It’s very easy to use, quite fast when applied properly, and flexible in its capabilities. With Pandas, a lot of the functions that would have normally required more work, for example retrieving some basic statistics about your data, are just a single function call away!" }, { "code": null, "e": 776, "s": 586, "text": "Still, sometimes we’re more comfortable with one tool over another. If you’re used to looking through your data on Excel, Tableau, or SQL, then switching to Pandas is still a bit of a jump." }, { "code": null, "e": 900, "s": 776, "text": "There’s a great Python library for helping smooth over that transition if you’re coming from a background of SQL: Pandasql." }, { "code": null, "e": 1220, "s": 900, "text": "Pandasql allows you to write SQL queries for querying your data from a pandas dataframe. This allows you to get around the normal requirement of having to learn a lot of Python in Pandas. Instead, you can simply write your regular SQL query within a function call and run it on a Pandas dataframe to retrieve your data!" }, { "code": null, "e": 1266, "s": 1220, "text": "We can install the Pandasql with a quick pip:" }, { "code": null, "e": 1287, "s": 1266, "text": "pip install pandasql" }, { "code": null, "e": 1397, "s": 1287, "text": "Let’s start working with an actual dataset. We’ll load in the iris flowers dataset using the seaborn library:" }, { "code": null, "e": 1465, "s": 1397, "text": "import pandasqlimport seaborn as snsdata = sns.load_dataset('iris')" }, { "code": null, "e": 1578, "s": 1465, "text": "Normally, if we wanted to retrieve the first 20 items in our dataframe, we’d do something like this with pandas:" }, { "code": null, "e": 1592, "s": 1578, "text": "data.head(20)" }, { "code": null, "e": 1835, "s": 1592, "text": "With pandasql we can write out our standard SQL query in the exact same way we normally do when running it on an SQL database. Just pass the name of the pandas dataframe as the name of the table you are parsing and the data will be retrieved:" }, { "code": null, "e": 1919, "s": 1835, "text": "sub_data = pandasql.sqldf(\"SELECT * FROM data LIMIT 20;\", globals())print(sub_data)" }, { "code": null, "e": 2087, "s": 1919, "text": "The regular filtering operations that we can do with WHERE in SQL are also applicable. Let’s pull all the data where petal_length is greater than 5 using pandas first:" }, { "code": null, "e": 2131, "s": 2087, "text": "sub_data = data[data[\"petal_length\"] > 5.0]" }, { "code": null, "e": 2215, "s": 2131, "text": "To do it in SQL, wecertain rows simply add our WHERE call to do the same filtering:" }, { "code": null, "e": 2300, "s": 2215, "text": "sub_data = pandasql.sqldf(\"SELECT * FROM data WHERE petal_length > 5.0;\", globals())" }, { "code": null, "e": 2366, "s": 2300, "text": "We can of course, always select only the columns we want as well:" }, { "code": null, "e": 2475, "s": 2366, "text": "sub_data = pandasql.sqldf(\"SELECT petal_width, petal_length FROM data WHERE petal_length > 5.0;\", globals())" }, { "code": null, "e": 2556, "s": 2475, "text": "And that’s how you can use SQL queries to retrieve data from a pandas dataframe." } ]
MongoDB query for exact match on multiple document fields
For exact match, set the values to be matched inside MongoDB $in(). Let us first create a collection with documents − > db.demo422.insertOne({"Name":"Chris","Marks":34}); { "acknowledged" : true, "insertedId" : ObjectId("5e73a4059822da45b30346e1") } > db.demo422.insertOne({"Name":"Chris","Marks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5e73a40a9822da45b30346e2") } > db.demo422.insertOne({"Name":"David","Marks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5e73a4149822da45b30346e3") } > db.demo422.insertOne({"Name":"Sam","Marks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5e73a41e9822da45b30346e4") } > db.demo422.insertOne({"Name":"David","Marks":89}); { "acknowledged" : true, "insertedId" : ObjectId("5e73a4239822da45b30346e5") } Display all documents from a collection with the help of find() method − > db.demo422.find(); This will produce the following output − { "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 } { "_id" : ObjectId("5e73a40a9822da45b30346e2"), "Name" : "Chris", "Marks" : 56 } { "_id" : ObjectId("5e73a4149822da45b30346e3"), "Name" : "David", "Marks" : 78 } { "_id" : ObjectId("5e73a41e9822da45b30346e4"), "Name" : "Sam", "Marks" : 45 } { "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 } Following is the query to get records with exact match on multiple document fields − > db.demo422.find({'$and': [{'Name': {'$in': ['Chris', 'David']}, 'Marks': {'$in': [34,89]}}]}); This will produce the following output − { "_id" : ObjectId("5e73a4059822da45b30346e1"), "Name" : "Chris", "Marks" : 34 } { "_id" : ObjectId("5e73a4239822da45b30346e5"), "Name" : "David", "Marks" : 89 }
[ { "code": null, "e": 1180, "s": 1062, "text": "For exact match, set the values to be matched inside MongoDB $in(). Let us first create a collection with documents −" }, { "code": null, "e": 1868, "s": 1180, "text": "> db.demo422.insertOne({\"Name\":\"Chris\",\"Marks\":34});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e73a4059822da45b30346e1\")\n}\n> db.demo422.insertOne({\"Name\":\"Chris\",\"Marks\":56});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e73a40a9822da45b30346e2\")\n}\n> db.demo422.insertOne({\"Name\":\"David\",\"Marks\":78});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e73a4149822da45b30346e3\")\n}\n> db.demo422.insertOne({\"Name\":\"Sam\",\"Marks\":45});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e73a41e9822da45b30346e4\")\n}\n> db.demo422.insertOne({\"Name\":\"David\",\"Marks\":89});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e73a4239822da45b30346e5\")\n}" }, { "code": null, "e": 1941, "s": 1868, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1962, "s": 1941, "text": "> db.demo422.find();" }, { "code": null, "e": 2003, "s": 1962, "text": "This will produce the following output −" }, { "code": null, "e": 2406, "s": 2003, "text": "{ \"_id\" : ObjectId(\"5e73a4059822da45b30346e1\"), \"Name\" : \"Chris\", \"Marks\" : 34 }\n{ \"_id\" : ObjectId(\"5e73a40a9822da45b30346e2\"), \"Name\" : \"Chris\", \"Marks\" : 56 }\n{ \"_id\" : ObjectId(\"5e73a4149822da45b30346e3\"), \"Name\" : \"David\", \"Marks\" : 78 }\n{ \"_id\" : ObjectId(\"5e73a41e9822da45b30346e4\"), \"Name\" : \"Sam\", \"Marks\" : 45 }\n{ \"_id\" : ObjectId(\"5e73a4239822da45b30346e5\"), \"Name\" : \"David\", \"Marks\" : 89 }" }, { "code": null, "e": 2491, "s": 2406, "text": "Following is the query to get records with exact match on multiple document fields −" }, { "code": null, "e": 2588, "s": 2491, "text": "> db.demo422.find({'$and': [{'Name': {'$in': ['Chris', 'David']}, 'Marks': {'$in': [34,89]}}]});" }, { "code": null, "e": 2629, "s": 2588, "text": "This will produce the following output −" }, { "code": null, "e": 2791, "s": 2629, "text": "{ \"_id\" : ObjectId(\"5e73a4059822da45b30346e1\"), \"Name\" : \"Chris\", \"Marks\" : 34 }\n{ \"_id\" : ObjectId(\"5e73a4239822da45b30346e5\"), \"Name\" : \"David\", \"Marks\" : 89 }" } ]
CSS - Outlines
Outlines are very similar to borders, but there are few major differences as well − An outline does not take up space. An outline does not take up space. Outlines do not have to be rectangular. Outlines do not have to be rectangular. Outline is always the same on all sides; you cannot specify different values for different sides of an element. Outline is always the same on all sides; you cannot specify different values for different sides of an element. NOTE − The outline properties are not supported by IE 6 or Netscape 7. You can set the following outline properties using CSS. The outline-width property is used to set the width of the outline. The outline-width property is used to set the width of the outline. The outline-style property is used to set the line style for the outline. The outline-style property is used to set the line style for the outline. The outline-color property is used to set the color of the outline. The outline-color property is used to set the color of the outline. The outline property is used to set all the above three properties in a single statement. The outline property is used to set all the above three properties in a single statement. The outline-width property specifies the width of the outline to be added to the box. Its value should be a length or one of the values thin, medium, or thick, just like the border-width attribute. A width of zero pixels means no outline. Here is an example − <html> <head> </head> <body> <p style = "outline-width:thin; outline-style:solid;"> This text is having thin outline. </p> <br /> <p style = "outline-width:thick; outline-style:solid;"> This text is having thick outline. </p> <br /> <p style = "outline-width:5px; outline-style:solid;"> This text is having 5x outline. </p> </body> </html> It will produce the following result − This text is having thin outline. This text is having thick outline. This text is having 5x outline. The outline-style property specifies the style for the line (solid, dotted, or dashed) that goes around an element. It can take one of the following values − none − No border. (Equivalent of outline-width:0;) none − No border. (Equivalent of outline-width:0;) solid − Outline is a single solid line. solid − Outline is a single solid line. dotted − Outline is a series of dots. dotted − Outline is a series of dots. dashed − Outline is a series of short lines. dashed − Outline is a series of short lines. double − Outline is two solid lines. double − Outline is two solid lines. groove − Outline looks as though it is carved into the page. groove − Outline looks as though it is carved into the page. ridge − Outline looks the opposite of groove. ridge − Outline looks the opposite of groove. inset − Outline makes the box look like it is embedded in the page. inset − Outline makes the box look like it is embedded in the page. outset − Outline makes the box look like it is coming out of the canvas. outset − Outline makes the box look like it is coming out of the canvas. hidden − Same as none. hidden − Same as none. Here is an example − <html> <head> </head> <body> <p style = "outline-width:thin; outline-style:solid;"> This text is having thin solid outline. </p> <br /> <p style = "outline-width:thick; outline-style:dashed;"> This text is having thick dashed outline. </p> <br /> <p style = "outline-width:5px;outline-style:dotted;"> This text is having 5x dotted outline. </p> </body> </html> It will produce the following result − This text is having thin solid outline. This text is having thick dashed outline. This text is having 5x dotted outline. The outline-color property allows you to specify the color of the outline. Its value should either be a color name, a hex color, or an RGB value, as with the color and border-color properties. Here is an example − <html> <head> </head> <body> <p style = "outline-width:thin; outline-style:solid;outline-color:red"> This text is having thin solid red outline. </p> <br /> <p style = "outline-width:thick; outline-style:dashed;outline-color:#009900"> This text is having thick dashed green outline. </p> <br /> <p style = "outline-width:5px;outline-style:dotted;outline-color:rgb(13,33,232)"> This text is having 5x dotted blue outline. </p> </body> </html> It will produce the following result − This text is having thin solid red outline. This text is having thick dashed green outline. This text is having 5x dotted blue outline. The outline property is a shorthand property that allows you to specify values for any of the three properties discussed previously in any order but in a single statement. Here is an example − <html> <head> </head> <body> <p style = "outline:thin solid red;"> This text is having thin solid red outline. </p> <br /> <p style = "outline:thick dashed #009900;"> This text is having thick dashed green outline. </p> <br /> <p style = "outline:5px dotted rgb(13,33,232);"> This text is having 5x dotted blue outline. </p> </body> </html> It will produce the following result − This text is having thin solid red outline. This text is having thick dashed green outline. This text is having 5x dotted blue outline. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2710, "s": 2626, "text": "Outlines are very similar to borders, but there are few major differences as well −" }, { "code": null, "e": 2745, "s": 2710, "text": "An outline does not take up space." }, { "code": null, "e": 2780, "s": 2745, "text": "An outline does not take up space." }, { "code": null, "e": 2820, "s": 2780, "text": "Outlines do not have to be rectangular." }, { "code": null, "e": 2860, "s": 2820, "text": "Outlines do not have to be rectangular." }, { "code": null, "e": 2972, "s": 2860, "text": "Outline is always the same on all sides; you cannot specify different values for different sides of an element." }, { "code": null, "e": 3084, "s": 2972, "text": "Outline is always the same on all sides; you cannot specify different values for different sides of an element." }, { "code": null, "e": 3155, "s": 3084, "text": "NOTE − The outline properties are not supported by IE 6 or Netscape 7." }, { "code": null, "e": 3211, "s": 3155, "text": "You can set the following outline properties using CSS." }, { "code": null, "e": 3279, "s": 3211, "text": "The outline-width property is used to set the width of the outline." }, { "code": null, "e": 3347, "s": 3279, "text": "The outline-width property is used to set the width of the outline." }, { "code": null, "e": 3421, "s": 3347, "text": "The outline-style property is used to set the line style for the outline." }, { "code": null, "e": 3495, "s": 3421, "text": "The outline-style property is used to set the line style for the outline." }, { "code": null, "e": 3563, "s": 3495, "text": "The outline-color property is used to set the color of the outline." }, { "code": null, "e": 3631, "s": 3563, "text": "The outline-color property is used to set the color of the outline." }, { "code": null, "e": 3721, "s": 3631, "text": "The outline property is used to set all the above three properties in a single statement." }, { "code": null, "e": 3811, "s": 3721, "text": "The outline property is used to set all the above three properties in a single statement." }, { "code": null, "e": 4009, "s": 3811, "text": "The outline-width property specifies the width of the outline to be added to the box. Its value should be a length or one of the values thin, medium, or thick, just like the border-width attribute." }, { "code": null, "e": 4050, "s": 4009, "text": "A width of zero pixels means no outline." }, { "code": null, "e": 4071, "s": 4050, "text": "Here is an example −" }, { "code": null, "e": 4517, "s": 4071, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"outline-width:thin; outline-style:solid;\">\n This text is having thin outline.\n </p>\n <br />\n \n <p style = \"outline-width:thick; outline-style:solid;\">\n This text is having thick outline.\n </p>\n <br />\n \n <p style = \"outline-width:5px; outline-style:solid;\">\n This text is having 5x outline.\n </p>\n </body>\n</html> " }, { "code": null, "e": 4556, "s": 4517, "text": "It will produce the following result −" }, { "code": null, "e": 4595, "s": 4556, "text": "\n This text is having thin outline.\n" }, { "code": null, "e": 4635, "s": 4595, "text": "\n This text is having thick outline.\n" }, { "code": null, "e": 4672, "s": 4635, "text": "\n This text is having 5x outline.\n" }, { "code": null, "e": 4830, "s": 4672, "text": "The outline-style property specifies the style for the line (solid, dotted, or dashed) that goes around an element. It can take one of the following values −" }, { "code": null, "e": 4881, "s": 4830, "text": "none − No border. (Equivalent of outline-width:0;)" }, { "code": null, "e": 4932, "s": 4881, "text": "none − No border. (Equivalent of outline-width:0;)" }, { "code": null, "e": 4972, "s": 4932, "text": "solid − Outline is a single solid line." }, { "code": null, "e": 5012, "s": 4972, "text": "solid − Outline is a single solid line." }, { "code": null, "e": 5050, "s": 5012, "text": "dotted − Outline is a series of dots." }, { "code": null, "e": 5088, "s": 5050, "text": "dotted − Outline is a series of dots." }, { "code": null, "e": 5133, "s": 5088, "text": "dashed − Outline is a series of short lines." }, { "code": null, "e": 5178, "s": 5133, "text": "dashed − Outline is a series of short lines." }, { "code": null, "e": 5215, "s": 5178, "text": "double − Outline is two solid lines." }, { "code": null, "e": 5252, "s": 5215, "text": "double − Outline is two solid lines." }, { "code": null, "e": 5313, "s": 5252, "text": "groove − Outline looks as though it is carved into the page." }, { "code": null, "e": 5374, "s": 5313, "text": "groove − Outline looks as though it is carved into the page." }, { "code": null, "e": 5420, "s": 5374, "text": "ridge − Outline looks the opposite of groove." }, { "code": null, "e": 5466, "s": 5420, "text": "ridge − Outline looks the opposite of groove." }, { "code": null, "e": 5534, "s": 5466, "text": "inset − Outline makes the box look like it is embedded in the page." }, { "code": null, "e": 5602, "s": 5534, "text": "inset − Outline makes the box look like it is embedded in the page." }, { "code": null, "e": 5675, "s": 5602, "text": "outset − Outline makes the box look like it is coming out of the canvas." }, { "code": null, "e": 5748, "s": 5675, "text": "outset − Outline makes the box look like it is coming out of the canvas." }, { "code": null, "e": 5771, "s": 5748, "text": "hidden − Same as none." }, { "code": null, "e": 5794, "s": 5771, "text": "hidden − Same as none." }, { "code": null, "e": 5815, "s": 5794, "text": "Here is an example −" }, { "code": null, "e": 6283, "s": 5815, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"outline-width:thin; outline-style:solid;\">\n This text is having thin solid outline.\n </p>\n <br />\n \n <p style = \"outline-width:thick; outline-style:dashed;\">\n This text is having thick dashed outline.\n </p>\n <br />\n \n <p style = \"outline-width:5px;outline-style:dotted;\">\n This text is having 5x dotted outline.\n </p>\n </body>\n</html> " }, { "code": null, "e": 6322, "s": 6283, "text": "It will produce the following result −" }, { "code": null, "e": 6368, "s": 6322, "text": "\n This text is having thin solid outline.\n" }, { "code": null, "e": 6415, "s": 6368, "text": "\n This text is having thick dashed outline.\n" }, { "code": null, "e": 6459, "s": 6415, "text": "\n This text is having 5x dotted outline.\n" }, { "code": null, "e": 6652, "s": 6459, "text": "The outline-color property allows you to specify the color of the outline. Its value should either be a color name, a hex color, or an RGB value, as with the color and border-color properties." }, { "code": null, "e": 6673, "s": 6652, "text": "Here is an example −" }, { "code": null, "e": 7222, "s": 6673, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"outline-width:thin; outline-style:solid;outline-color:red\">\n This text is having thin solid red outline.\n </p>\n <br />\n \n <p style = \"outline-width:thick; outline-style:dashed;outline-color:#009900\">\n This text is having thick dashed green outline.\n </p>\n <br />\n \n <p style = \"outline-width:5px;outline-style:dotted;outline-color:rgb(13,33,232)\">\n This text is having 5x dotted blue outline.\n </p>\n </body>\n</html> " }, { "code": null, "e": 7261, "s": 7222, "text": "It will produce the following result −" }, { "code": null, "e": 7311, "s": 7261, "text": "\n This text is having thin solid red outline.\n" }, { "code": null, "e": 7364, "s": 7311, "text": "\n This text is having thick dashed green outline.\n" }, { "code": null, "e": 7413, "s": 7364, "text": "\n This text is having 5x dotted blue outline.\n" }, { "code": null, "e": 7585, "s": 7413, "text": "The outline property is a shorthand property that allows you to specify values for any of the three properties discussed previously in any order but in a single statement." }, { "code": null, "e": 7606, "s": 7585, "text": "Here is an example −" }, { "code": null, "e": 8053, "s": 7606, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"outline:thin solid red;\">\n This text is having thin solid red outline.\n </p>\n <br />\n \n <p style = \"outline:thick dashed #009900;\">\n This text is having thick dashed green outline.\n </p>\n <br />\n \n <p style = \"outline:5px dotted rgb(13,33,232);\">\n This text is having 5x dotted blue outline.\n </p>\n </body>\n</html> " }, { "code": null, "e": 8092, "s": 8053, "text": "It will produce the following result −" }, { "code": null, "e": 8141, "s": 8092, "text": "\n This text is having thin solid red outline.\n" }, { "code": null, "e": 8194, "s": 8141, "text": "\n This text is having thick dashed green outline.\n" }, { "code": null, "e": 8243, "s": 8194, "text": "\n This text is having 5x dotted blue outline.\n" }, { "code": null, "e": 8278, "s": 8243, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8292, "s": 8278, "text": " Anadi Sharma" }, { "code": null, "e": 8327, "s": 8292, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8344, "s": 8327, "text": " Frahaan Hussain" }, { "code": null, "e": 8379, "s": 8344, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8410, "s": 8379, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8445, "s": 8410, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8476, "s": 8445, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8511, "s": 8476, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8542, "s": 8511, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8575, "s": 8542, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 8606, "s": 8575, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8613, "s": 8606, "text": " Print" }, { "code": null, "e": 8624, "s": 8613, "text": " Add Notes" } ]
How to set cookies to expire in 30 minutes in JavaScript?
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time. You can try to run the following example to set cookies to expire in 30 minutes Live Demo <html> <head> <script> <!-- function WriteCookie() { var now = new Date(); var minutes = 30; now.setTime(now.getTime() + (minutes * 60 * 1000)); cookievalue = escape(document.myform.customer.value) + ";" document.cookie="name=" + cookievalue; document.cookie = "expires=" + now.toUTCString() + ";" document.write ("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie()"/> </form> </body> </html>
[ { "code": null, "e": 1281, "s": 1062, "text": "You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time." }, { "code": null, "e": 1361, "s": 1281, "text": "You can try to run the following example to set cookies to expire in 30 minutes" }, { "code": null, "e": 1371, "s": 1361, "text": "Live Demo" }, { "code": null, "e": 2138, "s": 1371, "text": "<html>\n <head>\n <script>\n <!--\n function WriteCookie() {\n var now = new Date();\n var minutes = 30;\n now.setTime(now.getTime() + (minutes * 60 * 1000));\n cookievalue = escape(document.myform.customer.value) + \";\"\n\n document.cookie=\"name=\" + cookievalue;\n document.cookie = \"expires=\" + now.toUTCString() + \";\"\n document.write (\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script>\n </head>\n <body>\n <form name=\"myform\" action=\"\">\n Enter name: <input type=\"text\" name=\"customer\"/>\n <input type=\"button\" value=\"Set Cookie\" onclick=\"WriteCookie()\"/>\n </form>\n </body>\n</html>" } ]
Modular Arithmetic - GeeksforGeeks
04 May, 2020 Modular arithmetic is the branch of arithmetic mathematics related with the “mod” functionality. Basically, modular arithmetic is related with computation of “mod” of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other. Here we will discuss briefly about all modular arithmetic operations. Quotient Remainder Theorem :It states that, for any pair of integers a and b (b is positive), there exists two unique integers q and r such that: a = b x q + rwhere 0 <= r < b Example:If a = 20, b = 6then q = 3, r = 220 = 6 x 3 + 2 Modular Addition :Rule for modular addition is: (a + b) mod m = ((a mod m) + (b mod m)) mod m Example: (15 + 17) % 7 = ((15 % 7) + (17 % 7)) % 7 = (1 + 3) % 7 = 4 % 7 = 4 Same rule is for modular subtraction. We don’t require much modular subtraction but it can also be done in same way. Modular Multiplication :Rule for modular multiplication is: (a x b) mod m = ((a mod m) x (b mod m)) mod m Example: (12 x 13) % 5 = ((12 % 5) x (13 % 5)) % 5 = (2 x 3) % 5 = 6 % 5 = 1 Modular Division :Modular division is totally different from modular addition, subtraction and multiplication. It also does not exist always. (a / b) mod m is not equal to ((a mod m) / (b mod m)) mod m. This is calculated using following formula: (a / b) mod m = (a x (inverse of b if exists)) mod m Modular Inverse :The modular inverse of a mod m exists only if a and m are relatively prime i.e. gcd(a, m) = 1.Hence, for finding inverse of a under modulo m,if (a x b) mod m = 1 then b is modular inverse of a.Example:a = 5, m = 7(5 x 3) % 7 = 1hence, 3 is modulo inverse of 5 under 7. Modular Exponentiation :Finding a^b mod m is the modular exponentiation. There are two approaches for this – recursive and iterative.Example: a = 5, b = 2, m = 7 (5 ^ 2) % 7 = 25 % 7 = 4 Below are some more important concepts related to Modular Arithmetic Euler’s Totient Function Compute n! under modulo p Wilson’s Theorem How to compute mod of a big number? Find value of y mod (2 raised to power x) Recent Articles on Modular Arithmetic. Modular Arithmetic Engineering Mathematics Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Univariate, Bivariate and Multivariate data and its analysis Mathematics | Graph Isomorphisms and Connectivity Activation Functions Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Properties of Boolean Algebra Mathematics | Euler and Hamiltonian Paths Mathematics | Graph Theory Basics - Set 1 Betweenness Centrality (Centrality Measure)
[ { "code": null, "e": 24792, "s": 24764, "text": "\n04 May, 2020" }, { "code": null, "e": 25161, "s": 24792, "text": "Modular arithmetic is the branch of arithmetic mathematics related with the “mod” functionality. Basically, modular arithmetic is related with computation of “mod” of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other. Here we will discuss briefly about all modular arithmetic operations." }, { "code": null, "e": 25307, "s": 25161, "text": "Quotient Remainder Theorem :It states that, for any pair of integers a and b (b is positive), there exists two unique integers q and r such that:" }, { "code": null, "e": 25337, "s": 25307, "text": "a = b x q + rwhere 0 <= r < b" }, { "code": null, "e": 25393, "s": 25337, "text": "Example:If a = 20, b = 6then q = 3, r = 220 = 6 x 3 + 2" }, { "code": null, "e": 25441, "s": 25393, "text": "Modular Addition :Rule for modular addition is:" }, { "code": null, "e": 25487, "s": 25441, "text": "(a + b) mod m = ((a mod m) + (b mod m)) mod m" }, { "code": null, "e": 25496, "s": 25487, "text": "Example:" }, { "code": null, "e": 25565, "s": 25496, "text": "(15 + 17) % 7\n= ((15 % 7) + (17 % 7)) % 7\n= (1 + 3) % 7\n= 4 % 7\n= 4\n" }, { "code": null, "e": 25682, "s": 25565, "text": "Same rule is for modular subtraction. We don’t require much modular subtraction but it can also be done in same way." }, { "code": null, "e": 25742, "s": 25682, "text": "Modular Multiplication :Rule for modular multiplication is:" }, { "code": null, "e": 25788, "s": 25742, "text": "(a x b) mod m = ((a mod m) x (b mod m)) mod m" }, { "code": null, "e": 25797, "s": 25788, "text": "Example:" }, { "code": null, "e": 25866, "s": 25797, "text": "(12 x 13) % 5\n= ((12 % 5) x (13 % 5)) % 5\n= (2 x 3) % 5\n= 6 % 5\n= 1\n" }, { "code": null, "e": 26008, "s": 25866, "text": "Modular Division :Modular division is totally different from modular addition, subtraction and multiplication. It also does not exist always." }, { "code": null, "e": 26070, "s": 26008, "text": "(a / b) mod m is not equal to ((a mod m) / (b mod m)) mod m.\n" }, { "code": null, "e": 26114, "s": 26070, "text": "This is calculated using following formula:" }, { "code": null, "e": 26167, "s": 26114, "text": "(a / b) mod m = (a x (inverse of b if exists)) mod m" }, { "code": null, "e": 26453, "s": 26167, "text": "Modular Inverse :The modular inverse of a mod m exists only if a and m are relatively prime i.e. gcd(a, m) = 1.Hence, for finding inverse of a under modulo m,if (a x b) mod m = 1 then b is modular inverse of a.Example:a = 5, m = 7(5 x 3) % 7 = 1hence, 3 is modulo inverse of 5 under 7." }, { "code": null, "e": 26595, "s": 26453, "text": "Modular Exponentiation :Finding a^b mod m is the modular exponentiation. There are two approaches for this – recursive and iterative.Example:" }, { "code": null, "e": 26641, "s": 26595, "text": "a = 5, b = 2, m = 7\n(5 ^ 2) % 7 = 25 % 7 = 4\n" }, { "code": null, "e": 26710, "s": 26641, "text": "Below are some more important concepts related to Modular Arithmetic" }, { "code": null, "e": 26735, "s": 26710, "text": "Euler’s Totient Function" }, { "code": null, "e": 26761, "s": 26735, "text": "Compute n! under modulo p" }, { "code": null, "e": 26778, "s": 26761, "text": "Wilson’s Theorem" }, { "code": null, "e": 26814, "s": 26778, "text": "How to compute mod of a big number?" }, { "code": null, "e": 26856, "s": 26814, "text": "Find value of y mod (2 raised to power x)" }, { "code": null, "e": 26895, "s": 26856, "text": "Recent Articles on Modular Arithmetic." }, { "code": null, "e": 26914, "s": 26895, "text": "Modular Arithmetic" }, { "code": null, "e": 26938, "s": 26914, "text": "Engineering Mathematics" }, { "code": null, "e": 26957, "s": 26938, "text": "Modular Arithmetic" }, { "code": null, "e": 27055, "s": 26957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27064, "s": 27055, "text": "Comments" }, { "code": null, "e": 27077, "s": 27064, "text": "Old Comments" }, { "code": null, "e": 27138, "s": 27077, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 27188, "s": 27138, "text": "Mathematics | Graph Isomorphisms and Connectivity" }, { "code": null, "e": 27209, "s": 27188, "text": "Activation Functions" }, { "code": null, "e": 27268, "s": 27209, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 27291, "s": 27268, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 27314, "s": 27291, "text": "Set Notations in LaTeX" }, { "code": null, "e": 27344, "s": 27314, "text": "Properties of Boolean Algebra" }, { "code": null, "e": 27386, "s": 27344, "text": "Mathematics | Euler and Hamiltonian Paths" }, { "code": null, "e": 27428, "s": 27386, "text": "Mathematics | Graph Theory Basics - Set 1" } ]
C# Cast method
To cast elements, use the Cast() method. The following is our list. List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" }; Now, cast and use the Cast() method with substring() method to display the first two letters of every string in the list. IEnumerable<string> res = myList.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2)); Let us see the complete example. Live Demo using System; using System.Linq; using System.Collections.Generic; class Demo { static void Main() { List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" }; // getting first 2 letters from every string IEnumerable<string> res = list.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2)); foreach (string str in res) Console.WriteLine(str); } } ke mo jo mo
[ { "code": null, "e": 1103, "s": 1062, "text": "To cast elements, use the Cast() method." }, { "code": null, "e": 1130, "s": 1103, "text": "The following is our list." }, { "code": null, "e": 1211, "s": 1130, "text": "List<object> myList = new List<object> { \"Mac\", \"Windows\", \"Linux\", \"Solaris\" };" }, { "code": null, "e": 1333, "s": 1211, "text": "Now, cast and use the Cast() method with substring() method to display the first two letters of every string in the list." }, { "code": null, "e": 1431, "s": 1333, "text": "IEnumerable<string> res = myList.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));" }, { "code": null, "e": 1464, "s": 1431, "text": "Let us see the complete example." }, { "code": null, "e": 1475, "s": 1464, "text": " Live Demo" }, { "code": null, "e": 1894, "s": 1475, "text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n List<object> list = new List<object> { \"keyboard\", \"mouse\", \"joystick\", \"monitor\" };\n // getting first 2 letters from every string\n IEnumerable<string> res = list.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));\n foreach (string str in res)\n Console.WriteLine(str);\n }\n}" }, { "code": null, "e": 1906, "s": 1894, "text": "ke\nmo\njo\nmo" } ]
A step-by-step guide for clustering images | by Erdogan Taskesen | Towards Data Science
For the detection and exploration of natural groups or clusters of images by carefully pre-processing images, utilizing well-known feature extraction approaches, and evaluation of the goodness of the clustering. A theoretical background followed by a hands-on tutorial. Many computer vision tasks rely on (deep) neural networks, and aim to predict “what’s on the image”. However, not all tasks require supervised approaches or neural networks. With an unsupervised approach, we can aim to determine natural groups or clusters of images without being constrained to a fixed number of (learned) categories. In this blog, I will summarize the concepts of unsupervised clustering, followed by a hands-on tutorial on how to pre-process images, extract features (PCA, HOG), and group images with high similarity taking into account the goodness of the clustering. I will demonstrate the clustering of the MNIST dataset, the 101 objects dataset, the flower dataset, and finally the clustering of faces using the Olivetti dataset. All results are derived using the Python library clustimage. Image recognition is a computer vision task for which the recognition part can be separated into supervised and unsupervised approaches. In the case of the supervised task, the goal can be to classify the image or an object on the image. Nowadays there are various pre-learned models for the classification tasks. The common theme is that all supervised models require a learning step where ground truth labels are used to learn the objects for the model. Some models can readily recognizable hundreds of objects and this number is steadily increasing but the majority of domain-specific objects will likely remain unknown in pre-learned models. In such cases, the transition towards unsupervised clustering approaches seems inevitable. Building high-quality labeled datasets is a laborious task and favors the use of clustering approaches. In general, unsupervised machine learning is the task of inferring a function to describe the hidden structure from “unlabeled” data. Unsupervised tasks are broader than only clustering, and can also be used for various other tasks such as data exploration, outlier detection, and feature extraction. In this blog, I will focus on unsupervised clustering approaches with application in image recognition. However, clustering of images requires multiple steps, and each of them can influence the final clustering result. Let’s start with a schematic overview and work our way into the rabbit hole. Clustering of images is a multi-step process for which the steps are to pre-process the images, extract the features, cluster the images on similarity, and evaluate for the optimal number of clusters using a measure of goodness. See also the schematic overview in Figure 1. All these steps are readily implemented in the python package clustimage which only needs the path locations or the raw pixel values as an input. I will describe each of these steps in the following sections but let’s start with a brief background on unsupervised clustering and some terminology. With unsupervised clustering, we aim to determine “natural” or “data-driven” groups in the data without using apriori knowledge about labels or categories. The challenge of using different unsupervised clustering methods is that it will result in different partitioning of the samples and thus different groupings since each method implicitly impose a structure on the data. Thus the question arises; What is a “good” clustering? Figure 2A depicts a bunch of samples in a 2-dimensional space. Intuitively we may describe it as a group of samples (aka the images) that are cluttered together. I would state that there are two clusters without using any label information. Why? Because of the distances between the dots, and the relatively larger “gap” between the cluttered samples. With this in mind, we can convert our intuition of “clusters” into a mathematical statement such as; the variance of samples within a so-called-cluster should be small (within variance σW, red and blue), and at the same time, the variance between the clusters should be large (between variance, σB) as depicted in Figure 2B. The distance between samples (or the intrinsic relationships) can be measured with a distance metric (e.g., Euclidean distance), and stored in a so-called dissimilarity matrix. The distance between groups of samples can then be computed using the linkage type (for hierarchical clustering). The most well-known distance metric is the Euclidean distance. Although it is set as the default metric in many methods, it is not always the best choice. Understand the mathematical properties of metrics so that it fits the statistical properties of the data and aligns with the research question. A schematic overview of various distance metrics is depicted in Figure 3 [1]. In the case of image similarity, the Euclidean distance is recommended when features are extracted using Principal Component Analysis (PCA) [2] or Histograms of Oriented Gradients (HOG). The process of hierarchical clustering involves an approach of grouping samples into a larger cluster. In this process, the distances between two sub-clusters need to be computed for which the different types of linkages describe how the clusters are connected (Figure 4). Briefly, Single linkage between two clusters is the proximity between their two closest samples. It produces a long chain and is therefore ideal to cluster spherical data but also for outlier detection. Complete linkage between two clusters is the proximity between their two most distant samples. Intuitively, the two most distant samples cannot be much more dissimilar than other quite dissimilar pairs. It forces clusters to be spherical and have often “compact” contours by their borders, but they are not necessarily compact inside. Average linkage between two clusters is the arithmetic mean of all the proximities between the objects of one, on one side, and the objects of the other, on the other side. Centroid linkage is the proximity between the geometric centroids of the clusters. Choose the metric and linkage type carefully because it directly affects the final clustering results. With this in mind, we can start preprocessing the images. Before we can extract features from the images, we need to perform some preprocessing steps to make sure that images are comparable in color, value range, and image size. The preprocessing steps are utilized from open-cv and pipelined in clustimage. colorscale: Conversion of the image into e.g. grayscale (2-D) or color (3-D).scale: Normalize all pixel values between the minimum and maximum range of [0, 255].dim: Resize each image to make sure that the number of features is the same. colorscale: Conversion of the image into e.g. grayscale (2-D) or color (3-D). scale: Normalize all pixel values between the minimum and maximum range of [0, 255]. dim: Resize each image to make sure that the number of features is the same. pip install clustimage After preprocessing the images, we can start extracting features from images using the pixel value information. There are many approaches to extract features but I will focus on PCA and HOG features as these are well-established techniques that can generalize very well across different types of objects. I will briefly recap PCA and HOG but for more details I recommend reading other articles and blogs. With PCA we can reduce dimensionality and extract Principal Components (PC) where most of the variance is seen. It is utterly important that all images must have the same width and height, and also be preprocessed similarly because the pixel values will form the feature space. Suppose we have 100 grayscaled 2D images of 128x128 pixels. Each image will be flattened and form a vector of size 16384. The vectors can now be stacked and form a new NxM array, where N is 100 samples and M are the 16384 features. The feature extraction will take place on the NxM array. Within clustimage, we can either specify the exact number of PCs to be extracted or we can set the minimum amount of explained variance that the PCs should contain in total. In the latter case, the number of PCs will be automatically determined. HOG is a feature descriptor to extract features related to the direction and orientation of edges from image data. In general, it is a simplified representation of the image that contains only the most important information, such as the number of occurrences of gradient orientation in localized portions of an image. A summary is as follows: The HOG descriptor focuses on the structure or the shape of an object. HOG features contain both edge and direction information.The complete image is broken down into smaller regions (localized portions) and for each region, the gradient orientation is calculated.Finally, the HOG would generate a Histogram for each of these regions separately. The histograms are created using the gradient orientations of the pixel values, hence the name Histogram of Oriented Gradients. The HOG descriptor focuses on the structure or the shape of an object. HOG features contain both edge and direction information. The complete image is broken down into smaller regions (localized portions) and for each region, the gradient orientation is calculated. Finally, the HOG would generate a Histogram for each of these regions separately. The histograms are created using the gradient orientations of the pixel values, hence the name Histogram of Oriented Gradients. Not all applications are useful when using HOG features as it “only” provides the outline of the image. For example, if the use-case is to group different generic objects, HOG features can do a great job but a deeper similarity within the object may be difficult as the details can be lost. Nevertheless, If an increase of HOG features is desired, you can decrease the pixels per cell (e.g. 4,4). At this point, we pre-processed the images, extracted the features, and with the goal in our mind, we choose the linkage type and can start clustering the images to find groups that are similar based on the distance metric. However, a clustering approach does not provide information about the separability, goodness or the optimal number of clusters. To evaluate the clustering, there are various approaches for which the Silhouette score and Davies–Bouldin (DB) are the most well-known methods. Each comes with its properties for which a summary is as follows: Davies–Bouldin index (dbindex): Intuitively it can be described as a measure of the within-cluster distances, and between cluster distances. The score is bounded between [0, 1], lower is better. Note that, since it measures the distance between clusters centroids it is restricted to using the Euclidean distances. Silhouette score: The silhouette value is a measure of how similar a sample is to its cluster (cohesion) compared to other clusters (separation). The score is bounded between [-1, 1], where a high value indicates that the object is well matched to its cluster and poorly matched to neighboring clusters. Thus higher scores are better. In contrast to the DBindex, the Silhouette score is a sample-wise measure, i.e., measures the average similarity of the samples within a cluster and their distance to the other objects in the other clusters. The silhouette score can be used in combination with any distance metric. For the evaluation of clusters, the clusteval library is utilized in clustimage and contains three evaluation methods: Silhouette, DBindex, and the Derivatives method. The evaluation approaches should be used in combination with clustering methods, such as agglomerative, k-means, or dbscan which are also included in clustimage. Here again, it is important to understand the mathematical properties of the methods so that it matches with the statistical properties of the (expected) clusters. As an example, DBscan in combination with the Silhouette evaluation can detect clusters with different densities and shapes while k-means assumes that clusters are convex shaped. Be aware that the cluster evaluation approaches can easily be fooled as scores can gradually improve by an increase of the number of clusters. It can be wise to set the search range for the number of clusters to find the local minima/maxima. MNIST is a well-known handwritten digits dataset that is great to examine and showcase the performance of methods. Let’s load the dataset and run clustimage to detect the clusters. In this scenario, I will extract features using PCA and leave all other parameters to the defaults. The default settings are as follows: for the preprocessing, the grayscale is set to False (setting it to True would not change the results as the images are readily grayscaled), and the image dimensions are reduced to 128,128 if needed. PCA is used for feature extraction where the number of Principal Components is selected that cover 95% of the variance. Clusters are detected using the agglomerative approach with Euclidean distance metric and ward linkage. The clustering and the optimal number of clusters are evaluated with the Silhouette-score. The search range for the number of clusters is bounded between [3, 25]. For visualization purposes, tSNE is performed to reduce the high dimensional space and scatter the samples relative to each other. As you may notice, there are a lot of parameters for which all functions are readily pipelined in clustimage to cluster the images and determine the optimal number of clusters. The output is stored in results and in the object itself. Let’s have a look at the results. The dimensionality is reduced to 29 features (Figure 6) and stored in the feat key. The explained variance can be plotted with cl.pca.plot(). The coordinates of the embedding are stored in xycoord, and the cluster labels can be found in labels. To get a bit more intuition about the performance, we can make various plots such as the goodness of the clustering, the consistency of similarly detected samples per cluster, and a scatter plot. We evaluated the hierarchical clustering using the Silhouette score for which an optimum of 10 clusters is detected (highest relative score in Figure 7A). The dataset also contains 10 digits [0 to 9] but we need to examine whether the clusters do also represent the digits. In Figure 7B we can see the coefficient values per sample. Many samples have a high value which means that the clustering configuration is appropriate. If there would have been many points with low or negative values, then the clustering configuration may have too many or too few clusters. Thus overall, both graphs indicate a good clustering of the samples. cl.clusteval.plot() cl.clusteval.scatter() To investigate the distribution of samples in clusters, we can plot the dendrogram with cl.plot_dendrogram(). The dendrogram gives insights into the distribution of samples across the 10 clusters, and the distances between clusters seem more or less evenly distributed without strong outliers or other effects that can disturb the clustering results. With the functionality cl.plot_unique() we can plot the centroid image per cluster. In addition, all images per cluster can also be averaged by setting the following parameter: cl.plot_unique(img_mean=True) . The latter option helps to get more intuition whether the images per cluster are alike. As an example, if we look at cluster 7 in Figure 9, the centroid of the cluster seems to be digit number 3 whereas the average image seems more like a 9? This is an indication that the cluster may behold images that are not exactly alike. With the scatterplot function cl.scatter(zoom=5) we can scatter the samples in the embedded 2D tSNE space and get an intuition of the distribution of the samples relative to each other. Note that the samples (digit images) are colored on the cluster labels that are determined in the high dimensional space. The 2D tSNE embedding is only for visualization purposes in this case. For each cluster, the centroid is determined in the 2D space and the image closest to the centroid is plotted. In general, we see a clear separation of the clusters for which some digits may need further inspection, such as clusters 4 and 5. To see the cluster labels, we can set the zoom parameter to None, cl.scatter(zoom=None). To deeper examine the images in the clusters, we can use the plot functionality cl.plot(cmap=’binary’, labels=[4,5]) . Here we only plot the clusters of interest, such as clusters 4 and 5. Cluster 4 seems to contain the digits 1 and 9 and cluster 5 the digits 1, 4, and 9. With clustimage, it is also possible to extract features using Histogram of Oriented Gradients by setting the method to hog. Because the image sizes of the MNIST are small, it also requires reducing the number of pixels per cell to compute the hog features. Let’s cluster again the MNIST dataset but now using the HOG features. With pixels_per_cell:(2,2) the following results are achieved. Fourteen clusters are detected based on the maximum Silhouette score. Note that the second local optimum is at 10 clusters though. When we compare the clustering results (Figure 12B) to the clustering results using PCA (Figure 10), the clusters using HOG features appear less distinctive based on a visual examination. We can deeper examine the clusters when plotting the unique images per cluster using the image closest to the centroid, and the average image per cluster. Nonetheless, the results seem reasonable. Clustering the MNIST dataset is fun but now we will cluster two real-world datasets. The first dataset contains a large number of different objects, and the second dataset is relatively small but contains different subtypes of flowers. A large dataset containing 101 objects is the Caltech101 dataset. The dataset contains 9144 real-world images belonging to 101 categories. About 40 to 800 images per category. The size of each image is roughly 300 x 200 pixels and can be downloaded at the Caltech website. As an input to clustimage, we can simply provide the path location where all images are stored. All images in subdirectories will be recursively collected. An optimum of 63 clusters is detected (Figure 14A) for which the centroid image for the clusters is shown in Figure 14C which is less than the 101 known input objects. Nevertheless, some clusters are very well separated from the bulk (Figure 14B) and contain images with high similarity (Figure 14D). The clusters that are more centered in the 2-D space may not be as pure as demonstrated in Figure 14D because of the nature of the tSNE algorithm. Overall, some objects tend to cluster very well whereas others may require further fine-tuning of model parameters or maybe even a different feature extraction approach. The flower dataset contains 210 images and is clustered based using the HOG method. In the case of the flower dataset, the HOG features seem to produce better results compared to using PCA features based on a visual inspection (results not shown) even though that colors are lost during the feature extraction approach. If the number of images becomes larger, it is also possible to set the method to pca-hog that will perform a PCA on the HOG features and thereby can significantly reduce the number of features saving memory and still retain the results. An optimum of 6 clusters is detected (Figure 15A) for which the centroid image for the clusters is shown in Figures 15B and C. The HOG features for the centroid images are shown in Figure 15D. Clustering of faces is also possible with the clustimage library. This however may require an additional step, namely the extraction of faces from the images. The extraction of faces from the images can be performed using the cl.extract_faces() functionality that in turn uses the haar cascades of openCV, more specifically, the haarcascade_frontalface_default.xml. In this example, we will be loading the well-known Olivetti faces dataset with 400 facial images. For this dataset, there is no need to extract the faces because the faces are readily cropped. When we run clustimage, an optimum of 18 clusters is detected (Figure 16A), and the tSNE embedding with the cluster labels is shown in Figure 16B. We do see some separation of the clusters for which each cluster can now be inspected using the cl.plot() functionality. Besides clustering functionalities, the clustimage library also contains a functionality to search for images. With the find functionality, an input image can be provided and similar images will be returned. Two approaches are implemented: Based on the k-nearest neighbor. Based on significance after probability density fitting. For both approaches, the adjacency matrix is computed across all images using the specified distance metric (default Euclidean). In the case of the k-nearest neighbor approach, the k-nearest neighbors are selected, and logically it will always result in a hit. In the case of density fitting, the adjacency matrix is used to estimate the best fit for the loc/scale/arg parameters across the tested distributions [‘norm’, ‘expon’, ‘uniform’, ‘gamma’, ‘t’]. The fitted distribution forms the similarity distribution of samples. For each new unseen input image, the probability of similarity is computed across all images, and the images are returned that are P<alpha in the lower bound of the distribution. This approach will only return the significant hits. In the case that both k and alpha parameters are specified, the union of detected samples is taken. Let’s use the flower-dataset to find a similar image using an input image from a path location. In the example above we aim to detect similar images for two input images. For demonstration purposes, these images were also in the fit_transform functionality itself. Or in other words, we should be able to detect at least the identical image. Figure 17 demonstrates the images for which the similarity was significant with P<0.05. Note that the results can slightly change because of the stochastic component in fitting the distribution. I touched on the concepts of unsupervised clustering and how to go from raw input images towards the clustering of highly similar images. Clustering of images requires multiple steps and various methods. Taking different steps and/or methods will yield different grouping since it implicitly imposes a structure on the data, and thus the partitioning of the samples. The clustimage package can help to use well-known feature extraction, evaluation, and clustering methods. The results can easily be explored by the various plotting functionalities. Furthermore, it can also be used for the detection of significantly similar images for a new unseen image. If you aim to find (near-)identical images (photos), I would recommend reading this blog, which is all about the detection of Duplicate Images Using Image Hash Functions using the undouble library. It has become a lengthy article but the bottom line is to always make sure that the mathematical properties of the methods match the statistical properties of the data. Be Safe. Stay Frosty. Cheers E. If you found this article helpful, help support my content by signing up for a Medium membership using my referral link or follow me to access similar blogs. clustimage Colab notebook clustimage Github/Documentation clusteval Github/Documentation undouble Github/Documentation Let’s connect on LinkedIn Follow me on Github Maarten Grootendorst, 9 Distance Measures in Data Science, Towards Data Science, Feb 2021.Kimberly L. Elmore et al, Euclidean Distance as a Similarity Metric for Principal Component Analysis, AMS, 01 Mar 2001Sergei Evgenievich Ivanov et al, The Recognition and Classification of Objects Based on the Modified Distance Metric, Procedia Computer Science 136 (2018) Maarten Grootendorst, 9 Distance Measures in Data Science, Towards Data Science, Feb 2021. Kimberly L. Elmore et al, Euclidean Distance as a Similarity Metric for Principal Component Analysis, AMS, 01 Mar 2001 Sergei Evgenievich Ivanov et al, The Recognition and Classification of Objects Based on the Modified Distance Metric, Procedia Computer Science 136 (2018)
[ { "code": null, "e": 442, "s": 172, "text": "For the detection and exploration of natural groups or clusters of images by carefully pre-processing images, utilizing well-known feature extraction approaches, and evaluation of the goodness of the clustering. A theoretical background followed by a hands-on tutorial." }, { "code": null, "e": 1256, "s": 442, "text": "Many computer vision tasks rely on (deep) neural networks, and aim to predict “what’s on the image”. However, not all tasks require supervised approaches or neural networks. With an unsupervised approach, we can aim to determine natural groups or clusters of images without being constrained to a fixed number of (learned) categories. In this blog, I will summarize the concepts of unsupervised clustering, followed by a hands-on tutorial on how to pre-process images, extract features (PCA, HOG), and group images with high similarity taking into account the goodness of the clustering. I will demonstrate the clustering of the MNIST dataset, the 101 objects dataset, the flower dataset, and finally the clustering of faces using the Olivetti dataset. All results are derived using the Python library clustimage." }, { "code": null, "e": 2097, "s": 1256, "text": "Image recognition is a computer vision task for which the recognition part can be separated into supervised and unsupervised approaches. In the case of the supervised task, the goal can be to classify the image or an object on the image. Nowadays there are various pre-learned models for the classification tasks. The common theme is that all supervised models require a learning step where ground truth labels are used to learn the objects for the model. Some models can readily recognizable hundreds of objects and this number is steadily increasing but the majority of domain-specific objects will likely remain unknown in pre-learned models. In such cases, the transition towards unsupervised clustering approaches seems inevitable. Building high-quality labeled datasets is a laborious task and favors the use of clustering approaches." }, { "code": null, "e": 2231, "s": 2097, "text": "In general, unsupervised machine learning is the task of inferring a function to describe the hidden structure from “unlabeled” data." }, { "code": null, "e": 2694, "s": 2231, "text": "Unsupervised tasks are broader than only clustering, and can also be used for various other tasks such as data exploration, outlier detection, and feature extraction. In this blog, I will focus on unsupervised clustering approaches with application in image recognition. However, clustering of images requires multiple steps, and each of them can influence the final clustering result. Let’s start with a schematic overview and work our way into the rabbit hole." }, { "code": null, "e": 3114, "s": 2694, "text": "Clustering of images is a multi-step process for which the steps are to pre-process the images, extract the features, cluster the images on similarity, and evaluate for the optimal number of clusters using a measure of goodness. See also the schematic overview in Figure 1. All these steps are readily implemented in the python package clustimage which only needs the path locations or the raw pixel values as an input." }, { "code": null, "e": 3265, "s": 3114, "text": "I will describe each of these steps in the following sections but let’s start with a brief background on unsupervised clustering and some terminology." }, { "code": null, "e": 4047, "s": 3265, "text": "With unsupervised clustering, we aim to determine “natural” or “data-driven” groups in the data without using apriori knowledge about labels or categories. The challenge of using different unsupervised clustering methods is that it will result in different partitioning of the samples and thus different groupings since each method implicitly impose a structure on the data. Thus the question arises; What is a “good” clustering? Figure 2A depicts a bunch of samples in a 2-dimensional space. Intuitively we may describe it as a group of samples (aka the images) that are cluttered together. I would state that there are two clusters without using any label information. Why? Because of the distances between the dots, and the relatively larger “gap” between the cluttered samples." }, { "code": null, "e": 4663, "s": 4047, "text": "With this in mind, we can convert our intuition of “clusters” into a mathematical statement such as; the variance of samples within a so-called-cluster should be small (within variance σW, red and blue), and at the same time, the variance between the clusters should be large (between variance, σB) as depicted in Figure 2B. The distance between samples (or the intrinsic relationships) can be measured with a distance metric (e.g., Euclidean distance), and stored in a so-called dissimilarity matrix. The distance between groups of samples can then be computed using the linkage type (for hierarchical clustering)." }, { "code": null, "e": 4818, "s": 4663, "text": "The most well-known distance metric is the Euclidean distance. Although it is set as the default metric in many methods, it is not always the best choice." }, { "code": null, "e": 4962, "s": 4818, "text": "Understand the mathematical properties of metrics so that it fits the statistical properties of the data and aligns with the research question." }, { "code": null, "e": 5227, "s": 4962, "text": "A schematic overview of various distance metrics is depicted in Figure 3 [1]. In the case of image similarity, the Euclidean distance is recommended when features are extracted using Principal Component Analysis (PCA) [2] or Histograms of Oriented Gradients (HOG)." }, { "code": null, "e": 5500, "s": 5227, "text": "The process of hierarchical clustering involves an approach of grouping samples into a larger cluster. In this process, the distances between two sub-clusters need to be computed for which the different types of linkages describe how the clusters are connected (Figure 4)." }, { "code": null, "e": 6455, "s": 5500, "text": "Briefly, Single linkage between two clusters is the proximity between their two closest samples. It produces a long chain and is therefore ideal to cluster spherical data but also for outlier detection. Complete linkage between two clusters is the proximity between their two most distant samples. Intuitively, the two most distant samples cannot be much more dissimilar than other quite dissimilar pairs. It forces clusters to be spherical and have often “compact” contours by their borders, but they are not necessarily compact inside. Average linkage between two clusters is the arithmetic mean of all the proximities between the objects of one, on one side, and the objects of the other, on the other side. Centroid linkage is the proximity between the geometric centroids of the clusters. Choose the metric and linkage type carefully because it directly affects the final clustering results. With this in mind, we can start preprocessing the images." }, { "code": null, "e": 6705, "s": 6455, "text": "Before we can extract features from the images, we need to perform some preprocessing steps to make sure that images are comparable in color, value range, and image size. The preprocessing steps are utilized from open-cv and pipelined in clustimage." }, { "code": null, "e": 6943, "s": 6705, "text": "colorscale: Conversion of the image into e.g. grayscale (2-D) or color (3-D).scale: Normalize all pixel values between the minimum and maximum range of [0, 255].dim: Resize each image to make sure that the number of features is the same." }, { "code": null, "e": 7021, "s": 6943, "text": "colorscale: Conversion of the image into e.g. grayscale (2-D) or color (3-D)." }, { "code": null, "e": 7106, "s": 7021, "text": "scale: Normalize all pixel values between the minimum and maximum range of [0, 255]." }, { "code": null, "e": 7183, "s": 7106, "text": "dim: Resize each image to make sure that the number of features is the same." }, { "code": null, "e": 7206, "s": 7183, "text": "pip install clustimage" }, { "code": null, "e": 7611, "s": 7206, "text": "After preprocessing the images, we can start extracting features from images using the pixel value information. There are many approaches to extract features but I will focus on PCA and HOG features as these are well-established techniques that can generalize very well across different types of objects. I will briefly recap PCA and HOG but for more details I recommend reading other articles and blogs." }, { "code": null, "e": 8424, "s": 7611, "text": "With PCA we can reduce dimensionality and extract Principal Components (PC) where most of the variance is seen. It is utterly important that all images must have the same width and height, and also be preprocessed similarly because the pixel values will form the feature space. Suppose we have 100 grayscaled 2D images of 128x128 pixels. Each image will be flattened and form a vector of size 16384. The vectors can now be stacked and form a new NxM array, where N is 100 samples and M are the 16384 features. The feature extraction will take place on the NxM array. Within clustimage, we can either specify the exact number of PCs to be extracted or we can set the minimum amount of explained variance that the PCs should contain in total. In the latter case, the number of PCs will be automatically determined." }, { "code": null, "e": 8767, "s": 8424, "text": "HOG is a feature descriptor to extract features related to the direction and orientation of edges from image data. In general, it is a simplified representation of the image that contains only the most important information, such as the number of occurrences of gradient orientation in localized portions of an image. A summary is as follows:" }, { "code": null, "e": 9241, "s": 8767, "text": "The HOG descriptor focuses on the structure or the shape of an object. HOG features contain both edge and direction information.The complete image is broken down into smaller regions (localized portions) and for each region, the gradient orientation is calculated.Finally, the HOG would generate a Histogram for each of these regions separately. The histograms are created using the gradient orientations of the pixel values, hence the name Histogram of Oriented Gradients." }, { "code": null, "e": 9370, "s": 9241, "text": "The HOG descriptor focuses on the structure or the shape of an object. HOG features contain both edge and direction information." }, { "code": null, "e": 9507, "s": 9370, "text": "The complete image is broken down into smaller regions (localized portions) and for each region, the gradient orientation is calculated." }, { "code": null, "e": 9717, "s": 9507, "text": "Finally, the HOG would generate a Histogram for each of these regions separately. The histograms are created using the gradient orientations of the pixel values, hence the name Histogram of Oriented Gradients." }, { "code": null, "e": 10114, "s": 9717, "text": "Not all applications are useful when using HOG features as it “only” provides the outline of the image. For example, if the use-case is to group different generic objects, HOG features can do a great job but a deeper similarity within the object may be difficult as the details can be lost. Nevertheless, If an increase of HOG features is desired, you can decrease the pixels per cell (e.g. 4,4)." }, { "code": null, "e": 10677, "s": 10114, "text": "At this point, we pre-processed the images, extracted the features, and with the goal in our mind, we choose the linkage type and can start clustering the images to find groups that are similar based on the distance metric. However, a clustering approach does not provide information about the separability, goodness or the optimal number of clusters. To evaluate the clustering, there are various approaches for which the Silhouette score and Davies–Bouldin (DB) are the most well-known methods. Each comes with its properties for which a summary is as follows:" }, { "code": null, "e": 10992, "s": 10677, "text": "Davies–Bouldin index (dbindex): Intuitively it can be described as a measure of the within-cluster distances, and between cluster distances. The score is bounded between [0, 1], lower is better. Note that, since it measures the distance between clusters centroids it is restricted to using the Euclidean distances." }, { "code": null, "e": 11609, "s": 10992, "text": "Silhouette score: The silhouette value is a measure of how similar a sample is to its cluster (cohesion) compared to other clusters (separation). The score is bounded between [-1, 1], where a high value indicates that the object is well matched to its cluster and poorly matched to neighboring clusters. Thus higher scores are better. In contrast to the DBindex, the Silhouette score is a sample-wise measure, i.e., measures the average similarity of the samples within a cluster and their distance to the other objects in the other clusters. The silhouette score can be used in combination with any distance metric." }, { "code": null, "e": 12282, "s": 11609, "text": "For the evaluation of clusters, the clusteval library is utilized in clustimage and contains three evaluation methods: Silhouette, DBindex, and the Derivatives method. The evaluation approaches should be used in combination with clustering methods, such as agglomerative, k-means, or dbscan which are also included in clustimage. Here again, it is important to understand the mathematical properties of the methods so that it matches with the statistical properties of the (expected) clusters. As an example, DBscan in combination with the Silhouette evaluation can detect clusters with different densities and shapes while k-means assumes that clusters are convex shaped." }, { "code": null, "e": 12425, "s": 12282, "text": "Be aware that the cluster evaluation approaches can easily be fooled as scores can gradually improve by an increase of the number of clusters." }, { "code": null, "e": 12524, "s": 12425, "text": "It can be wise to set the search range for the number of clusters to find the local minima/maxima." }, { "code": null, "e": 13560, "s": 12524, "text": "MNIST is a well-known handwritten digits dataset that is great to examine and showcase the performance of methods. Let’s load the dataset and run clustimage to detect the clusters. In this scenario, I will extract features using PCA and leave all other parameters to the defaults. The default settings are as follows: for the preprocessing, the grayscale is set to False (setting it to True would not change the results as the images are readily grayscaled), and the image dimensions are reduced to 128,128 if needed. PCA is used for feature extraction where the number of Principal Components is selected that cover 95% of the variance. Clusters are detected using the agglomerative approach with Euclidean distance metric and ward linkage. The clustering and the optimal number of clusters are evaluated with the Silhouette-score. The search range for the number of clusters is bounded between [3, 25]. For visualization purposes, tSNE is performed to reduce the high dimensional space and scatter the samples relative to each other." }, { "code": null, "e": 14270, "s": 13560, "text": "As you may notice, there are a lot of parameters for which all functions are readily pipelined in clustimage to cluster the images and determine the optimal number of clusters. The output is stored in results and in the object itself. Let’s have a look at the results. The dimensionality is reduced to 29 features (Figure 6) and stored in the feat key. The explained variance can be plotted with cl.pca.plot(). The coordinates of the embedding are stored in xycoord, and the cluster labels can be found in labels. To get a bit more intuition about the performance, we can make various plots such as the goodness of the clustering, the consistency of similarly detected samples per cluster, and a scatter plot." }, { "code": null, "e": 14904, "s": 14270, "text": "We evaluated the hierarchical clustering using the Silhouette score for which an optimum of 10 clusters is detected (highest relative score in Figure 7A). The dataset also contains 10 digits [0 to 9] but we need to examine whether the clusters do also represent the digits. In Figure 7B we can see the coefficient values per sample. Many samples have a high value which means that the clustering configuration is appropriate. If there would have been many points with low or negative values, then the clustering configuration may have too many or too few clusters. Thus overall, both graphs indicate a good clustering of the samples." }, { "code": null, "e": 14947, "s": 14904, "text": "cl.clusteval.plot() cl.clusteval.scatter()" }, { "code": null, "e": 15298, "s": 14947, "text": "To investigate the distribution of samples in clusters, we can plot the dendrogram with cl.plot_dendrogram(). The dendrogram gives insights into the distribution of samples across the 10 clusters, and the distances between clusters seem more or less evenly distributed without strong outliers or other effects that can disturb the clustering results." }, { "code": null, "e": 15834, "s": 15298, "text": "With the functionality cl.plot_unique() we can plot the centroid image per cluster. In addition, all images per cluster can also be averaged by setting the following parameter: cl.plot_unique(img_mean=True) . The latter option helps to get more intuition whether the images per cluster are alike. As an example, if we look at cluster 7 in Figure 9, the centroid of the cluster seems to be digit number 3 whereas the average image seems more like a 9? This is an indication that the cluster may behold images that are not exactly alike." }, { "code": null, "e": 16544, "s": 15834, "text": "With the scatterplot function cl.scatter(zoom=5) we can scatter the samples in the embedded 2D tSNE space and get an intuition of the distribution of the samples relative to each other. Note that the samples (digit images) are colored on the cluster labels that are determined in the high dimensional space. The 2D tSNE embedding is only for visualization purposes in this case. For each cluster, the centroid is determined in the 2D space and the image closest to the centroid is plotted. In general, we see a clear separation of the clusters for which some digits may need further inspection, such as clusters 4 and 5. To see the cluster labels, we can set the zoom parameter to None, cl.scatter(zoom=None)." }, { "code": null, "e": 16817, "s": 16544, "text": "To deeper examine the images in the clusters, we can use the plot functionality cl.plot(cmap=’binary’, labels=[4,5]) . Here we only plot the clusters of interest, such as clusters 4 and 5. Cluster 4 seems to contain the digits 1 and 9 and cluster 5 the digits 1, 4, and 9." }, { "code": null, "e": 17145, "s": 16817, "text": "With clustimage, it is also possible to extract features using Histogram of Oriented Gradients by setting the method to hog. Because the image sizes of the MNIST are small, it also requires reducing the number of pixels per cell to compute the hog features. Let’s cluster again the MNIST dataset but now using the HOG features." }, { "code": null, "e": 17208, "s": 17145, "text": "With pixels_per_cell:(2,2) the following results are achieved." }, { "code": null, "e": 17724, "s": 17208, "text": "Fourteen clusters are detected based on the maximum Silhouette score. Note that the second local optimum is at 10 clusters though. When we compare the clustering results (Figure 12B) to the clustering results using PCA (Figure 10), the clusters using HOG features appear less distinctive based on a visual examination. We can deeper examine the clusters when plotting the unique images per cluster using the image closest to the centroid, and the average image per cluster. Nonetheless, the results seem reasonable." }, { "code": null, "e": 17960, "s": 17724, "text": "Clustering the MNIST dataset is fun but now we will cluster two real-world datasets. The first dataset contains a large number of different objects, and the second dataset is relatively small but contains different subtypes of flowers." }, { "code": null, "e": 18389, "s": 17960, "text": "A large dataset containing 101 objects is the Caltech101 dataset. The dataset contains 9144 real-world images belonging to 101 categories. About 40 to 800 images per category. The size of each image is roughly 300 x 200 pixels and can be downloaded at the Caltech website. As an input to clustimage, we can simply provide the path location where all images are stored. All images in subdirectories will be recursively collected." }, { "code": null, "e": 19007, "s": 18389, "text": "An optimum of 63 clusters is detected (Figure 14A) for which the centroid image for the clusters is shown in Figure 14C which is less than the 101 known input objects. Nevertheless, some clusters are very well separated from the bulk (Figure 14B) and contain images with high similarity (Figure 14D). The clusters that are more centered in the 2-D space may not be as pure as demonstrated in Figure 14D because of the nature of the tSNE algorithm. Overall, some objects tend to cluster very well whereas others may require further fine-tuning of model parameters or maybe even a different feature extraction approach." }, { "code": null, "e": 19564, "s": 19007, "text": "The flower dataset contains 210 images and is clustered based using the HOG method. In the case of the flower dataset, the HOG features seem to produce better results compared to using PCA features based on a visual inspection (results not shown) even though that colors are lost during the feature extraction approach. If the number of images becomes larger, it is also possible to set the method to pca-hog that will perform a PCA on the HOG features and thereby can significantly reduce the number of features saving memory and still retain the results." }, { "code": null, "e": 19757, "s": 19564, "text": "An optimum of 6 clusters is detected (Figure 15A) for which the centroid image for the clusters is shown in Figures 15B and C. The HOG features for the centroid images are shown in Figure 15D." }, { "code": null, "e": 20316, "s": 19757, "text": "Clustering of faces is also possible with the clustimage library. This however may require an additional step, namely the extraction of faces from the images. The extraction of faces from the images can be performed using the cl.extract_faces() functionality that in turn uses the haar cascades of openCV, more specifically, the haarcascade_frontalface_default.xml. In this example, we will be loading the well-known Olivetti faces dataset with 400 facial images. For this dataset, there is no need to extract the faces because the faces are readily cropped." }, { "code": null, "e": 20584, "s": 20316, "text": "When we run clustimage, an optimum of 18 clusters is detected (Figure 16A), and the tSNE embedding with the cluster labels is shown in Figure 16B. We do see some separation of the clusters for which each cluster can now be inspected using the cl.plot() functionality." }, { "code": null, "e": 20824, "s": 20584, "text": "Besides clustering functionalities, the clustimage library also contains a functionality to search for images. With the find functionality, an input image can be provided and similar images will be returned. Two approaches are implemented:" }, { "code": null, "e": 20857, "s": 20824, "text": "Based on the k-nearest neighbor." }, { "code": null, "e": 20914, "s": 20857, "text": "Based on significance after probability density fitting." }, { "code": null, "e": 21868, "s": 20914, "text": "For both approaches, the adjacency matrix is computed across all images using the specified distance metric (default Euclidean). In the case of the k-nearest neighbor approach, the k-nearest neighbors are selected, and logically it will always result in a hit. In the case of density fitting, the adjacency matrix is used to estimate the best fit for the loc/scale/arg parameters across the tested distributions [‘norm’, ‘expon’, ‘uniform’, ‘gamma’, ‘t’]. The fitted distribution forms the similarity distribution of samples. For each new unseen input image, the probability of similarity is computed across all images, and the images are returned that are P<alpha in the lower bound of the distribution. This approach will only return the significant hits. In the case that both k and alpha parameters are specified, the union of detected samples is taken. Let’s use the flower-dataset to find a similar image using an input image from a path location." }, { "code": null, "e": 22309, "s": 21868, "text": "In the example above we aim to detect similar images for two input images. For demonstration purposes, these images were also in the fit_transform functionality itself. Or in other words, we should be able to detect at least the identical image. Figure 17 demonstrates the images for which the similarity was significant with P<0.05. Note that the results can slightly change because of the stochastic component in fitting the distribution." }, { "code": null, "e": 23332, "s": 22309, "text": "I touched on the concepts of unsupervised clustering and how to go from raw input images towards the clustering of highly similar images. Clustering of images requires multiple steps and various methods. Taking different steps and/or methods will yield different grouping since it implicitly imposes a structure on the data, and thus the partitioning of the samples. The clustimage package can help to use well-known feature extraction, evaluation, and clustering methods. The results can easily be explored by the various plotting functionalities. Furthermore, it can also be used for the detection of significantly similar images for a new unseen image. If you aim to find (near-)identical images (photos), I would recommend reading this blog, which is all about the detection of Duplicate Images Using Image Hash Functions using the undouble library. It has become a lengthy article but the bottom line is to always make sure that the mathematical properties of the methods match the statistical properties of the data." }, { "code": null, "e": 23354, "s": 23332, "text": "Be Safe. Stay Frosty." }, { "code": null, "e": 23364, "s": 23354, "text": "Cheers E." }, { "code": null, "e": 23522, "s": 23364, "text": "If you found this article helpful, help support my content by signing up for a Medium membership using my referral link or follow me to access similar blogs." }, { "code": null, "e": 23548, "s": 23522, "text": "clustimage Colab notebook" }, { "code": null, "e": 23580, "s": 23548, "text": "clustimage Github/Documentation" }, { "code": null, "e": 23611, "s": 23580, "text": "clusteval Github/Documentation" }, { "code": null, "e": 23641, "s": 23611, "text": "undouble Github/Documentation" }, { "code": null, "e": 23667, "s": 23641, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 23687, "s": 23667, "text": "Follow me on Github" }, { "code": null, "e": 24050, "s": 23687, "text": "Maarten Grootendorst, 9 Distance Measures in Data Science, Towards Data Science, Feb 2021.Kimberly L. Elmore et al, Euclidean Distance as a Similarity Metric for Principal Component Analysis, AMS, 01 Mar 2001Sergei Evgenievich Ivanov et al, The Recognition and Classification of Objects Based on the Modified Distance Metric, Procedia Computer Science 136 (2018)" }, { "code": null, "e": 24141, "s": 24050, "text": "Maarten Grootendorst, 9 Distance Measures in Data Science, Towards Data Science, Feb 2021." }, { "code": null, "e": 24260, "s": 24141, "text": "Kimberly L. Elmore et al, Euclidean Distance as a Similarity Metric for Principal Component Analysis, AMS, 01 Mar 2001" } ]
Explain the unary operations of algebra relations in DBMS?
Query is a question or requesting information. Query language is a language which is used to retrieve information from a database. Query language is divided into two types − Procedural language Procedural language Non-procedural language Non-procedural language Information is retrieved from the database by specifying the sequence of operations to be performed. For Example − Relational algebra. Structure Query language (SQL) is based on relational algebra. Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output. The different types of relational algebra operations are as follows − Select operation Select operation Project operation Project operation Rename operation Rename operation Union operation Union operation Intersection operation Intersection operation Difference operation Difference operation Cartesian product operation Cartesian product operation Join operation Join operation Division operation Division operation Select, project, rename comes under unary operation (operate on one table). It displays the records that satisfy a condition and is denoted by sigma (σ). It is a horizontal subset of the original relation. The syntax for the select operation is as follows − σcondition(table name) Consider the student table given below − To display all the records of student table, use the command given below − σ(student) To display all the records of CSE branch in student table, we can use the command mentioned below − σbranch=cse(student) To display all the records in student tables whose regno>2, we can use the command given below − σRegNo>2(student) To display the record of ECE branch section B students, use the command given below − σbranch=ECE ^ section=B(student) To display the records of section B CSE and IT branch, use the following command − σSection=B ^ Branch=cse ∨ branch=IT(student) Consider the EMPLOYEE TABLE as another example to know about selection operation − Retrieve information about those employees whose salary is greater than 20,000. If one condition is specified then, we get the following − If one condition is specified then, we get the following − σ salary > 20,000 (emp) If more than one condition specified in the query then ( AND: ∧, OR:∨ , Not:#, equal: =, >, <, >=, <=) If more than one condition specified in the query then ( AND: ∧, OR:∨ , Not:#, equal: =, >, <, >=, <=) Relational operator will be used to combine the multiple conditions into a single statement. Example − If we wish to retrieve information of those employees whose salary > 20,000 and working as the Head of the Department (HOD) and Department number is 20. σ salary > 20,000 ^LOC=HOD ^Deptno=20(emp) It displays the specific column of a table. It is denoted by pie (Π). It is a vertical subset of the original relation. It eliminates duplicate tuples. The syntax of projection operation is as follows − ∏regno(student) Consider the student table given below − To display regno column of student table, use the following command − ∏regno(student) To display branch, section column of student table, use the command given below − ∏branch,section(student) To display regno, section of ECE students, use the command mentioned below − ∏regno,section(σbranch=ECE(student)) Note − Conditions can be written in select operation but not in projection operation. Consider the employee table to know more about projection. If no condition is specified in the query then, If no condition is specified in the query then, ∏ empid, ename, salary, address, dno (emp) If condition is specified then, the composition of the select and projection is as follows − If condition is specified then, the composition of the select and projection is as follows − ∏ empid, ename, salary, address, dno (σ salary >20,00 ^ LOC = HOD ^ dno=20) (emp) It is used to assign a new name to a relation. It is denoted by ρ (rho). The syntax for rename operation is as follows − ρnewname (tablename or expression) Consider the student table given below − The student table is renamed with newstudent with the help of the following − ρnewstudent (student) The names, branch columns of the student table are renamed and newbranch respectively with the help of the following command − ρnewname,newbranch(Πname,branch( student)) Binary operations are applied on two compatible relations. Two relations R1, R2 are to be compatible, if they are of the same degree and the domain of corresponding attributes are the same. The Rho in DDL used for name of relation and in DML used for name of attributes. SQL Old name New name Renaming can be used by three methods, which are as follows − Changing name of the relation. Changing name of the relation. Changing name of the attribute. Changing name of the attribute. Changing both. Changing both.
[ { "code": null, "e": 1193, "s": 1062, "text": "Query is a question or requesting information. Query language is a language which is used to retrieve information from a database." }, { "code": null, "e": 1236, "s": 1193, "text": "Query language is divided into two types −" }, { "code": null, "e": 1256, "s": 1236, "text": "Procedural language" }, { "code": null, "e": 1276, "s": 1256, "text": "Procedural language" }, { "code": null, "e": 1300, "s": 1276, "text": "Non-procedural language" }, { "code": null, "e": 1324, "s": 1300, "text": "Non-procedural language" }, { "code": null, "e": 1425, "s": 1324, "text": "Information is retrieved from the database by specifying the sequence of operations to be performed." }, { "code": null, "e": 1459, "s": 1425, "text": "For Example − Relational algebra." }, { "code": null, "e": 1522, "s": 1459, "text": "Structure Query language (SQL) is based on relational algebra." }, { "code": null, "e": 1655, "s": 1522, "text": "Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output." }, { "code": null, "e": 1725, "s": 1655, "text": "The different types of relational algebra operations are as follows −" }, { "code": null, "e": 1742, "s": 1725, "text": "Select operation" }, { "code": null, "e": 1759, "s": 1742, "text": "Select operation" }, { "code": null, "e": 1777, "s": 1759, "text": "Project operation" }, { "code": null, "e": 1795, "s": 1777, "text": "Project operation" }, { "code": null, "e": 1812, "s": 1795, "text": "Rename operation" }, { "code": null, "e": 1829, "s": 1812, "text": "Rename operation" }, { "code": null, "e": 1845, "s": 1829, "text": "Union operation" }, { "code": null, "e": 1861, "s": 1845, "text": "Union operation" }, { "code": null, "e": 1884, "s": 1861, "text": "Intersection operation" }, { "code": null, "e": 1907, "s": 1884, "text": "Intersection operation" }, { "code": null, "e": 1928, "s": 1907, "text": "Difference operation" }, { "code": null, "e": 1949, "s": 1928, "text": "Difference operation" }, { "code": null, "e": 1977, "s": 1949, "text": "Cartesian product operation" }, { "code": null, "e": 2005, "s": 1977, "text": "Cartesian product operation" }, { "code": null, "e": 2020, "s": 2005, "text": "Join operation" }, { "code": null, "e": 2035, "s": 2020, "text": "Join operation" }, { "code": null, "e": 2054, "s": 2035, "text": "Division operation" }, { "code": null, "e": 2073, "s": 2054, "text": "Division operation" }, { "code": null, "e": 2149, "s": 2073, "text": "Select, project, rename comes under unary operation (operate on one table)." }, { "code": null, "e": 2279, "s": 2149, "text": "It displays the records that satisfy a condition and is denoted by sigma (σ). It is a horizontal subset of the original relation." }, { "code": null, "e": 2331, "s": 2279, "text": "The syntax for the select operation is as follows −" }, { "code": null, "e": 2354, "s": 2331, "text": "σcondition(table name)" }, { "code": null, "e": 2395, "s": 2354, "text": "Consider the student table given below −" }, { "code": null, "e": 2470, "s": 2395, "text": "To display all the records of student table, use the command given below −" }, { "code": null, "e": 2481, "s": 2470, "text": "σ(student)" }, { "code": null, "e": 2581, "s": 2481, "text": "To display all the records of CSE branch in student table, we can use the command mentioned below −" }, { "code": null, "e": 2602, "s": 2581, "text": "σbranch=cse(student)" }, { "code": null, "e": 2699, "s": 2602, "text": "To display all the records in student tables whose regno>2, we can use the command given below −" }, { "code": null, "e": 2717, "s": 2699, "text": "σRegNo>2(student)" }, { "code": null, "e": 2803, "s": 2717, "text": "To display the record of ECE branch section B students, use the command given below −" }, { "code": null, "e": 2836, "s": 2803, "text": "σbranch=ECE ^ section=B(student)" }, { "code": null, "e": 2919, "s": 2836, "text": "To display the records of section B CSE and IT branch, use the following command −" }, { "code": null, "e": 2964, "s": 2919, "text": "σSection=B ^ Branch=cse ∨ branch=IT(student)" }, { "code": null, "e": 3047, "s": 2964, "text": "Consider the EMPLOYEE TABLE as another example to know about selection operation −" }, { "code": null, "e": 3127, "s": 3047, "text": "Retrieve information about those employees whose salary is greater than 20,000." }, { "code": null, "e": 3186, "s": 3127, "text": "If one condition is specified then, we get the following −" }, { "code": null, "e": 3245, "s": 3186, "text": "If one condition is specified then, we get the following −" }, { "code": null, "e": 3269, "s": 3245, "text": "σ salary > 20,000 (emp)" }, { "code": null, "e": 3372, "s": 3269, "text": "If more than one condition specified in the query then ( AND: ∧, OR:∨ , Not:#, equal: =, >, <, >=, <=)" }, { "code": null, "e": 3475, "s": 3372, "text": "If more than one condition specified in the query then ( AND: ∧, OR:∨ , Not:#, equal: =, >, <, >=, <=)" }, { "code": null, "e": 3568, "s": 3475, "text": "Relational operator will be used to combine the multiple conditions into a single statement." }, { "code": null, "e": 3731, "s": 3568, "text": "Example − If we wish to retrieve information of those employees whose salary > 20,000 and working as the Head of the Department (HOD) and Department number is 20." }, { "code": null, "e": 3774, "s": 3731, "text": "σ salary > 20,000 ^LOC=HOD ^Deptno=20(emp)" }, { "code": null, "e": 3926, "s": 3774, "text": "It displays the specific column of a table. It is denoted by pie (Π). It is a vertical subset of the original relation. It eliminates duplicate tuples." }, { "code": null, "e": 3977, "s": 3926, "text": "The syntax of projection operation is as follows −" }, { "code": null, "e": 3993, "s": 3977, "text": "∏regno(student)" }, { "code": null, "e": 4034, "s": 3993, "text": "Consider the student table given below −" }, { "code": null, "e": 4104, "s": 4034, "text": "To display regno column of student table, use the following command −" }, { "code": null, "e": 4120, "s": 4104, "text": "∏regno(student)" }, { "code": null, "e": 4202, "s": 4120, "text": "To display branch, section column of student table, use the command given below −" }, { "code": null, "e": 4227, "s": 4202, "text": "∏branch,section(student)" }, { "code": null, "e": 4304, "s": 4227, "text": "To display regno, section of ECE students, use the command mentioned below −" }, { "code": null, "e": 4341, "s": 4304, "text": "∏regno,section(σbranch=ECE(student))" }, { "code": null, "e": 4427, "s": 4341, "text": "Note − Conditions can be written in select operation but not in projection operation." }, { "code": null, "e": 4486, "s": 4427, "text": "Consider the employee table to know more about projection." }, { "code": null, "e": 4534, "s": 4486, "text": "If no condition is specified in the query then," }, { "code": null, "e": 4582, "s": 4534, "text": "If no condition is specified in the query then," }, { "code": null, "e": 4625, "s": 4582, "text": "∏ empid, ename, salary, address, dno (emp)" }, { "code": null, "e": 4718, "s": 4625, "text": "If condition is specified then, the composition of the select and projection is as follows −" }, { "code": null, "e": 4811, "s": 4718, "text": "If condition is specified then, the composition of the select and projection is as follows −" }, { "code": null, "e": 4893, "s": 4811, "text": "∏ empid, ename, salary, address, dno (σ salary >20,00 ^ LOC = HOD ^ dno=20) (emp)" }, { "code": null, "e": 4966, "s": 4893, "text": "It is used to assign a new name to a relation. It is denoted by ρ (rho)." }, { "code": null, "e": 5014, "s": 4966, "text": "The syntax for rename operation is as follows −" }, { "code": null, "e": 5049, "s": 5014, "text": "ρnewname (tablename or expression)" }, { "code": null, "e": 5090, "s": 5049, "text": "Consider the student table given below −" }, { "code": null, "e": 5168, "s": 5090, "text": "The student table is renamed with newstudent with the help of the following −" }, { "code": null, "e": 5190, "s": 5168, "text": "ρnewstudent (student)" }, { "code": null, "e": 5317, "s": 5190, "text": "The names, branch columns of the student table are renamed and newbranch respectively with the help of the following command −" }, { "code": null, "e": 5360, "s": 5317, "text": "ρnewname,newbranch(Πname,branch( student))" }, { "code": null, "e": 5419, "s": 5360, "text": "Binary operations are applied on two compatible relations." }, { "code": null, "e": 5550, "s": 5419, "text": "Two relations R1, R2 are to be compatible, if they are of the same degree and the domain of corresponding attributes are the same." }, { "code": null, "e": 5631, "s": 5550, "text": "The Rho in DDL used for name of relation and in DML used for name of attributes." }, { "code": null, "e": 5704, "s": 5631, "text": " SQL Old name New name" }, { "code": null, "e": 5766, "s": 5704, "text": "Renaming can be used by three methods, which are as follows −" }, { "code": null, "e": 5797, "s": 5766, "text": "Changing name of the relation." }, { "code": null, "e": 5828, "s": 5797, "text": "Changing name of the relation." }, { "code": null, "e": 5860, "s": 5828, "text": "Changing name of the attribute." }, { "code": null, "e": 5892, "s": 5860, "text": "Changing name of the attribute." }, { "code": null, "e": 5907, "s": 5892, "text": "Changing both." }, { "code": null, "e": 5922, "s": 5907, "text": "Changing both." } ]
Count the number of elements which are greater than any of element on right side of an array
04 Aug, 2021 Given an array Arr[]. The task is to count the number of elements Arr[i] in the given array such that one or more smaller elements are present on the right side of the element Arr[i] in array. Examples: Input: Arr[] = { 3, 9, 4, 6, 7, 5 } Output: 3Numbers that counts are: 9, 6, 7 9 – As all numbers are present after 9 are smaller than 9, 6 – 5 is smaller element present after it, 7 – 5 is smaller element which is present after it. Input: Arr[] = { 3, 2, 1, 2, 3, 4, 5 } Output: 2 Approach: Start traversing array from the last till first element of the array. While traversing maintain a min variable which stores the minimum element till now and a counter variable. Compare min variable with the current element. If min variable is smaller than current element Arr[i], increase the counter and if min is greater than Arr[i] then update the min. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation#include <bits/stdc++.h>using namespace std; // function to return the countint count_greater(int arr[], int n){ int min = INT_MAX; int counter = 0; // Comparing the given element // with minimum element till // occurred till now. for (int i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codeint main(){ int arr[] = { 3, 2, 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(int); cout << count_greater(arr, n) << endl; return 0;} // Java implementation of the approachclass GFG{ // function to return the countstatic int count_greater(int arr[], int n){ int min = Integer.MAX_VALUE; int counter = 0; // Comparing the given element // with minimum element till // occurred till now. for (int i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 2, 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println(count_greater(arr, n));}} // This code is contributed by 29AjayKumar # Python3 implementation for the above approachimport sys # function to return the countdef count_greater(arr, n) : min = sys.maxsize; counter = 0; # Comparing the given element # with minimum element till # occurred till now. for i in range(n - 1, -1, -1) : if (arr[i] > min) : counter += 1; # Updating the min variable if (arr[i] <= min) : min = arr[i]; return counter; # Driver codeif __name__ == "__main__" : arr = [ 3, 2, 1, 2, 3, 4, 5 ]; n = len(arr); print(count_greater(arr, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // function to return the countstatic int count_greater(int []arr, int n){ int min = int.MaxValue; int counter = 0; // Comparing the given element // with minimum element till // occurred till now. for (int i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codestatic public void Main (){ int []arr = { 3, 2, 1, 2, 3, 4, 5 }; int n = arr.Length; Console.Write(count_greater(arr, n));}} // This code is contributed by ajit. <script> // Javascript implementation // Function to return the countfunction count_greater(arr, n){ let min = Number.MAX_VALUE; let counter = 0; // Comparing the given element // with minimum element till // occurred till now. for(let i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codelet arr = [ 3, 2, 1, 2, 3, 4, 5 ];let n = arr.length; document.write(count_greater(arr, n) + "<br>"); // This code is contributed by rishavmahato348 </script> 2 Time Complexity: O(N)Auxiliary Space: O(1) 29AjayKumar jit_t ankthon shubham_singh rishavmahato348 pankajsharmagfg Constructive Algorithms Algorithms Arrays Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Aug, 2021" }, { "code": null, "e": 246, "s": 53, "text": "Given an array Arr[]. The task is to count the number of elements Arr[i] in the given array such that one or more smaller elements are present on the right side of the element Arr[i] in array." }, { "code": null, "e": 258, "s": 246, "text": "Examples: " }, { "code": null, "e": 490, "s": 258, "text": "Input: Arr[] = { 3, 9, 4, 6, 7, 5 } Output: 3Numbers that counts are: 9, 6, 7 9 – As all numbers are present after 9 are smaller than 9, 6 – 5 is smaller element present after it, 7 – 5 is smaller element which is present after it." }, { "code": null, "e": 541, "s": 490, "text": "Input: Arr[] = { 3, 2, 1, 2, 3, 4, 5 } Output: 2 " }, { "code": null, "e": 907, "s": 541, "text": "Approach: Start traversing array from the last till first element of the array. While traversing maintain a min variable which stores the minimum element till now and a counter variable. Compare min variable with the current element. If min variable is smaller than current element Arr[i], increase the counter and if min is greater than Arr[i] then update the min." }, { "code": null, "e": 960, "s": 907, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 964, "s": 960, "text": "C++" }, { "code": null, "e": 969, "s": 964, "text": "Java" }, { "code": null, "e": 977, "s": 969, "text": "Python3" }, { "code": null, "e": 980, "s": 977, "text": "C#" }, { "code": null, "e": 991, "s": 980, "text": "Javascript" }, { "code": "// C++ implementation#include <bits/stdc++.h>using namespace std; // function to return the countint count_greater(int arr[], int n){ int min = INT_MAX; int counter = 0; // Comparing the given element // with minimum element till // occurred till now. for (int i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codeint main(){ int arr[] = { 3, 2, 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(int); cout << count_greater(arr, n) << endl; return 0;}", "e": 1642, "s": 991, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // function to return the countstatic int count_greater(int arr[], int n){ int min = Integer.MAX_VALUE; int counter = 0; // Comparing the given element // with minimum element till // occurred till now. for (int i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 2, 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println(count_greater(arr, n));}} // This code is contributed by 29AjayKumar", "e": 2356, "s": 1642, "text": null }, { "code": "# Python3 implementation for the above approachimport sys # function to return the countdef count_greater(arr, n) : min = sys.maxsize; counter = 0; # Comparing the given element # with minimum element till # occurred till now. for i in range(n - 1, -1, -1) : if (arr[i] > min) : counter += 1; # Updating the min variable if (arr[i] <= min) : min = arr[i]; return counter; # Driver codeif __name__ == \"__main__\" : arr = [ 3, 2, 1, 2, 3, 4, 5 ]; n = len(arr); print(count_greater(arr, n)); # This code is contributed by AnkitRai01", "e": 2972, "s": 2356, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // function to return the countstatic int count_greater(int []arr, int n){ int min = int.MaxValue; int counter = 0; // Comparing the given element // with minimum element till // occurred till now. for (int i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codestatic public void Main (){ int []arr = { 3, 2, 1, 2, 3, 4, 5 }; int n = arr.Length; Console.Write(count_greater(arr, n));}} // This code is contributed by ajit.", "e": 3678, "s": 2972, "text": null }, { "code": "<script> // Javascript implementation // Function to return the countfunction count_greater(arr, n){ let min = Number.MAX_VALUE; let counter = 0; // Comparing the given element // with minimum element till // occurred till now. for(let i = n - 1; i >= 0; i--) { if (arr[i] > min) { counter++; } // Updating the min variable if (arr[i] <= min) { min = arr[i]; } } return counter;} // Driver codelet arr = [ 3, 2, 1, 2, 3, 4, 5 ];let n = arr.length; document.write(count_greater(arr, n) + \"<br>\"); // This code is contributed by rishavmahato348 </script>", "e": 4331, "s": 3678, "text": null }, { "code": null, "e": 4333, "s": 4331, "text": "2" }, { "code": null, "e": 4378, "s": 4335, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 4390, "s": 4378, "text": "29AjayKumar" }, { "code": null, "e": 4396, "s": 4390, "text": "jit_t" }, { "code": null, "e": 4404, "s": 4396, "text": "ankthon" }, { "code": null, "e": 4418, "s": 4404, "text": "shubham_singh" }, { "code": null, "e": 4434, "s": 4418, "text": "rishavmahato348" }, { "code": null, "e": 4450, "s": 4434, "text": "pankajsharmagfg" }, { "code": null, "e": 4474, "s": 4450, "text": "Constructive Algorithms" }, { "code": null, "e": 4485, "s": 4474, "text": "Algorithms" }, { "code": null, "e": 4492, "s": 4485, "text": "Arrays" }, { "code": null, "e": 4499, "s": 4492, "text": "Arrays" }, { "code": null, "e": 4510, "s": 4499, "text": "Algorithms" } ]
numpy.ndarray.resize() function – Python
11 Jun, 2020 numpy.ndarray.resize() function change shape and size of array in-place. Syntax : numpy.ndarray.resize(new_shape, refcheck = True) Parameters :new_shape :[tuple of ints, or n ints] Shape of resized array.refcheck :[bool, optional] If False, reference count will not be checked. Default is True. Return : None Code #1 : # Python program explaining# numpy.ndarray.resize() function # importing numpy as geek import numpy as geek arr = geek.array([[0, 1], [2, 3]]) # this function change the shape and size# of the array & return Nonegfg = arr.resize((2, 1)) print (gfg) Output : None Code #2 : # Python program explaining# numpy.ndarray.resize() function # importing numpy as geek import numpy as geek arr = geek.array([[0, 1], [2, 3]], order = 'F') # this function change the shape and size# of the array & return Nonegfg = arr.resize((2, 1)) print (gfg) Output : None Python numpy-ndarray Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Introduction To PYTHON Python OOPs Concepts Python | os.path.join() method 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 | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2020" }, { "code": null, "e": 101, "s": 28, "text": "numpy.ndarray.resize() function change shape and size of array in-place." }, { "code": null, "e": 159, "s": 101, "text": "Syntax : numpy.ndarray.resize(new_shape, refcheck = True)" }, { "code": null, "e": 323, "s": 159, "text": "Parameters :new_shape :[tuple of ints, or n ints] Shape of resized array.refcheck :[bool, optional] If False, reference count will not be checked. Default is True." }, { "code": null, "e": 337, "s": 323, "text": "Return : None" }, { "code": null, "e": 347, "s": 337, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.ndarray.resize() function # importing numpy as geek import numpy as geek arr = geek.array([[0, 1], [2, 3]]) # this function change the shape and size# of the array & return Nonegfg = arr.resize((2, 1)) print (gfg)", "e": 609, "s": 347, "text": null }, { "code": null, "e": 618, "s": 609, "text": "Output :" }, { "code": null, "e": 624, "s": 618, "text": "None\n" }, { "code": null, "e": 635, "s": 624, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.ndarray.resize() function # importing numpy as geek import numpy as geek arr = geek.array([[0, 1], [2, 3]], order = 'F') # this function change the shape and size# of the array & return Nonegfg = arr.resize((2, 1)) print (gfg)", "e": 911, "s": 635, "text": null }, { "code": null, "e": 920, "s": 911, "text": "Output :" }, { "code": null, "e": 926, "s": 920, "text": "None\n" }, { "code": null, "e": 947, "s": 926, "text": "Python numpy-ndarray" }, { "code": null, "e": 960, "s": 947, "text": "Python-numpy" }, { "code": null, "e": 967, "s": 960, "text": "Python" }, { "code": null, "e": 1065, "s": 967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1097, "s": 1065, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1124, "s": 1097, "text": "Python Classes and Objects" }, { "code": null, "e": 1147, "s": 1124, "text": "Introduction To PYTHON" }, { "code": null, "e": 1168, "s": 1147, "text": "Python OOPs Concepts" }, { "code": null, "e": 1199, "s": 1168, "text": "Python | os.path.join() method" }, { "code": null, "e": 1255, "s": 1199, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1297, "s": 1255, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1339, "s": 1297, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1378, "s": 1339, "text": "Python | Get unique values from a list" } ]
How to run multiple npm scripts in parallel?
09 Feb, 2021 As there is no straightforward way provided by npm to run multiple scripts in parallel, We can try coming up with a solution in the following way: Create a basic React App project on the Localhost server and at the same time, we want to run the build operation of the project. Now what we can do is we can make use of the npm-run-all package, which will make it easy for us to host the project on the Localhost server, and also we can run the optimized build for production simultaneously. Approach 1(npm-run all package): We can use the” npm-run all” package to run different scripts at the same time. First, we have to install the package itself by using the command. npm install npm-run-all — save-dev After installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously. Now, our next step would be to open up a terminal on Mac or command prompt on Windows and “cd” into the project directory and type the command “./node_modules/.bin/npm-run-all build start ” and press Enter. In the local installation case which we did, npm-run-all will be installed into our project’s node_modulesdirectory. PATH environment variable does not include there, so we have to use ./node_modules/.bin/npm-run-all (or $(npm bin)/npm-run-all) to run npm-run-all command. Console Output: Build operation executed successfully The app is hosted successfully on the server Therefore, we can now see that our app is successfully hosted on a local server, and the build operation executed perfectly with the help of a single package “npm-run-all”. Browser Output: Approach 2 (Using Concurrently package): In this approach, we will be using the Concurrently package . Using this package we can combine different script commands such as “npm run start” and “npm run build ” into a single script and then run it in the command line. First, install the package in your project directory using this command : npm install concurrently --save Again after installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously. Now we have to include a dev script inside the scripts in the package.json file which will hold our different commands combined. With –kill-others switch, all commands are killed if one dies. We can follow this to create our own dev script : "dev": "concurrently \"command1 arg\" \"command2 arg\"" Now we can simply run the whole command by simply using : npm run dev Console output: NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Feb, 2021" }, { "code": null, "e": 201, "s": 54, "text": "As there is no straightforward way provided by npm to run multiple scripts in parallel, We can try coming up with a solution in the following way:" }, { "code": null, "e": 544, "s": 201, "text": "Create a basic React App project on the Localhost server and at the same time, we want to run the build operation of the project. Now what we can do is we can make use of the npm-run-all package, which will make it easy for us to host the project on the Localhost server, and also we can run the optimized build for production simultaneously." }, { "code": null, "e": 724, "s": 544, "text": "Approach 1(npm-run all package): We can use the” npm-run all” package to run different scripts at the same time. First, we have to install the package itself by using the command." }, { "code": null, "e": 759, "s": 724, "text": "npm install npm-run-all — save-dev" }, { "code": null, "e": 1052, "s": 759, "text": "After installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously." }, { "code": null, "e": 1259, "s": 1052, "text": "Now, our next step would be to open up a terminal on Mac or command prompt on Windows and “cd” into the project directory and type the command “./node_modules/.bin/npm-run-all build start ” and press Enter." }, { "code": null, "e": 1444, "s": 1259, "text": "In the local installation case which we did, npm-run-all will be installed into our project’s node_modulesdirectory. PATH environment variable does not include there, so we have to use" }, { "code": null, "e": 1534, "s": 1444, "text": "./node_modules/.bin/npm-run-all \n(or $(npm bin)/npm-run-all) to run npm-run-all command." }, { "code": null, "e": 1550, "s": 1534, "text": "Console Output:" }, { "code": null, "e": 1588, "s": 1550, "text": "Build operation executed successfully" }, { "code": null, "e": 1633, "s": 1588, "text": "The app is hosted successfully on the server" }, { "code": null, "e": 1806, "s": 1633, "text": "Therefore, we can now see that our app is successfully hosted on a local server, and the build operation executed perfectly with the help of a single package “npm-run-all”." }, { "code": null, "e": 1822, "s": 1806, "text": "Browser Output:" }, { "code": null, "e": 2088, "s": 1822, "text": "Approach 2 (Using Concurrently package): In this approach, we will be using the Concurrently package . Using this package we can combine different script commands such as “npm run start” and “npm run build ” into a single script and then run it in the command line." }, { "code": null, "e": 2162, "s": 2088, "text": "First, install the package in your project directory using this command :" }, { "code": null, "e": 2194, "s": 2162, "text": "npm install concurrently --save" }, { "code": null, "e": 2495, "s": 2194, "text": "Again after installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously. " }, { "code": null, "e": 2624, "s": 2495, "text": "Now we have to include a dev script inside the scripts in the package.json file which will hold our different commands combined." }, { "code": null, "e": 2689, "s": 2624, "text": " With –kill-others switch, all commands are killed if one dies." }, { "code": null, "e": 2739, "s": 2689, "text": "We can follow this to create our own dev script :" }, { "code": null, "e": 2795, "s": 2739, "text": "\"dev\": \"concurrently \\\"command1 arg\\\" \\\"command2 arg\\\"\"" }, { "code": null, "e": 2854, "s": 2795, "text": "Now we can simply run the whole command by simply using :" }, { "code": null, "e": 2866, "s": 2854, "text": "npm run dev" }, { "code": null, "e": 2882, "s": 2866, "text": "Console output:" }, { "code": null, "e": 2899, "s": 2882, "text": "NodeJS-Questions" }, { "code": null, "e": 2906, "s": 2899, "text": "Picked" }, { "code": null, "e": 2930, "s": 2906, "text": "Technical Scripter 2020" }, { "code": null, "e": 2938, "s": 2930, "text": "Node.js" }, { "code": null, "e": 2957, "s": 2938, "text": "Technical Scripter" }, { "code": null, "e": 2974, "s": 2957, "text": "Web Technologies" } ]
Node.js crypto.verify() Function
24 Sep, 2021 The crypto.verify() is a method of the inbuilt module of node.js crypto that is used to verify the signature of data that is hashed using a different kind of hashing functions Like SHA256 algorithm etc. Syntax: crypto.verify(algorithm, data, publicKey, signature) Parameters: algorithm: It is a string-type value. A signature can be verified by applying the name of signature algorithms, like ‘SHA256’. The algorithm must be the same in which the signature was created. data: The data argument must be an instance of the buffer, Typed Array, or Data View. key: It should be the public key of the key object. If you have not any public key then you can create private and public keys using crypto.generateKeyPairSync() method. signature: The signature argument must be an instance of Buffer, Typed Array, or Data View. Returned value: This function returns a boolean value. Return True if a signature is verified else false. Example: Filename: index.js Javascript // Importing Required Modulesconst crypto = require('crypto');const buffer = require('buffer'); // Creating a private keyconst { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048,});// Using Hashing Algorithmconst algorithm = "SHA256"; // Converting string to bufferconst data = Buffer.from("I Love GeeksForGeeks"); // Sign the data and returned signature in bufferconst signature = crypto.sign(algorithm, data , privateKey); // Verifying signature using crypto.verify() functionconst isVerified = crypto.verify(algorithm, data, publicKey, signature); // Printing the resultconsole.log(`Is signature verified: ${isVerified}`); Run index.js using the below command: node index.js Output: Reference:https://nodejs.org/api/crypto.html#crypto_crypto_verify_algorithm_data_key_signature anikaseth98 Node.js-crypto-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 232, "s": 28, "text": "The crypto.verify() is a method of the inbuilt module of node.js crypto that is used to verify the signature of data that is hashed using a different kind of hashing functions Like SHA256 algorithm etc." }, { "code": null, "e": 240, "s": 232, "text": "Syntax:" }, { "code": null, "e": 293, "s": 240, "text": "crypto.verify(algorithm, data, publicKey, signature)" }, { "code": null, "e": 305, "s": 293, "text": "Parameters:" }, { "code": null, "e": 500, "s": 305, "text": "algorithm: It is a string-type value. A signature can be verified by applying the name of signature algorithms, like ‘SHA256’. The algorithm must be the same in which the signature was created." }, { "code": null, "e": 587, "s": 500, "text": "data: The data argument must be an instance of the buffer, Typed Array, or Data View." }, { "code": null, "e": 757, "s": 587, "text": "key: It should be the public key of the key object. If you have not any public key then you can create private and public keys using crypto.generateKeyPairSync() method." }, { "code": null, "e": 849, "s": 757, "text": "signature: The signature argument must be an instance of Buffer, Typed Array, or Data View." }, { "code": null, "e": 955, "s": 849, "text": "Returned value: This function returns a boolean value. Return True if a signature is verified else false." }, { "code": null, "e": 964, "s": 955, "text": "Example:" }, { "code": null, "e": 983, "s": 964, "text": "Filename: index.js" }, { "code": null, "e": 994, "s": 983, "text": "Javascript" }, { "code": "// Importing Required Modulesconst crypto = require('crypto');const buffer = require('buffer'); // Creating a private keyconst { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048,});// Using Hashing Algorithmconst algorithm = \"SHA256\"; // Converting string to bufferconst data = Buffer.from(\"I Love GeeksForGeeks\"); // Sign the data and returned signature in bufferconst signature = crypto.sign(algorithm, data , privateKey); // Verifying signature using crypto.verify() functionconst isVerified = crypto.verify(algorithm, data, publicKey, signature); // Printing the resultconsole.log(`Is signature verified: ${isVerified}`);", "e": 1654, "s": 994, "text": null }, { "code": null, "e": 1692, "s": 1654, "text": "Run index.js using the below command:" }, { "code": null, "e": 1706, "s": 1692, "text": "node index.js" }, { "code": null, "e": 1714, "s": 1706, "text": "Output:" }, { "code": null, "e": 1809, "s": 1714, "text": "Reference:https://nodejs.org/api/crypto.html#crypto_crypto_verify_algorithm_data_key_signature" }, { "code": null, "e": 1823, "s": 1811, "text": "anikaseth98" }, { "code": null, "e": 1845, "s": 1823, "text": "Node.js-crypto-module" }, { "code": null, "e": 1852, "s": 1845, "text": "Picked" }, { "code": null, "e": 1860, "s": 1852, "text": "Node.js" }, { "code": null, "e": 1877, "s": 1860, "text": "Web Technologies" } ]
Create a GUI for Weather Forecast using openweathermap API in Python
05 Sep, 2020 Prerequisites: Find current weather of any city using openweathermap API The idea of this article is to provide a simple GUI application to users to get the current temperature of any city they wish to see. The system also provides a simple user interface for simplification of application. It also provides an amazing UX for its users. The features of this application will be that this will be a real-time weather forecast app that returns the current temperature, maximum and minimum temperature, humidity, latitude, and longitude coordinates of the searched city, current date, and time. It can also change its theme according to the time of day. openweathermap is a service that provides weather data, including current weather data, forecasts, and historical data to the developers of web services and mobile applications. Tkinter: It is the fastest and easiest way to create GUI applications. This is included in the Python standard modules so there is no need to install it externally. PIL: PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. json: This module is used to handle JSON files and comes built in with Python. So there is no need to install it externally requests: It is used for making HTTP requests to a specified URL. This module does not comes built in with Python. To install it type the below command in the terminal. pip install requests Images Used in the below application: moon.png sun.png logo.png Below is the implementation. Python3 # python3 -- Weather Application using API # importing the librariesfrom tkinter import *import requestsimport jsonimport datetimefrom PIL import ImageTk, Image # necessary detailsroot = Tk()root.title("Weather App")root.geometry("450x700")root['background'] = "white" # Imagenew = ImageTk.PhotoImage(Image.open('logo.png'))panel = Label(root, image=new)panel.place(x=0, y=520) # Datesdt = datetime.datetime.now()date = Label(root, text=dt.strftime('%A--'), bg='white', font=("bold", 15))date.place(x=5, y=130)month = Label(root, text=dt.strftime('%m %B'), bg='white', font=("bold", 15))month.place(x=100, y=130) # Timehour = Label(root, text=dt.strftime('%I : %M %p'), bg='white', font=("bold", 15))hour.place(x=10, y=160) # Theme for the respective time the application is usedif int((dt.strftime('%I'))) >= 8 & int((dt.strftime('%I'))) <= 5: img = ImageTk.PhotoImage(Image.open('moon.png')) panel = Label(root, image=img) panel.place(x=210, y=200)else: img = ImageTk.PhotoImage(Image.open('sun.png')) panel = Label(root, image=img) panel.place(x=210, y=200) # City Searchcity_name = StringVar()city_entry = Entry(root, textvariable=city_name, width=45)city_entry.grid(row=1, column=0, ipady=10, stick=W+E+N+S) def city_name(): # API Call api_request = requests.get("https://api.openweathermap.org/data/2.5/weather?q=" + city_entry.get() + "&units=metric&appid="+api_key) api = json.loads(api_request.content) # Temperatures y = api['main'] current_temprature = y['temp'] humidity = y['humidity'] tempmin = y['temp_min'] tempmax = y['temp_max'] # Coordinates x = api['coord'] longtitude = x['lon'] latitude = x['lat'] # Country z = api['sys'] country = z['country'] citi = api['name'] # Adding the received info into the screen lable_temp.configure(text=current_temprature) lable_humidity.configure(text=humidity) max_temp.configure(text=tempmax) min_temp.configure(text=tempmin) lable_lon.configure(text=longtitude) lable_lat.configure(text=latitude) lable_country.configure(text=country) lable_citi.configure(text=citi) # Search Bar and Buttoncity_nameButton = Button(root, text="Search", command=city_name)city_nameButton.grid(row=1, column=1, padx=5, stick=W+E+N+S) # Country Names and Coordinateslable_citi = Label(root, text="...", width=0, bg='white', font=("bold", 15))lable_citi.place(x=10, y=63) lable_country = Label(root, text="...", width=0, bg='white', font=("bold", 15))lable_country.place(x=135, y=63) lable_lon = Label(root, text="...", width=0, bg='white', font=("Helvetica", 15))lable_lon.place(x=25, y=95)lable_lat = Label(root, text="...", width=0, bg='white', font=("Helvetica", 15))lable_lat.place(x=95, y=95) # Current Temperature lable_temp = Label(root, text="...", width=0, bg='white', font=("Helvetica", 110), fg='black')lable_temp.place(x=18, y=220) # Other temperature details humi = Label(root, text="Humidity: ", width=0, bg='white', font=("bold", 15))humi.place(x=3, y=400) lable_humidity = Label(root, text="...", width=0, bg='white', font=("bold", 15))lable_humidity.place(x=107, y=400) maxi = Label(root, text="Max. Temp.: ", width=0, bg='white', font=("bold", 15))maxi.place(x=3, y=430) max_temp = Label(root, text="...", width=0, bg='white', font=("bold", 15))max_temp.place(x=128, y=430) mini = Label(root, text="Min. Temp.: ", width=0, bg='white', font=("bold", 15))mini.place(x=3, y=460) min_temp = Label(root, text="...", width=0, bg='white', font=("bold", 15))min_temp.place(x=128, y=460) # Notenote = Label(root, text="All temperatures in degree celsius", bg='white', font=("italic", 10))note.place(x=95, y=495) root.mainloop() Output: Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 101, "s": 28, "text": "Prerequisites: Find current weather of any city using openweathermap API" }, { "code": null, "e": 679, "s": 101, "text": "The idea of this article is to provide a simple GUI application to users to get the current temperature of any city they wish to see. The system also provides a simple user interface for simplification of application. It also provides an amazing UX for its users. The features of this application will be that this will be a real-time weather forecast app that returns the current temperature, maximum and minimum temperature, humidity, latitude, and longitude coordinates of the searched city, current date, and time. It can also change its theme according to the time of day." }, { "code": null, "e": 857, "s": 679, "text": "openweathermap is a service that provides weather data, including current weather data, forecasts, and historical data to the developers of web services and mobile applications." }, { "code": null, "e": 1022, "s": 857, "text": "Tkinter: It is the fastest and easiest way to create GUI applications. This is included in the Python standard modules so there is no need to install it externally." }, { "code": null, "e": 1132, "s": 1022, "text": "PIL: PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities." }, { "code": null, "e": 1256, "s": 1132, "text": "json: This module is used to handle JSON files and comes built in with Python. So there is no need to install it externally" }, { "code": null, "e": 1425, "s": 1256, "text": "requests: It is used for making HTTP requests to a specified URL. This module does not comes built in with Python. To install it type the below command in the terminal." }, { "code": null, "e": 1446, "s": 1425, "text": "pip install requests" }, { "code": null, "e": 1484, "s": 1446, "text": "Images Used in the below application:" }, { "code": null, "e": 1493, "s": 1484, "text": "moon.png" }, { "code": null, "e": 1501, "s": 1493, "text": "sun.png" }, { "code": null, "e": 1510, "s": 1501, "text": "logo.png" }, { "code": null, "e": 1539, "s": 1510, "text": "Below is the implementation." }, { "code": null, "e": 1547, "s": 1539, "text": "Python3" }, { "code": "# python3 -- Weather Application using API # importing the librariesfrom tkinter import *import requestsimport jsonimport datetimefrom PIL import ImageTk, Image # necessary detailsroot = Tk()root.title(\"Weather App\")root.geometry(\"450x700\")root['background'] = \"white\" # Imagenew = ImageTk.PhotoImage(Image.open('logo.png'))panel = Label(root, image=new)panel.place(x=0, y=520) # Datesdt = datetime.datetime.now()date = Label(root, text=dt.strftime('%A--'), bg='white', font=(\"bold\", 15))date.place(x=5, y=130)month = Label(root, text=dt.strftime('%m %B'), bg='white', font=(\"bold\", 15))month.place(x=100, y=130) # Timehour = Label(root, text=dt.strftime('%I : %M %p'), bg='white', font=(\"bold\", 15))hour.place(x=10, y=160) # Theme for the respective time the application is usedif int((dt.strftime('%I'))) >= 8 & int((dt.strftime('%I'))) <= 5: img = ImageTk.PhotoImage(Image.open('moon.png')) panel = Label(root, image=img) panel.place(x=210, y=200)else: img = ImageTk.PhotoImage(Image.open('sun.png')) panel = Label(root, image=img) panel.place(x=210, y=200) # City Searchcity_name = StringVar()city_entry = Entry(root, textvariable=city_name, width=45)city_entry.grid(row=1, column=0, ipady=10, stick=W+E+N+S) def city_name(): # API Call api_request = requests.get(\"https://api.openweathermap.org/data/2.5/weather?q=\" + city_entry.get() + \"&units=metric&appid=\"+api_key) api = json.loads(api_request.content) # Temperatures y = api['main'] current_temprature = y['temp'] humidity = y['humidity'] tempmin = y['temp_min'] tempmax = y['temp_max'] # Coordinates x = api['coord'] longtitude = x['lon'] latitude = x['lat'] # Country z = api['sys'] country = z['country'] citi = api['name'] # Adding the received info into the screen lable_temp.configure(text=current_temprature) lable_humidity.configure(text=humidity) max_temp.configure(text=tempmax) min_temp.configure(text=tempmin) lable_lon.configure(text=longtitude) lable_lat.configure(text=latitude) lable_country.configure(text=country) lable_citi.configure(text=citi) # Search Bar and Buttoncity_nameButton = Button(root, text=\"Search\", command=city_name)city_nameButton.grid(row=1, column=1, padx=5, stick=W+E+N+S) # Country Names and Coordinateslable_citi = Label(root, text=\"...\", width=0, bg='white', font=(\"bold\", 15))lable_citi.place(x=10, y=63) lable_country = Label(root, text=\"...\", width=0, bg='white', font=(\"bold\", 15))lable_country.place(x=135, y=63) lable_lon = Label(root, text=\"...\", width=0, bg='white', font=(\"Helvetica\", 15))lable_lon.place(x=25, y=95)lable_lat = Label(root, text=\"...\", width=0, bg='white', font=(\"Helvetica\", 15))lable_lat.place(x=95, y=95) # Current Temperature lable_temp = Label(root, text=\"...\", width=0, bg='white', font=(\"Helvetica\", 110), fg='black')lable_temp.place(x=18, y=220) # Other temperature details humi = Label(root, text=\"Humidity: \", width=0, bg='white', font=(\"bold\", 15))humi.place(x=3, y=400) lable_humidity = Label(root, text=\"...\", width=0, bg='white', font=(\"bold\", 15))lable_humidity.place(x=107, y=400) maxi = Label(root, text=\"Max. Temp.: \", width=0, bg='white', font=(\"bold\", 15))maxi.place(x=3, y=430) max_temp = Label(root, text=\"...\", width=0, bg='white', font=(\"bold\", 15))max_temp.place(x=128, y=430) mini = Label(root, text=\"Min. Temp.: \", width=0, bg='white', font=(\"bold\", 15))mini.place(x=3, y=460) min_temp = Label(root, text=\"...\", width=0, bg='white', font=(\"bold\", 15))min_temp.place(x=128, y=460) # Notenote = Label(root, text=\"All temperatures in degree celsius\", bg='white', font=(\"italic\", 10))note.place(x=95, y=495) root.mainloop()", "e": 5515, "s": 1547, "text": null }, { "code": null, "e": 5523, "s": 5515, "text": "Output:" }, { "code": null, "e": 5539, "s": 5523, "text": "Python-projects" }, { "code": null, "e": 5554, "s": 5539, "text": "python-utility" }, { "code": null, "e": 5561, "s": 5554, "text": "Python" } ]
How to Convert ArrayList to LinkedHashSet in Java? - GeeksforGeeks
20 Sep, 2021 ArrayList is a data structure that overcomes the shortcomings of the common array in Java wherein the size has to be explicitly specified beforehand. The length of the array data structure cannot be modified which is taken care of the ArrayList data structure. This data structure is also known as the dynamic array and can grow or be modified as the need be. It is a class under the Collections framework and can be included in the java program by importing java.util package. LinkedHashSet is an enhanced version of the traditional HashSet class in Java by providing the added functionality of ordering which was missing in the HashSet. It maintains the order in which the elements were inserted into it, unlike the HashSet where the ordering was unpredictable. It is implemented using a doubly-linked list and can be iterated over using the iterator. This article deals with the conversion of ArrayList to LinkedHashSet using 4 different approaches which are listed as follows : Passing the ArrayList as a parameter during the initialization of the LinkedHashSet constructor.Using the addAll() method of the LinkedHashSet class.Using the add() method of the LinkedHashSet class while iterating over all the elements of the ArrayList.Using stream to first convert the ArrayList to Set which is further converted to LinkedHashSet. Passing the ArrayList as a parameter during the initialization of the LinkedHashSet constructor. Using the addAll() method of the LinkedHashSet class. Using the add() method of the LinkedHashSet class while iterating over all the elements of the ArrayList. Using stream to first convert the ArrayList to Set which is further converted to LinkedHashSet. Approach 1 Using this approach we merely, pass the ArrayList as a parameter while initializing the LinkedHashSet class Syntax LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C. LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c); Example Java // java program to convert ArrayList// to LinkedHashSet // importing the utils packageimport java.util.*; class GFG { // defining the method void arrayListToLinkedHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // adding values in the ArrayList arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // printing the list System.out.println("The array list : " + arrayList); // initializing the LinkedHashSet class // passing the ArrayList as parameter LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>(arrayList); // printing the LinkedHashSet System.out.println("The converted " + "Linked Hash Set : " + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToLinkedHashSet(); }} The array list : [Geeks, For, Geeks] The converted Linked Hash Set : [Geeks, For] Explanation:The ArrayList contains three entries which are [Geeks, For, Geeks]. This is converted to an ordered set and only contains two values: Geeks and For. Since Set don’t allow multiple similar values. Approach 2 Using this approach, we use the predefined method addAll() of the LinkedHashSet class after initializing it to populate the LinkedHashSet. Syntax: LinkedHashSet.addAll(Collection C) Parameters: Parameter C is a collection of any type that is to be added to the set. Return Value: The method returns true if it successfully appends the elements of the collection C to this Set otherwise it returns False. Example Java // java program to convert ArrayList// to LinkedHashSet // importing the java.utils packageimport java.util.*; class GFG { // defining the method void arrayListToLinkedHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // filling the ArrayList with values arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // printing the list System.out.println("The Array List : " + arrayList); // initializing the LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(); // using the addAll() to // fill the HashSet linkedHashSet.addAll(arrayList); // printing the LinkedHashSet System.out.println("The Linked " + "Hash Set : " + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToLinkedHashSet(); }} The Array List : [Geeks, For, Geeks] The Linked Hash Set : [Geeks, For] Approach 3 Using this approach, we iterate over the ArrayList and in each iteration fill the LinkedHashSet with the value using the predefined add() method of the LinkedHashSet class. Syntax: Hash_Set.add(Object element) Parameters: The parameter element is of the type LinkedHashSet and refers to the element to be added to the Set. Return Value: The function returns True if the element is not present in the LinkedHashSet otherwise False if the element is already present in the LinkedHashSet. Example Java // java program to convert ArrayList// to LinkedHashSet // importing the java.utils packageimport java.util.*; class GFG { // defining the method void arrayListToHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // filling the ArrayList with values arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // printing the list System.out.println("The Array List : " + arrayList); // declaring the iterator Iterator<String> itr = arrayList.iterator(); // initializing the LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(); // loop to iterate through the ArrayList while (itr.hasNext()) // using the add() // to fill the HashSet linkedHashSet.add(itr.next()); // printing the LinkedHashSet System.out.println("The Linked Hash Set : " + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToHashSet(); }} The Array List : [Geeks, For, Geeks] The Linked Hash Set : [Geeks, For] Approach 4 Under this approach, we first convert the ArrayList to a stream which is then converted to a Set. This Set is finally converted to a LinkedHashSet. Stream class is only available for JDK versions 8 or above. Example Java // java program to convert ArrayList// to LinkedHashSet import java.util.*;import java.util.stream.*; class GFG { // defining the method void arrayListToLinkedHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // filling the ArrayList with values arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // printing the list System.out.println("The Array List : " + arrayList); // creating a stream from the ArrayList Stream<String> stream = arrayList.stream(); // creating a set from the Stream // using the predefined toSet() // method of the Collectors class Set<String> set = stream.collect(Collectors.toSet()); // converting the Set to // LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(set); // printing the LinkedHashSet System.out.println("The Linked Hash Set : " + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToLinkedHashSet(); }} The Array List : [Geeks, For, Geeks] The Linked Hash Set : [Geeks, For] Converting ArrayList Of Custom Class Objects To LinkedHashSet The above examples illustrate the procedure to convert ArrayList of primitive data types such as Integer, String, and so on. Here, we are going to use the above approaches to convert an ArrayList of custom class objects to LinkedHashSet. An interesting feature of the conversion is that this allows duplication of objects which was not allowed in the above scenarios. The reason for the same being that each time a new object of the same class is created and the equals() method which is used to check elements before entering them in the set when compares the objects, finds unique references since each new object holds a new reference. This allows for the same data to be present in the LinkedHashSet in more than one places. Example Java // java code to convert an ArrayList// of custom class objects to// LinkedHashSet // importing the librariesimport java.util.*; // the custom classclass Sports { // global variable name of type String // to hold the name of the sport private String name; // constructor public Sports(String name) { // initializing the name this.name = name; } // method to return the string public String returnString() { return name + " is a great sport"; }} // primary classclass GFG { // declaring the method static void arrayListToLinkedHashSet() { // creating an array list of type // class Sports ArrayList<Sports> listOfSports = new ArrayList<Sports>(); // adding the new instances of Sports // in the array list listOfSports.add(new Sports("Football")); listOfSports.add(new Sports("Basketball")); listOfSports.add(new Sports("Football")); // printing the list System.out.println("The Array List : " + listOfSports); // declaring an iterator of type Sports // to iterate over the list Iterator<Sports> itr = listOfSports.iterator(); // iterating over the list while (itr.hasNext()) // printing the contents // by calling the returnString() System.out.println(itr.next().returnString()); // initializing the linkedhashset // of type Sports LinkedHashSet<Sports> linkedHashSet = new LinkedHashSet<Sports>(listOfSports); // printing the contents of the // linked hash set System.out.println("The Linked Hash Set : " + linkedHashSet); // declaring an iterator to iterate // over linkedhashset Iterator<Sports> itr1 = linkedHashSet.iterator(); // iterating over the linkedhashset while (itr1.hasNext()) { // calling the returnString() // of Sports System.out.println(itr1.next().returnString()); } } // Driver Code public static void main(String[] args) { // calling the method arrayListToLinkedHashSet(); }} The Array List : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f] Football is a great sport Basketball is a great sport Football is a great sport The Linked Hash Set : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f] Football is a great sport Basketball is a great sport Football is a great sport Explanation:In the first line, the contents of ArrayList are printed which as can be seen are references to class Sports. In the following three lines, the contents of the returnString() method of Sports class are printed. It should be noted that all references are unique and hence the LinkedHashSet allows them even though the contents might be the same. In the following line, the contents of LinkedHashSet is printed which are again references to the class Sports. The lines following that are the returnString() method calls. gabaa406 arorakashish0911 Java-ArrayList java-LinkedHashSet Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n20 Sep, 2021" }, { "code": null, "e": 25716, "s": 25237, "text": "ArrayList is a data structure that overcomes the shortcomings of the common array in Java wherein the size has to be explicitly specified beforehand. The length of the array data structure cannot be modified which is taken care of the ArrayList data structure. This data structure is also known as the dynamic array and can grow or be modified as the need be. It is a class under the Collections framework and can be included in the java program by importing java.util package. " }, { "code": null, "e": 26092, "s": 25716, "text": "LinkedHashSet is an enhanced version of the traditional HashSet class in Java by providing the added functionality of ordering which was missing in the HashSet. It maintains the order in which the elements were inserted into it, unlike the HashSet where the ordering was unpredictable. It is implemented using a doubly-linked list and can be iterated over using the iterator." }, { "code": null, "e": 26220, "s": 26092, "text": "This article deals with the conversion of ArrayList to LinkedHashSet using 4 different approaches which are listed as follows :" }, { "code": null, "e": 26570, "s": 26220, "text": "Passing the ArrayList as a parameter during the initialization of the LinkedHashSet constructor.Using the addAll() method of the LinkedHashSet class.Using the add() method of the LinkedHashSet class while iterating over all the elements of the ArrayList.Using stream to first convert the ArrayList to Set which is further converted to LinkedHashSet." }, { "code": null, "e": 26667, "s": 26570, "text": "Passing the ArrayList as a parameter during the initialization of the LinkedHashSet constructor." }, { "code": null, "e": 26721, "s": 26667, "text": "Using the addAll() method of the LinkedHashSet class." }, { "code": null, "e": 26827, "s": 26721, "text": "Using the add() method of the LinkedHashSet class while iterating over all the elements of the ArrayList." }, { "code": null, "e": 26923, "s": 26827, "text": "Using stream to first convert the ArrayList to Set which is further converted to LinkedHashSet." }, { "code": null, "e": 26934, "s": 26923, "text": "Approach 1" }, { "code": null, "e": 27042, "s": 26934, "text": "Using this approach we merely, pass the ArrayList as a parameter while initializing the LinkedHashSet class" }, { "code": null, "e": 27049, "s": 27042, "text": "Syntax" }, { "code": null, "e": 27150, "s": 27049, "text": "LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C." }, { "code": null, "e": 27208, "s": 27150, "text": "LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);" }, { "code": null, "e": 27216, "s": 27208, "text": "Example" }, { "code": null, "e": 27221, "s": 27216, "text": "Java" }, { "code": "// java program to convert ArrayList// to LinkedHashSet // importing the utils packageimport java.util.*; class GFG { // defining the method void arrayListToLinkedHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // adding values in the ArrayList arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // printing the list System.out.println(\"The array list : \" + arrayList); // initializing the LinkedHashSet class // passing the ArrayList as parameter LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>(arrayList); // printing the LinkedHashSet System.out.println(\"The converted \" + \"Linked Hash Set : \" + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToLinkedHashSet(); }}", "e": 28290, "s": 27221, "text": null }, { "code": null, "e": 28372, "s": 28290, "text": "The array list : [Geeks, For, Geeks]\nThe converted Linked Hash Set : [Geeks, For]" }, { "code": null, "e": 28580, "s": 28372, "text": "Explanation:The ArrayList contains three entries which are [Geeks, For, Geeks]. This is converted to an ordered set and only contains two values: Geeks and For. Since Set don’t allow multiple similar values." }, { "code": null, "e": 28591, "s": 28580, "text": "Approach 2" }, { "code": null, "e": 28730, "s": 28591, "text": "Using this approach, we use the predefined method addAll() of the LinkedHashSet class after initializing it to populate the LinkedHashSet." }, { "code": null, "e": 28739, "s": 28730, "text": "Syntax: " }, { "code": null, "e": 28774, "s": 28739, "text": "LinkedHashSet.addAll(Collection C)" }, { "code": null, "e": 28858, "s": 28774, "text": "Parameters: Parameter C is a collection of any type that is to be added to the set." }, { "code": null, "e": 28996, "s": 28858, "text": "Return Value: The method returns true if it successfully appends the elements of the collection C to this Set otherwise it returns False." }, { "code": null, "e": 29005, "s": 28996, "text": "Example " }, { "code": null, "e": 29010, "s": 29005, "text": "Java" }, { "code": "// java program to convert ArrayList// to LinkedHashSet // importing the java.utils packageimport java.util.*; class GFG { // defining the method void arrayListToLinkedHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // filling the ArrayList with values arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // printing the list System.out.println(\"The Array List : \" + arrayList); // initializing the LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(); // using the addAll() to // fill the HashSet linkedHashSet.addAll(arrayList); // printing the LinkedHashSet System.out.println(\"The Linked \" + \"Hash Set : \" + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToLinkedHashSet(); }}", "e": 30085, "s": 29010, "text": null }, { "code": null, "e": 30157, "s": 30085, "text": "The Array List : [Geeks, For, Geeks]\nThe Linked Hash Set : [Geeks, For]" }, { "code": null, "e": 30168, "s": 30157, "text": "Approach 3" }, { "code": null, "e": 30341, "s": 30168, "text": "Using this approach, we iterate over the ArrayList and in each iteration fill the LinkedHashSet with the value using the predefined add() method of the LinkedHashSet class." }, { "code": null, "e": 30350, "s": 30341, "text": "Syntax: " }, { "code": null, "e": 30379, "s": 30350, "text": "Hash_Set.add(Object element)" }, { "code": null, "e": 30492, "s": 30379, "text": "Parameters: The parameter element is of the type LinkedHashSet and refers to the element to be added to the Set." }, { "code": null, "e": 30655, "s": 30492, "text": "Return Value: The function returns True if the element is not present in the LinkedHashSet otherwise False if the element is already present in the LinkedHashSet." }, { "code": null, "e": 30664, "s": 30655, "text": "Example " }, { "code": null, "e": 30669, "s": 30664, "text": "Java" }, { "code": "// java program to convert ArrayList// to LinkedHashSet // importing the java.utils packageimport java.util.*; class GFG { // defining the method void arrayListToHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // filling the ArrayList with values arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // printing the list System.out.println(\"The Array List : \" + arrayList); // declaring the iterator Iterator<String> itr = arrayList.iterator(); // initializing the LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(); // loop to iterate through the ArrayList while (itr.hasNext()) // using the add() // to fill the HashSet linkedHashSet.add(itr.next()); // printing the LinkedHashSet System.out.println(\"The Linked Hash Set : \" + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToHashSet(); }}", "e": 31898, "s": 30669, "text": null }, { "code": null, "e": 31970, "s": 31898, "text": "The Array List : [Geeks, For, Geeks]\nThe Linked Hash Set : [Geeks, For]" }, { "code": null, "e": 31981, "s": 31970, "text": "Approach 4" }, { "code": null, "e": 32189, "s": 31981, "text": "Under this approach, we first convert the ArrayList to a stream which is then converted to a Set. This Set is finally converted to a LinkedHashSet. Stream class is only available for JDK versions 8 or above." }, { "code": null, "e": 32198, "s": 32189, "text": "Example " }, { "code": null, "e": 32203, "s": 32198, "text": "Java" }, { "code": "// java program to convert ArrayList// to LinkedHashSet import java.util.*;import java.util.stream.*; class GFG { // defining the method void arrayListToLinkedHashSet() { // initializing the ArrayList ArrayList<String> arrayList = new ArrayList<>(); // filling the ArrayList with values arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // printing the list System.out.println(\"The Array List : \" + arrayList); // creating a stream from the ArrayList Stream<String> stream = arrayList.stream(); // creating a set from the Stream // using the predefined toSet() // method of the Collectors class Set<String> set = stream.collect(Collectors.toSet()); // converting the Set to // LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(set); // printing the LinkedHashSet System.out.println(\"The Linked Hash Set : \" + linkedHashSet); } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // calling the method ob.arrayListToLinkedHashSet(); }}", "e": 33475, "s": 32203, "text": null }, { "code": null, "e": 33547, "s": 33475, "text": "The Array List : [Geeks, For, Geeks]\nThe Linked Hash Set : [Geeks, For]" }, { "code": null, "e": 33609, "s": 33547, "text": "Converting ArrayList Of Custom Class Objects To LinkedHashSet" }, { "code": null, "e": 34338, "s": 33609, "text": "The above examples illustrate the procedure to convert ArrayList of primitive data types such as Integer, String, and so on. Here, we are going to use the above approaches to convert an ArrayList of custom class objects to LinkedHashSet. An interesting feature of the conversion is that this allows duplication of objects which was not allowed in the above scenarios. The reason for the same being that each time a new object of the same class is created and the equals() method which is used to check elements before entering them in the set when compares the objects, finds unique references since each new object holds a new reference. This allows for the same data to be present in the LinkedHashSet in more than one places." }, { "code": null, "e": 34346, "s": 34338, "text": "Example" }, { "code": null, "e": 34351, "s": 34346, "text": "Java" }, { "code": "// java code to convert an ArrayList// of custom class objects to// LinkedHashSet // importing the librariesimport java.util.*; // the custom classclass Sports { // global variable name of type String // to hold the name of the sport private String name; // constructor public Sports(String name) { // initializing the name this.name = name; } // method to return the string public String returnString() { return name + \" is a great sport\"; }} // primary classclass GFG { // declaring the method static void arrayListToLinkedHashSet() { // creating an array list of type // class Sports ArrayList<Sports> listOfSports = new ArrayList<Sports>(); // adding the new instances of Sports // in the array list listOfSports.add(new Sports(\"Football\")); listOfSports.add(new Sports(\"Basketball\")); listOfSports.add(new Sports(\"Football\")); // printing the list System.out.println(\"The Array List : \" + listOfSports); // declaring an iterator of type Sports // to iterate over the list Iterator<Sports> itr = listOfSports.iterator(); // iterating over the list while (itr.hasNext()) // printing the contents // by calling the returnString() System.out.println(itr.next().returnString()); // initializing the linkedhashset // of type Sports LinkedHashSet<Sports> linkedHashSet = new LinkedHashSet<Sports>(listOfSports); // printing the contents of the // linked hash set System.out.println(\"The Linked Hash Set : \" + linkedHashSet); // declaring an iterator to iterate // over linkedhashset Iterator<Sports> itr1 = linkedHashSet.iterator(); // iterating over the linkedhashset while (itr1.hasNext()) { // calling the returnString() // of Sports System.out.println(itr1.next().returnString()); } } // Driver Code public static void main(String[] args) { // calling the method arrayListToLinkedHashSet(); }}", "e": 36586, "s": 34351, "text": null }, { "code": null, "e": 36889, "s": 36586, "text": "The Array List : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f]\nFootball is a great sport\nBasketball is a great sport\nFootball is a great sport\nThe Linked Hash Set : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f]\nFootball is a great sport\nBasketball is a great sport\nFootball is a great sport" }, { "code": null, "e": 37420, "s": 36889, "text": "Explanation:In the first line, the contents of ArrayList are printed which as can be seen are references to class Sports. In the following three lines, the contents of the returnString() method of Sports class are printed. It should be noted that all references are unique and hence the LinkedHashSet allows them even though the contents might be the same. In the following line, the contents of LinkedHashSet is printed which are again references to the class Sports. The lines following that are the returnString() method calls." }, { "code": null, "e": 37431, "s": 37422, "text": "gabaa406" }, { "code": null, "e": 37448, "s": 37431, "text": "arorakashish0911" }, { "code": null, "e": 37463, "s": 37448, "text": "Java-ArrayList" }, { "code": null, "e": 37482, "s": 37463, "text": "java-LinkedHashSet" }, { "code": null, "e": 37489, "s": 37482, "text": "Picked" }, { "code": null, "e": 37494, "s": 37489, "text": "Java" }, { "code": null, "e": 37508, "s": 37494, "text": "Java Programs" }, { "code": null, "e": 37513, "s": 37508, "text": "Java" }, { "code": null, "e": 37611, "s": 37513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37626, "s": 37611, "text": "Stream In Java" }, { "code": null, "e": 37647, "s": 37626, "text": "Constructors in Java" }, { "code": null, "e": 37666, "s": 37647, "text": "Exceptions in Java" }, { "code": null, "e": 37696, "s": 37666, "text": "Functional Interfaces in Java" }, { "code": null, "e": 37742, "s": 37696, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 37768, "s": 37742, "text": "Java Programming Examples" }, { "code": null, "e": 37802, "s": 37768, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 37849, "s": 37802, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 37881, "s": 37849, "text": "How to Iterate HashMap in Java?" } ]
Finding Similar Quora Questions with BOW, TFIDF and Xgboost | by Susan Li | Towards Data Science
Quora is a question-and-answer website where questions are asked, answered, edited, and organized by its community of users in the form of opinions. In September 2018, Quora reported hitting 300 million monthly users. With over 300 million people visit Quora every month, it’s no surprise that many people ask duplicated questions, that is, questions that have same intent. For example, questions like “How can I be a good geologist?” and “What should I do to be a great geologist?” are duplicate questions because they all have the same intent and should be answered once and once only. Quora tries very hard to eliminate duplicate questions, but NLP is a very hard problem. With so many ways to describe one and the same meaning, just look at the examples above. Quora users have provided great help that merged similar questions like so: In this post, we will develop a machine learning and NLP system to classify whether question pairs are duplicates or not and we start from a model that is BOW or TF-IDF with Xgboost. BOW and TF-IDF are two of the most common methods people use in information retrieval. Generally speaking, SVMs and Naive Bayes are more common for classification problem, however, because their accuracy is dependent of the training data, Xgboost provided the best accuracy in this particular data set. XGBoost is a gradient boosting framework that has become massively popular, especially in the Kaggle community. Therefore, I decided to use this model as a baseline model, because it is simple to set up, easy to understand and has a reasonable chance of providing decent results. Our baseline model will allow us to get a quick performance benchmark. If we find that the performance it provides is not sufficient, then inspecting what the simple model is struggling with can help us choose a next approach. The Quora duplicate questions public dataset contains over 400K pairs of Quora questions. In our experiments we split the data randomly into 70% of train examples and 30% of test examples. import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_csv('quora_train.csv')df.dropna(axis=0, inplace=True)df.groupby("is_duplicate")['id'].count().plot.bar() The classes are not perfectly balanced, but it is not bad, we are not going to balance them. Before cleaning the text, we preview a few question pairs to determine how to clean them. df.drop(['id', 'qid1', 'qid2'], axis=1, inplace=True)a = 0 for i in range(a,a+10): print(df.question1[i]) print(df.question2[i]) print() You may have noticed that we have off a lot work to do in terms of text cleaning. After some inspections, a few tries and ideas from https://www.kaggle.com/currie32/the-importance-of-cleaning-text, I decided to clean the text as follows: Not to remove stop words, because words like “what”, “which” and “how” may have strong signals. Not to stem words. Remove punctuation. Correct typos. Change abbreviations to its original terms. Remove comma between numbers. Change special chars to words. And so on. After cleaning text, we preview those question pairs again. a = 0 for i in range(a,a+10): print(df.question1[i]) print(df.question2[i]) print() Much better! We are well experienced in classifying single texts for some time — but the ability to accurately model the relationships between texts is relative new. Here I use Panda's concatfunction to concatenate two text objects features from question1 and question2 into one. The scipy.sparse.hstackis used to stack sparse matrices horizontally (column wise). This following strategy (CountVectorizer) is called the Bag of Words. Documents are described by word occurrences while completely ignoring the relative position information of the words in the document. It tokenizes the documents and counts the occurrences of token and return them as a sparse matrix. The Xgboost was used with the following parameters, selected based on the performance from the validation data: max_depth=50n_estimators=80objective='binary:logistic'eta=0.3 The tf–idf is the product of two statistics, term frequency and inverse document frequency, it is one of the most popular term-weighting schemes today. we apply tf-idf normalization to a sparse matrix of occurrence counts, from word level, n-gram level and character level. A subtle point about feature engineering is that it requires knowing feature statistics that we most likely do not know in practice. In order to compute the tf-idf representation, we have to compute the inverse document frequencies based on the training data and use these statistics to scale both the training and test data. In scikit-learn, fitting the feature transformer on the training data amounts to collecting the relevant statistics. The fitted transformer can then be applied to the test data. Our highest validation score is 0.80, not bad at all for starters! So far our best Xgboost model is character level TF-IDF+Xgboost, the recall of duplicate questions, that is, the proportion of duplicate questions that our model is able to detect over the total amount of duplicate questions is 0.67. And this is crucial for the problem at hand, we want to detect and eliminate as many duplicate questions as possible. With this in mind, we will develop a word2vec and Xgboost model to see whether this result can be improved, which will be the next article. Jupyter notebook for this post can be found on Github. Happy weekend!
[ { "code": null, "e": 321, "s": 172, "text": "Quora is a question-and-answer website where questions are asked, answered, edited, and organized by its community of users in the form of opinions." }, { "code": null, "e": 760, "s": 321, "text": "In September 2018, Quora reported hitting 300 million monthly users. With over 300 million people visit Quora every month, it’s no surprise that many people ask duplicated questions, that is, questions that have same intent. For example, questions like “How can I be a good geologist?” and “What should I do to be a great geologist?” are duplicate questions because they all have the same intent and should be answered once and once only." }, { "code": null, "e": 1013, "s": 760, "text": "Quora tries very hard to eliminate duplicate questions, but NLP is a very hard problem. With so many ways to describe one and the same meaning, just look at the examples above. Quora users have provided great help that merged similar questions like so:" }, { "code": null, "e": 1196, "s": 1013, "text": "In this post, we will develop a machine learning and NLP system to classify whether question pairs are duplicates or not and we start from a model that is BOW or TF-IDF with Xgboost." }, { "code": null, "e": 2006, "s": 1196, "text": "BOW and TF-IDF are two of the most common methods people use in information retrieval. Generally speaking, SVMs and Naive Bayes are more common for classification problem, however, because their accuracy is dependent of the training data, Xgboost provided the best accuracy in this particular data set. XGBoost is a gradient boosting framework that has become massively popular, especially in the Kaggle community. Therefore, I decided to use this model as a baseline model, because it is simple to set up, easy to understand and has a reasonable chance of providing decent results. Our baseline model will allow us to get a quick performance benchmark. If we find that the performance it provides is not sufficient, then inspecting what the simple model is struggling with can help us choose a next approach." }, { "code": null, "e": 2195, "s": 2006, "text": "The Quora duplicate questions public dataset contains over 400K pairs of Quora questions. In our experiments we split the data randomly into 70% of train examples and 30% of test examples." }, { "code": null, "e": 2420, "s": 2195, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_csv('quora_train.csv')df.dropna(axis=0, inplace=True)df.groupby(\"is_duplicate\")['id'].count().plot.bar()" }, { "code": null, "e": 2513, "s": 2420, "text": "The classes are not perfectly balanced, but it is not bad, we are not going to balance them." }, { "code": null, "e": 2603, "s": 2513, "text": "Before cleaning the text, we preview a few question pairs to determine how to clean them." }, { "code": null, "e": 2749, "s": 2603, "text": "df.drop(['id', 'qid1', 'qid2'], axis=1, inplace=True)a = 0 for i in range(a,a+10): print(df.question1[i]) print(df.question2[i]) print()" }, { "code": null, "e": 2987, "s": 2749, "text": "You may have noticed that we have off a lot work to do in terms of text cleaning. After some inspections, a few tries and ideas from https://www.kaggle.com/currie32/the-importance-of-cleaning-text, I decided to clean the text as follows:" }, { "code": null, "e": 3083, "s": 2987, "text": "Not to remove stop words, because words like “what”, “which” and “how” may have strong signals." }, { "code": null, "e": 3102, "s": 3083, "text": "Not to stem words." }, { "code": null, "e": 3122, "s": 3102, "text": "Remove punctuation." }, { "code": null, "e": 3137, "s": 3122, "text": "Correct typos." }, { "code": null, "e": 3181, "s": 3137, "text": "Change abbreviations to its original terms." }, { "code": null, "e": 3211, "s": 3181, "text": "Remove comma between numbers." }, { "code": null, "e": 3253, "s": 3211, "text": "Change special chars to words. And so on." }, { "code": null, "e": 3313, "s": 3253, "text": "After cleaning text, we preview those question pairs again." }, { "code": null, "e": 3406, "s": 3313, "text": "a = 0 for i in range(a,a+10): print(df.question1[i]) print(df.question2[i]) print()" }, { "code": null, "e": 3419, "s": 3406, "text": "Much better!" }, { "code": null, "e": 3770, "s": 3419, "text": "We are well experienced in classifying single texts for some time — but the ability to accurately model the relationships between texts is relative new. Here I use Panda's concatfunction to concatenate two text objects features from question1 and question2 into one. The scipy.sparse.hstackis used to stack sparse matrices horizontally (column wise)." }, { "code": null, "e": 4073, "s": 3770, "text": "This following strategy (CountVectorizer) is called the Bag of Words. Documents are described by word occurrences while completely ignoring the relative position information of the words in the document. It tokenizes the documents and counts the occurrences of token and return them as a sparse matrix." }, { "code": null, "e": 4185, "s": 4073, "text": "The Xgboost was used with the following parameters, selected based on the performance from the validation data:" }, { "code": null, "e": 4247, "s": 4185, "text": "max_depth=50n_estimators=80objective='binary:logistic'eta=0.3" }, { "code": null, "e": 4399, "s": 4247, "text": "The tf–idf is the product of two statistics, term frequency and inverse document frequency, it is one of the most popular term-weighting schemes today." }, { "code": null, "e": 4521, "s": 4399, "text": "we apply tf-idf normalization to a sparse matrix of occurrence counts, from word level, n-gram level and character level." }, { "code": null, "e": 5025, "s": 4521, "text": "A subtle point about feature engineering is that it requires knowing feature statistics that we most likely do not know in practice. In order to compute the tf-idf representation, we have to compute the inverse document frequencies based on the training data and use these statistics to scale both the training and test data. In scikit-learn, fitting the feature transformer on the training data amounts to collecting the relevant statistics. The fitted transformer can then be applied to the test data." }, { "code": null, "e": 5092, "s": 5025, "text": "Our highest validation score is 0.80, not bad at all for starters!" }, { "code": null, "e": 5444, "s": 5092, "text": "So far our best Xgboost model is character level TF-IDF+Xgboost, the recall of duplicate questions, that is, the proportion of duplicate questions that our model is able to detect over the total amount of duplicate questions is 0.67. And this is crucial for the problem at hand, we want to detect and eliminate as many duplicate questions as possible." }, { "code": null, "e": 5584, "s": 5444, "text": "With this in mind, we will develop a word2vec and Xgboost model to see whether this result can be improved, which will be the next article." } ]
jQuery focus() with Example
The focus() method in jQuery is used to trigger the focus event. The focus event occurs when an element gets focus. The syntax is as follows − $(selector).focus() Let us now see an example to implement the jQuery focus() method − <!DOCTYPE html> <html> <head> <style> .demo { color: blue; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn").click(function(){ $("input").focus(); $("p").html("focus event triggered"); }); }); </script> </head> <body> <h2>Student Details</h2> Student Name: <input type="text"><br> <br><br> <button id="btn">Trigger Event</button> <p class="demo"></p> </body> </html> This will produce the following output − Above, click “Trigger Event” to trigger the focus event −
[ { "code": null, "e": 1178, "s": 1062, "text": "The focus() method in jQuery is used to trigger the focus event. The focus event occurs when an element gets focus." }, { "code": null, "e": 1205, "s": 1178, "text": "The syntax is as follows −" }, { "code": null, "e": 1225, "s": 1205, "text": "$(selector).focus()" }, { "code": null, "e": 1292, "s": 1225, "text": "Let us now see an example to implement the jQuery focus() method −" }, { "code": null, "e": 1806, "s": 1292, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n .demo {\n color: blue;\n }\n</style>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function(){\n $(\"#btn\").click(function(){\n $(\"input\").focus();\n $(\"p\").html(\"focus event triggered\");\n });\n });\n</script>\n</head>\n<body>\n<h2>Student Details</h2>\nStudent Name: <input type=\"text\"><br>\n<br><br>\n<button id=\"btn\">Trigger Event</button>\n<p class=\"demo\"></p>\n</body>\n</html>" }, { "code": null, "e": 1847, "s": 1806, "text": "This will produce the following output −" }, { "code": null, "e": 1905, "s": 1847, "text": "Above, click “Trigger Event” to trigger the focus event −" } ]
Java Program to Find the Frequency of Odd & Even Numbers in the Matrix - GeeksforGeeks
29 Oct, 2020 Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in the matrix N = number of columns Example: Input : M = 3 N = 5 Output: Odd Number Frequency = 9 Even Number Frequency = 6 Input : M = 3 N = 3 {{1, 2, 5}, {6, 7, 9}, {3, 2, 1}} Output: Odd Number Frequency = 6 Even Number Frequency = 3 Approach Initialize two counters as even = 0 & odd = 0 Traverse through every element present in the matrix and check whether (element % 2 == 0) If Yes then increment even++ Else increment odd++ Below is the implementation of the approach in Java Java // Importing Classes/Filesimport java.io.*; class GFG { // Function to compute frequency of odd/even numbers public static void findFreq(int[][] arr, int m, int n) { // Initializing the counter variables int even = 0, odd = 0; // Nested if loops // Traversing through each // element in the matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Checking if the element // is divisible by 2 if (arr[i][j] % 2 == 0) { // Increment even counter even++; } else { // Increment odd counter odd++; } } } // Printing Counts of Enen // and odd numbers in matrix System.out.println("Odd Number Frequency: " + odd); System.out.println("Even Number Frequence: " + even); } // Main Driver Method public static void main(String[] args) { // Providing inputs to the matrix int m = 3, n = 5; // Here, m = Number of rows, // n = Number of columns // Entering elements in the matrix int[][] arr = { { 3, 4, 5, 6, 3 }, { 4, 3, 2, 7, 9 }, { 1, 5, 7, 2, 4 } }; // Calling function to count frequency by // passing inputs to the function findFreq findFreq(arr, m, n); }} Odd Number Frequency: 9 Even Number Frequence: 6 Time Complexity: As the single-dimensional array is traversed it depends on the size of the array over which the operation performs because rest execution either is of the same order or taking some constant space in the memory(variables). Here the traversal is over all the elements of the row and for every row in the matrix. So it depends on the product of rows and columns. Hence, the time complexity is of order(degree) Space Complexity: Just assigning memory to variables that later gets released with the scope of the variables. As no other auxiliary space is created for the operations to execute. Hence, the space required is constant which is released afterward. 1 is assigned by default hence space complexity is of order 1. Time Complexity = O(Rows*Columns) or O(m * n) Space Complexity = O(1) 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": 25347, "s": 25319, "text": "\n29 Oct, 2020" }, { "code": null, "e": 25546, "s": 25347, "text": "Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. " }, { "code": null, "e": 25656, "s": 25546, "text": "The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n " }, { "code": null, "e": 25675, "s": 25656, "text": "Here in the matrix" }, { "code": null, "e": 25708, "s": 25675, "text": "M = number of rows in the matrix" }, { "code": null, "e": 25730, "s": 25708, "text": "N = number of columns" }, { "code": null, "e": 25739, "s": 25730, "text": "Example:" }, { "code": null, "e": 25973, "s": 25739, "text": "Input : M = 3\n N = 5\nOutput: Odd Number Frequency = 9\n Even Number Frequency = 6\n \nInput : M = 3\n N = 3\n {{1, 2, 5},\n {6, 7, 9},\n {3, 2, 1}}\nOutput: Odd Number Frequency = 6\n Even Number Frequency = 3 \n" }, { "code": null, "e": 25983, "s": 25973, "text": "Approach " }, { "code": null, "e": 26029, "s": 25983, "text": "Initialize two counters as even = 0 & odd = 0" }, { "code": null, "e": 26119, "s": 26029, "text": "Traverse through every element present in the matrix and check whether (element % 2 == 0)" }, { "code": null, "e": 26148, "s": 26119, "text": "If Yes then increment even++" }, { "code": null, "e": 26169, "s": 26148, "text": "Else increment odd++" }, { "code": null, "e": 26221, "s": 26169, "text": "Below is the implementation of the approach in Java" }, { "code": null, "e": 26226, "s": 26221, "text": "Java" }, { "code": "// Importing Classes/Filesimport java.io.*; class GFG { // Function to compute frequency of odd/even numbers public static void findFreq(int[][] arr, int m, int n) { // Initializing the counter variables int even = 0, odd = 0; // Nested if loops // Traversing through each // element in the matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // Checking if the element // is divisible by 2 if (arr[i][j] % 2 == 0) { // Increment even counter even++; } else { // Increment odd counter odd++; } } } // Printing Counts of Enen // and odd numbers in matrix System.out.println(\"Odd Number Frequency: \" + odd); System.out.println(\"Even Number Frequence: \" + even); } // Main Driver Method public static void main(String[] args) { // Providing inputs to the matrix int m = 3, n = 5; // Here, m = Number of rows, // n = Number of columns // Entering elements in the matrix int[][] arr = { { 3, 4, 5, 6, 3 }, { 4, 3, 2, 7, 9 }, { 1, 5, 7, 2, 4 } }; // Calling function to count frequency by // passing inputs to the function findFreq findFreq(arr, m, n); }}", "e": 27748, "s": 26226, "text": null }, { "code": null, "e": 27797, "s": 27748, "text": "Odd Number Frequency: 9\nEven Number Frequence: 6" }, { "code": null, "e": 28221, "s": 27797, "text": "Time Complexity: As the single-dimensional array is traversed it depends on the size of the array over which the operation performs because rest execution either is of the same order or taking some constant space in the memory(variables). Here the traversal is over all the elements of the row and for every row in the matrix. So it depends on the product of rows and columns. Hence, the time complexity is of order(degree)" }, { "code": null, "e": 28534, "s": 28221, "text": "Space Complexity: Just assigning memory to variables that later gets released with the scope of the variables. As no other auxiliary space is created for the operations to execute. Hence, the space required is constant which is released afterward. 1 is assigned by default hence space complexity is of order 1. " }, { "code": null, "e": 28606, "s": 28534, "text": "Time Complexity = O(Rows*Columns) or O(m * n)\nSpace Complexity = O(1)\n" }, { "code": null, "e": 28611, "s": 28606, "text": "Java" }, { "code": null, "e": 28625, "s": 28611, "text": "Java Programs" }, { "code": null, "e": 28630, "s": 28625, "text": "Java" }, { "code": null, "e": 28728, "s": 28630, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28743, "s": 28728, "text": "Stream In Java" }, { "code": null, "e": 28762, "s": 28743, "text": "Exceptions in Java" }, { "code": null, "e": 28783, "s": 28762, "text": "Constructors in Java" }, { "code": null, "e": 28813, "s": 28783, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28859, "s": 28813, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28885, "s": 28859, "text": "Java Programming Examples" }, { "code": null, "e": 28919, "s": 28885, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28966, "s": 28919, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28998, "s": 28966, "text": "How to Iterate HashMap in Java?" } ]
Taking Screenshots using pyscreenshot in Python
05 Sep, 2020 Python offers multiple libraries to ease our work. Here we will learn how to take a screenshot using Python. Python provides a module called pyscreenshot for this task. It is only a pure Python wrapper, a thin layer over existing backends. Performance and interactivity are not important for this library. Install the package pyscreenshot using the below command in your command prompt. pip install pyscreenshot Here we will learn the simplest way of taking a screenshot using pyscreenshot module. Here we will use the function show() to view the screenshot. Python3 # Program to take screenshot import pyscreenshot # To capture the screenimage = pyscreenshot.grab() # To display the captured screenshotimage.show() # To save the screenshotimage.save("GeeksforGeeks.png") Output: Full Screenshot Here is the simple Python program to capture the part of the screen. Here we need to provide the pixel positions in the grab() function. We need to pass the coordinates in the form of a tuple. Python3 # Program for partial screenshot import pyscreenshot # im=pyscreenshot.grab(bbox=(x1,x2,y1,y2))image = pyscreenshot.grab(bbox=(10, 10, 500, 500)) # To view the screenshotimage.show() # To save the screenshotimage.save("GeeksforGeeks.png") Output: Partial Screenshot Important Points: We need to install pillow (PIL) package before installing pyscreenshot package. Here show() function works as print i.e. It displays the captured screenshot. We need to pass the coordinates in tuple. We can save the screenshot to a file or PIL image memory. python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 334, "s": 28, "text": "Python offers multiple libraries to ease our work. Here we will learn how to take a screenshot using Python. Python provides a module called pyscreenshot for this task. It is only a pure Python wrapper, a thin layer over existing backends. Performance and interactivity are not important for this library." }, { "code": null, "e": 415, "s": 334, "text": "Install the package pyscreenshot using the below command in your command prompt." }, { "code": null, "e": 440, "s": 415, "text": "pip install pyscreenshot" }, { "code": null, "e": 588, "s": 440, "text": "Here we will learn the simplest way of taking a screenshot using pyscreenshot module. Here we will use the function show() to view the screenshot. " }, { "code": null, "e": 596, "s": 588, "text": "Python3" }, { "code": "# Program to take screenshot import pyscreenshot # To capture the screenimage = pyscreenshot.grab() # To display the captured screenshotimage.show() # To save the screenshotimage.save(\"GeeksforGeeks.png\")", "e": 805, "s": 596, "text": null }, { "code": null, "e": 813, "s": 805, "text": "Output:" }, { "code": null, "e": 829, "s": 813, "text": "Full Screenshot" }, { "code": null, "e": 1023, "s": 829, "text": "Here is the simple Python program to capture the part of the screen. Here we need to provide the pixel positions in the grab() function. We need to pass the coordinates in the form of a tuple. " }, { "code": null, "e": 1031, "s": 1023, "text": "Python3" }, { "code": "# Program for partial screenshot import pyscreenshot # im=pyscreenshot.grab(bbox=(x1,x2,y1,y2))image = pyscreenshot.grab(bbox=(10, 10, 500, 500)) # To view the screenshotimage.show() # To save the screenshotimage.save(\"GeeksforGeeks.png\")", "e": 1274, "s": 1031, "text": null }, { "code": null, "e": 1282, "s": 1274, "text": "Output:" }, { "code": null, "e": 1301, "s": 1282, "text": "Partial Screenshot" }, { "code": null, "e": 1319, "s": 1301, "text": "Important Points:" }, { "code": null, "e": 1399, "s": 1319, "text": "We need to install pillow (PIL) package before installing pyscreenshot package." }, { "code": null, "e": 1477, "s": 1399, "text": "Here show() function works as print i.e. It displays the captured screenshot." }, { "code": null, "e": 1519, "s": 1477, "text": "We need to pass the coordinates in tuple." }, { "code": null, "e": 1577, "s": 1519, "text": "We can save the screenshot to a file or PIL image memory." }, { "code": null, "e": 1592, "s": 1577, "text": "python-modules" }, { "code": null, "e": 1607, "s": 1592, "text": "python-utility" }, { "code": null, "e": 1614, "s": 1607, "text": "Python" } ]
Java.util.concurrent.ExecutorService Interface with Examples
13 May, 2022 The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status. The ExecutorService interface is implemented in a utility class called Executors. It defines methods that provide an implementation of the ExecutorService interface and many other interfaces, with some default settings. The class hierarchy is as follows: --> java.util.concurrent Package --> Interface ExecutorService Class Note: ScheduledExecutorService is Implementing Sub-Interfaces and classes implemented are as follows: AbstractExecutorService ForkJoinPool ScheduledThreadPoolExecutor ThreadPoolExecutor Implementation: Executors Java // Java Program to Demonstrate ExecutorService Interface // Importing required classesimport java.util.concurrent.*; // Class// Main classpublic class SimpleExecutor { // Main driver method public static void main(String[] args) { // Creating objects of CountDownLatch class CountDownLatch cd1 = new CountDownLatch(5); CountDownLatch cd2 = new CountDownLatch(5); CountDownLatch cd3 = new CountDownLatch(5); CountDownLatch cd4 = new CountDownLatch(5); // Creating objects of ExecutorService class ExecutorService es = Executors.newFixedThreadPool(2); // Display message only for better readability System.out.println("Starting"); // Executing the tasks es.execute(new MyThread(cd1, "A")); es.execute(new MyThread(cd2, "B")); es.execute(new MyThread(cd3, "C")); es.execute(new MyThread(cd4, "D")); // Try block to check for exceptions try { // Waiting for tasks to complete cd1.await(); cd2.await(); cd3.await(); cd4.await(); } // Catch block to handle exceptions catch (InterruptedException e) { System.out.println(e); } // Making all current executing threads to terminate es.shutdown(); // Display message only for better readability System.out.println("Done"); }} // Class 2// Helper classclass MyThread implements Runnable { // Class data members String name; CountDownLatch latch; // Constructor MyThread(CountDownLatch latch, String name) { // this keyword refers to current instance itself this.name = name; this.latch = latch; new Thread(this); } // Method // Called automatically when thread is started public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + ": " + i); latch.countDown(); } }} Output: surindertarika1234 anikakapoor solankimayank sumitgumber28 Java - util package Java-concurrent-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java Introduction to Java Constructors in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n13 May, 2022" }, { "code": null, "e": 559, "s": 54, "text": "The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status. The ExecutorService interface is implemented in a utility class called Executors. It defines methods that provide an implementation of the ExecutorService interface and many other interfaces, with some default settings." }, { "code": null, "e": 595, "s": 559, "text": "The class hierarchy is as follows: " }, { "code": null, "e": 669, "s": 595, "text": "--> java.util.concurrent Package\n --> Interface ExecutorService Class " }, { "code": null, "e": 771, "s": 669, "text": "Note: ScheduledExecutorService is Implementing Sub-Interfaces and classes implemented are as follows:" }, { "code": null, "e": 795, "s": 771, "text": "AbstractExecutorService" }, { "code": null, "e": 808, "s": 795, "text": "ForkJoinPool" }, { "code": null, "e": 836, "s": 808, "text": "ScheduledThreadPoolExecutor" }, { "code": null, "e": 855, "s": 836, "text": "ThreadPoolExecutor" }, { "code": null, "e": 882, "s": 855, "text": "Implementation: Executors " }, { "code": null, "e": 887, "s": 882, "text": "Java" }, { "code": "// Java Program to Demonstrate ExecutorService Interface // Importing required classesimport java.util.concurrent.*; // Class// Main classpublic class SimpleExecutor { // Main driver method public static void main(String[] args) { // Creating objects of CountDownLatch class CountDownLatch cd1 = new CountDownLatch(5); CountDownLatch cd2 = new CountDownLatch(5); CountDownLatch cd3 = new CountDownLatch(5); CountDownLatch cd4 = new CountDownLatch(5); // Creating objects of ExecutorService class ExecutorService es = Executors.newFixedThreadPool(2); // Display message only for better readability System.out.println(\"Starting\"); // Executing the tasks es.execute(new MyThread(cd1, \"A\")); es.execute(new MyThread(cd2, \"B\")); es.execute(new MyThread(cd3, \"C\")); es.execute(new MyThread(cd4, \"D\")); // Try block to check for exceptions try { // Waiting for tasks to complete cd1.await(); cd2.await(); cd3.await(); cd4.await(); } // Catch block to handle exceptions catch (InterruptedException e) { System.out.println(e); } // Making all current executing threads to terminate es.shutdown(); // Display message only for better readability System.out.println(\"Done\"); }} // Class 2// Helper classclass MyThread implements Runnable { // Class data members String name; CountDownLatch latch; // Constructor MyThread(CountDownLatch latch, String name) { // this keyword refers to current instance itself this.name = name; this.latch = latch; new Thread(this); } // Method // Called automatically when thread is started public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + \": \" + i); latch.countDown(); } }}", "e": 2892, "s": 887, "text": null }, { "code": null, "e": 2900, "s": 2892, "text": "Output:" }, { "code": null, "e": 2921, "s": 2902, "text": "surindertarika1234" }, { "code": null, "e": 2933, "s": 2921, "text": "anikakapoor" }, { "code": null, "e": 2947, "s": 2933, "text": "solankimayank" }, { "code": null, "e": 2961, "s": 2947, "text": "sumitgumber28" }, { "code": null, "e": 2981, "s": 2961, "text": "Java - util package" }, { "code": null, "e": 3005, "s": 2981, "text": "Java-concurrent-package" }, { "code": null, "e": 3010, "s": 3005, "text": "Java" }, { "code": null, "e": 3015, "s": 3010, "text": "Java" }, { "code": null, "e": 3113, "s": 3015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3132, "s": 3113, "text": "Interfaces in Java" }, { "code": null, "e": 3150, "s": 3132, "text": "ArrayList in Java" }, { "code": null, "e": 3170, "s": 3150, "text": "Collections in Java" }, { "code": null, "e": 3185, "s": 3170, "text": "Stream In Java" }, { "code": null, "e": 3217, "s": 3185, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3237, "s": 3217, "text": "Stack Class in Java" }, { "code": null, "e": 3261, "s": 3237, "text": "Singleton Class in Java" }, { "code": null, "e": 3273, "s": 3261, "text": "Set in Java" }, { "code": null, "e": 3294, "s": 3273, "text": "Introduction to Java" } ]
SASS | Use variables across multiple files
30 Jan, 2020 To use variables across multiple files in SASS is carried out by @import rule of SASS. @import rule which import Sass and CSS stylesheets for providing variables, @mixins and functions.Such that combine all stylesheets together for compiled css. It also imports URL such as frameworks like Bootstrap etc.. The @import no longer encouraged in future updates so prefer @use rule instead. Syntax: /* importing name and file path is /_file.scss */ @import 'file'; Approach 1: Import multiple Sass partialsTo import multiple sass partials with @import by adding @import followed by first filename within quotes then comma(, ) then followed by second filename within quotes end with semicolon/* importing name and file path is /_file1.scss and /_file2.scss */ @import 'file1', 'file2' ; Example 1: Below example illustrates above approach.SASS files/* _colors.scss */$primary:#00ff40;$secondary: #f44336;$tretiary:#03a9f4;$tera: #ffeb3b;$dark:#000000;$grey:#919191;$light:#dddddd;$white:#FFFFFF; /* _std.scss */html,body,ul,ol { margin: 0; padding: 0;}body { color:$grey; font-family: Helvetica, sans-serif; background-image: url('/img/backimg.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: cover; } /*_section.scss*/ div{ padding: { top: 20px; left: 10px; right: 10px; bottom: 20px; } h1{ color: $secondary !important; align-items: center; } }/* style.scss*/@import 'colors';@import 'std', 'section';Compiled CSS file: style.csshtml, body, ul, ol { margin: 0; padding: 0; } body { color: #919191; font-family: Helvetica, sans-serif; background-image: url("/img/backimg.jpg"); background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: cover; } div { padding-top: 20px; padding-left: 10px; padding-right: 10px; padding-bottom: 20px; } div h1 { color: #f44336 !important; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } To import multiple sass partials with @import by adding @import followed by first filename within quotes then comma(, ) then followed by second filename within quotes end with semicolon /* importing name and file path is /_file1.scss and /_file2.scss */ @import 'file1', 'file2' ; /* importing name and file path is /_file1.scss and /_file2.scss */ @import 'file1', 'file2' ; Example 1: Below example illustrates above approach.SASS files /* _colors.scss */$primary:#00ff40;$secondary: #f44336;$tretiary:#03a9f4;$tera: #ffeb3b;$dark:#000000;$grey:#919191;$light:#dddddd;$white:#FFFFFF; /* _std.scss */html,body,ul,ol { margin: 0; padding: 0;}body { color:$grey; font-family: Helvetica, sans-serif; background-image: url('/img/backimg.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: cover; } /*_section.scss*/ div{ padding: { top: 20px; left: 10px; right: 10px; bottom: 20px; } h1{ color: $secondary !important; align-items: center; } }/* style.scss*/@import 'colors';@import 'std', 'section'; Compiled CSS file: style.css html, body, ul, ol { margin: 0; padding: 0; } body { color: #919191; font-family: Helvetica, sans-serif; background-image: url("/img/backimg.jpg"); background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: cover; } div { padding-top: 20px; padding-left: 10px; padding-right: 10px; padding-bottom: 20px; } div h1 { color: #f44336 !important; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } Approach 2: Import Plain CSSTo load Plain CSS with @import by following way:@import followed by path of CSS file with extension .css wrapped within double quotes.In case of URL path, complete URL specified within url(” “);/* importing plain CSS*/ @import "mytheme.css"; @import "http://fonts.googleapis.com/css?family=Droid+Sans"; @import url("http://fonts.googleapis.com/css?family=Droid+Sans"); @import url(mytheme); @import "landscape" screen and (orientation: landscape); Example 2:Below example illustrates above approach.SASS file: style.scss@mixin google-font($family) { @import url("http://fonts.googleapis.com/css?family=#{$family}");} @include google-font("Serif Sans");Compiled CSS file: style.css@import url("http://fonts.googleapis.com/css?family=Serif Sans"); To load Plain CSS with @import by following way: @import followed by path of CSS file with extension .css wrapped within double quotes. In case of URL path, complete URL specified within url(” “); /* importing plain CSS*/ @import "mytheme.css"; @import "http://fonts.googleapis.com/css?family=Droid+Sans"; @import url("http://fonts.googleapis.com/css?family=Droid+Sans"); @import url(mytheme); @import "landscape" screen and (orientation: landscape); /* importing plain CSS*/ @import "mytheme.css"; @import "http://fonts.googleapis.com/css?family=Droid+Sans"; @import url("http://fonts.googleapis.com/css?family=Droid+Sans"); @import url(mytheme); @import "landscape" screen and (orientation: landscape); Example 2:Below example illustrates above approach.SASS file: style.scss @mixin google-font($family) { @import url("http://fonts.googleapis.com/css?family=#{$family}");} @include google-font("Serif Sans"); Compiled CSS file: style.css @import url("http://fonts.googleapis.com/css?family=Serif Sans"); Approach 3: Import Modules and configure ModulesTo load modules and configure modules with @import by following way:To make this easier.Sass also supports import-only files such as follows:_filename.scss is imported to import only filesfilename.import.scss which as@forward "filename" as filename-*; In case @use this method not recommended.To configure modules, modules loaded through @import by defining global variables with respect to initial load of that module.Example 3:Below example illustrates above approach.SASS files/*_libray.scss */ $purple:Purple;$white:white;button{ color:$white; border-color:$purple; background-color:$purple; padding :10px;} /* _library.import.scss */ @forward 'library' as lib-*; /* style.sass */ $lib-color: indigo;@import "library";Compiled CSS file: style.cssbutton{ color: white; border-color:indigo; background-color:indigo; padding :10px; } To load modules and configure modules with @import by following way: To make this easier.Sass also supports import-only files such as follows: _filename.scss is imported to import only filesfilename.import.scss which as@forward "filename" as filename-*; @forward "filename" as filename-*; In case @use this method not recommended. To configure modules, modules loaded through @import by defining global variables with respect to initial load of that module. Example 3:Below example illustrates above approach.SASS files /*_libray.scss */ $purple:Purple;$white:white;button{ color:$white; border-color:$purple; background-color:$purple; padding :10px;} /* _library.import.scss */ @forward 'library' as lib-*; /* style.sass */ $lib-color: indigo;@import "library"; Compiled CSS file: style.css button{ color: white; border-color:indigo; background-color:indigo; padding :10px; } Reference: https://sass-lang.com/documentation/at-rules/import Picked SASS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ? Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 115, "s": 28, "text": "To use variables across multiple files in SASS is carried out by @import rule of SASS." }, { "code": null, "e": 274, "s": 115, "text": "@import rule which import Sass and CSS stylesheets for providing variables, @mixins and functions.Such that combine all stylesheets together for compiled css." }, { "code": null, "e": 334, "s": 274, "text": "It also imports URL such as frameworks like Bootstrap etc.." }, { "code": null, "e": 414, "s": 334, "text": "The @import no longer encouraged in future updates so prefer @use rule instead." }, { "code": null, "e": 422, "s": 414, "text": "Syntax:" }, { "code": null, "e": 489, "s": 422, "text": "/* importing name and file path is /_file.scss */\n@import 'file';\n" }, { "code": null, "e": 2148, "s": 489, "text": "Approach 1: Import multiple Sass partialsTo import multiple sass partials with @import by adding @import followed by first filename within quotes then comma(, ) then followed by second filename within quotes end with semicolon/* importing name and file path is /_file1.scss and /_file2.scss */\n@import 'file1', 'file2' ;\nExample 1: Below example illustrates above approach.SASS files/* _colors.scss */$primary:#00ff40;$secondary: #f44336;$tretiary:#03a9f4;$tera: #ffeb3b;$dark:#000000;$grey:#919191;$light:#dddddd;$white:#FFFFFF; /* _std.scss */html,body,ul,ol { margin: 0; padding: 0;}body { color:$grey; font-family: Helvetica, sans-serif; background-image: url('/img/backimg.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: cover; } /*_section.scss*/ div{ padding: { top: 20px; left: 10px; right: 10px; bottom: 20px; } h1{ color: $secondary !important; align-items: center; } }/* style.scss*/@import 'colors';@import 'std', 'section';Compiled CSS file: style.csshtml,\nbody,\nul,\nol {\n margin: 0;\n padding: 0;\n}\n\nbody {\n color: #919191;\n font-family: Helvetica, sans-serif;\n background-image: url(\"/img/backimg.jpg\");\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-position: center;\n background-size: cover;\n}\n\ndiv {\n padding-top: 20px;\n padding-left: 10px;\n padding-right: 10px;\n padding-bottom: 20px;\n}\n\ndiv h1 {\n color: #f44336 !important;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n}\n" }, { "code": null, "e": 2334, "s": 2148, "text": "To import multiple sass partials with @import by adding @import followed by first filename within quotes then comma(, ) then followed by second filename within quotes end with semicolon" }, { "code": null, "e": 2431, "s": 2334, "text": "/* importing name and file path is /_file1.scss and /_file2.scss */\n@import 'file1', 'file2' ;\n" }, { "code": null, "e": 2528, "s": 2431, "text": "/* importing name and file path is /_file1.scss and /_file2.scss */\n@import 'file1', 'file2' ;\n" }, { "code": null, "e": 2591, "s": 2528, "text": "Example 1: Below example illustrates above approach.SASS files" }, { "code": "/* _colors.scss */$primary:#00ff40;$secondary: #f44336;$tretiary:#03a9f4;$tera: #ffeb3b;$dark:#000000;$grey:#919191;$light:#dddddd;$white:#FFFFFF; /* _std.scss */html,body,ul,ol { margin: 0; padding: 0;}body { color:$grey; font-family: Helvetica, sans-serif; background-image: url('/img/backimg.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: cover; } /*_section.scss*/ div{ padding: { top: 20px; left: 10px; right: 10px; bottom: 20px; } h1{ color: $secondary !important; align-items: center; } }/* style.scss*/@import 'colors';@import 'std', 'section';", "e": 3326, "s": 2591, "text": null }, { "code": null, "e": 3355, "s": 3326, "text": "Compiled CSS file: style.css" }, { "code": null, "e": 3868, "s": 3355, "text": "html,\nbody,\nul,\nol {\n margin: 0;\n padding: 0;\n}\n\nbody {\n color: #919191;\n font-family: Helvetica, sans-serif;\n background-image: url(\"/img/backimg.jpg\");\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-position: center;\n background-size: cover;\n}\n\ndiv {\n padding-top: 20px;\n padding-left: 10px;\n padding-right: 10px;\n padding-bottom: 20px;\n}\n\ndiv h1 {\n color: #f44336 !important;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n}\n" }, { "code": null, "e": 4644, "s": 3868, "text": "Approach 2: Import Plain CSSTo load Plain CSS with @import by following way:@import followed by path of CSS file with extension .css wrapped within double quotes.In case of URL path, complete URL specified within url(” “);/* importing plain CSS*/\n@import \"mytheme.css\";\n@import \"http://fonts.googleapis.com/css?family=Droid+Sans\";\n@import url(\"http://fonts.googleapis.com/css?family=Droid+Sans\");\n@import url(mytheme);\n@import \"landscape\" screen and (orientation: landscape);\nExample 2:Below example illustrates above approach.SASS file: style.scss@mixin google-font($family) { @import url(\"http://fonts.googleapis.com/css?family=#{$family}\");} @include google-font(\"Serif Sans\");Compiled CSS file: style.css@import url(\"http://fonts.googleapis.com/css?family=Serif Sans\");" }, { "code": null, "e": 4693, "s": 4644, "text": "To load Plain CSS with @import by following way:" }, { "code": null, "e": 4780, "s": 4693, "text": "@import followed by path of CSS file with extension .css wrapped within double quotes." }, { "code": null, "e": 4841, "s": 4780, "text": "In case of URL path, complete URL specified within url(” “);" }, { "code": null, "e": 5096, "s": 4841, "text": "/* importing plain CSS*/\n@import \"mytheme.css\";\n@import \"http://fonts.googleapis.com/css?family=Droid+Sans\";\n@import url(\"http://fonts.googleapis.com/css?family=Droid+Sans\");\n@import url(mytheme);\n@import \"landscape\" screen and (orientation: landscape);\n" }, { "code": null, "e": 5351, "s": 5096, "text": "/* importing plain CSS*/\n@import \"mytheme.css\";\n@import \"http://fonts.googleapis.com/css?family=Droid+Sans\";\n@import url(\"http://fonts.googleapis.com/css?family=Droid+Sans\");\n@import url(mytheme);\n@import \"landscape\" screen and (orientation: landscape);\n" }, { "code": null, "e": 5424, "s": 5351, "text": "Example 2:Below example illustrates above approach.SASS file: style.scss" }, { "code": "@mixin google-font($family) { @import url(\"http://fonts.googleapis.com/css?family=#{$family}\");} @include google-font(\"Serif Sans\");", "e": 5559, "s": 5424, "text": null }, { "code": null, "e": 5588, "s": 5559, "text": "Compiled CSS file: style.css" }, { "code": null, "e": 5654, "s": 5588, "text": "@import url(\"http://fonts.googleapis.com/css?family=Serif Sans\");" }, { "code": null, "e": 6580, "s": 5654, "text": "Approach 3: Import Modules and configure ModulesTo load modules and configure modules with @import by following way:To make this easier.Sass also supports import-only files such as follows:_filename.scss is imported to import only filesfilename.import.scss which as@forward \"filename\" as filename-*;\nIn case @use this method not recommended.To configure modules, modules loaded through @import by defining global variables with respect to initial load of that module.Example 3:Below example illustrates above approach.SASS files/*_libray.scss */ $purple:Purple;$white:white;button{ color:$white; border-color:$purple; background-color:$purple; padding :10px;} /* _library.import.scss */ @forward 'library' as lib-*; /* style.sass */ $lib-color: indigo;@import \"library\";Compiled CSS file: style.cssbutton{\n color: white;\n border-color:indigo;\n background-color:indigo;\n padding :10px;\n}\n" }, { "code": null, "e": 6649, "s": 6580, "text": "To load modules and configure modules with @import by following way:" }, { "code": null, "e": 6723, "s": 6649, "text": "To make this easier.Sass also supports import-only files such as follows:" }, { "code": null, "e": 6835, "s": 6723, "text": "_filename.scss is imported to import only filesfilename.import.scss which as@forward \"filename\" as filename-*;\n" }, { "code": null, "e": 6871, "s": 6835, "text": "@forward \"filename\" as filename-*;\n" }, { "code": null, "e": 6913, "s": 6871, "text": "In case @use this method not recommended." }, { "code": null, "e": 7040, "s": 6913, "text": "To configure modules, modules loaded through @import by defining global variables with respect to initial load of that module." }, { "code": null, "e": 7102, "s": 7040, "text": "Example 3:Below example illustrates above approach.SASS files" }, { "code": "/*_libray.scss */ $purple:Purple;$white:white;button{ color:$white; border-color:$purple; background-color:$purple; padding :10px;} /* _library.import.scss */ @forward 'library' as lib-*; /* style.sass */ $lib-color: indigo;@import \"library\";", "e": 7367, "s": 7102, "text": null }, { "code": null, "e": 7396, "s": 7367, "text": "Compiled CSS file: style.css" }, { "code": null, "e": 7502, "s": 7396, "text": "button{\n color: white;\n border-color:indigo;\n background-color:indigo;\n padding :10px;\n}\n" }, { "code": null, "e": 7565, "s": 7502, "text": "Reference: https://sass-lang.com/documentation/at-rules/import" }, { "code": null, "e": 7572, "s": 7565, "text": "Picked" }, { "code": null, "e": 7577, "s": 7572, "text": "SASS" }, { "code": null, "e": 7594, "s": 7577, "text": "Web Technologies" }, { "code": null, "e": 7692, "s": 7594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7753, "s": 7692, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7796, "s": 7753, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7868, "s": 7796, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7908, "s": 7868, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7932, "s": 7908, "text": "REST API (Introduction)" }, { "code": null, "e": 7965, "s": 7932, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 8025, "s": 7965, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 8083, "s": 8025, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 8144, "s": 8083, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Logistic Regression in Python - Quick Guide
Logistic Regression is a statistical method of classification of objects. This chapter will give an introduction to logistic regression with the help of some examples. To understand logistic regression, you should know what classification means. Let us consider the following examples to understand this better − A doctor classifies the tumor as malignant or benign. A bank transaction may be fraudulent or genuine. For many years, humans have been performing such tasks - albeit they are error-prone. The question is can we train machines to do these tasks for us with a better accuracy? One such example of machine doing the classification is the email Client on your machine that classifies every incoming mail as “spam” or “not spam” and it does it with a fairly large accuracy. The statistical technique of logistic regression has been successfully applied in email client. In this case, we have trained our machine to solve a classification problem. Logistic Regression is just one part of machine learning used for solving this kind of binary classification problem. There are several other machine learning techniques that are already developed and are in practice for solving other kinds of problems. If you have noted, in all the above examples, the outcome of the predication has only two values - Yes or No. We call these as classes - so as to say we say that our classifier classifies the objects in two classes. In technical terms, we can say that the outcome or target variable is dichotomous in nature. There are other classification problems in which the output may be classified into more than two classes. For example, given a basket full of fruits, you are asked to separate fruits of different kinds. Now, the basket may contain Oranges, Apples, Mangoes, and so on. So when you separate out the fruits, you separate them out in more than two classes. This is a multivariate classification problem. Consider that a bank approaches you to develop a machine learning application that will help them in identifying the potential clients who would open a Term Deposit (also called Fixed Deposit by some banks) with them. The bank regularly conducts a survey by means of telephonic calls or web forms to collect information about the potential clients. The survey is general in nature and is conducted over a very large audience out of which many may not be interested in dealing with this bank itself. Out of the rest, only a few may be interested in opening a Term Deposit. Others may be interested in other facilities offered by the bank. So the survey is not necessarily conducted for identifying the customers opening TDs. Your task is to identify all those customers with high probability of opening TD from the humongous survey data that the bank is going to share with you. Fortunately, one such kind of data is publicly available for those aspiring to develop machine learning models. This data was prepared by some students at UC Irvine with external funding. The database is available as a part of UCI Machine Learning Repository and is widely used by students, educators, and researchers all over the world. The data can be downloaded from here. In the next chapters, let us now perform the application development using the same data. In this chapter, we will understand the process involved in setting up a project to perform logistic regression in Python, in detail. We will be using Jupyter - one of the most widely used platforms for machine learning. If you do not have Jupyter installed on your machine, download it from here. For installation, you can follow the instructions on their site to install the platform. As the site suggests, you may prefer to use Anaconda Distribution which comes along with Python and many commonly used Python packages for scientific computing and data science. This will alleviate the need for installing these packages individually. After the successful installation of Jupyter, start a new project, your screen at this stage would look like the following ready to accept your code. Now, change the name of the project from Untitled1 to “Logistic Regression” by clicking the title name and editing it. First, we will be importing several Python packages that we will need in our code. For this purpose, type or cut-and-paste the following code in the code editor − In [1]: # import statements import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split Your Notebook should look like the following at this stage − Run the code by clicking on the Run button. If no errors are generated, you have successfully installed Jupyter and are now ready for the rest of the development. The first three import statements import pandas, numpy and matplotlib.pyplot packages in our project. The next three statements import the specified modules from sklearn. Our next task is to download the data required for our project. We will learn this in the next chapter. The steps involved in getting data for performing logistic regression in Python are discussed in detail in this chapter. If you have not already downloaded the UCI dataset mentioned earlier, download it now from here. Click on the Data Folder. You will see the following screen − Download the bank.zip file by clicking on the given link. The zip file contains the following files − We will use the bank.csv file for our model development. The bank-names.txt file contains the description of the database that you are going to need later. The bank-full.csv contains a much larger dataset that you may use for more advanced developments. Here we have included the bank.csv file in the downloadable source zip. This file contains the comma-delimited fields. We have also made a few modifications in the file. It is recommended that you use the file included in the project source zip for your learning. To load the data from the csv file that you copied just now, type the following statement and run the code. In [2]: df = pd.read_csv('bank.csv', header=0) You will also be able to examine the loaded data by running the following code statement − IN [3]: df.head() Once the command is run, you will see the following output − Basically, it has printed the first five rows of the loaded data. Examine the 21 columns present. We will be using only few columns from these for our model development. Next, we need to clean the data. The data may contain some rows with NaN. To eliminate such rows, use the following command − IN [4]: df = df.dropna() Fortunately, the bank.csv does not contain any rows with NaN, so this step is not truly required in our case. However, in general it is difficult to discover such rows in a huge database. So it is always safer to run the above statement to clean the data. Note − You can easily examine the data size at any point of time by using the following statement − IN [5]: print (df.shape) (41188, 21) The number of rows and columns would be printed in the output as shown in the second line above. Next thing to do is to examine the suitability of each column for the model that we are trying to build. Whenever any organization conducts a survey, they try to collect as much information as possible from the customer, with the idea that this information would be useful to the organization one way or the other, at a later point of time. To solve the current problem, we have to pick up the information that is directly relevant to our problem. Now, let us see how to select the data fields useful to us. Run the following statement in the code editor. In [6]: print(list(df.columns)) You will see the following output − ['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'emp_var_rate', 'cons_price_idx', 'cons_conf_idx', 'euribor3m', 'nr_employed', 'y'] The output shows the names of all the columns in the database. The last column “y” is a Boolean value indicating whether this customer has a term deposit with the bank. The values of this field are either “y” or “n”. You can read the description and purpose of each column in the banks-name.txt file that was downloaded as part of the data. Examining the column names, you will know that some of the fields have no significance to the problem at hand. For example, fields such as month, day_of_week, campaign, etc. are of no use to us. We will eliminate these fields from our database. To drop a column, we use the drop command as shown below − In [8]: #drop columns which are not needed. df.drop(df.columns[[0, 3, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19]], axis = 1, inplace = True) The command says that drop column number 0, 3, 7, 8, and so on. To ensure that the index is properly selected, use the following statement − In [7]: df.columns[9] Out[7]: 'day_of_week' This prints the column name for the given index. After dropping the columns which are not required, examine the data with the head statement. The screen output is shown here − In [9]: df.head() Out[9]: job marital default housing loan poutcome y 0 blue-collar married unknown yes no nonexistent 0 1 technician married no no no nonexistent 0 2 management single no yes no success 1 3 services married no no no nonexistent 0 4 retired married no yes no success 1 Now, we have only the fields which we feel are important for our data analysis and prediction. The importance of Data Scientist comes into picture at this step. The data scientist has to select the appropriate columns for model building. For example, the type of job though at the first glance may not convince everybody for inclusion in the database, it will be a very useful field. Not all types of customers will open the TD. The lower income people may not open the TDs, while the higher income people will usually park their excess money in TDs. So the type of job becomes significantly relevant in this scenario. Likewise, carefully select the columns which you feel will be relevant for your analysis. In the next chapter, we will prepare our data for building the model. For creating the classifier, we must prepare the data in a format that is asked by the classifier building module. We prepare the data by doing One Hot Encoding. We will discuss shortly what we mean by encoding data. First, let us run the code. Run the following command in the code window. In [10]: # creating one hot encoding of the categorical columns. data = pd.get_dummies(df, columns =['job', 'marital', 'default', 'housing', 'loan', 'poutcome']) As the comment says, the above statement will create the one hot encoding of the data. Let us see what has it created? Examine the created data called “data” by printing the head records in the database. In [11]: data.head() You will see the following output − To understand the above data, we will list out the column names by running the data.columns command as shown below − In [12]: data.columns Out[12]: Index(['y', 'job_admin.', 'job_blue-collar', 'job_entrepreneur', 'job_housemaid', 'job_management', 'job_retired', 'job_self-employed', 'job_services', 'job_student', 'job_technician', 'job_unemployed', 'job_unknown', 'marital_divorced', 'marital_married', 'marital_single', 'marital_unknown', 'default_no', 'default_unknown', 'default_yes', 'housing_no', 'housing_unknown', 'housing_yes', 'loan_no', 'loan_unknown', 'loan_yes', 'poutcome_failure', 'poutcome_nonexistent', 'poutcome_success'], dtype='object') Now, we will explain how the one hot encoding is done by the get_dummies command. The first column in the newly generated database is “y” field which indicates whether this client has subscribed to a TD or not. Now, let us look at the columns which are encoded. The first encoded column is “job”. In the database, you will find that the “job” column has many possible values such as “admin”, “blue-collar”, “entrepreneur”, and so on. For each possible value, we have a new column created in the database, with the column name appended as a prefix. Thus, we have columns called “job_admin”, “job_blue-collar”, and so on. For each encoded field in our original database, you will find a list of columns added in the created database with all possible values that the column takes in the original database. Carefully examine the list of columns to understand how the data is mapped to a new database. To understand the generated data, let us print out the entire data using the data command. The partial output after running the command is shown below. In [13]: data The above screen shows the first twelve rows. If you scroll down further, you would see that the mapping is done for all the rows. A partial screen output further down the database is shown here for your quick reference. To understand the mapped data, let us examine the first row. It says that this customer has not subscribed to TD as indicated by the value in the “y” field. It also indicates that this customer is a “blue-collar” customer. Scrolling down horizontally, it will tell you that he has a “housing” and has taken no “loan”. After this one hot encoding, we need some more data processing before we can start building our model. If we examine the columns in the mapped database, you will find the presence of few columns ending with “unknown”. For example, examine the column at index 12 with the following command shown in the screenshot − In [14]: data.columns[12] Out[14]: 'job_unknown' This indicates the job for the specified customer is unknown. Obviously, there is no point in including such columns in our analysis and model building. Thus, all columns with the “unknown” value should be dropped. This is done with the following command − In [15]: data.drop(data.columns[[12, 16, 18, 21, 24]], axis=1, inplace=True) Ensure that you specify the correct column numbers. In case of a doubt, you can examine the column name anytime by specifying its index in the columns command as described earlier. After dropping the undesired columns, you can examine the final list of columns as shown in the output below − In [16]: data.columns Out[16]: Index(['y', 'job_admin.', 'job_blue-collar', 'job_entrepreneur', 'job_housemaid', 'job_management', 'job_retired', 'job_self-employed', 'job_services', 'job_student', 'job_technician', 'job_unemployed', 'marital_divorced', 'marital_married', 'marital_single', 'default_no', 'default_yes', 'housing_no', 'housing_yes', 'loan_no', 'loan_yes', 'poutcome_failure', 'poutcome_nonexistent', 'poutcome_success'], dtype='object') At this point, our data is ready for model building. We have about forty-one thousand and odd records. If we use the entire data for model building, we will not be left with any data for testing. So generally, we split the entire data set into two parts, say 70/30 percentage. We use 70% of the data for model building and the rest for testing the accuracy in prediction of our created model. You may use a different splitting ratio as per your requirement. Before we split the data, we separate out the data into two arrays X and Y. The X array contains all the features (data columns) that we want to analyze and Y array is a single dimensional array of boolean values that is the output of the prediction. To understand this, let us run some code. Firstly, execute the following Python statement to create the X array − In [17]: X = data.iloc[:,1:] To examine the contents of X use head to print a few initial records. The following screen shows the contents of the X array. In [18]: X.head () The array has several rows and 23 columns. Next, we will create output array containing “y” values. To create an array for the predicted value column, use the following Python statement − In [19]: Y = data.iloc[:,0] Examine its contents by calling head. The screen output below shows the result − In [20]: Y.head() Out[20]: 0 0 1 0 2 1 3 0 4 1 Name: y, dtype: int64 Now, split the data using the following command − In [21]: X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0) This will create the four arrays called X_train, Y_train, X_test, and Y_test. As before, you may examine the contents of these arrays by using the head command. We will use X_train and Y_train arrays for training our model and X_test and Y_test arrays for testing and validating. Now, we are ready to build our classifier. We will look into it in the next chapter. It is not required that you have to build the classifier from scratch. Building classifiers is complex and requires knowledge of several areas such as Statistics, probability theories, optimization techniques, and so on. There are several pre-built libraries available in the market which have a fully-tested and very efficient implementation of these classifiers. We will use one such pre-built model from the sklearn. Creating the Logistic Regression classifier from sklearn toolkit is trivial and is done in a single program statement as shown here − In [22]: classifier = LogisticRegression(solver='lbfgs',random_state=0) Once the classifier is created, you will feed your training data into the classifier so that it can tune its internal parameters and be ready for the predictions on your future data. To tune the classifier, we run the following statement − In [23]: classifier.fit(X_train, Y_train) The classifier is now ready for testing. The following code is the output of execution of the above two statements − Out[23]: LogisticRegression(C = 1.0, class_weight = None, dual = False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='warn', n_jobs=None, penalty='l2', random_state=0, solver='lbfgs', tol=0.0001, verbose=0, warm_start=False)) Now, we are ready to test the created classifier. We will deal this in the next chapter. We need to test the above created classifier before we put it into production use. If the testing reveals that the model does not meet the desired accuracy, we will have to go back in the above process, select another set of features (data fields), build the model again, and test it. This will be an iterative step until the classifier meets your requirement of desired accuracy. So let us test our classifier. To test the classifier, we use the test data generated in the earlier stage. We call the predict method on the created object and pass the X array of the test data as shown in the following command − In [24]: predicted_y = classifier.predict(X_test) This generates a single dimensional array for the entire training data set giving the prediction for each row in the X array. You can examine this array by using the following command − In [25]: predicted_y The following is the output upon the execution the above two commands − Out[25]: array([0, 0, 0, ..., 0, 0, 0]) The output indicates that the first and last three customers are not the potential candidates for the Term Deposit. You can examine the entire array to sort out the potential customers. To do so, use the following Python code snippet − In [26]: for x in range(len(predicted_y)): if (predicted_y[x] == 1): print(x, end="\t") The output of running the above code is shown below − The output shows the indexes of all rows who are probable candidates for subscribing to TD. You can now give this output to the bank’s marketing team who would pick up the contact details for each customer in the selected row and proceed with their job. Before we put this model into production, we need to verify the accuracy of prediction. To test the accuracy of the model, use the score method on the classifier as shown below − In [27]: print('Accuracy: {:.2f}'.format(classifier.score(X_test, Y_test))) The screen output of running this command is shown below − Accuracy: 0.90 It shows that the accuracy of our model is 90% which is considered very good in most of the applications. Thus, no further tuning is required. Now, our customer is ready to run the next campaign, get the list of potential customers and chase them for opening the TD with a probable high rate of success. As you have seen from the above example, applying logistic regression for machine learning is not a difficult task. However, it comes with its own limitations. The logistic regression will not be able to handle a large number of categorical features. In the example we have discussed so far, we reduced the number of features to a very large extent. However, if these features were important in our prediction, we would have been forced to include them, but then the logistic regression would fail to give us a good accuracy. Logistic regression is also vulnerable to overfitting. It cannot be applied to a non-linear problem. It will perform poorly with independent variables which are not correlated to the target and are correlated to each other. Thus, you will have to carefully evaluate the suitability of logistic regression to the problem that you are trying to solve. There are many areas of machine learning where other techniques are specified devised. To name a few, we have algorithms such as k-nearest neighbours (kNN), Linear Regression, Support Vector Machines (SVM), Decision Trees, Naive Bayes, and so on. Before finalizing on a particular model, you will have to evaluate the applicability of these various techniques to the problem that we are trying to solve. Logistic Regression is a statistical technique of binary classification. In this tutorial, you learned how to train the machine to use logistic regression. Creating machine learning models, the most important requirement is the availability of the data. Without adequate and relevant data, you cannot simply make the machine to learn. Once you have data, your next major task is cleansing the data, eliminating the unwanted rows, fields, and select the appropriate fields for your model development. After this is done, you need to map the data into a format required by the classifier for its training. Thus, the data preparation is a major task in any machine learning application. Once you are ready with the data, you can select a particular type of classifier. In this tutorial, you learned how to use a logistic regression classifier provided in the sklearn library. To train the classifier, we use about 70% of the data for training the model. We use the rest of the data for testing. We test the accuracy of the model. If this is not within acceptable limits, we go back to selecting the new set of features. Once again, follow the entire process of preparing data, train the model, and test it, until you are satisfied with its accuracy. Before taking up any machine learning project, you must learn and have exposure to a wide variety of techniques which have been developed so far and which have been applied successfully in the industry.
[ { "code": null, "e": 2035, "s": 1867, "text": "Logistic Regression is a statistical method of classification of objects. This chapter will give an introduction to logistic regression with the help of some examples." }, { "code": null, "e": 2180, "s": 2035, "text": "To understand logistic regression, you should know what classification means. Let us consider the following examples to understand this better −" }, { "code": null, "e": 2234, "s": 2180, "text": "A doctor classifies the tumor as malignant or benign." }, { "code": null, "e": 2283, "s": 2234, "text": "A bank transaction may be fraudulent or genuine." }, { "code": null, "e": 2456, "s": 2283, "text": "For many years, humans have been performing such tasks - albeit they are error-prone. The question is can we train machines to do these tasks for us with a better accuracy?" }, { "code": null, "e": 2823, "s": 2456, "text": "One such example of machine doing the classification is the email Client on your machine that classifies every incoming mail as “spam” or “not spam” and it does it with a fairly large accuracy. The statistical technique of logistic regression has been successfully applied in email client. In this case, we have trained our machine to solve a classification problem." }, { "code": null, "e": 3077, "s": 2823, "text": "Logistic Regression is just one part of machine learning used for solving this kind of binary classification problem. There are several other machine learning techniques that are already developed and are in practice for solving other kinds of problems." }, { "code": null, "e": 3386, "s": 3077, "text": "If you have noted, in all the above examples, the outcome of the predication has only two values - Yes or No. We call these as classes - so as to say we say that our classifier classifies the objects in two classes. In technical terms, we can say that the outcome or target variable is dichotomous in nature." }, { "code": null, "e": 3786, "s": 3386, "text": "There are other classification problems in which the output may be classified into more than two classes. For example, given a basket full of fruits, you are asked to separate fruits of different kinds. Now, the basket may contain Oranges, Apples, Mangoes, and so on. So when you separate out the fruits, you separate them out in more than two classes. This is a multivariate classification problem." }, { "code": null, "e": 4664, "s": 3786, "text": "Consider that a bank approaches you to develop a machine learning application that will help them in identifying the potential clients who would open a Term Deposit (also called Fixed Deposit by some banks) with them. The bank regularly conducts a survey by means of telephonic calls or web forms to collect information about the potential clients. The survey is general in nature and is conducted over a very large audience out of which many may not be interested in dealing with this bank itself. Out of the rest, only a few may be interested in opening a Term Deposit. Others may be interested in other facilities offered by the bank. So the survey is not necessarily conducted for identifying the customers opening TDs. Your task is to identify all those customers with high probability of opening TD from the humongous survey data that the bank is going to share with you." }, { "code": null, "e": 5040, "s": 4664, "text": "Fortunately, one such kind of data is publicly available for those aspiring to develop machine learning models. This data was prepared by some students at UC Irvine with external funding. The database is available as a part of UCI Machine Learning Repository and is widely used by students, educators, and researchers all over the world. The data can be downloaded from here." }, { "code": null, "e": 5130, "s": 5040, "text": "In the next chapters, let us now perform the application development using the same data." }, { "code": null, "e": 5264, "s": 5130, "text": "In this chapter, we will understand the process involved in setting up a project to perform logistic regression in Python, in detail." }, { "code": null, "e": 5768, "s": 5264, "text": "We will be using Jupyter - one of the most widely used platforms for machine learning. If you do not have Jupyter installed on your machine, download it from here. For installation, you can follow the instructions on their site to install the platform. As the site suggests, you may prefer to use Anaconda Distribution which comes along with Python and many commonly used Python packages for scientific computing and data science. This will alleviate the need for installing these packages individually." }, { "code": null, "e": 5918, "s": 5768, "text": "After the successful installation of Jupyter, start a new project, your screen at this stage would look like the following ready to accept your code." }, { "code": null, "e": 6037, "s": 5918, "text": "Now, change the name of the project from Untitled1 to “Logistic Regression” by clicking the title name and editing it." }, { "code": null, "e": 6120, "s": 6037, "text": "First, we will be importing several Python packages that we will need in our code." }, { "code": null, "e": 6200, "s": 6120, "text": "For this purpose, type or cut-and-paste the following code in the code editor −" }, { "code": null, "e": 6457, "s": 6200, "text": "In [1]: # import statements\n import pandas as pd\n import numpy as np\n import matplotlib.pyplot as plt\n\n from sklearn import preprocessing\n from sklearn.linear_model import LogisticRegression\n from sklearn.model_selection import train_test_split" }, { "code": null, "e": 6518, "s": 6457, "text": "Your Notebook should look like the following at this stage −" }, { "code": null, "e": 6681, "s": 6518, "text": "Run the code by clicking on the Run button. If no errors are generated, you have successfully installed Jupyter and are now ready for the rest of the development." }, { "code": null, "e": 6852, "s": 6681, "text": "The first three import statements import pandas, numpy and matplotlib.pyplot packages in our project. The next three statements import the specified modules from sklearn." }, { "code": null, "e": 6956, "s": 6852, "text": "Our next task is to download the data required for our project. We will learn this in the next chapter." }, { "code": null, "e": 7077, "s": 6956, "text": "The steps involved in getting data for performing logistic regression in Python are discussed in detail in this chapter." }, { "code": null, "e": 7236, "s": 7077, "text": "If you have not already downloaded the UCI dataset mentioned earlier, download it now from here. Click on the Data Folder. You will see the following screen −" }, { "code": null, "e": 7338, "s": 7236, "text": "Download the bank.zip file by clicking on the given link. The zip file contains the following files −" }, { "code": null, "e": 7592, "s": 7338, "text": "We will use the bank.csv file for our model development. The bank-names.txt file contains the description of the database that you are going to need later. The bank-full.csv contains a much larger dataset that you may use for more advanced developments." }, { "code": null, "e": 7856, "s": 7592, "text": "Here we have included the bank.csv file in the downloadable source zip. This file contains the comma-delimited fields. We have also made a few modifications in the file. It is recommended that you use the file included in the project source zip for your learning." }, { "code": null, "e": 7964, "s": 7856, "text": "To load the data from the csv file that you copied just now, type the following statement and run the code." }, { "code": null, "e": 8012, "s": 7964, "text": "In [2]: df = pd.read_csv('bank.csv', header=0)\n" }, { "code": null, "e": 8103, "s": 8012, "text": "You will also be able to examine the loaded data by running the following code statement −" }, { "code": null, "e": 8122, "s": 8103, "text": "IN [3]: df.head()\n" }, { "code": null, "e": 8183, "s": 8122, "text": "Once the command is run, you will see the following output −" }, { "code": null, "e": 8353, "s": 8183, "text": "Basically, it has printed the first five rows of the loaded data. Examine the 21 columns present. We will be using only few columns from these for our model development." }, { "code": null, "e": 8479, "s": 8353, "text": "Next, we need to clean the data. The data may contain some rows with NaN. To eliminate such rows, use the following command −" }, { "code": null, "e": 8505, "s": 8479, "text": "IN [4]: df = df.dropna()\n" }, { "code": null, "e": 8761, "s": 8505, "text": "Fortunately, the bank.csv does not contain any rows with NaN, so this step is not truly required in our case. However, in general it is difficult to discover such rows in a huge database. So it is always safer to run the above statement to clean the data." }, { "code": null, "e": 8861, "s": 8761, "text": "Note − You can easily examine the data size at any point of time by using the following statement −" }, { "code": null, "e": 8899, "s": 8861, "text": "IN [5]: print (df.shape)\n(41188, 21)\n" }, { "code": null, "e": 8996, "s": 8899, "text": "The number of rows and columns would be printed in the output as shown in the second line above." }, { "code": null, "e": 9101, "s": 8996, "text": "Next thing to do is to examine the suitability of each column for the model that we are trying to build." }, { "code": null, "e": 9444, "s": 9101, "text": "Whenever any organization conducts a survey, they try to collect as much information as possible from the customer, with the idea that this information would be useful to the organization one way or the other, at a later point of time. To solve the current problem, we have to pick up the information that is directly relevant to our problem." }, { "code": null, "e": 9552, "s": 9444, "text": "Now, let us see how to select the data fields useful to us. Run the following statement in the code editor." }, { "code": null, "e": 9585, "s": 9552, "text": "In [6]: print(list(df.columns))\n" }, { "code": null, "e": 9621, "s": 9585, "text": "You will see the following output −" }, { "code": null, "e": 9870, "s": 9621, "text": "['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', \n'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', \n'previous', 'poutcome', 'emp_var_rate', 'cons_price_idx', 'cons_conf_idx', \n'euribor3m', 'nr_employed', 'y']\n" }, { "code": null, "e": 10211, "s": 9870, "text": "The output shows the names of all the columns in the database. The last column “y” is a Boolean value indicating whether this customer has a term deposit with the bank. The values of this field are either “y” or “n”. You can read the description and purpose of each column in the banks-name.txt file that was downloaded as part of the data." }, { "code": null, "e": 10515, "s": 10211, "text": "Examining the column names, you will know that some of the fields have no significance to the problem at hand. For example, fields such as month, day_of_week, campaign, etc. are of no use to us. We will eliminate these fields from our database. To drop a column, we use the drop command as shown below −" }, { "code": null, "e": 10666, "s": 10515, "text": "In [8]: #drop columns which are not needed.\n df.drop(df.columns[[0, 3, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19]], \n axis = 1, inplace = True)\n" }, { "code": null, "e": 10807, "s": 10666, "text": "The command says that drop column number 0, 3, 7, 8, and so on. To ensure that the index is properly selected, use the following statement −" }, { "code": null, "e": 10852, "s": 10807, "text": "In [7]: df.columns[9]\nOut[7]: 'day_of_week'\n" }, { "code": null, "e": 10901, "s": 10852, "text": "This prints the column name for the given index." }, { "code": null, "e": 11028, "s": 10901, "text": "After dropping the columns which are not required, examine the data with the head statement. The screen output is shown here −" }, { "code": null, "e": 11409, "s": 11028, "text": "In [9]: df.head()\nOut[9]:\n job marital default housing loan poutcome y\n0 blue-collar married unknown yes no nonexistent 0\n1 technician married no no no nonexistent 0\n2 management single no yes no success 1\n3 services married no no no nonexistent 0\n4 retired married no yes no success 1\n" }, { "code": null, "e": 11647, "s": 11409, "text": "Now, we have only the fields which we feel are important for our data analysis and prediction. The importance of Data Scientist comes into picture at this step. The data scientist has to select the appropriate columns for model building." }, { "code": null, "e": 12118, "s": 11647, "text": "For example, the type of job though at the first glance may not convince everybody for inclusion in the database, it will be a very useful field. Not all types of customers will open the TD. The lower income people may not open the TDs, while the higher income people will usually park their excess money in TDs. So the type of job becomes significantly relevant in this scenario. Likewise, carefully select the columns which you feel will be relevant for your analysis." }, { "code": null, "e": 12188, "s": 12118, "text": "In the next chapter, we will prepare our data for building the model." }, { "code": null, "e": 12350, "s": 12188, "text": "For creating the classifier, we must prepare the data in a format that is asked by the classifier building module. We prepare the data by doing One Hot Encoding." }, { "code": null, "e": 12479, "s": 12350, "text": "We will discuss shortly what we mean by encoding data. First, let us run the code. Run the following command in the code window." }, { "code": null, "e": 12641, "s": 12479, "text": "In [10]: # creating one hot encoding of the categorical columns.\ndata = pd.get_dummies(df, columns =['job', 'marital', 'default', 'housing', 'loan', 'poutcome'])" }, { "code": null, "e": 12845, "s": 12641, "text": "As the comment says, the above statement will create the one hot encoding of the data. Let us see what has it created? Examine the created data called “data” by printing the head records in the database." }, { "code": null, "e": 12867, "s": 12845, "text": "In [11]: data.head()\n" }, { "code": null, "e": 12903, "s": 12867, "text": "You will see the following output −" }, { "code": null, "e": 13020, "s": 12903, "text": "To understand the above data, we will list out the column names by running the data.columns command as shown below −" }, { "code": null, "e": 13565, "s": 13020, "text": "In [12]: data.columns\nOut[12]: Index(['y', 'job_admin.', 'job_blue-collar', 'job_entrepreneur',\n'job_housemaid', 'job_management', 'job_retired', 'job_self-employed', \n'job_services', 'job_student', 'job_technician', 'job_unemployed',\n'job_unknown', 'marital_divorced', 'marital_married', 'marital_single', \n'marital_unknown', 'default_no', 'default_unknown', 'default_yes', \n'housing_no', 'housing_unknown', 'housing_yes', 'loan_no',\n'loan_unknown', 'loan_yes', 'poutcome_failure', 'poutcome_nonexistent', \n'poutcome_success'], dtype='object')" }, { "code": null, "e": 14113, "s": 13565, "text": "Now, we will explain how the one hot encoding is done by the get_dummies command. The first column in the newly generated database is “y” field which indicates whether this client has subscribed to a TD or not. Now, let us look at the columns which are encoded. The first encoded column is “job”. In the database, you will find that the “job” column has many possible values such as “admin”, “blue-collar”, “entrepreneur”, and so on. For each possible value, we have a new column created in the database, with the column name appended as a prefix." }, { "code": null, "e": 14463, "s": 14113, "text": "Thus, we have columns called “job_admin”, “job_blue-collar”, and so on. For each encoded field in our original database, you will find a list of columns added in the created database with all possible values that the column takes in the original database. Carefully examine the list of columns to understand how the data is mapped to a new database." }, { "code": null, "e": 14615, "s": 14463, "text": "To understand the generated data, let us print out the entire data using the data command. The partial output after running the command is shown below." }, { "code": null, "e": 14630, "s": 14615, "text": "In [13]: data\n" }, { "code": null, "e": 14761, "s": 14630, "text": "The above screen shows the first twelve rows. If you scroll down further, you would see that the mapping is done for all the rows." }, { "code": null, "e": 14851, "s": 14761, "text": "A partial screen output further down the database is shown here for your quick reference." }, { "code": null, "e": 14912, "s": 14851, "text": "To understand the mapped data, let us examine the first row." }, { "code": null, "e": 15169, "s": 14912, "text": "It says that this customer has not subscribed to TD as indicated by the value in the “y” field. It also indicates that this customer is a “blue-collar” customer. Scrolling down horizontally, it will tell you that he has a “housing” and has taken no “loan”." }, { "code": null, "e": 15272, "s": 15169, "text": "After this one hot encoding, we need some more data processing before we can start building our model." }, { "code": null, "e": 15484, "s": 15272, "text": "If we examine the columns in the mapped database, you will find the presence of few columns ending with “unknown”. For example, examine the column at index 12 with the following command shown in the screenshot −" }, { "code": null, "e": 15534, "s": 15484, "text": "In [14]: data.columns[12]\nOut[14]: 'job_unknown'\n" }, { "code": null, "e": 15791, "s": 15534, "text": "This indicates the job for the specified customer is unknown. Obviously, there is no point in including such columns in our analysis and model building. Thus, all columns with the “unknown” value should be dropped. This is done with the following command −" }, { "code": null, "e": 15869, "s": 15791, "text": "In [15]: data.drop(data.columns[[12, 16, 18, 21, 24]], axis=1, inplace=True)\n" }, { "code": null, "e": 16050, "s": 15869, "text": "Ensure that you specify the correct column numbers. In case of a doubt, you can examine the column name anytime by specifying its index in the columns command as described earlier." }, { "code": null, "e": 16161, "s": 16050, "text": "After dropping the undesired columns, you can examine the final list of columns as shown in the output below −" }, { "code": null, "e": 16618, "s": 16161, "text": "In [16]: data.columns\nOut[16]: Index(['y', 'job_admin.', 'job_blue-collar', 'job_entrepreneur', \n'job_housemaid', 'job_management', 'job_retired', 'job_self-employed', \n'job_services', 'job_student', 'job_technician', 'job_unemployed',\n'marital_divorced', 'marital_married', 'marital_single', 'default_no', \n'default_yes', 'housing_no', 'housing_yes', 'loan_no', 'loan_yes',\n'poutcome_failure', 'poutcome_nonexistent', 'poutcome_success'], \ndtype='object')" }, { "code": null, "e": 16671, "s": 16618, "text": "At this point, our data is ready for model building." }, { "code": null, "e": 17076, "s": 16671, "text": "We have about forty-one thousand and odd records. If we use the entire data for model building, we will not be left with any data for testing. So generally, we split the entire data set into two parts, say 70/30 percentage. We use 70% of the data for model building and the rest for testing the accuracy in prediction of our created model. You may use a different splitting ratio as per your requirement." }, { "code": null, "e": 17369, "s": 17076, "text": "Before we split the data, we separate out the data into two arrays X and Y. The X array contains all the features (data columns) that we want to analyze and Y array is a single dimensional array of boolean values that is the output of the prediction. To understand this, let us run some code." }, { "code": null, "e": 17441, "s": 17369, "text": "Firstly, execute the following Python statement to create the X array −" }, { "code": null, "e": 17471, "s": 17441, "text": "In [17]: X = data.iloc[:,1:]\n" }, { "code": null, "e": 17597, "s": 17471, "text": "To examine the contents of X use head to print a few initial records. The following screen shows the contents of the X array." }, { "code": null, "e": 17617, "s": 17597, "text": "In [18]: X.head ()\n" }, { "code": null, "e": 17660, "s": 17617, "text": "The array has several rows and 23 columns." }, { "code": null, "e": 17717, "s": 17660, "text": "Next, we will create output array containing “y” values." }, { "code": null, "e": 17805, "s": 17717, "text": "To create an array for the predicted value column, use the following Python statement −" }, { "code": null, "e": 17834, "s": 17805, "text": "In [19]: Y = data.iloc[:,0]\n" }, { "code": null, "e": 17915, "s": 17834, "text": "Examine its contents by calling head. The screen output below shows the result −" }, { "code": null, "e": 17999, "s": 17915, "text": "In [20]: Y.head()\nOut[20]: 0 0\n1 0\n2 1\n3 0\n4 1\nName: y, dtype: int64\n" }, { "code": null, "e": 18049, "s": 17999, "text": "Now, split the data using the following command −" }, { "code": null, "e": 18133, "s": 18049, "text": "In [21]: X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0)\n" }, { "code": null, "e": 18413, "s": 18133, "text": "This will create the four arrays called X_train, Y_train, X_test, and Y_test. As before, you may examine the contents of these arrays by using the head command. We will use X_train and Y_train arrays for training our model and X_test and Y_test arrays for testing and validating." }, { "code": null, "e": 18498, "s": 18413, "text": "Now, we are ready to build our classifier. We will look into it in the next chapter." }, { "code": null, "e": 18918, "s": 18498, "text": "It is not required that you have to build the classifier from scratch. Building classifiers is complex and requires knowledge of several areas such as Statistics, probability theories, optimization techniques, and so on. There are several pre-built libraries available in the market which have a fully-tested and very efficient implementation of these classifiers. We will use one such pre-built model from the sklearn." }, { "code": null, "e": 19052, "s": 18918, "text": "Creating the Logistic Regression classifier from sklearn toolkit is trivial and is done in a single program statement as shown here −" }, { "code": null, "e": 19125, "s": 19052, "text": "In [22]: classifier = LogisticRegression(solver='lbfgs',random_state=0)\n" }, { "code": null, "e": 19365, "s": 19125, "text": "Once the classifier is created, you will feed your training data into the classifier so that it can tune its internal parameters and be ready for the predictions on your future data. To tune the classifier, we run the following statement −" }, { "code": null, "e": 19408, "s": 19365, "text": "In [23]: classifier.fit(X_train, Y_train)\n" }, { "code": null, "e": 19525, "s": 19408, "text": "The classifier is now ready for testing. The following code is the output of execution of the above two statements −" }, { "code": null, "e": 19786, "s": 19525, "text": "Out[23]: LogisticRegression(C = 1.0, class_weight = None, dual = False, \n fit_intercept=True, intercept_scaling=1, max_iter=100, \n multi_class='warn', n_jobs=None, penalty='l2', random_state=0, \n solver='lbfgs', tol=0.0001, verbose=0, warm_start=False))\n" }, { "code": null, "e": 19875, "s": 19786, "text": "Now, we are ready to test the created classifier. We will deal this in the next chapter." }, { "code": null, "e": 20287, "s": 19875, "text": "We need to test the above created classifier before we put it into production use. If the testing reveals that the model does not meet the desired accuracy, we will have to go back in the above process, select another set of features (data fields), build the model again, and test it. This will be an iterative step until the classifier meets your requirement of desired accuracy. So let us test our classifier." }, { "code": null, "e": 20487, "s": 20287, "text": "To test the classifier, we use the test data generated in the earlier stage. We call the predict method on the created object and pass the X array of the test data as shown in the following command −" }, { "code": null, "e": 20538, "s": 20487, "text": "In [24]: predicted_y = classifier.predict(X_test)\n" }, { "code": null, "e": 20724, "s": 20538, "text": "This generates a single dimensional array for the entire training data set giving the prediction for each row in the X array. You can examine this array by using the following command −" }, { "code": null, "e": 20746, "s": 20724, "text": "In [25]: predicted_y\n" }, { "code": null, "e": 20818, "s": 20746, "text": "The following is the output upon the execution the above two commands −" }, { "code": null, "e": 20859, "s": 20818, "text": "Out[25]: array([0, 0, 0, ..., 0, 0, 0])\n" }, { "code": null, "e": 21095, "s": 20859, "text": "The output indicates that the first and last three customers are not the potential candidates for the Term Deposit. You can examine the entire array to sort out the potential customers. To do so, use the following Python code snippet −" }, { "code": null, "e": 21193, "s": 21095, "text": "In [26]: for x in range(len(predicted_y)):\n if (predicted_y[x] == 1):\n print(x, end=\"\\t\")\n" }, { "code": null, "e": 21247, "s": 21193, "text": "The output of running the above code is shown below −" }, { "code": null, "e": 21501, "s": 21247, "text": "The output shows the indexes of all rows who are probable candidates for subscribing to TD. You can now give this output to the bank’s marketing team who would pick up the contact details for each customer in the selected row and proceed with their job." }, { "code": null, "e": 21589, "s": 21501, "text": "Before we put this model into production, we need to verify the accuracy of prediction." }, { "code": null, "e": 21680, "s": 21589, "text": "To test the accuracy of the model, use the score method on the classifier as shown below −" }, { "code": null, "e": 21757, "s": 21680, "text": "In [27]: print('Accuracy: {:.2f}'.format(classifier.score(X_test, Y_test)))\n" }, { "code": null, "e": 21816, "s": 21757, "text": "The screen output of running this command is shown below −" }, { "code": null, "e": 21832, "s": 21816, "text": "Accuracy: 0.90\n" }, { "code": null, "e": 22136, "s": 21832, "text": "It shows that the accuracy of our model is 90% which is considered very good in most of the applications. Thus, no further tuning is required. Now, our customer is ready to run the next campaign, get the list of potential customers and chase them for opening the TD with a probable high rate of success." }, { "code": null, "e": 22486, "s": 22136, "text": "As you have seen from the above example, applying logistic regression for machine learning is not a difficult task. However, it comes with its own limitations. The logistic regression will not be able to handle a large number of categorical features. In the example we have discussed so far, we reduced the number of features to a very large extent." }, { "code": null, "e": 23012, "s": 22486, "text": "However, if these features were important in our prediction, we would have been forced to include them, but then the logistic regression would fail to give us a good accuracy. Logistic regression is also vulnerable to overfitting. It cannot be applied to a non-linear problem. It will perform poorly with independent variables which are not correlated to the target and are correlated to each other. Thus, you will have to carefully evaluate the suitability of logistic regression to the problem that you are trying to solve." }, { "code": null, "e": 23416, "s": 23012, "text": "There are many areas of machine learning where other techniques are specified devised. To name a few, we have algorithms such as k-nearest neighbours (kNN), Linear Regression, Support Vector Machines (SVM), Decision Trees, Naive Bayes, and so on. Before finalizing on a particular model, you will have to evaluate the applicability of these various techniques to the problem that we are trying to solve." }, { "code": null, "e": 23751, "s": 23416, "text": "Logistic Regression is a statistical technique of binary classification. In this tutorial, you learned how to train the machine to use logistic regression. Creating machine learning models, the most important requirement is the availability of the data. Without adequate and relevant data, you cannot simply make the machine to learn." }, { "code": null, "e": 24182, "s": 23751, "text": "Once you have data, your next major task is cleansing the data, eliminating the unwanted rows, fields, and select the appropriate fields for your model development. After this is done, you need to map the data into a format required by the classifier for its training. Thus, the data preparation is a major task in any machine learning application. Once you are ready with the data, you can select a particular type of classifier." }, { "code": null, "e": 24533, "s": 24182, "text": "In this tutorial, you learned how to use a logistic regression classifier provided in the sklearn library. To train the classifier, we use about 70% of the data for training the model. We use the rest of the data for testing. We test the accuracy of the model. If this is not within acceptable limits, we go back to selecting the new set of features." } ]
Number of subsequences with zero sum
21 Jun, 2022 Given an array arr[] of N integers. The task is to count the number of sub-sequences whose sum is 0. Examples: Input: arr[] = {-1, 2, -2, 1} Output: 3 All possible sub-sequences are {-1, 1}, {2, -2} and {-1, 2, -2, 1} Input: arr[] = {-2, -4, -1, 6, -2} Output: 2 Approach: The problem can be solved using recursion. Recursively, we start from the first index, and either select the number to be added in the subsequence or we do not select the number at an index. Once the index exceeds N, we need to check if the sum evaluated is 0 or not and the count of numbers taken in subsequence should be a minimum of one. If it is, then we simply return 1 which is added to the number of ways. Dynamic Programming cannot be used to solve this problem because of the sum value which can be anything that is not possible to store in any dimensional array. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of the required sub-sequencesint countSubSeq(int i, int sum, int cnt, int a[], int n){ // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) return 1; else return 0; } int ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans;} // Driver codeint main(){ int a[] = { -1, 2, -2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << countSubSeq(0, 0, 0, a, n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the count // of the required sub-sequences static int countSubSeq(int i, int sum, int cnt, int a[], int n) { // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) { return 1; } else { return 0; } } int ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans; } // Driver code public static void main(String[] args) { int a[] = {-1, 2, -2, 1}; int n = a.length; System.out.println(countSubSeq(0, 0, 0, a, n)); }} // This code has been contributed by 29AjayKumar # Python3 implementation of the approach # Function to return the count# of the required sub-sequencesdef countSubSeq(i, Sum, cnt, a, n): # Base case if (i == n): # Check if the Sum is 0 # and at least a single element # is in the sub-sequence if (Sum == 0 and cnt > 0): return 1 else: return 0 ans = 0 # Do not take the number in # the current sub-sequence ans += countSubSeq(i + 1, Sum, cnt, a, n) # Take the number in the # current sub-sequence ans += countSubSeq(i + 1, Sum + a[i], cnt + 1, a, n) return ans # Driver codea = [-1, 2, -2, 1]n = len(a)print(countSubSeq(0, 0, 0, a, n)) # This code is contributed by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to return the count // of the required sub-sequences static int countSubSeq(int i, int sum, int cnt, int []a, int n) { // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) { return 1; } else { return 0; } } int ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans; } // Driver code public static void Main() { int []a = {-1, 2, -2, 1}; int n = a.Length; Console.Write(countSubSeq(0, 0, 0, a, n)); }} // This code is contributed by Akanksha Rai <?php// PHP implementation of the approach // Function to return the count// of the required sub-sequencesfunction countSubSeq($i, $sum, $cnt, $a, $n){ // Base case if ($i == $n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if ($sum == 0 && $cnt > 0) return 1; else return 0; } $ans = 0; // Do not take the number in // the current sub-sequence $ans += countSubSeq($i + 1, $sum, $cnt, $a, $n); // Take the number in the // current sub-sequence $ans += countSubSeq($i + 1, $sum + $a[$i], $cnt + 1, $a, $n); return $ans;} // Driver code$a = array( -1, 2, -2, 1 );$n = count($a) ; echo countSubSeq(0, 0, 0, $a, $n); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function to return the count// of the required sub-sequencesfunction countSubSeq(i, sum, cnt, a, n){ // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) return 1; else return 0; } let ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans;} // Driver code let a = [ -1, 2, -2, 1 ]; let n = a.length; document.write(countSubSeq(0, 0, 0, a, n)); </script> 3 Time Complexity: O(2N), as we are using recursion and T(N) = O(1) + 2*T(N-1) which will be equivalent to T(N) = (2^N – 1)*O(1). Where N is the number of elements in the array. Auxiliary Space: O(1), as we are not using any extra space. ankthon 29AjayKumar Akanksha_Rai mohit kumar 29 rishavmahato348 rohitkumarsinghcna subsequence Arrays Combinatorial Recursion Arrays Recursion Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Find duplicates in O(n) time and O(1) extra space | Set 1 Chocolate Distribution Problem Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 165, "s": 52, "text": "Given an array arr[] of N integers. The task is to count the number of sub-sequences whose sum is 0. Examples: " }, { "code": null, "e": 319, "s": 165, "text": "Input: arr[] = {-1, 2, -2, 1} Output: 3 All possible sub-sequences are {-1, 1}, {2, -2} and {-1, 2, -2, 1} Input: arr[] = {-2, -4, -1, 6, -2} Output: 2 " }, { "code": null, "e": 957, "s": 321, "text": "Approach: The problem can be solved using recursion. Recursively, we start from the first index, and either select the number to be added in the subsequence or we do not select the number at an index. Once the index exceeds N, we need to check if the sum evaluated is 0 or not and the count of numbers taken in subsequence should be a minimum of one. If it is, then we simply return 1 which is added to the number of ways. Dynamic Programming cannot be used to solve this problem because of the sum value which can be anything that is not possible to store in any dimensional array. Below is the implementation of the above approach: " }, { "code": null, "e": 961, "s": 957, "text": "C++" }, { "code": null, "e": 966, "s": 961, "text": "Java" }, { "code": null, "e": 974, "s": 966, "text": "Python3" }, { "code": null, "e": 977, "s": 974, "text": "C#" }, { "code": null, "e": 981, "s": 977, "text": "PHP" }, { "code": null, "e": 992, "s": 981, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of the required sub-sequencesint countSubSeq(int i, int sum, int cnt, int a[], int n){ // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) return 1; else return 0; } int ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans;} // Driver codeint main(){ int a[] = { -1, 2, -2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << countSubSeq(0, 0, 0, a, n); return 0;}", "e": 1868, "s": 992, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the count // of the required sub-sequences static int countSubSeq(int i, int sum, int cnt, int a[], int n) { // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) { return 1; } else { return 0; } } int ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans; } // Driver code public static void main(String[] args) { int a[] = {-1, 2, -2, 1}; int n = a.length; System.out.println(countSubSeq(0, 0, 0, a, n)); }} // This code has been contributed by 29AjayKumar", "e": 2984, "s": 1868, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count# of the required sub-sequencesdef countSubSeq(i, Sum, cnt, a, n): # Base case if (i == n): # Check if the Sum is 0 # and at least a single element # is in the sub-sequence if (Sum == 0 and cnt > 0): return 1 else: return 0 ans = 0 # Do not take the number in # the current sub-sequence ans += countSubSeq(i + 1, Sum, cnt, a, n) # Take the number in the # current sub-sequence ans += countSubSeq(i + 1, Sum + a[i], cnt + 1, a, n) return ans # Driver codea = [-1, 2, -2, 1]n = len(a)print(countSubSeq(0, 0, 0, a, n)) # This code is contributed by mohit kumar", "e": 3731, "s": 2984, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count // of the required sub-sequences static int countSubSeq(int i, int sum, int cnt, int []a, int n) { // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) { return 1; } else { return 0; } } int ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans; } // Driver code public static void Main() { int []a = {-1, 2, -2, 1}; int n = a.Length; Console.Write(countSubSeq(0, 0, 0, a, n)); }} // This code is contributed by Akanksha Rai", "e": 4838, "s": 3731, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count// of the required sub-sequencesfunction countSubSeq($i, $sum, $cnt, $a, $n){ // Base case if ($i == $n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if ($sum == 0 && $cnt > 0) return 1; else return 0; } $ans = 0; // Do not take the number in // the current sub-sequence $ans += countSubSeq($i + 1, $sum, $cnt, $a, $n); // Take the number in the // current sub-sequence $ans += countSubSeq($i + 1, $sum + $a[$i], $cnt + 1, $a, $n); return $ans;} // Driver code$a = array( -1, 2, -2, 1 );$n = count($a) ; echo countSubSeq(0, 0, 0, $a, $n); // This code is contributed by Ryuga?>", "e": 5675, "s": 4838, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count// of the required sub-sequencesfunction countSubSeq(i, sum, cnt, a, n){ // Base case if (i == n) { // Check if the sum is 0 // and at least a single element // is in the sub-sequence if (sum == 0 && cnt > 0) return 1; else return 0; } let ans = 0; // Do not take the number in // the current sub-sequence ans += countSubSeq(i + 1, sum, cnt, a, n); // Take the number in the // current sub-sequence ans += countSubSeq(i + 1, sum + a[i], cnt + 1, a, n); return ans;} // Driver code let a = [ -1, 2, -2, 1 ]; let n = a.length; document.write(countSubSeq(0, 0, 0, a, n)); </script>", "e": 6465, "s": 5675, "text": null }, { "code": null, "e": 6467, "s": 6465, "text": "3" }, { "code": null, "e": 6645, "s": 6469, "text": "Time Complexity: O(2N), as we are using recursion and T(N) = O(1) + 2*T(N-1) which will be equivalent to T(N) = (2^N – 1)*O(1). Where N is the number of elements in the array." }, { "code": null, "e": 6705, "s": 6645, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 6713, "s": 6705, "text": "ankthon" }, { "code": null, "e": 6725, "s": 6713, "text": "29AjayKumar" }, { "code": null, "e": 6738, "s": 6725, "text": "Akanksha_Rai" }, { "code": null, "e": 6753, "s": 6738, "text": "mohit kumar 29" }, { "code": null, "e": 6769, "s": 6753, "text": "rishavmahato348" }, { "code": null, "e": 6788, "s": 6769, "text": "rohitkumarsinghcna" }, { "code": null, "e": 6800, "s": 6788, "text": "subsequence" }, { "code": null, "e": 6807, "s": 6800, "text": "Arrays" }, { "code": null, "e": 6821, "s": 6807, "text": "Combinatorial" }, { "code": null, "e": 6831, "s": 6821, "text": "Recursion" }, { "code": null, "e": 6838, "s": 6831, "text": "Arrays" }, { "code": null, "e": 6848, "s": 6838, "text": "Recursion" }, { "code": null, "e": 6862, "s": 6848, "text": "Combinatorial" }, { "code": null, "e": 6960, "s": 6862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6992, "s": 6960, "text": "Introduction to Data Structures" }, { "code": null, "e": 7039, "s": 6992, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7064, "s": 7039, "text": "Window Sliding Technique" }, { "code": null, "e": 7122, "s": 7064, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 7153, "s": 7122, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7213, "s": 7153, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7251, "s": 7213, "text": "Permutation and Combination in Python" }, { "code": null, "e": 7279, "s": 7251, "text": "Factorial of a large number" }, { "code": null, "e": 7316, "s": 7279, "text": "Count of subsets with sum equal to X" } ]
Power in Mathematics
06 Jul, 2022 The power of a number says how many times to use the number in a multiplication. Powers are also called Exponents or Indices. For example, 8^2 could be called “8 to the power 2” or “8 to the second power”, or simply “8 squared”. Some interesting fact about Power : If the indices is 1, then you just have the number itself. For example, 5^1 = 5If the indices is 0, then you get 1. For example, 5^0 = 1Exponents make it easier to write and use many multiplicationsNegative exponent means how many times to divide one by the number.For example, 5^-1 = 1 /5 = 0.2 If the indices is 1, then you just have the number itself. For example, 5^1 = 5 If the indices is 0, then you get 1. For example, 5^0 = 1 Exponents make it easier to write and use many multiplications Negative exponent means how many times to divide one by the number.For example, 5^-1 = 1 /5 = 0.2 How we check if a number is power of y for a given integer x ?Naive solution: Given two positive numbers x and y, check if y is a power of x or not.Examples : Input: x = 10, y = 1 Output: True Input: x = 10, y = 1000 Output: True Input: x = 10, y = 1001 Output: False Approach : A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not. C++ Java Python3 C# PHP Javascript // C++ program to check if a number is power of// another number#include <bits/stdc++.h>using namespace std; /* Returns 1 if y is a power of x */bool isPower(int x, long int y){ // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly comput power of x long int pow = 1; while (pow < y) pow *= x; // Check if power of x becomes y return (pow == y);} /* Driver program to test above function */int main(){ cout << (isPower(10, 1) ? "True" : "False") << endl; cout << (isPower(1, 20) ? "True" : "False") << endl; cout << (isPower(2, 128) ? "True" : "False") << endl; cout << (isPower(2, 30) ? "True" : "False") << endl; return 0;} // Java program to check if a number is power of// another numberpublic class Test { // driver method to test power method public static void main(String[] args) { // check the result for true/false and print. System.out.println(isPower(10, 1) ? "True" : "False"); System.out.println(isPower(1, 20) ? "True" : "False"); System.out.println(isPower(2, 128) ? "True" : "False"); System.out.println(isPower(2, 30) ? "True" : "False"); } /* Returns true if y is a power of x */ public static boolean isPower(int x, int y) { // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly compute power of x int pow = 1; while (pow < y) pow = pow * x; // Check if power of x becomes y return (pow == y); }} # Python program to check# if a number is power of# another number # Returns true if y is a# power of xdef isPower (x, y): # The only power of 1 # is 1 itself if (x == 1): return (y == 1) # Repeatedly compute # power of x pow = 1 while (pow < y): pow = pow * x # Check if power of x # becomes y return (pow == y) # Driver Code# check the result for# true/false and print.if(isPower(10, 1)): print("True")else: print("False") if(isPower(1, 20)): print("True")else: print("False") if(isPower(2, 128)): print("True")else: print("False") if(isPower(2, 30)): print("True")else: print("False") // C# program to check if a number// is power of another numberusing System; class GFG{ // Returns true if y is a power of x public static bool isPower (int x, int y) { // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly compute power of x int pow = 1; while (pow < y) pow = pow * x; // Check if power of x becomes y return (pow == y); } // Driver Code public static void Main () { //check the result for true/false and print. Console.WriteLine(isPower(10, 1) ? "True" : "False"); Console.WriteLine(isPower(1, 20) ? "True" : "False"); Console.WriteLine(isPower(2, 128) ? "True" : "False"); Console.WriteLine(isPower(2, 30) ? "True" : "False"); } } <?php// PHP program to check if a// number is power of another number /* Returns 1 if y is a power of x */function isPower($x, $y){ // The only power of 1 is 1 itself if ($x == 1) return ($y == 1 ? "True" : "False"); // Repeatedly comput power of x $pow = 1; while ($pow < $y) $pow *= $x; // Check if power of x becomes y return ($pow == $y ? "True" : "False");} // Driver Codeecho isPower(10, 1) . "\n";echo isPower(1, 20) . "\n";echo isPower(2, 128) . "\n";echo isPower(2, 30) . "\n"; ?> <script> // Javascript program to check if a number is power of// another number /* Returns 1 if y is a power of x */function isPower( x, y){ // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly comput power of x let pow = 1; while (pow < y) pow *= x; // Check if power of x becomes y return (pow == y);} // Driver Code document.write((isPower(10, 1) ? "True" : "False") + "</br>"); document.write((isPower(1, 20) ? "True" : "False") + "</br>"); document.write((isPower(2, 128) ? "True" : "False") + "</br>"); document.write((isPower(2, 30) ? "True" : "False") + "</br>"); </script> Output: True False True False Time complexity of above solution is O(Logxy) Auxiliary Space: O(1)Basic Program related to Power : Find unit digit of x raised to power y Check if a number can be expressed as x^y (x raised to power y) Find the multiple of x which is closest to a^b All possible numbers of N digits and base B without leading zeros Check if a number can be expressed as a^b | Set 2 Write you own Power without using multiplication(*) and division(/) operators More problems related to Powers : Total number of subsets in which the product of the elements is even Sum of first N natural numbers which are not powers of K GCD of a number raised to some power and another number Largest N digit number divisible by given three numbers Check whether a given Number is Power-Isolated or not Recent Articles on Power! jana_sayantan subham348 maths-power Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2022" }, { "code": null, "e": 259, "s": 28, "text": "The power of a number says how many times to use the number in a multiplication. Powers are also called Exponents or Indices. For example, 8^2 could be called “8 to the power 2” or “8 to the second power”, or simply “8 squared”. " }, { "code": null, "e": 297, "s": 259, "text": "Some interesting fact about Power : " }, { "code": null, "e": 593, "s": 297, "text": "If the indices is 1, then you just have the number itself. For example, 5^1 = 5If the indices is 0, then you get 1. For example, 5^0 = 1Exponents make it easier to write and use many multiplicationsNegative exponent means how many times to divide one by the number.For example, 5^-1 = 1 /5 = 0.2" }, { "code": null, "e": 673, "s": 593, "text": "If the indices is 1, then you just have the number itself. For example, 5^1 = 5" }, { "code": null, "e": 731, "s": 673, "text": "If the indices is 0, then you get 1. For example, 5^0 = 1" }, { "code": null, "e": 794, "s": 731, "text": "Exponents make it easier to write and use many multiplications" }, { "code": null, "e": 892, "s": 794, "text": "Negative exponent means how many times to divide one by the number.For example, 5^-1 = 1 /5 = 0.2" }, { "code": null, "e": 1053, "s": 892, "text": "How we check if a number is power of y for a given integer x ?Naive solution: Given two positive numbers x and y, check if y is a power of x or not.Examples : " }, { "code": null, "e": 1167, "s": 1053, "text": "Input: x = 10, y = 1\nOutput: True\n\nInput: x = 10, y = 1000\nOutput: True\n\nInput: x = 10, y = 1001\nOutput: False" }, { "code": null, "e": 1296, "s": 1167, "text": "Approach : A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not. " }, { "code": null, "e": 1300, "s": 1296, "text": "C++" }, { "code": null, "e": 1305, "s": 1300, "text": "Java" }, { "code": null, "e": 1313, "s": 1305, "text": "Python3" }, { "code": null, "e": 1316, "s": 1313, "text": "C#" }, { "code": null, "e": 1320, "s": 1316, "text": "PHP" }, { "code": null, "e": 1331, "s": 1320, "text": "Javascript" }, { "code": "// C++ program to check if a number is power of// another number#include <bits/stdc++.h>using namespace std; /* Returns 1 if y is a power of x */bool isPower(int x, long int y){ // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly comput power of x long int pow = 1; while (pow < y) pow *= x; // Check if power of x becomes y return (pow == y);} /* Driver program to test above function */int main(){ cout << (isPower(10, 1) ? \"True\" : \"False\") << endl; cout << (isPower(1, 20) ? \"True\" : \"False\") << endl; cout << (isPower(2, 128) ? \"True\" : \"False\") << endl; cout << (isPower(2, 30) ? \"True\" : \"False\") << endl; return 0;}", "e": 2033, "s": 1331, "text": null }, { "code": "// Java program to check if a number is power of// another numberpublic class Test { // driver method to test power method public static void main(String[] args) { // check the result for true/false and print. System.out.println(isPower(10, 1) ? \"True\" : \"False\"); System.out.println(isPower(1, 20) ? \"True\" : \"False\"); System.out.println(isPower(2, 128) ? \"True\" : \"False\"); System.out.println(isPower(2, 30) ? \"True\" : \"False\"); } /* Returns true if y is a power of x */ public static boolean isPower(int x, int y) { // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly compute power of x int pow = 1; while (pow < y) pow = pow * x; // Check if power of x becomes y return (pow == y); }}", "e": 2882, "s": 2033, "text": null }, { "code": "# Python program to check# if a number is power of# another number # Returns true if y is a# power of xdef isPower (x, y): # The only power of 1 # is 1 itself if (x == 1): return (y == 1) # Repeatedly compute # power of x pow = 1 while (pow < y): pow = pow * x # Check if power of x # becomes y return (pow == y) # Driver Code# check the result for# true/false and print.if(isPower(10, 1)): print(\"True\")else: print(\"False\") if(isPower(1, 20)): print(\"True\")else: print(\"False\") if(isPower(2, 128)): print(\"True\")else: print(\"False\") if(isPower(2, 30)): print(\"True\")else: print(\"False\") ", "e": 3542, "s": 2882, "text": null }, { "code": "// C# program to check if a number// is power of another numberusing System; class GFG{ // Returns true if y is a power of x public static bool isPower (int x, int y) { // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly compute power of x int pow = 1; while (pow < y) pow = pow * x; // Check if power of x becomes y return (pow == y); } // Driver Code public static void Main () { //check the result for true/false and print. Console.WriteLine(isPower(10, 1) ? \"True\" : \"False\"); Console.WriteLine(isPower(1, 20) ? \"True\" : \"False\"); Console.WriteLine(isPower(2, 128) ? \"True\" : \"False\"); Console.WriteLine(isPower(2, 30) ? \"True\" : \"False\"); } }", "e": 4354, "s": 3542, "text": null }, { "code": "<?php// PHP program to check if a// number is power of another number /* Returns 1 if y is a power of x */function isPower($x, $y){ // The only power of 1 is 1 itself if ($x == 1) return ($y == 1 ? \"True\" : \"False\"); // Repeatedly comput power of x $pow = 1; while ($pow < $y) $pow *= $x; // Check if power of x becomes y return ($pow == $y ? \"True\" : \"False\");} // Driver Codeecho isPower(10, 1) . \"\\n\";echo isPower(1, 20) . \"\\n\";echo isPower(2, 128) . \"\\n\";echo isPower(2, 30) . \"\\n\"; ?>", "e": 4881, "s": 4354, "text": null }, { "code": "<script> // Javascript program to check if a number is power of// another number /* Returns 1 if y is a power of x */function isPower( x, y){ // The only power of 1 is 1 itself if (x == 1) return (y == 1); // Repeatedly comput power of x let pow = 1; while (pow < y) pow *= x; // Check if power of x becomes y return (pow == y);} // Driver Code document.write((isPower(10, 1) ? \"True\" : \"False\") + \"</br>\"); document.write((isPower(1, 20) ? \"True\" : \"False\") + \"</br>\"); document.write((isPower(2, 128) ? \"True\" : \"False\") + \"</br>\"); document.write((isPower(2, 30) ? \"True\" : \"False\") + \"</br>\"); </script>", "e": 5554, "s": 4881, "text": null }, { "code": null, "e": 5564, "s": 5554, "text": "Output: " }, { "code": null, "e": 5586, "s": 5564, "text": "True\nFalse\nTrue\nFalse" }, { "code": null, "e": 5632, "s": 5586, "text": "Time complexity of above solution is O(Logxy)" }, { "code": null, "e": 5688, "s": 5632, "text": "Auxiliary Space: O(1)Basic Program related to Power : " }, { "code": null, "e": 5727, "s": 5688, "text": "Find unit digit of x raised to power y" }, { "code": null, "e": 5791, "s": 5727, "text": "Check if a number can be expressed as x^y (x raised to power y)" }, { "code": null, "e": 5838, "s": 5791, "text": "Find the multiple of x which is closest to a^b" }, { "code": null, "e": 5904, "s": 5838, "text": "All possible numbers of N digits and base B without leading zeros" }, { "code": null, "e": 5954, "s": 5904, "text": "Check if a number can be expressed as a^b | Set 2" }, { "code": null, "e": 6032, "s": 5954, "text": "Write you own Power without using multiplication(*) and division(/) operators" }, { "code": null, "e": 6068, "s": 6032, "text": "More problems related to Powers : " }, { "code": null, "e": 6137, "s": 6068, "text": "Total number of subsets in which the product of the elements is even" }, { "code": null, "e": 6194, "s": 6137, "text": "Sum of first N natural numbers which are not powers of K" }, { "code": null, "e": 6250, "s": 6194, "text": "GCD of a number raised to some power and another number" }, { "code": null, "e": 6306, "s": 6250, "text": "Largest N digit number divisible by given three numbers" }, { "code": null, "e": 6360, "s": 6306, "text": "Check whether a given Number is Power-Isolated or not" }, { "code": null, "e": 6388, "s": 6360, "text": "Recent Articles on Power! " }, { "code": null, "e": 6402, "s": 6388, "text": "jana_sayantan" }, { "code": null, "e": 6412, "s": 6402, "text": "subham348" }, { "code": null, "e": 6424, "s": 6412, "text": "maths-power" }, { "code": null, "e": 6437, "s": 6424, "text": "Mathematical" }, { "code": null, "e": 6456, "s": 6437, "text": "School Programming" }, { "code": null, "e": 6469, "s": 6456, "text": "Mathematical" }, { "code": null, "e": 6567, "s": 6469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6599, "s": 6567, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6645, "s": 6599, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 6689, "s": 6645, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 6738, "s": 6689, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 6780, "s": 6738, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 6798, "s": 6780, "text": "Python Dictionary" }, { "code": null, "e": 6823, "s": 6798, "text": "Reverse a string in Java" }, { "code": null, "e": 6839, "s": 6823, "text": "Arrays in C/C++" }, { "code": null, "e": 6862, "s": 6839, "text": "Introduction To PYTHON" } ]
Sort an array according to absolute difference with a given value “using constant extra space”
30 Apr, 2021 Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., element having minimum difference comes first and so on, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.Examples: Input : arr[] = {10, 5, 3, 9, 2} x = 7 Output : arr[] = {5, 9, 10, 3, 2} Explanation : 7 - 10 = 3(abs) 7 - 5 = 2 7 - 3 = 4 7 - 9 = 2(abs) 7 - 2 = 5 So according to the difference with X, elements are arranged as 5, 9, 10, 3, 2. Input : arr[] = {1, 2, 3, 4, 5} x = 6 Output : arr[] = {5, 4, 3, 2, 1} The above problem has already been explained in a previous post here. It takes O(n log n) time and O(n) extra space. The below solution though has a relatively bad time complexity i.e O(n^2) but it does the work without using any additional space or memory. The solution is a based on Insertion Sort . For every i (1<= i < n) we compare the absolute value of the difference of arr[i] with the given number x (Let this be ‘diff’ ). We then compare this difference with the difference of abs(arr[j]-x) where 0<= j < i (Let this if abdiff). If diff is greater than abdiff, we shift the values in the array to accommodate arr[i] in it’s correct position. C++ Java Python 3 C# PHP Javascript // C++ program to sort an array based on absolute// difference with a given value x.#include <bits/stdc++.h>using namespace std; void arrange(int arr[], int n, int x){ // Below lines are similar to insertion sort for (int i = 1; i < n; i++) { int diff = abs(arr[i] - x); // Insert arr[i] at correct place int j = i - 1; if (abs(arr[j] - x) > diff) { int temp = arr[i]; while (abs(arr[j] - x) > diff && j >= 0) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } }} // Function to print the arrayvoid print(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Main Functionint main(){ int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; arrange(arr, n, x); print(arr, n); return 0;} // Java program to sort an array based on absolute// difference with a given value x.class GFG { static void arrange(int arr[], int n, int x){ // Below lines are similar to insertion sort for (int i = 1; i < n; i++) { int diff = Math.abs(arr[i] - x); // Insert arr[i] at correct place int j = i - 1; if (Math.abs(arr[j] - x) > diff) { int temp = arr[i]; while (j >= 0 && Math.abs(arr[j] - x) > diff) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } }} // Function to print the arraystatic void print(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Driver codepublic static void main(String[] args) { int arr[] = { 10, 5, 3, 9, 2 }; int n = arr.length; int x = 7; arrange(arr, n, x); print(arr, n); }} // This code is contributed by PrinciRaj1992 # Python 3 program to sort an array# based on absolute difference with# a given value x.def arrange(arr, n, x): # Below lines are similar to # insertion sort for i in range(1, n) : diff = abs(arr[i] - x) # Insert arr[i] at correct place j = i - 1 if (abs(arr[j] - x) > diff) : temp = arr[i] while (abs(arr[j] - x) > diff and j >= 0) : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = temp # Function to print the arraydef print_1(arr, n): for i in range(n): print(arr[i], end = " ") # Driver Codeif __name__ == "__main__": arr = [ 10, 5, 3, 9, 2 ] n = len(arr) x = 7 arrange(arr, n, x) print_1(arr, n) # This code is contributed by ita_c // C# program to sort an array based on absolute// difference with a given value x.using System; class GFG{ static void arrange(int []arr, int n, int x) { // Below lines are similar to insertion sort for (int i = 1; i < n; i++) { int diff = Math.Abs(arr[i] - x); // Insert arr[i] at correct place int j = i - 1; if (Math.Abs(arr[j] - x) > diff) { int temp = arr[i]; while (j >= 0 && Math.Abs(arr[j] - x) > diff) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } } // Function to print the array static void print(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main() { int []arr = { 10, 5, 3, 9, 2 }; int n = arr.Length; int x = 7; arrange(arr, n, x); print(arr, n); }} // This code is contributed by 29AjayKumar <?php// PHP program to sort an array based on// absolute difference with a given value x. function arrange($arr, $n, $x){ // Below lines are similar to // insertion sort for ($i = 1; $i < $n; $i++) { $diff = abs($arr[$i] - $x); // Insert arr[i] at correct place $j = $i - 1; if (abs($arr[$j] - $x) > $diff) { $temp = $arr[$i]; while (abs($arr[$j] - $x) > $diff && $j >= 0) { $arr[$j + 1] = $arr[$j]; $j--; } $arr[$j + 1] = $temp; } } return $arr;} // Function to print the arrayfunction print_arr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Driver Code$arr = array(10, 5, 3, 9, 2);$n = sizeof($arr);$x = 7; $arr1 = arrange($arr, $n, $x);print_arr($arr1, $n); // This code is contributed// by Akanksha Rai?> <script> // Javascript program to sort// an array based on absolute// difference with a given value x. function arrange(arr,n,x) { // Below lines are similar // to insertion sort for (let i = 1; i < n; i++) { let diff = Math.abs(arr[i] - x); // Insert arr[i] at correct place let j = i - 1; if (Math.abs(arr[j] - x) > diff) { let temp = arr[i]; while (j >= 0 && Math.abs(arr[j] - x) > diff) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } } // Function to print the array function print(arr,n) { for (let i = 0; i < n; i++) document.write(arr[i] + " "); } // Driver code let arr=[10, 5, 3, 9, 2 ]; let n = arr.length; let x = 7; arrange(arr, n, x); print(arr, n); // This code is contributed // by avanitrachhadiya2155 </script> Output: 5 9 10 3 2 Time Complexity: O(n^2) where n is the size of the array. Auxiliary Space: O(1)This article is contributed by Rohit Rao. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp Akanksha_Rai princiraj1992 29AjayKumar avanitrachhadiya2155 Insertion Sort Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Longest Common Prefix using Sorting Sort a nearly sorted (or K sorted) array Segregate 0s and 1s in an array Sorting in Java Find whether an array is subset of another array Quick Sort vs Merge Sort Stability in sorting algorithms Find all triplets with zero sum
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Apr, 2021" }, { "code": null, "e": 385, "s": 54, "text": "Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., element having minimum difference comes first and so on, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.Examples: " }, { "code": null, "e": 716, "s": 385, "text": "Input : arr[] = {10, 5, 3, 9, 2}\n x = 7\nOutput : arr[] = {5, 9, 10, 3, 2}\nExplanation : \n7 - 10 = 3(abs)\n7 - 5 = 2\n7 - 3 = 4 \n7 - 9 = 2(abs)\n7 - 2 = 5\nSo according to the difference with X, \nelements are arranged as 5, 9, 10, 3, 2.\n\nInput : arr[] = {1, 2, 3, 4, 5}\n x = 6\nOutput : arr[] = {5, 4, 3, 2, 1}" }, { "code": null, "e": 1370, "s": 718, "text": "The above problem has already been explained in a previous post here. It takes O(n log n) time and O(n) extra space. The below solution though has a relatively bad time complexity i.e O(n^2) but it does the work without using any additional space or memory. The solution is a based on Insertion Sort . For every i (1<= i < n) we compare the absolute value of the difference of arr[i] with the given number x (Let this be ‘diff’ ). We then compare this difference with the difference of abs(arr[j]-x) where 0<= j < i (Let this if abdiff). If diff is greater than abdiff, we shift the values in the array to accommodate arr[i] in it’s correct position. " }, { "code": null, "e": 1374, "s": 1370, "text": "C++" }, { "code": null, "e": 1379, "s": 1374, "text": "Java" }, { "code": null, "e": 1388, "s": 1379, "text": "Python 3" }, { "code": null, "e": 1391, "s": 1388, "text": "C#" }, { "code": null, "e": 1395, "s": 1391, "text": "PHP" }, { "code": null, "e": 1406, "s": 1395, "text": "Javascript" }, { "code": "// C++ program to sort an array based on absolute// difference with a given value x.#include <bits/stdc++.h>using namespace std; void arrange(int arr[], int n, int x){ // Below lines are similar to insertion sort for (int i = 1; i < n; i++) { int diff = abs(arr[i] - x); // Insert arr[i] at correct place int j = i - 1; if (abs(arr[j] - x) > diff) { int temp = arr[i]; while (abs(arr[j] - x) > diff && j >= 0) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } }} // Function to print the arrayvoid print(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Main Functionint main(){ int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; arrange(arr, n, x); print(arr, n); return 0;}", "e": 2286, "s": 1406, "text": null }, { "code": "// Java program to sort an array based on absolute// difference with a given value x.class GFG { static void arrange(int arr[], int n, int x){ // Below lines are similar to insertion sort for (int i = 1; i < n; i++) { int diff = Math.abs(arr[i] - x); // Insert arr[i] at correct place int j = i - 1; if (Math.abs(arr[j] - x) > diff) { int temp = arr[i]; while (j >= 0 && Math.abs(arr[j] - x) > diff) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } }} // Function to print the arraystatic void print(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");} // Driver codepublic static void main(String[] args) { int arr[] = { 10, 5, 3, 9, 2 }; int n = arr.length; int x = 7; arrange(arr, n, x); print(arr, n); }} // This code is contributed by PrinciRaj1992", "e": 3231, "s": 2286, "text": null }, { "code": "# Python 3 program to sort an array# based on absolute difference with# a given value x.def arrange(arr, n, x): # Below lines are similar to # insertion sort for i in range(1, n) : diff = abs(arr[i] - x) # Insert arr[i] at correct place j = i - 1 if (abs(arr[j] - x) > diff) : temp = arr[i] while (abs(arr[j] - x) > diff and j >= 0) : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = temp # Function to print the arraydef print_1(arr, n): for i in range(n): print(arr[i], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [ 10, 5, 3, 9, 2 ] n = len(arr) x = 7 arrange(arr, n, x) print_1(arr, n) # This code is contributed by ita_c", "e": 4029, "s": 3231, "text": null }, { "code": "// C# program to sort an array based on absolute// difference with a given value x.using System; class GFG{ static void arrange(int []arr, int n, int x) { // Below lines are similar to insertion sort for (int i = 1; i < n; i++) { int diff = Math.Abs(arr[i] - x); // Insert arr[i] at correct place int j = i - 1; if (Math.Abs(arr[j] - x) > diff) { int temp = arr[i]; while (j >= 0 && Math.Abs(arr[j] - x) > diff) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } } // Function to print the array static void print(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main() { int []arr = { 10, 5, 3, 9, 2 }; int n = arr.Length; int x = 7; arrange(arr, n, x); print(arr, n); }} // This code is contributed by 29AjayKumar", "e": 5118, "s": 4029, "text": null }, { "code": "<?php// PHP program to sort an array based on// absolute difference with a given value x. function arrange($arr, $n, $x){ // Below lines are similar to // insertion sort for ($i = 1; $i < $n; $i++) { $diff = abs($arr[$i] - $x); // Insert arr[i] at correct place $j = $i - 1; if (abs($arr[$j] - $x) > $diff) { $temp = $arr[$i]; while (abs($arr[$j] - $x) > $diff && $j >= 0) { $arr[$j + 1] = $arr[$j]; $j--; } $arr[$j + 1] = $temp; } } return $arr;} // Function to print the arrayfunction print_arr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \";} // Driver Code$arr = array(10, 5, 3, 9, 2);$n = sizeof($arr);$x = 7; $arr1 = arrange($arr, $n, $x);print_arr($arr1, $n); // This code is contributed// by Akanksha Rai?>", "e": 6023, "s": 5118, "text": null }, { "code": "<script> // Javascript program to sort// an array based on absolute// difference with a given value x. function arrange(arr,n,x) { // Below lines are similar // to insertion sort for (let i = 1; i < n; i++) { let diff = Math.abs(arr[i] - x); // Insert arr[i] at correct place let j = i - 1; if (Math.abs(arr[j] - x) > diff) { let temp = arr[i]; while (j >= 0 && Math.abs(arr[j] - x) > diff) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } } // Function to print the array function print(arr,n) { for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); } // Driver code let arr=[10, 5, 3, 9, 2 ]; let n = arr.length; let x = 7; arrange(arr, n, x); print(arr, n); // This code is contributed // by avanitrachhadiya2155 </script>", "e": 7011, "s": 6023, "text": null }, { "code": null, "e": 7021, "s": 7011, "text": "Output: " }, { "code": null, "e": 7032, "s": 7021, "text": "5 9 10 3 2" }, { "code": null, "e": 7528, "s": 7032, "text": "Time Complexity: O(n^2) where n is the size of the array. Auxiliary Space: O(1)This article is contributed by Rohit Rao. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7534, "s": 7528, "text": "ukasp" }, { "code": null, "e": 7547, "s": 7534, "text": "Akanksha_Rai" }, { "code": null, "e": 7561, "s": 7547, "text": "princiraj1992" }, { "code": null, "e": 7573, "s": 7561, "text": "29AjayKumar" }, { "code": null, "e": 7594, "s": 7573, "text": "avanitrachhadiya2155" }, { "code": null, "e": 7609, "s": 7594, "text": "Insertion Sort" }, { "code": null, "e": 7617, "s": 7609, "text": "Sorting" }, { "code": null, "e": 7625, "s": 7617, "text": "Sorting" }, { "code": null, "e": 7723, "s": 7625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7754, "s": 7723, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7790, "s": 7754, "text": "Longest Common Prefix using Sorting" }, { "code": null, "e": 7831, "s": 7790, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 7863, "s": 7831, "text": "Segregate 0s and 1s in an array" }, { "code": null, "e": 7879, "s": 7863, "text": "Sorting in Java" }, { "code": null, "e": 7928, "s": 7879, "text": "Find whether an array is subset of another array" }, { "code": null, "e": 7953, "s": 7928, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 7985, "s": 7953, "text": "Stability in sorting algorithms" } ]
Convert Character String to Variable Name in R
09 May, 2021 In this article we will discuss how to convert a character string to the variable name in the R programming language i.e. we are going to assign the character string to the variable as the variable name We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function. Syntax: assign(“variable_name”,value) Parameter: variable_name is the name of the value value is the variable. Example: R # assign variable name to 3 valueassign("variable_name",3) # print variable nameprint(variable_name) Output: [1] 3 We can also create a vector with a group of variables and assign a single variable name. Example: R # create 5 variables at a timeassign("vector1",c(1,2,3,4,5)) # print variable nameprint(vector1) Output: [1] 1 2 3 4 5 This function allows you to call any R function. It allows using a list to hold the arguments of the function along with passing of single arguments. Syntax: do.call(“=”,list(“variable_name”, value)) Where “=” is an assign operator The variable name is the named assigned to the value and value is the input value/variable. Example: R do.call("=",list("a", 1)) print(a) Output: [1] 1 Example: R do.call("=",list("a", c(1,2,3,4,5))) print(a) Output: [1] 1 2 3 4 5 Picked R-strings R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2021" }, { "code": null, "e": 231, "s": 28, "text": "In this article we will discuss how to convert a character string to the variable name in the R programming language i.e. we are going to assign the character string to the variable as the variable name" }, { "code": null, "e": 386, "s": 231, "text": "We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function." }, { "code": null, "e": 424, "s": 386, "text": "Syntax: assign(“variable_name”,value)" }, { "code": null, "e": 435, "s": 424, "text": "Parameter:" }, { "code": null, "e": 474, "s": 435, "text": "variable_name is the name of the value" }, { "code": null, "e": 497, "s": 474, "text": "value is the variable." }, { "code": null, "e": 506, "s": 497, "text": "Example:" }, { "code": null, "e": 508, "s": 506, "text": "R" }, { "code": "# assign variable name to 3 valueassign(\"variable_name\",3) # print variable nameprint(variable_name)", "e": 610, "s": 508, "text": null }, { "code": null, "e": 618, "s": 610, "text": "Output:" }, { "code": null, "e": 624, "s": 618, "text": "[1] 3" }, { "code": null, "e": 713, "s": 624, "text": "We can also create a vector with a group of variables and assign a single variable name." }, { "code": null, "e": 722, "s": 713, "text": "Example:" }, { "code": null, "e": 724, "s": 722, "text": "R" }, { "code": "# create 5 variables at a timeassign(\"vector1\",c(1,2,3,4,5)) # print variable nameprint(vector1)", "e": 822, "s": 724, "text": null }, { "code": null, "e": 830, "s": 822, "text": "Output:" }, { "code": null, "e": 844, "s": 830, "text": "[1] 1 2 3 4 5" }, { "code": null, "e": 994, "s": 844, "text": "This function allows you to call any R function. It allows using a list to hold the arguments of the function along with passing of single arguments." }, { "code": null, "e": 1002, "s": 994, "text": "Syntax:" }, { "code": null, "e": 1044, "s": 1002, "text": "do.call(“=”,list(“variable_name”, value))" }, { "code": null, "e": 1076, "s": 1044, "text": "Where “=” is an assign operator" }, { "code": null, "e": 1168, "s": 1076, "text": "The variable name is the named assigned to the value and value is the input value/variable." }, { "code": null, "e": 1177, "s": 1168, "text": "Example:" }, { "code": null, "e": 1179, "s": 1177, "text": "R" }, { "code": "do.call(\"=\",list(\"a\", 1)) print(a)", "e": 1215, "s": 1179, "text": null }, { "code": null, "e": 1223, "s": 1215, "text": "Output:" }, { "code": null, "e": 1229, "s": 1223, "text": "[1] 1" }, { "code": null, "e": 1238, "s": 1229, "text": "Example:" }, { "code": null, "e": 1240, "s": 1238, "text": "R" }, { "code": "do.call(\"=\",list(\"a\", c(1,2,3,4,5))) print(a)", "e": 1287, "s": 1240, "text": null }, { "code": null, "e": 1295, "s": 1287, "text": "Output:" }, { "code": null, "e": 1310, "s": 1295, "text": "[1] 1 2 3 4 5 " }, { "code": null, "e": 1317, "s": 1310, "text": "Picked" }, { "code": null, "e": 1327, "s": 1317, "text": "R-strings" }, { "code": null, "e": 1338, "s": 1327, "text": "R Language" }, { "code": null, "e": 1349, "s": 1338, "text": "R Programs" } ]
Find sum of sum of all sub-sequences
07 Jul, 2022 Given an array of n integers. The task is to find the sum of each sub-sequence of the array. Examples : Input : arr[] = { 6, 8, 5 } Output : 76 All subsequence sum are: { 6 }, sum = 6 { 8 }, sum = 8 { 5 }, sum = 5 { 6, 8 }, sum = 14 { 6, 5 }, sum = 11 { 8, 5 }, sum = 13 { 6, 8, 5 }, sum = 19 Total sum = 76. Input : arr[] = {1, 2} Output : 6 Method 1 (brute force): Generate all the sub-sequence and find the sum of each sub-sequence. Method 2 (efficient approach): For an array of size n, we have 2^n sub-sequences (including empty) in total. Observe, in total 2n sub-sequences, each element occurs 2n-1 times. For example, arr[] = { 5, 6, 7 } So, the sum of all sub-sequence will be (sum of all the elements) * 2n-1. Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find sum of all sub-sequences// of an array.#include<bits/stdc++.h>using namespace std; // Return sum of sum of all sub-sequence.int sum(int arr[], int n){ int ans = 0; // Finding sum of the array. for (int i = 0; i < n; i++) ans += arr[i]; return ans * pow(2, n - 1);} // Driver Codeint main(){ int arr[] = { 6, 7, 8 }; int n = sizeof(arr)/sizeof(arr[0]); cout << sum(arr, n) << endl; return 0;} // Java program to find sum of// all sub-sequences of an array.import java.io.*;import java.math.*; class GFG { // Return sum of sum of all sub-sequence. static int sum(int arr[], int n) { int ans = 0; // Finding sum of the array. for (int i = 0; i < n; i++) ans += arr[i]; return ans * (int)(Math.pow(2, n - 1)); } // Driver Code public static void main(String args[]) { int arr[]= { 6, 7, 8 }; int n = arr.length; System.out.println(sum(arr, n)); }} // This code is contributed by Nikita Tiwari. # Python 3 program to find sum of# all sub-sequences of an array. # Return sum of sum of all sub-sequence.def sm(arr , n) : ans = 0 # Finding sum of the array. for i in range(0, n) : ans = ans + arr[i] return ans * pow(2, n - 1) # Driver Codearr = [ 6, 7, 8 ]n=len(arr) print(sm(arr, n)) # This code is contributed by Nikita Tiwari. // C# program to find sum of// all sub-sequences of an array.using System; class GFG{ // Return sum of sum of all sub-sequence. static int sum(int []arr, int n) { int ans = 0; // Finding sum of the array. for (int i = 0; i < n; i++) ans += arr[i]; return ans * (int)(Math.Pow(2, n - 1)); } // Driver Code public static void Main() { int []arr= { 6, 7, 8 }; int n = arr.Length; Console.Write(sum(arr, n)); }} // This code is contributed by nitin mittal <?php// PHP program to find sum of// all sub-sequences of an array. // Return sum of sum of// all sub-sequence.function sum($arr, $n){ $ans = 0; // Finding sum of the array. for ($i = 0; $i < $n; $i++) $ans += $arr[$i]; return $ans * pow(2, $n - 1);} // Driver Code$arr = array(6, 7, 8);$n = sizeof($arr);echo sum($arr, $n) ; // This code is contributed by nitin mittal.?> <script> // JavaScript program to find sum of all sub-sequences// of an array. // Return sum of sum of all sub-sequence.function sum(arr, n){ var ans = 0; // Finding sum of the array. for (var i = 0; i < n; i++) ans += arr[i]; return ans * Math.pow(2, n - 1);} // Driver Codevar arr = [6, 7, 8];var n = arr.length;document.write( sum(arr, n)); </script> 84 Time complexity: O(n)Auxiliary space: O(1) This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal Majorssn noob2000 shaheeneallamaiqbal hardikkoriintern subsequence Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 145, "s": 52, "text": "Given an array of n integers. The task is to find the sum of each sub-sequence of the array." }, { "code": null, "e": 157, "s": 145, "text": "Examples : " }, { "code": null, "e": 398, "s": 157, "text": "Input : arr[] = { 6, 8, 5 }\nOutput : 76\nAll subsequence sum are:\n{ 6 }, sum = 6\n{ 8 }, sum = 8\n{ 5 }, sum = 5\n{ 6, 8 }, sum = 14\n{ 6, 5 }, sum = 11\n{ 8, 5 }, sum = 13\n{ 6, 8, 5 }, sum = 19\nTotal sum = 76.\n\nInput : arr[] = {1, 2}\nOutput : 6" }, { "code": null, "e": 491, "s": 398, "text": "Method 1 (brute force): Generate all the sub-sequence and find the sum of each sub-sequence." }, { "code": null, "e": 702, "s": 491, "text": "Method 2 (efficient approach): For an array of size n, we have 2^n sub-sequences (including empty) in total. Observe, in total 2n sub-sequences, each element occurs 2n-1 times. For example, arr[] = { 5, 6, 7 } " }, { "code": null, "e": 776, "s": 702, "text": "So, the sum of all sub-sequence will be (sum of all the elements) * 2n-1." }, { "code": null, "e": 824, "s": 776, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 828, "s": 824, "text": "C++" }, { "code": null, "e": 833, "s": 828, "text": "Java" }, { "code": null, "e": 841, "s": 833, "text": "Python3" }, { "code": null, "e": 844, "s": 841, "text": "C#" }, { "code": null, "e": 848, "s": 844, "text": "PHP" }, { "code": null, "e": 859, "s": 848, "text": "Javascript" }, { "code": "// C++ program to find sum of all sub-sequences// of an array.#include<bits/stdc++.h>using namespace std; // Return sum of sum of all sub-sequence.int sum(int arr[], int n){ int ans = 0; // Finding sum of the array. for (int i = 0; i < n; i++) ans += arr[i]; return ans * pow(2, n - 1);} // Driver Codeint main(){ int arr[] = { 6, 7, 8 }; int n = sizeof(arr)/sizeof(arr[0]); cout << sum(arr, n) << endl; return 0;}", "e": 1289, "s": 859, "text": null }, { "code": "// Java program to find sum of// all sub-sequences of an array.import java.io.*;import java.math.*; class GFG { // Return sum of sum of all sub-sequence. static int sum(int arr[], int n) { int ans = 0; // Finding sum of the array. for (int i = 0; i < n; i++) ans += arr[i]; return ans * (int)(Math.pow(2, n - 1)); } // Driver Code public static void main(String args[]) { int arr[]= { 6, 7, 8 }; int n = arr.length; System.out.println(sum(arr, n)); }} // This code is contributed by Nikita Tiwari.", "e": 1868, "s": 1289, "text": null }, { "code": "# Python 3 program to find sum of# all sub-sequences of an array. # Return sum of sum of all sub-sequence.def sm(arr , n) : ans = 0 # Finding sum of the array. for i in range(0, n) : ans = ans + arr[i] return ans * pow(2, n - 1) # Driver Codearr = [ 6, 7, 8 ]n=len(arr) print(sm(arr, n)) # This code is contributed by Nikita Tiwari.", "e": 2237, "s": 1868, "text": null }, { "code": "// C# program to find sum of// all sub-sequences of an array.using System; class GFG{ // Return sum of sum of all sub-sequence. static int sum(int []arr, int n) { int ans = 0; // Finding sum of the array. for (int i = 0; i < n; i++) ans += arr[i]; return ans * (int)(Math.Pow(2, n - 1)); } // Driver Code public static void Main() { int []arr= { 6, 7, 8 }; int n = arr.Length; Console.Write(sum(arr, n)); }} // This code is contributed by nitin mittal", "e": 2770, "s": 2237, "text": null }, { "code": "<?php// PHP program to find sum of// all sub-sequences of an array. // Return sum of sum of// all sub-sequence.function sum($arr, $n){ $ans = 0; // Finding sum of the array. for ($i = 0; $i < $n; $i++) $ans += $arr[$i]; return $ans * pow(2, $n - 1);} // Driver Code$arr = array(6, 7, 8);$n = sizeof($arr);echo sum($arr, $n) ; // This code is contributed by nitin mittal.?>", "e": 3168, "s": 2770, "text": null }, { "code": "<script> // JavaScript program to find sum of all sub-sequences// of an array. // Return sum of sum of all sub-sequence.function sum(arr, n){ var ans = 0; // Finding sum of the array. for (var i = 0; i < n; i++) ans += arr[i]; return ans * Math.pow(2, n - 1);} // Driver Codevar arr = [6, 7, 8];var n = arr.length;document.write( sum(arr, n)); </script>", "e": 3531, "s": 3168, "text": null }, { "code": null, "e": 3535, "s": 3531, "text": "84\n" }, { "code": null, "e": 3581, "s": 3535, "text": "Time complexity: O(n)Auxiliary space: O(1) " }, { "code": null, "e": 3877, "s": 3581, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3890, "s": 3877, "text": "nitin mittal" }, { "code": null, "e": 3899, "s": 3890, "text": "Majorssn" }, { "code": null, "e": 3908, "s": 3899, "text": "noob2000" }, { "code": null, "e": 3928, "s": 3908, "text": "shaheeneallamaiqbal" }, { "code": null, "e": 3945, "s": 3928, "text": "hardikkoriintern" }, { "code": null, "e": 3957, "s": 3945, "text": "subsequence" }, { "code": null, "e": 3964, "s": 3957, "text": "Arrays" }, { "code": null, "e": 3971, "s": 3964, "text": "Arrays" }, { "code": null, "e": 4069, "s": 3971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4137, "s": 4069, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 4181, "s": 4137, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 4213, "s": 4181, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4261, "s": 4213, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 4275, "s": 4261, "text": "Linear Search" }, { "code": null, "e": 4298, "s": 4275, "text": "Introduction to Arrays" }, { "code": null, "e": 4354, "s": 4298, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 4381, "s": 4354, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 4413, "s": 4381, "text": "Introduction to Data Structures" } ]
How to Create Volatile Table in Teradata?
11 Aug, 2021 Volatile tables are as same as simple tables but with a small difference i.e. they are volatile in nature. Like a simple table, the volatile table is also formed by the user and can only be used until the user is logged into. Once the user is logged off or disconnects, the Teradata manager automatically drops the table from the session. After dropping the table by Teradata manager, the data and definition inserted in the volatile table will be erased automatically. Suppose, you are the user and working with the Teradata database and you have to form a couple of tables in the same database. The first option is you have to create simple tables in the same database and drop them after use. The second option is you can create volatile tables whose data and definition are automatically dropped by the Teradata database after you logged off from the database and that will be the more smart way. We will follow the below syntax for volatile table syntax. Syntax: CREATE [SET | MULTISET] VOLATILE TABLE TABEL_NAME ( COLUMN1 DATATYPE; COLUMN2 DATATYPE; . . . COLUMN_N datatype) <INDEX_DEFINITION> ON COMMIT [DELETE|PRESERVE] ROWS; Example: The following example will create a volatile table of the name ‘geek’. CREATE VOLATILE TABLE GEEK ( ROLLNO INT, FIRST_NAME VARCHAR(15), LAST_NAME VARCHAR(15) ) PRIMARY INDEX (ROLLNO) ON COMMIT PRESERVE ROWS; Here, you can clearly see the last line written as ON COMMIT PRESERVE ROWS this line will preserve the data after inserting it by you. The default value is ON COMMIT DELETE ROWS. Data insertion in the volatile table: Let’s insert some data in the volatile table. INSERT INTO GEEK VALUES (1,'Aman','Goyal'); INSERT INTO GEEK VALUES (2,'Pritam','Soni'); INSERT INTO GEEK VALUES (3,'Swati','Jain'); Select data from the volatile table: We will run the select statement into the volatile table. SELECT * FROM GEEK ORDER BY ROLLNO; Output: At last, if we disconnect from the current session and after re-logging, run the same select statement again, we will find that the table student does not exist anymore in the database. SELECT * FROM GEEK ORDER BY ROLLNO; *** Failure 3807 Object 'GEEK' does not exist. Statement# 1, Info =0 *** Total elapsed time was 1 second Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 160, "s": 52, "text": "Volatile tables are as same as simple tables but with a small difference i.e. they are volatile in nature. " }, { "code": null, "e": 392, "s": 160, "text": "Like a simple table, the volatile table is also formed by the user and can only be used until the user is logged into. Once the user is logged off or disconnects, the Teradata manager automatically drops the table from the session." }, { "code": null, "e": 523, "s": 392, "text": "After dropping the table by Teradata manager, the data and definition inserted in the volatile table will be erased automatically." }, { "code": null, "e": 749, "s": 523, "text": "Suppose, you are the user and working with the Teradata database and you have to form a couple of tables in the same database. The first option is you have to create simple tables in the same database and drop them after use." }, { "code": null, "e": 955, "s": 749, "text": "The second option is you can create volatile tables whose data and definition are automatically dropped by the Teradata database after you logged off from the database and that will be the more smart way. " }, { "code": null, "e": 1014, "s": 955, "text": "We will follow the below syntax for volatile table syntax." }, { "code": null, "e": 1022, "s": 1014, "text": "Syntax:" }, { "code": null, "e": 1190, "s": 1022, "text": "CREATE [SET | MULTISET] VOLATILE TABLE TABEL_NAME \n(\nCOLUMN1 DATATYPE;\nCOLUMN2 DATATYPE;\n.\n.\n.\nCOLUMN_N datatype)\n<INDEX_DEFINITION>\nON COMMIT [DELETE|PRESERVE] ROWS;\n" }, { "code": null, "e": 1199, "s": 1190, "text": "Example:" }, { "code": null, "e": 1270, "s": 1199, "text": "The following example will create a volatile table of the name ‘geek’." }, { "code": null, "e": 1408, "s": 1270, "text": "CREATE VOLATILE TABLE GEEK\n(\nROLLNO INT,\nFIRST_NAME VARCHAR(15),\nLAST_NAME VARCHAR(15)\n)\nPRIMARY INDEX (ROLLNO)\nON COMMIT PRESERVE ROWS;\n" }, { "code": null, "e": 1543, "s": 1408, "text": "Here, you can clearly see the last line written as ON COMMIT PRESERVE ROWS this line will preserve the data after inserting it by you." }, { "code": null, "e": 1587, "s": 1543, "text": "The default value is ON COMMIT DELETE ROWS." }, { "code": null, "e": 1625, "s": 1587, "text": "Data insertion in the volatile table:" }, { "code": null, "e": 1671, "s": 1625, "text": "Let’s insert some data in the volatile table." }, { "code": null, "e": 1805, "s": 1671, "text": "INSERT INTO GEEK VALUES (1,'Aman','Goyal');\nINSERT INTO GEEK VALUES (2,'Pritam','Soni');\nINSERT INTO GEEK VALUES (3,'Swati','Jain');\n" }, { "code": null, "e": 1842, "s": 1805, "text": "Select data from the volatile table:" }, { "code": null, "e": 1900, "s": 1842, "text": "We will run the select statement into the volatile table." }, { "code": null, "e": 1936, "s": 1900, "text": "SELECT * FROM GEEK ORDER BY ROLLNO;" }, { "code": null, "e": 1944, "s": 1936, "text": "Output:" }, { "code": null, "e": 2130, "s": 1944, "text": "At last, if we disconnect from the current session and after re-logging, run the same select statement again, we will find that the table student does not exist anymore in the database." }, { "code": null, "e": 2271, "s": 2130, "text": "SELECT * FROM GEEK ORDER BY ROLLNO;\n*** Failure 3807 Object 'GEEK' does not exist.\nStatement# 1, Info =0\n*** Total elapsed time was 1 second" }, { "code": null, "e": 2278, "s": 2271, "text": "Picked" }, { "code": null, "e": 2288, "s": 2278, "text": "SQL-Query" }, { "code": null, "e": 2292, "s": 2288, "text": "SQL" }, { "code": null, "e": 2296, "s": 2292, "text": "SQL" }, { "code": null, "e": 2394, "s": 2296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2460, "s": 2394, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2484, "s": 2460, "text": "Window functions in SQL" }, { "code": null, "e": 2516, "s": 2484, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2549, "s": 2516, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2566, "s": 2549, "text": "SQL using Python" }, { "code": null, "e": 2596, "s": 2566, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2674, "s": 2596, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2710, "s": 2674, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2741, "s": 2710, "text": "SQL Query to Compare Two Dates" } ]
Minimization of Boolean Functions
25 Nov, 2019 As discussed in the “Representation of Boolean Functions” every boolean function can be expressed as a sum of minterms or a product of maxterms. Since the number of literals in such an expression is usually high, and the complexity of the digital logic gates that implement a Boolean function is directly related to the complexity of the algebraic expression from which the function is implemented, it is preferable to have the most simplified form of the algebraic expression.The process of simplifying the algebraic expression of a boolean function is called minimization. Minimization is important since it reduces the cost and complexity of the associated circuit.For example, the function can be minimized to . The circuits associated with above expressions is –It is clear from the above image that the minimized version of the expression takes a less number of logic gates and also reduces the complexity of the circuit substantially. Minimization is hence important to find the most economic equivalent representation of a boolean function.Minimization can be done using Algebraic Manipulation or K-Map method. Each method has it’s own merits and demerits. Minimization using Algebraic Manipulation – This method is the simplest of all methods used for minimization. It is suitable for medium sized expressions involving 4 or 5 variables. Algebraic manipulation is a manual method, hence it is prone to human error.Common Laws used in algebraic manipulation : Example 1 – Minimize the following boolean function using algebraic manipulation- Solution – Properties refer to the three common laws mentioned above. Minimization using K-Map – The Algebraic manipulation method is tedious and cumbersome. The K-Map method is faster and can be used to solve boolean functions of upto 5 variables. Please refer this link to learn more about K-Map. Example 2 – Consider the same expression from example-1 and minimize it using K-Map. Solution – The following is a 4 variable K-Map of the given expression.The above figure highlights the prime implicants in green, red and blue.The green one spans the whole third row, which gives us – The red one spans 4 squares, which gives us – The blue one spans 4 squares, which gives us – So, the minimized boolean expression is- GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. 1. GATE CS 2012, Question 302. GATE CS 2007, Question 323. GATE CS 2014 Set-3, Question 174. GATE CS 2005, Question 185. GATE CS 2004, Question 176. GATE CS 2003, Question 457. GATE CS 2002, Question 12 References- K-Map – WikipediaDigital Design, 5th edition by Morris Mano and Michael Ciletti This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers Difference between RAM and ROM Introduction to memory and memory units Analog to Digital Conversion Difference between Half adder and full adder Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2019" }, { "code": null, "e": 1218, "s": 52, "text": "As discussed in the “Representation of Boolean Functions” every boolean function can be expressed as a sum of minterms or a product of maxterms. Since the number of literals in such an expression is usually high, and the complexity of the digital logic gates that implement a Boolean function is directly related to the complexity of the algebraic expression from which the function is implemented, it is preferable to have the most simplified form of the algebraic expression.The process of simplifying the algebraic expression of a boolean function is called minimization. Minimization is important since it reduces the cost and complexity of the associated circuit.For example, the function can be minimized to . The circuits associated with above expressions is –It is clear from the above image that the minimized version of the expression takes a less number of logic gates and also reduces the complexity of the circuit substantially. Minimization is hence important to find the most economic equivalent representation of a boolean function.Minimization can be done using Algebraic Manipulation or K-Map method. Each method has it’s own merits and demerits." }, { "code": null, "e": 1262, "s": 1218, "text": "Minimization using Algebraic Manipulation –" }, { "code": null, "e": 1521, "s": 1262, "text": "This method is the simplest of all methods used for minimization. It is suitable for medium sized expressions involving 4 or 5 variables. Algebraic manipulation is a manual method, hence it is prone to human error.Common Laws used in algebraic manipulation :" }, { "code": null, "e": 1603, "s": 1521, "text": "Example 1 – Minimize the following boolean function using algebraic manipulation-" }, { "code": null, "e": 1677, "s": 1603, "text": "Solution – Properties refer to the three common laws mentioned above. " }, { "code": null, "e": 1709, "s": 1682, "text": "Minimization using K-Map –" }, { "code": null, "e": 1911, "s": 1709, "text": "The Algebraic manipulation method is tedious and cumbersome. The K-Map method is faster and can be used to solve boolean functions of upto 5 variables. Please refer this link to learn more about K-Map." }, { "code": null, "e": 1996, "s": 1911, "text": "Example 2 – Consider the same expression from example-1 and minimize it using K-Map." }, { "code": null, "e": 2332, "s": 1996, "text": "Solution – The following is a 4 variable K-Map of the given expression.The above figure highlights the prime implicants in green, red and blue.The green one spans the whole third row, which gives us – The red one spans 4 squares, which gives us – The blue one spans 4 squares, which gives us – So, the minimized boolean expression is- " }, { "code": null, "e": 2357, "s": 2332, "text": "GATE CS Corner Questions" }, { "code": null, "e": 2555, "s": 2357, "text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 2758, "s": 2555, "text": "1. GATE CS 2012, Question 302. GATE CS 2007, Question 323. GATE CS 2014 Set-3, Question 174. GATE CS 2005, Question 185. GATE CS 2004, Question 176. GATE CS 2003, Question 457. GATE CS 2002, Question 12" }, { "code": null, "e": 2770, "s": 2758, "text": "References-" }, { "code": null, "e": 2850, "s": 2770, "text": "K-Map – WikipediaDigital Design, 5th edition by Morris Mano and Michael Ciletti" }, { "code": null, "e": 3152, "s": 2850, "text": "This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3277, "s": 3152, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3312, "s": 3277, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 3320, "s": 3312, "text": "GATE CS" }, { "code": null, "e": 3418, "s": 3320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3459, "s": 3418, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 3490, "s": 3459, "text": "Difference between RAM and ROM" }, { "code": null, "e": 3530, "s": 3490, "text": "Introduction to memory and memory units" }, { "code": null, "e": 3559, "s": 3530, "text": "Analog to Digital Conversion" }, { "code": null, "e": 3604, "s": 3559, "text": "Difference between Half adder and full adder" }, { "code": null, "e": 3624, "s": 3604, "text": "Layers of OSI Model" }, { "code": null, "e": 3648, "s": 3624, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3675, "s": 3648, "text": "Types of Operating Systems" }, { "code": null, "e": 3688, "s": 3675, "text": "TCP/IP Model" } ]
Method Class | getGenericParameterTypes() method in Java
04 Nov, 2019 The java.lang.reflect.Method.getGenericParameterTypes() method of Method class returns an array of Type objects that represent the parameter types, declared in method at time of coding. It means that the getGenericParameterTypes() method returns array of parameters that belongs to method object. It returns an array of length 0 if the method object takes no parameters. If a formal parameter type is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters used in the source code. e.g for method public void getValue(T value){} substitute a type parameter T with a parameterized type (i.e., List) then method will return “java.util.List” as parameter type. Syntax: public Type[] getGenericParameterTypes() Return Value: This method returns an array of Types that represent the formal parameter types of the method object, in declaration order. Exception: This method throws following exceptions: GenericSignatureFormatError – if the generic method signature is not same as the format specified in The JVM Specification. TypeNotPresentException – if parameter types refers to a non-existent type declaration. MalformedParameterizedTypeException – if the underlying parameter types refers to a parameterized type that cannot be instantiated for any reason. Below programs illustrates getGenericParameterTypes() method of Method class: Program 1: Print all Parameter type declared for Method // Program Demonstrate how to apply getGenericParameterTypes() method// of Method Class. import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = demoClass.class; // get Method Object Method[] methods = classobj.getMethods(); // iterate through methods for (Method method : methods) { // only taking method defined in the demo class if (method.getName().equals("setValue") || method.getName().equals("getValue") || method.getName().equals("setManyValues")) { // apply getGenericParameterTypes() method Type[] parameters = method.getGenericParameterTypes(); // print parameter Types of method Object System.out.println("\nMethod Name : " + method.getName()); System.out.println("No of Parameters : " + parameters.length); System.out.println("Parameter object details:"); for (Type type : parameters) { System.out.println(type.getTypeName()); } } } } catch (Exception e) { e.printStackTrace(); } }}// a simple classclass demoClass { // method containing two parameter public void setValue(String value1, String value2) { System.out.println("setValue"); } // method containing no parameter public String getValue() { System.out.println("getValue"); return "getValue"; } // method containg many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println("setManyValues"); }} Method Name : setManyValues No of Parameters : 3 Parameter object details: int double java.lang.String Method Name : getValue No of Parameters : 0 Parameter object details: Method Name : setValue No of Parameters : 2 Parameter object details: java.lang.String java.lang.String Program 2: Check if the Method object contains parameter or not // Program Demonstrate how to apply getGenericParameterTypes()// method of Method Class.import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = sample.class; Method[] methods = classobj.getMethods(); /*check whether setManyValues() method contains int parameter or not and print no of string parameter it contains*/ for (Method method : methods) { if (method.getName().equals("setValue")) { int count = containsParameter( method, (Type)java.lang.String.class); System.out.println("No of String" + " Parameters in setValue(): " + count); } } // check whether setManyValues() method // contains int parameter or not // and print no of string parameter it contains for (Method method : methods) { if (method.getName().equals("setManyValues")) { int count = containsParameter(method, (Type) int.class); System.out.println("No of int Parameters" + " in setManyValues(): " + count); } } } catch (Exception e) { e.printStackTrace(); } } // count no of parameters contain by // method same as passed to method private static int containsParameter(Method method, Type parameterName) { int count = 0; // get all parameter types list // using getGenericParameterTypes() Type parameters[] = method.getGenericParameterTypes(); for (int i = 0; i < parameters.length; i++) { // check contains parameter or not if (parameters[i] == parameterName) { count++; } } return count; }}// a simple classclass sample { // method containing two parameter public void setValue(String value1, String value2) { System.out.println("setValue"); } // method containing many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println("setManyValues"); }} No of String Parameters in setValue(): 2 No of int Parameters in setManyValues(): 1 Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getGenericParameterTypes– Akanksha_Rai Java-Functions Java-lang package java-lang-reflect-package Java-Method Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Nov, 2019" }, { "code": null, "e": 399, "s": 28, "text": "The java.lang.reflect.Method.getGenericParameterTypes() method of Method class returns an array of Type objects that represent the parameter types, declared in method at time of coding. It means that the getGenericParameterTypes() method returns array of parameters that belongs to method object. It returns an array of length 0 if the method object takes no parameters." }, { "code": null, "e": 735, "s": 399, "text": "If a formal parameter type is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters used in the source code. e.g for method public void getValue(T value){} substitute a type parameter T with a parameterized type (i.e., List) then method will return “java.util.List” as parameter type." }, { "code": null, "e": 743, "s": 735, "text": "Syntax:" }, { "code": null, "e": 784, "s": 743, "text": "public Type[] getGenericParameterTypes()" }, { "code": null, "e": 922, "s": 784, "text": "Return Value: This method returns an array of Types that represent the formal parameter types of the method object, in declaration order." }, { "code": null, "e": 974, "s": 922, "text": "Exception: This method throws following exceptions:" }, { "code": null, "e": 1098, "s": 974, "text": "GenericSignatureFormatError – if the generic method signature is not same as the format specified in The JVM Specification." }, { "code": null, "e": 1186, "s": 1098, "text": "TypeNotPresentException – if parameter types refers to a non-existent type declaration." }, { "code": null, "e": 1333, "s": 1186, "text": "MalformedParameterizedTypeException – if the underlying parameter types refers to a parameterized type that cannot be instantiated for any reason." }, { "code": null, "e": 1411, "s": 1333, "text": "Below programs illustrates getGenericParameterTypes() method of Method class:" }, { "code": null, "e": 1467, "s": 1411, "text": "Program 1: Print all Parameter type declared for Method" }, { "code": "// Program Demonstrate how to apply getGenericParameterTypes() method// of Method Class. import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = demoClass.class; // get Method Object Method[] methods = classobj.getMethods(); // iterate through methods for (Method method : methods) { // only taking method defined in the demo class if (method.getName().equals(\"setValue\") || method.getName().equals(\"getValue\") || method.getName().equals(\"setManyValues\")) { // apply getGenericParameterTypes() method Type[] parameters = method.getGenericParameterTypes(); // print parameter Types of method Object System.out.println(\"\\nMethod Name : \" + method.getName()); System.out.println(\"No of Parameters : \" + parameters.length); System.out.println(\"Parameter object details:\"); for (Type type : parameters) { System.out.println(type.getTypeName()); } } } } catch (Exception e) { e.printStackTrace(); } }}// a simple classclass demoClass { // method containing two parameter public void setValue(String value1, String value2) { System.out.println(\"setValue\"); } // method containing no parameter public String getValue() { System.out.println(\"getValue\"); return \"getValue\"; } // method containg many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println(\"setManyValues\"); }}", "e": 3511, "s": 1467, "text": null }, { "code": null, "e": 3791, "s": 3511, "text": "Method Name : setManyValues\nNo of Parameters : 3\nParameter object details:\nint\ndouble\njava.lang.String\n\nMethod Name : getValue\nNo of Parameters : 0\nParameter object details:\n\nMethod Name : setValue\nNo of Parameters : 2\nParameter object details:\njava.lang.String\njava.lang.String\n" }, { "code": null, "e": 3855, "s": 3791, "text": "Program 2: Check if the Method object contains parameter or not" }, { "code": "// Program Demonstrate how to apply getGenericParameterTypes()// method of Method Class.import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = sample.class; Method[] methods = classobj.getMethods(); /*check whether setManyValues() method contains int parameter or not and print no of string parameter it contains*/ for (Method method : methods) { if (method.getName().equals(\"setValue\")) { int count = containsParameter( method, (Type)java.lang.String.class); System.out.println(\"No of String\" + \" Parameters in setValue(): \" + count); } } // check whether setManyValues() method // contains int parameter or not // and print no of string parameter it contains for (Method method : methods) { if (method.getName().equals(\"setManyValues\")) { int count = containsParameter(method, (Type) int.class); System.out.println(\"No of int Parameters\" + \" in setManyValues(): \" + count); } } } catch (Exception e) { e.printStackTrace(); } } // count no of parameters contain by // method same as passed to method private static int containsParameter(Method method, Type parameterName) { int count = 0; // get all parameter types list // using getGenericParameterTypes() Type parameters[] = method.getGenericParameterTypes(); for (int i = 0; i < parameters.length; i++) { // check contains parameter or not if (parameters[i] == parameterName) { count++; } } return count; }}// a simple classclass sample { // method containing two parameter public void setValue(String value1, String value2) { System.out.println(\"setValue\"); } // method containing many parameter public void setManyValues(int value1, double value2, String value3) { System.out.println(\"setManyValues\"); }}", "e": 6529, "s": 3855, "text": null }, { "code": null, "e": 6614, "s": 6529, "text": "No of String Parameters in setValue(): 2\nNo of int Parameters in setManyValues(): 1\n" }, { "code": null, "e": 6723, "s": 6614, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getGenericParameterTypes–" }, { "code": null, "e": 6736, "s": 6723, "text": "Akanksha_Rai" }, { "code": null, "e": 6751, "s": 6736, "text": "Java-Functions" }, { "code": null, "e": 6769, "s": 6751, "text": "Java-lang package" }, { "code": null, "e": 6795, "s": 6769, "text": "java-lang-reflect-package" }, { "code": null, "e": 6813, "s": 6795, "text": "Java-Method Class" }, { "code": null, "e": 6818, "s": 6813, "text": "Java" }, { "code": null, "e": 6823, "s": 6818, "text": "Java" }, { "code": null, "e": 6921, "s": 6823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6936, "s": 6921, "text": "Stream In Java" }, { "code": null, "e": 6957, "s": 6936, "text": "Introduction to Java" }, { "code": null, "e": 6978, "s": 6957, "text": "Constructors in Java" }, { "code": null, "e": 6997, "s": 6978, "text": "Exceptions in Java" }, { "code": null, "e": 7014, "s": 6997, "text": "Generics in Java" }, { "code": null, "e": 7044, "s": 7014, "text": "Functional Interfaces in Java" }, { "code": null, "e": 7070, "s": 7044, "text": "Java Programming Examples" }, { "code": null, "e": 7086, "s": 7070, "text": "Strings in Java" }, { "code": null, "e": 7123, "s": 7086, "text": "Differences between JDK, JRE and JVM" } ]
Find the number of primitive roots modulo prime
29 Jun, 2022 Given a prime . The task is to count all the primitive roots of .A primitive root is an integer x (1 <= x < p) such that none of the integers x – 1, x2 – 1, ...., xp – 2 – 1 are divisible by but xp – 1 – 1 is divisible by . Examples: Input: P = 3 Output: 1 The only primitive root modulo 3 is 2. Input: P = 5 Output: 2 Primitive roots modulo 5 are 2 and 3. Approach: There is always at least one primitive root for all primes. So, using Eulers totient function we can say that f(p-1) is the required answer where f(n) is euler totient function.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find the number of// primitive roots modulo prime#include <bits/stdc++.h>using namespace std; // Function to return the count of// primitive roots modulo pint countPrimitiveRoots(int p){ int result = 1; for (int i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver codeint main(){ int p = 5; cout << countPrimitiveRoots(p - 1); return 0;} // Java program to find the number of// primitive roots modulo prime import java.io.*; class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to return the count of// primitive roots modulo pstatic int countPrimitiveRoots(int p){ int result = 1; for (int i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver code public static void main (String[] args) { int p = 5; System.out.println( countPrimitiveRoots(p - 1)); }}// This code is contributed by anuj_67.. # Python 3 program to find the number# of primitive roots modulo primefrom math import gcd # Function to return the count of# primitive roots modulo pdef countPrimitiveRoots(p): result = 1 for i in range(2, p, 1): if (gcd(i, p) == 1): result += 1 return result # Driver codeif __name__ == '__main__': p = 5 print(countPrimitiveRoots(p - 1)) # This code is contributed by# Surendra_Gangwar // C# program to find the number of// primitive roots modulo prime using System; class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to return the count of// primitive roots modulo pstatic int countPrimitiveRoots(int p){ int result = 1; for (int i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver code static public void Main (String []args) { int p = 5; Console.WriteLine( countPrimitiveRoots(p - 1)); }}// This code is contributed by Arnab Kundu <?php// PHP program to find the number of// primitive roots modulo prime // Recursive function to return// gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if ($a == 0) return b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // Function to return the count of// primitive roots modulo pfunction countPrimitiveRoots($p){ $result = 1; for ($i = 2; $i < $p; $i++) if (__gcd($i, $p) == 1) $result++; return $result;} // Driver code$p = 5; echo countPrimitiveRoots($p - 1); // This code is contributed by anuj_67?> <script> // Javascript program to find the number of// primitive roots modulo prime // Recursive function to return gcd of a and b function __gcd( a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to return the count of// primitive roots modulo pfunction countPrimitiveRoots(p){ var result = 1; for (var i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver codevar p = 5;document.write( countPrimitiveRoots(p - 1)); </script> 2 Time Complexity: O(p * log(min(a, b))), where a and b are two parameters of gcd. Auxiliary Space: O(log(min(a, b))) inderDuMCA andrew1234 vt_m SURENDRA_GANGWAR itsok vansikasharma1329 euler-totient Modular Arithmetic number-theory Prime Number Competitive Programming Mathematical number-theory Mathematical Prime Number Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Algorithm Library | C++ Magicians STL Algorithm Bitwise Hacks for Competitive Programming Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2022" }, { "code": null, "e": 264, "s": 28, "text": "Given a prime . The task is to count all the primitive roots of .A primitive root is an integer x (1 <= x < p) such that none of the integers x – 1, x2 – 1, ...., xp – 2 – 1 are divisible by but xp – 1 – 1 is divisible by . Examples: " }, { "code": null, "e": 389, "s": 264, "text": "Input: P = 3 Output: 1 The only primitive root modulo 3 is 2. Input: P = 5 Output: 2 Primitive roots modulo 5 are 2 and 3. " }, { "code": null, "e": 631, "s": 391, "text": "Approach: There is always at least one primitive root for all primes. So, using Eulers totient function we can say that f(p-1) is the required answer where f(n) is euler totient function.Below is the implementation of the above approach: " }, { "code": null, "e": 635, "s": 631, "text": "C++" }, { "code": null, "e": 640, "s": 635, "text": "Java" }, { "code": null, "e": 648, "s": 640, "text": "Python3" }, { "code": null, "e": 651, "s": 648, "text": "C#" }, { "code": null, "e": 655, "s": 651, "text": "PHP" }, { "code": null, "e": 666, "s": 655, "text": "Javascript" }, { "code": "// CPP program to find the number of// primitive roots modulo prime#include <bits/stdc++.h>using namespace std; // Function to return the count of// primitive roots modulo pint countPrimitiveRoots(int p){ int result = 1; for (int i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver codeint main(){ int p = 5; cout << countPrimitiveRoots(p - 1); return 0;}", "e": 1086, "s": 666, "text": null }, { "code": "// Java program to find the number of// primitive roots modulo prime import java.io.*; class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to return the count of// primitive roots modulo pstatic int countPrimitiveRoots(int p){ int result = 1; for (int i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver code public static void main (String[] args) { int p = 5; System.out.println( countPrimitiveRoots(p - 1)); }}// This code is contributed by anuj_67..", "e": 1964, "s": 1086, "text": null }, { "code": "# Python 3 program to find the number# of primitive roots modulo primefrom math import gcd # Function to return the count of# primitive roots modulo pdef countPrimitiveRoots(p): result = 1 for i in range(2, p, 1): if (gcd(i, p) == 1): result += 1 return result # Driver codeif __name__ == '__main__': p = 5 print(countPrimitiveRoots(p - 1)) # This code is contributed by# Surendra_Gangwar", "e": 2388, "s": 1964, "text": null }, { "code": "// C# program to find the number of// primitive roots modulo prime using System; class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to return the count of// primitive roots modulo pstatic int countPrimitiveRoots(int p){ int result = 1; for (int i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver code static public void Main (String []args) { int p = 5; Console.WriteLine( countPrimitiveRoots(p - 1)); }}// This code is contributed by Arnab Kundu", "e": 3294, "s": 2388, "text": null }, { "code": "<?php// PHP program to find the number of// primitive roots modulo prime // Recursive function to return// gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if ($a == 0) return b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // Function to return the count of// primitive roots modulo pfunction countPrimitiveRoots($p){ $result = 1; for ($i = 2; $i < $p; $i++) if (__gcd($i, $p) == 1) $result++; return $result;} // Driver code$p = 5; echo countPrimitiveRoots($p - 1); // This code is contributed by anuj_67?>", "e": 4004, "s": 3294, "text": null }, { "code": "<script> // Javascript program to find the number of// primitive roots modulo prime // Recursive function to return gcd of a and b function __gcd( a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to return the count of// primitive roots modulo pfunction countPrimitiveRoots(p){ var result = 1; for (var i = 2; i < p; i++) if (__gcd(i, p) == 1) result++; return result;} // Driver codevar p = 5;document.write( countPrimitiveRoots(p - 1)); </script>", "e": 4724, "s": 4004, "text": null }, { "code": null, "e": 4726, "s": 4724, "text": "2" }, { "code": null, "e": 4809, "s": 4728, "text": "Time Complexity: O(p * log(min(a, b))), where a and b are two parameters of gcd." }, { "code": null, "e": 4844, "s": 4809, "text": "Auxiliary Space: O(log(min(a, b)))" }, { "code": null, "e": 4855, "s": 4844, "text": "inderDuMCA" }, { "code": null, "e": 4866, "s": 4855, "text": "andrew1234" }, { "code": null, "e": 4871, "s": 4866, "text": "vt_m" }, { "code": null, "e": 4888, "s": 4871, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 4894, "s": 4888, "text": "itsok" }, { "code": null, "e": 4912, "s": 4894, "text": "vansikasharma1329" }, { "code": null, "e": 4926, "s": 4912, "text": "euler-totient" }, { "code": null, "e": 4945, "s": 4926, "text": "Modular Arithmetic" }, { "code": null, "e": 4959, "s": 4945, "text": "number-theory" }, { "code": null, "e": 4972, "s": 4959, "text": "Prime Number" }, { "code": null, "e": 4996, "s": 4972, "text": "Competitive Programming" }, { "code": null, "e": 5009, "s": 4996, "text": "Mathematical" }, { "code": null, "e": 5023, "s": 5009, "text": "number-theory" }, { "code": null, "e": 5036, "s": 5023, "text": "Mathematical" }, { "code": null, "e": 5049, "s": 5036, "text": "Prime Number" }, { "code": null, "e": 5068, "s": 5049, "text": "Modular Arithmetic" }, { "code": null, "e": 5166, "s": 5068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5244, "s": 5166, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 5282, "s": 5244, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 5341, "s": 5282, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 5389, "s": 5341, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 5431, "s": 5389, "text": "Bitwise Hacks for Competitive Programming" }, { "code": null, "e": 5461, "s": 5431, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 5504, "s": 5461, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5564, "s": 5504, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5579, "s": 5564, "text": "C++ Data Types" } ]
Python | Extract Strings with only Alphabets
22 Apr, 2020 Sometimes, while working with Python lists, we can have a problem in which we need to extract only those strings which contains only alphabets and discard those which include digits. This has application in day-day programming and web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using isalpha() + list comprehensionThe combination of above functions can be used to perform this task. In this, we extract the string which are alphabets only using isalpha() and compile whole logic using list comprehension. # Python3 code to demonstrate working of # Extract Alphabet only Strings# Using isalpha() + list comprehension # initializing listtest_list = ['gfg', 'is23', 'best', 'for2', 'geeks'] # printing original listprint("The original list is : " + str(test_list)) # Extract Alphabet only Strings# Using isalpha() + list comprehensionres = [sub for sub in test_list if sub.isalpha()] # printing result print("Strings after filtering : " + str(res)) The original list is : ['gfg', 'is23', 'best', 'for2', 'geeks'] Strings after filtering : ['gfg', 'best', 'geeks'] Method #2 : Using filter() + lambdaThe combination of above methods can be used to perform this task. In this, we perform filtering using filter() and logic for extension to all strings is done using lambda. # Python3 code to demonstrate working of # Extract Alphabet only Strings# Using filter() + lambda # initializing listtest_list = ['gfg', 'is23', 'best', 'for2', 'geeks'] # printing original listprint("The original list is : " + str(test_list)) # Extract Alphabet only Strings# Using filter() + lambdares = list(filter(lambda sub: sub.isalpha(), test_list)) # printing result print("Strings after filtering : " + str(res)) The original list is : ['gfg', 'is23', 'best', 'for2', 'geeks'] Strings after filtering : ['gfg', 'best', 'geeks'] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 346, "s": 28, "text": "Sometimes, while working with Python lists, we can have a problem in which we need to extract only those strings which contains only alphabets and discard those which include digits. This has application in day-day programming and web development domain. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 585, "s": 346, "text": "Method #1 : Using isalpha() + list comprehensionThe combination of above functions can be used to perform this task. In this, we extract the string which are alphabets only using isalpha() and compile whole logic using list comprehension." }, { "code": "# Python3 code to demonstrate working of # Extract Alphabet only Strings# Using isalpha() + list comprehension # initializing listtest_list = ['gfg', 'is23', 'best', 'for2', 'geeks'] # printing original listprint(\"The original list is : \" + str(test_list)) # Extract Alphabet only Strings# Using isalpha() + list comprehensionres = [sub for sub in test_list if sub.isalpha()] # printing result print(\"Strings after filtering : \" + str(res)) ", "e": 1031, "s": 585, "text": null }, { "code": null, "e": 1147, "s": 1031, "text": "The original list is : ['gfg', 'is23', 'best', 'for2', 'geeks']\nStrings after filtering : ['gfg', 'best', 'geeks']\n" }, { "code": null, "e": 1357, "s": 1149, "text": "Method #2 : Using filter() + lambdaThe combination of above methods can be used to perform this task. In this, we perform filtering using filter() and logic for extension to all strings is done using lambda." }, { "code": "# Python3 code to demonstrate working of # Extract Alphabet only Strings# Using filter() + lambda # initializing listtest_list = ['gfg', 'is23', 'best', 'for2', 'geeks'] # printing original listprint(\"The original list is : \" + str(test_list)) # Extract Alphabet only Strings# Using filter() + lambdares = list(filter(lambda sub: sub.isalpha(), test_list)) # printing result print(\"Strings after filtering : \" + str(res)) ", "e": 1784, "s": 1357, "text": null }, { "code": null, "e": 1900, "s": 1784, "text": "The original list is : ['gfg', 'is23', 'best', 'for2', 'geeks']\nStrings after filtering : ['gfg', 'best', 'geeks']\n" }, { "code": null, "e": 1921, "s": 1900, "text": "Python list-programs" }, { "code": null, "e": 1944, "s": 1921, "text": "Python string-programs" }, { "code": null, "e": 1951, "s": 1944, "text": "Python" }, { "code": null, "e": 1967, "s": 1951, "text": "Python Programs" }, { "code": null, "e": 2065, "s": 1967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2083, "s": 2065, "text": "Python Dictionary" }, { "code": null, "e": 2125, "s": 2083, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2147, "s": 2125, "text": "Enumerate() in Python" }, { "code": null, "e": 2182, "s": 2147, "text": "Read a file line by line in Python" }, { "code": null, "e": 2214, "s": 2182, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2257, "s": 2214, "text": "Python program to convert a list to string" }, { "code": null, "e": 2279, "s": 2257, "text": "Defaultdict in Python" }, { "code": null, "e": 2318, "s": 2279, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2356, "s": 2318, "text": "Python | Convert a list to dictionary" } ]
How to trigger onchange event on input type=range while dragging in Firefox ?
21 Jun, 2019 Onchange: Onchange executes a JavaScript when a user changes the state of a select element. This attribute occurs only when the element becomes unfocused. Syntax: <select onchange="function()"> Attribute Value: It works on <select> element and fires the given JavaScript after the value is committed. Example: <!DOCTYPE html><html> <head> <title>Onchange</title> <script type="text/javascript"> function Optionselection(select) { var chosen = select.options[select.selectedIndex]; alert("Option Chosen by you is " + chosen.value); } </script></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Choose an option from the following:</p> <select onchange="Optionselection (this)"> <option value="C++" />C++ <option value="Java" />Java <option value="Python" />Python </select> </center></body> </html> Output:Before: After: It is a frequent UI design for a range slider to showcase the immediate change in the depicted value as the user moves the slider. This is not the case for the above-mentioned browser (chrome included).Although, one could argue that Firefox showcases the correct behavior because the onchange event executes only when the control loses focus (be it mouse drag or keyboard). But in order to display the changing value along with the moving slider, one needs to apply the oninput event attribute. Oninput: Much like the onchange event, this attribute works when it receives user input value. The main difference being its immediate execution when the value of element changes. Syntax: <element oninput = "script"> Program to illustrate Solution: <!DOCTYPE html><html> <head> <title>onchange event on input type=range</title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>onchange event on input "type=range"</p> <span id="value"></span> <input type="range" min="1" max="10" step="1" oninput="DisplayChange(this.value)"> <script> function DisplayChange(newvalue) { document.getElementById( "value").innerHTML = newvalue; } </script> </center></body> </html> Output:Before: After: JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2019" }, { "code": null, "e": 183, "s": 28, "text": "Onchange: Onchange executes a JavaScript when a user changes the state of a select element. This attribute occurs only when the element becomes unfocused." }, { "code": null, "e": 191, "s": 183, "text": "Syntax:" }, { "code": null, "e": 223, "s": 191, "text": "<select onchange=\"function()\">\n" }, { "code": null, "e": 330, "s": 223, "text": "Attribute Value: It works on <select> element and fires the given JavaScript after the value is committed." }, { "code": null, "e": 339, "s": 330, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Onchange</title> <script type=\"text/javascript\"> function Optionselection(select) { var chosen = select.options[select.selectedIndex]; alert(\"Option Chosen by you is \" + chosen.value); } </script></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Choose an option from the following:</p> <select onchange=\"Optionselection (this)\"> <option value=\"C++\" />C++ <option value=\"Java\" />Java <option value=\"Python\" />Python </select> </center></body> </html>", "e": 969, "s": 339, "text": null }, { "code": null, "e": 984, "s": 969, "text": "Output:Before:" }, { "code": null, "e": 991, "s": 984, "text": "After:" }, { "code": null, "e": 1486, "s": 991, "text": "It is a frequent UI design for a range slider to showcase the immediate change in the depicted value as the user moves the slider. This is not the case for the above-mentioned browser (chrome included).Although, one could argue that Firefox showcases the correct behavior because the onchange event executes only when the control loses focus (be it mouse drag or keyboard). But in order to display the changing value along with the moving slider, one needs to apply the oninput event attribute." }, { "code": null, "e": 1666, "s": 1486, "text": "Oninput: Much like the onchange event, this attribute works when it receives user input value. The main difference being its immediate execution when the value of element changes." }, { "code": null, "e": 1674, "s": 1666, "text": "Syntax:" }, { "code": null, "e": 1703, "s": 1674, "text": "<element oninput = \"script\">" }, { "code": null, "e": 1735, "s": 1703, "text": "Program to illustrate Solution:" }, { "code": "<!DOCTYPE html><html> <head> <title>onchange event on input type=range</title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>onchange event on input \"type=range\"</p> <span id=\"value\"></span> <input type=\"range\" min=\"1\" max=\"10\" step=\"1\" oninput=\"DisplayChange(this.value)\"> <script> function DisplayChange(newvalue) { document.getElementById( \"value\").innerHTML = newvalue; } </script> </center></body> </html>", "e": 2338, "s": 1735, "text": null }, { "code": null, "e": 2353, "s": 2338, "text": "Output:Before:" }, { "code": null, "e": 2360, "s": 2353, "text": "After:" }, { "code": null, "e": 2376, "s": 2360, "text": "JavaScript-Misc" }, { "code": null, "e": 2383, "s": 2376, "text": "Picked" }, { "code": null, "e": 2394, "s": 2383, "text": "JavaScript" }, { "code": null, "e": 2411, "s": 2394, "text": "Web Technologies" } ]
PHP | get_headers() Function
20 May, 2019 The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request. Syntax: get_headers( $url, $format, $context ) Parameters: This function accepts three parameters as mentioned above and described below: $url: It is a mandatory parameter of type string. It defines the target URL. $format: It is an optional parameter of type int. If its value is set to non-zero it will return an associative array otherwise indexed array. $context: It holds the valid resource context created by stream_context_create() function. Example 1: In this example, value of optional parameter $format is not assigned. <?php // Target URL$url = "https://www.geeksforgeeks.org"; // Fetching headers$headers = get_headers($url); // Printing headersprint_r($headers);?> Output: Array ( [0] => HTTP/1.1 200 OK [1] => Content-Type: text/html; charset=UTF-8 [2] => Connection: close [3] => Date: Sun, 19 May 2019 08:31:29 GMT [4] => Server: Apache [5] => Strict-Transport-Security: max-age=3600; includeSubDomains [6] => Cache-Control: s-maxage=21600, max-age=3, must-revalidate [7] => Access-Control-Allow-Credentials: true [8] => X-Frame-Options: DENY [9] => X-Content-Type-Options: nosniff [10] => Vary: Accept-Encoding, Cookie [11] => X-Cache: Miss from cloudfront [12] => Via: 1.1 aa0bb866c09b4e243eb9a97bcdb7fe32.cloudfront.net (CloudFront) [13] => X-Amz-Cf-Id: QAOIIj4eBsrX0hyZ-UHjOtqA2dQePcLbEUZJ3KRohjsSPfcrcAFaiQ== ) Example 2: In this example, value of optional parameter $format is set to non-zero. <?php // Target URL$url = "https://www.geeksforgeeks.org"; // Fetching headers$headers = get_headers($url, 1); // Printing headersprint_r($headers);?> Output: Array ( [0] => HTTP/1.1 200 OK [Content-Type] => text/html; charset=UTF-8 [Connection] => close [Date] => Sun, 19 May 2019 08:35:47 GMT [Server] => Apache [Strict-Transport-Security] => max-age=3600; includeSubDomains [Cache-Control] => s-maxage=21600, max-age=3, must-revalidate [Access-Control-Allow-Credentials] => true [X-Frame-Options] => DENY [X-Content-Type-Options] => nosniff [Vary] => Accept-Encoding, Cookie [X-Cache] => Miss from cloudfront [Via] => 1.1 95d17b4d563934eb90636ad03f8f524e.cloudfront.net (CloudFront) [X-Amz-Cf-Id] => se3QRyaWDeuHI3GrisMzAr4FJBamqMtbUNzhTPqAJhBoQZbWvy3UPw== ) PHP-function PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to check whether an array is empty using PHP? Comparing two dates in PHP How to get parameters from a URL string in PHP?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2019" }, { "code": null, "e": 150, "s": 28, "text": "The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request." }, { "code": null, "e": 158, "s": 150, "text": "Syntax:" }, { "code": null, "e": 197, "s": 158, "text": "get_headers( $url, $format, $context )" }, { "code": null, "e": 288, "s": 197, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 365, "s": 288, "text": "$url: It is a mandatory parameter of type string. It defines the target URL." }, { "code": null, "e": 508, "s": 365, "text": "$format: It is an optional parameter of type int. If its value is set to non-zero it will return an associative array otherwise indexed array." }, { "code": null, "e": 599, "s": 508, "text": "$context: It holds the valid resource context created by stream_context_create() function." }, { "code": null, "e": 680, "s": 599, "text": "Example 1: In this example, value of optional parameter $format is not assigned." }, { "code": "<?php // Target URL$url = \"https://www.geeksforgeeks.org\"; // Fetching headers$headers = get_headers($url); // Printing headersprint_r($headers);?>", "e": 831, "s": 680, "text": null }, { "code": null, "e": 839, "s": 831, "text": "Output:" }, { "code": null, "e": 1571, "s": 839, "text": "Array (\n [0] => HTTP/1.1 200 OK \n [1] => Content-Type: text/html; charset=UTF-8 \n [2] => Connection: close \n [3] => Date: Sun, 19 May 2019 08:31:29 GMT \n [4] => Server: Apache \n [5] => Strict-Transport-Security: max-age=3600; includeSubDomains \n [6] => Cache-Control: s-maxage=21600, max-age=3, must-revalidate \n [7] => Access-Control-Allow-Credentials: true \n [8] => X-Frame-Options: DENY \n [9] => X-Content-Type-Options: nosniff \n [10] => Vary: Accept-Encoding, Cookie \n [11] => X-Cache: Miss from cloudfront \n [12] => Via: 1.1 aa0bb866c09b4e243eb9a97bcdb7fe32.cloudfront.net (CloudFront) \n [13] => X-Amz-Cf-Id: QAOIIj4eBsrX0hyZ-UHjOtqA2dQePcLbEUZJ3KRohjsSPfcrcAFaiQ== \n) \n" }, { "code": null, "e": 1655, "s": 1571, "text": "Example 2: In this example, value of optional parameter $format is set to non-zero." }, { "code": "<?php // Target URL$url = \"https://www.geeksforgeeks.org\"; // Fetching headers$headers = get_headers($url, 1); // Printing headersprint_r($headers);?>", "e": 1809, "s": 1655, "text": null }, { "code": null, "e": 1817, "s": 1809, "text": "Output:" }, { "code": null, "e": 2549, "s": 1817, "text": "Array ( \n [0] => HTTP/1.1 200 OK \n [Content-Type] => text/html; charset=UTF-8 \n [Connection] => close \n [Date] => Sun, 19 May 2019 08:35:47 GMT \n [Server] => Apache \n [Strict-Transport-Security] => max-age=3600; includeSubDomains \n [Cache-Control] => s-maxage=21600, max-age=3, must-revalidate \n [Access-Control-Allow-Credentials] => true \n [X-Frame-Options] => DENY \n [X-Content-Type-Options] => nosniff \n [Vary] => Accept-Encoding, Cookie \n [X-Cache] => Miss from cloudfront \n [Via] => 1.1 95d17b4d563934eb90636ad03f8f524e.cloudfront.net (CloudFront) \n [X-Amz-Cf-Id] => se3QRyaWDeuHI3GrisMzAr4FJBamqMtbUNzhTPqAJhBoQZbWvy3UPw== \n) \n" }, { "code": null, "e": 2562, "s": 2549, "text": "PHP-function" }, { "code": null, "e": 2566, "s": 2562, "text": "PHP" }, { "code": null, "e": 2579, "s": 2566, "text": "PHP Programs" }, { "code": null, "e": 2596, "s": 2579, "text": "Web Technologies" }, { "code": null, "e": 2600, "s": 2596, "text": "PHP" }, { "code": null, "e": 2698, "s": 2600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2748, "s": 2698, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2788, "s": 2748, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2838, "s": 2788, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2883, "s": 2838, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2910, "s": 2883, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2960, "s": 2910, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3000, "s": 2960, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3050, "s": 3000, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 3077, "s": 3050, "text": "Comparing two dates in PHP" } ]
How to enable routing and navigation between component pages in Angular 8 ?
27 May, 2020 The task is to enable routing between angular components by making their routes when a user clicks the link, it will be navigated to page link corresponding to the required component. Let us know what is routing in Angular Angular 8 routing: The Angular 8 Router helps to navigate between pages that are being triggered by the user’s actions. The navigation happens when the user clicks on the link or enter the URL from the browser address bar. The link can contain the reference to the router on which the user will be directed. We can also pass other parameters with a link through angular routing. Approach: Create an Angular app.syntax:ng new app_name syntax: ng new app_name For routing you will need components, here we have made two components (home and dash) to display home page and dashboard.syntax:ng g c component_name syntax: ng g c component_name In app.module.ts, import RouterModule from @angular/router.syntax:import { RouterModule } from '@angular/router'; syntax: import { RouterModule } from '@angular/router'; Then in imports of app.module.ts define the paths.imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'dash', component:DashComponent } ]) ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'dash', component:DashComponent } ]) ], Now for HTML part, define the HTML for app.component.html. In link, define routerLink’s path as the component name.<a routerLink="/home">Home </a><br> <a routerLink="/dash">dashboard</a> <a routerLink="/home">Home </a><br> <a routerLink="/dash">dashboard</a> Apply router-outlet for your application in app.component.html.The routed views render in the <router-outlet><router-outlet></router-outlet> <router-outlet></router-outlet> Now just define HTML for home.component.html and dash.component.html file. Your angular web-app is ready. Code Implementation: app.module.ts:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { RouterModule } from '@angular/router';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HomeComponent } from './home/home.component';import { DashComponent } from './dash/dash.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, DashComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'dash', component:DashComponent } ]) ], providers: [], bootstrap: [AppComponent]})export class AppModule { } app.module.ts: import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { RouterModule } from '@angular/router';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HomeComponent } from './home/home.component';import { DashComponent } from './dash/dash.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, DashComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'dash', component:DashComponent } ]) ], providers: [], bootstrap: [AppComponent]})export class AppModule { } app.component.html<a routerLink="/home">Home </a><br><a routerLink="/dash">dashboard</a><router-outlet></router-outlet> app.component.html <a routerLink="/home">Home </a><br><a routerLink="/dash">dashboard</a><router-outlet></router-outlet> home.component.html<h1>GeeksforGeeks</h1> home.component.html <h1>GeeksforGeeks</h1> dash.component.html<h1>Hey GEEKS! Welcome to Dashboard</h1> dash.component.html <h1>Hey GEEKS! Welcome to Dashboard</h1> Output: Run the development server and click on the links: AngularJS-Misc AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2020" }, { "code": null, "e": 212, "s": 28, "text": "The task is to enable routing between angular components by making their routes when a user clicks the link, it will be navigated to page link corresponding to the required component." }, { "code": null, "e": 251, "s": 212, "text": "Let us know what is routing in Angular" }, { "code": null, "e": 270, "s": 251, "text": "Angular 8 routing:" }, { "code": null, "e": 630, "s": 270, "text": "The Angular 8 Router helps to navigate between pages that are being triggered by the user’s actions. The navigation happens when the user clicks on the link or enter the URL from the browser address bar. The link can contain the reference to the router on which the user will be directed. We can also pass other parameters with a link through angular routing." }, { "code": null, "e": 640, "s": 630, "text": "Approach:" }, { "code": null, "e": 685, "s": 640, "text": "Create an Angular app.syntax:ng new app_name" }, { "code": null, "e": 693, "s": 685, "text": "syntax:" }, { "code": null, "e": 709, "s": 693, "text": "ng new app_name" }, { "code": null, "e": 861, "s": 709, "text": "For routing you will need components, here we have made two components (home and dash) to display home page and dashboard.syntax:ng g c component_name\n" }, { "code": null, "e": 869, "s": 861, "text": "syntax:" }, { "code": null, "e": 892, "s": 869, "text": "ng g c component_name\n" }, { "code": null, "e": 1007, "s": 892, "text": "In app.module.ts, import RouterModule from @angular/router.syntax:import { RouterModule } from '@angular/router';\n" }, { "code": null, "e": 1015, "s": 1007, "text": "syntax:" }, { "code": null, "e": 1064, "s": 1015, "text": "import { RouterModule } from '@angular/router';\n" }, { "code": null, "e": 1305, "s": 1064, "text": "Then in imports of app.module.ts define the paths.imports: [\n BrowserModule,\n AppRoutingModule,\n RouterModule.forRoot([\n { path: 'home', component: HomeComponent },\n { path: 'dash', component:DashComponent } \n ])\n ],\n" }, { "code": null, "e": 1496, "s": 1305, "text": "imports: [\n BrowserModule,\n AppRoutingModule,\n RouterModule.forRoot([\n { path: 'home', component: HomeComponent },\n { path: 'dash', component:DashComponent } \n ])\n ],\n" }, { "code": null, "e": 1683, "s": 1496, "text": "Now for HTML part, define the HTML for app.component.html. In link, define routerLink’s path as the component name.<a routerLink=\"/home\">Home </a><br>\n<a routerLink=\"/dash\">dashboard</a>" }, { "code": null, "e": 1755, "s": 1683, "text": "<a routerLink=\"/home\">Home </a><br>\n<a routerLink=\"/dash\">dashboard</a>" }, { "code": null, "e": 1897, "s": 1755, "text": "Apply router-outlet for your application in app.component.html.The routed views render in the <router-outlet><router-outlet></router-outlet>\n" }, { "code": null, "e": 1930, "s": 1897, "text": "<router-outlet></router-outlet>\n" }, { "code": null, "e": 2005, "s": 1930, "text": "Now just define HTML for home.component.html and dash.component.html file." }, { "code": null, "e": 2036, "s": 2005, "text": "Your angular web-app is ready." }, { "code": null, "e": 2057, "s": 2036, "text": "Code Implementation:" }, { "code": null, "e": 2770, "s": 2057, "text": "app.module.ts:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { RouterModule } from '@angular/router';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HomeComponent } from './home/home.component';import { DashComponent } from './dash/dash.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, DashComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'dash', component:DashComponent } ]) ], providers: [], bootstrap: [AppComponent]})export class AppModule { }" }, { "code": null, "e": 2785, "s": 2770, "text": "app.module.ts:" }, { "code": "import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { RouterModule } from '@angular/router';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HomeComponent } from './home/home.component';import { DashComponent } from './dash/dash.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, DashComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'dash', component:DashComponent } ]) ], providers: [], bootstrap: [AppComponent]})export class AppModule { }", "e": 3484, "s": 2785, "text": null }, { "code": null, "e": 3604, "s": 3484, "text": "app.component.html<a routerLink=\"/home\">Home </a><br><a routerLink=\"/dash\">dashboard</a><router-outlet></router-outlet>" }, { "code": null, "e": 3623, "s": 3604, "text": "app.component.html" }, { "code": "<a routerLink=\"/home\">Home </a><br><a routerLink=\"/dash\">dashboard</a><router-outlet></router-outlet>", "e": 3725, "s": 3623, "text": null }, { "code": null, "e": 3767, "s": 3725, "text": "home.component.html<h1>GeeksforGeeks</h1>" }, { "code": null, "e": 3787, "s": 3767, "text": "home.component.html" }, { "code": "<h1>GeeksforGeeks</h1>", "e": 3810, "s": 3787, "text": null }, { "code": null, "e": 3870, "s": 3810, "text": "dash.component.html<h1>Hey GEEKS! Welcome to Dashboard</h1>" }, { "code": null, "e": 3890, "s": 3870, "text": "dash.component.html" }, { "code": "<h1>Hey GEEKS! Welcome to Dashboard</h1>", "e": 3931, "s": 3890, "text": null }, { "code": null, "e": 3939, "s": 3931, "text": "Output:" }, { "code": null, "e": 3990, "s": 3939, "text": "Run the development server and click on the links:" }, { "code": null, "e": 4005, "s": 3990, "text": "AngularJS-Misc" }, { "code": null, "e": 4015, "s": 4005, "text": "AngularJS" }, { "code": null, "e": 4032, "s": 4015, "text": "Web Technologies" } ]
Sum of heights of all individual nodes in a binary tree
26 May, 2021 Given a binary tree, find the sum of heights of all individual nodes in the tree. Example: For this tree: 1). Height of Node 1 - 3 2). Height of Node 2 - 2 3). Height of Node 3 - 1 4). Height of Node 4 - 1 5). Height of Node 5 - 1 Adding all of them = 8 Prerequisites:- Height of binary tree Simple Solution: We get the height of all individual nodes by parsing the tree in any of the following methods, i.e. Inorder, postorder, preorder(I performed inorder tree traversal), and getting their heights using the getHeight function, which checks both left and right subtree and returns the maximum of them. Finally, we add up all the individual heights. C++ Java Python3 C# Javascript // C++ program to find sum of heights of all// nodes in a binary tree#include <bits/stdc++.h> /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; /* Compute the "maxHeight" of a particular Node*/int getHeight(struct Node* Node){ if (Node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = getHeight(Node->left); int rHeight = getHeight(Node->right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* Node = (struct Node*) malloc(sizeof(struct Node)); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Function to sum of heights of individual Nodes Uses Inorder traversal */int getTotalHeight(struct Node* root){ if (root == NULL) return 0; return getTotalHeight(root->left) + getHeight(root) + getTotalHeight(root->right);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Sum of heights of all Nodes = %d", getTotalHeight(root)); return 0;} // Java program to find sum of heights of all// nodes in a binary treeclass GfG { /* A binary tree Node has data, pointer to left child and a pointer to right child */static class Node { int data; Node left; Node right;} /* Compute the "maxHeight" of a particular Node*/static int getHeight(Node Node){ if (Node == null) return 0; else { /* compute the height of each subtree */ int lHeight = getHeight(Node.left); int rHeight = getHeight(Node.right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Helper function that allocates a new Node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node);} /* Function to sum of heights of individual NodesUses Inorder traversal */static int getTotalHeight( Node root){ if (root == null) return 0; return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right);} // Driver codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); System.out.println("Sum of heights of all Nodes = " + getTotalHeight(root));}} # Python3 program to find sum of heights# of all nodes in a binary tree # Helper class that allocates a new Node# with the given data and None left and# right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # Compute the "maxHeight" of a# particular Nodedef getHeight(Node): if (Node == None): return 0 else: # compute the height of each subtree lHeight = getHeight(Node.left) rHeight = getHeight(Node.right) # use the larger one if (lHeight > rHeight): return (lHeight + 1) else: return (rHeight + 1) # Function to sum of heights of# individual Nodes Uses Inorder traversaldef getTotalHeight(root): if (root == None): return 0 return (getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right)) # Driver codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5)print("Sum of heights of all Nodes =", getTotalHeight(root)) # This code is contributed by PranchalK // C# program to find sum of heights of all// nodes in a binary treeusing System; class GfG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left; public Node right;} /* Compute the "maxHeight" of a particular Node*/static int getHeight(Node Node){ if (Node == null) return 0; else { /* compute the height of each subtree */ int lHeight = getHeight(Node.left); int rHeight = getHeight(Node.right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Helper function that allocates a new Node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node);} /* Function to sum of heights of individual NodesUses Inorder traversal */static int getTotalHeight( Node root){ if (root == null) return 0; return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right);} // Driver codepublic static void Main(String []args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); Console.Write("Sum of heights of all Nodes = " + getTotalHeight(root));}} // This code is contributed by Arnab Kundu <script>// Javascript program to find sum of heights of all// nodes in a binary tree /* A binary tree Node has data, pointer toleft child and a pointer to right child */class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} /* Compute the "maxHeight" of a particular Node*/function getHeight(Node){ if (Node == null) return 0; else { /* compute the height of each subtree */ let lHeight = getHeight(Node.left); let rHeight = getHeight(Node.right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Function to sum of heights of individual NodesUses Inorder traversal */function getTotalHeight(root){ if (root == null) return 0; return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right);} // Driver codelet root = new Node(1); root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);document.write("Sum of heights of all Nodes = " + getTotalHeight(root)); // This code is contributed by patel2127</script> Sum of heights of all Nodes = 8 Time Complexity: O(nh) where n is the total number of nodes and h is the height of the binary tree. Efficient Solution: The idea is to compute heights and sum them up in the same recursive call. C++ Java Python3 C# Javascript // C++ program to find sum of heights of all// nodes in a binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* Node = (struct Node*) malloc(sizeof(struct Node)); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Function to sum of heights of individual Nodes Uses Inorder traversal */int getTotalHeightUtil(struct Node* root, int &sum){ if (root == NULL) return 0; int lh = getTotalHeightUtil(root->left, sum); int rh = getTotalHeightUtil(root->right, sum); int h = max(lh, rh) + 1; sum = sum + h; return h;} int getTotalHeight(Node *root){ int sum = 0; getTotalHeightUtil(root, sum); return sum;} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Sum of heights of all Nodes = %d", getTotalHeight(root)); return 0;} // Java program to find sum of heights of all// nodes in a binary treeclass GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left; Node right; }; static int sum; /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node); } /* Function to sum of heights of individual Nodes Uses Inorder traversal */ static int getTotalHeightUtil(Node root) { if (root == null) { return 0; } int lh = getTotalHeightUtil(root.left); int rh = getTotalHeightUtil(root.right); int h = Math.max(lh, rh) + 1; sum = sum + h; return h; } static int getTotalHeight(Node root) { sum = 0; getTotalHeightUtil(root); return sum; } // Driver code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); System.out.printf("Sum of heights of all Nodes = %d", getTotalHeight(root)); }} // This code is contributed by PrinciRaj1992 # Python3 program to find sum of heights# of all nodes in a binary tree # A binary tree Node has data, pointer to# left child and a pointer to right childclass Node: def __init__(self, key): self.data = key self.left = None self.right = None sum = 0 # Function to sum of heights of individual# Nodes Uses Inorder traversaldef getTotalHeightUtil(root): global sum if (root == None): return 0 lh = getTotalHeightUtil(root.left) rh = getTotalHeightUtil(root.right) h = max(lh, rh) + 1 sum = sum + h return h def getTotalHeight(root): getTotalHeightUtil(root) return sum # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Sum of heights of all Nodes =", getTotalHeight(root)) # This code is contributed by mohit kumar 29 // C# program to find sum of heights of// all nodes in a binary treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ class Node { public int data; public Node left; public Node right; }; static int sum; /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node); } /* Function to sum of heights of individual Nodes Uses Inorder traversal */ static int getTotalHeightUtil(Node root) { if (root == null) { return 0; } int lh = getTotalHeightUtil(root.left); int rh = getTotalHeightUtil(root.right); int h = Math.Max(lh, rh) + 1; sum = sum + h; return h; } static int getTotalHeight(Node root) { sum = 0; getTotalHeightUtil(root); return sum; } // Driver code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); Console.Write("Sum of heights of all Nodes = {0}", getTotalHeight(root)); }} // This code is contributed by Princi Singh <script> // JavaScript program to find sum of heights of all// nodes in a binary tree /* A binary tree Node has data, pointer to left child and a pointer to right child */class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} let sum;/* Function to sum of heights of individual Nodes Uses Inorder traversal */function getTotalHeightUtil(root){ if (root == null) { return 0; } let lh = getTotalHeightUtil(root.left); let rh = getTotalHeightUtil(root.right); let h = Math.max(lh, rh) + 1; sum = sum + h; return h;} function getTotalHeight(root){ sum = 0; getTotalHeightUtil(root); return sum;} // Driver codelet root = new Node(1); root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);document.write("Sum of heights of all Nodes = ", getTotalHeight(root)); // This code is contributed by unknown2108 </script> Sum of heights of all Nodes = 8 Time Complexity: O(n) where n is the total number of nodes of the binary tree. akash1295 prerna saini PranchalKatiyar andrew1234 princiraj1992 princi singh be1398 mohit kumar 29 patel2127 unknown2108 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2021" }, { "code": null, "e": 134, "s": 52, "text": "Given a binary tree, find the sum of heights of all individual nodes in the tree." }, { "code": null, "e": 143, "s": 134, "text": "Example:" }, { "code": null, "e": 307, "s": 143, "text": "For this tree:\n1). Height of Node 1 - 3\n2). Height of Node 2 - 2\n3). Height of Node 3 - 1\n4). Height of Node 4 - 1\n5). Height of Node 5 - 1\n\nAdding all of them = 8" }, { "code": null, "e": 345, "s": 307, "text": "Prerequisites:- Height of binary tree" }, { "code": null, "e": 362, "s": 345, "text": "Simple Solution:" }, { "code": null, "e": 705, "s": 362, "text": "We get the height of all individual nodes by parsing the tree in any of the following methods, i.e. Inorder, postorder, preorder(I performed inorder tree traversal), and getting their heights using the getHeight function, which checks both left and right subtree and returns the maximum of them. Finally, we add up all the individual heights." }, { "code": null, "e": 709, "s": 705, "text": "C++" }, { "code": null, "e": 714, "s": 709, "text": "Java" }, { "code": null, "e": 722, "s": 714, "text": "Python3" }, { "code": null, "e": 725, "s": 722, "text": "C#" }, { "code": null, "e": 736, "s": 725, "text": "Javascript" }, { "code": "// C++ program to find sum of heights of all// nodes in a binary tree#include <bits/stdc++.h> /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; /* Compute the \"maxHeight\" of a particular Node*/int getHeight(struct Node* Node){ if (Node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = getHeight(Node->left); int rHeight = getHeight(Node->right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* Node = (struct Node*) malloc(sizeof(struct Node)); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Function to sum of heights of individual Nodes Uses Inorder traversal */int getTotalHeight(struct Node* root){ if (root == NULL) return 0; return getTotalHeight(root->left) + getHeight(root) + getTotalHeight(root->right);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(\"Sum of heights of all Nodes = %d\", getTotalHeight(root)); return 0;}", "e": 2262, "s": 736, "text": null }, { "code": "// Java program to find sum of heights of all// nodes in a binary treeclass GfG { /* A binary tree Node has data, pointer to left child and a pointer to right child */static class Node { int data; Node left; Node right;} /* Compute the \"maxHeight\" of a particular Node*/static int getHeight(Node Node){ if (Node == null) return 0; else { /* compute the height of each subtree */ int lHeight = getHeight(Node.left); int rHeight = getHeight(Node.right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Helper function that allocates a new Node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node);} /* Function to sum of heights of individual NodesUses Inorder traversal */static int getTotalHeight( Node root){ if (root == null) return 0; return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right);} // Driver codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); System.out.println(\"Sum of heights of all Nodes = \" + getTotalHeight(root));}}", "e": 3670, "s": 2262, "text": null }, { "code": "# Python3 program to find sum of heights# of all nodes in a binary tree # Helper class that allocates a new Node# with the given data and None left and# right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # Compute the \"maxHeight\" of a# particular Nodedef getHeight(Node): if (Node == None): return 0 else: # compute the height of each subtree lHeight = getHeight(Node.left) rHeight = getHeight(Node.right) # use the larger one if (lHeight > rHeight): return (lHeight + 1) else: return (rHeight + 1) # Function to sum of heights of# individual Nodes Uses Inorder traversaldef getTotalHeight(root): if (root == None): return 0 return (getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right)) # Driver codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5)print(\"Sum of heights of all Nodes =\", getTotalHeight(root)) # This code is contributed by PranchalK", "e": 4887, "s": 3670, "text": null }, { "code": "// C# program to find sum of heights of all// nodes in a binary treeusing System; class GfG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left; public Node right;} /* Compute the \"maxHeight\" of a particular Node*/static int getHeight(Node Node){ if (Node == null) return 0; else { /* compute the height of each subtree */ int lHeight = getHeight(Node.left); int rHeight = getHeight(Node.right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Helper function that allocates a new Node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node);} /* Function to sum of heights of individual NodesUses Inorder traversal */static int getTotalHeight( Node root){ if (root == null) return 0; return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right);} // Driver codepublic static void Main(String []args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); Console.Write(\"Sum of heights of all Nodes = \" + getTotalHeight(root));}} // This code is contributed by Arnab Kundu", "e": 6405, "s": 4887, "text": null }, { "code": "<script>// Javascript program to find sum of heights of all// nodes in a binary tree /* A binary tree Node has data, pointer toleft child and a pointer to right child */class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} /* Compute the \"maxHeight\" of a particular Node*/function getHeight(Node){ if (Node == null) return 0; else { /* compute the height of each subtree */ let lHeight = getHeight(Node.left); let rHeight = getHeight(Node.right); /* use the larger one */ if (lHeight > rHeight) return (lHeight + 1); else return (rHeight + 1); }} /* Function to sum of heights of individual NodesUses Inorder traversal */function getTotalHeight(root){ if (root == null) return 0; return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right);} // Driver codelet root = new Node(1); root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);document.write(\"Sum of heights of all Nodes = \" + getTotalHeight(root)); // This code is contributed by patel2127</script>", "e": 7581, "s": 6405, "text": null }, { "code": null, "e": 7613, "s": 7581, "text": "Sum of heights of all Nodes = 8" }, { "code": null, "e": 7715, "s": 7615, "text": "Time Complexity: O(nh) where n is the total number of nodes and h is the height of the binary tree." }, { "code": null, "e": 7735, "s": 7715, "text": "Efficient Solution:" }, { "code": null, "e": 7810, "s": 7735, "text": "The idea is to compute heights and sum them up in the same recursive call." }, { "code": null, "e": 7814, "s": 7810, "text": "C++" }, { "code": null, "e": 7819, "s": 7814, "text": "Java" }, { "code": null, "e": 7827, "s": 7819, "text": "Python3" }, { "code": null, "e": 7830, "s": 7827, "text": "C#" }, { "code": null, "e": 7841, "s": 7830, "text": "Javascript" }, { "code": "// C++ program to find sum of heights of all// nodes in a binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* Node = (struct Node*) malloc(sizeof(struct Node)); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Function to sum of heights of individual Nodes Uses Inorder traversal */int getTotalHeightUtil(struct Node* root, int &sum){ if (root == NULL) return 0; int lh = getTotalHeightUtil(root->left, sum); int rh = getTotalHeightUtil(root->right, sum); int h = max(lh, rh) + 1; sum = sum + h; return h;} int getTotalHeight(Node *root){ int sum = 0; getTotalHeightUtil(root, sum); return sum;} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(\"Sum of heights of all Nodes = %d\", getTotalHeight(root)); return 0;}", "e": 9137, "s": 7841, "text": null }, { "code": "// Java program to find sum of heights of all// nodes in a binary treeclass GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left; Node right; }; static int sum; /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node); } /* Function to sum of heights of individual Nodes Uses Inorder traversal */ static int getTotalHeightUtil(Node root) { if (root == null) { return 0; } int lh = getTotalHeightUtil(root.left); int rh = getTotalHeightUtil(root.right); int h = Math.max(lh, rh) + 1; sum = sum + h; return h; } static int getTotalHeight(Node root) { sum = 0; getTotalHeightUtil(root); return sum; } // Driver code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); System.out.printf(\"Sum of heights of all Nodes = %d\", getTotalHeight(root)); }} // This code is contributed by PrinciRaj1992", "e": 10598, "s": 9137, "text": null }, { "code": "# Python3 program to find sum of heights# of all nodes in a binary tree # A binary tree Node has data, pointer to# left child and a pointer to right childclass Node: def __init__(self, key): self.data = key self.left = None self.right = None sum = 0 # Function to sum of heights of individual# Nodes Uses Inorder traversaldef getTotalHeightUtil(root): global sum if (root == None): return 0 lh = getTotalHeightUtil(root.left) rh = getTotalHeightUtil(root.right) h = max(lh, rh) + 1 sum = sum + h return h def getTotalHeight(root): getTotalHeightUtil(root) return sum # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print(\"Sum of heights of all Nodes =\", getTotalHeight(root)) # This code is contributed by mohit kumar 29", "e": 11550, "s": 10598, "text": null }, { "code": "// C# program to find sum of heights of// all nodes in a binary treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ class Node { public int data; public Node left; public Node right; }; static int sum; /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node Node = new Node(); Node.data = data; Node.left = null; Node.right = null; return (Node); } /* Function to sum of heights of individual Nodes Uses Inorder traversal */ static int getTotalHeightUtil(Node root) { if (root == null) { return 0; } int lh = getTotalHeightUtil(root.left); int rh = getTotalHeightUtil(root.right); int h = Math.Max(lh, rh) + 1; sum = sum + h; return h; } static int getTotalHeight(Node root) { sum = 0; getTotalHeightUtil(root); return sum; } // Driver code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); Console.Write(\"Sum of heights of all Nodes = {0}\", getTotalHeight(root)); }} // This code is contributed by Princi Singh", "e": 13070, "s": 11550, "text": null }, { "code": "<script> // JavaScript program to find sum of heights of all// nodes in a binary tree /* A binary tree Node has data, pointer to left child and a pointer to right child */class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} let sum;/* Function to sum of heights of individual Nodes Uses Inorder traversal */function getTotalHeightUtil(root){ if (root == null) { return 0; } let lh = getTotalHeightUtil(root.left); let rh = getTotalHeightUtil(root.right); let h = Math.max(lh, rh) + 1; sum = sum + h; return h;} function getTotalHeight(root){ sum = 0; getTotalHeightUtil(root); return sum;} // Driver codelet root = new Node(1); root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);document.write(\"Sum of heights of all Nodes = \", getTotalHeight(root)); // This code is contributed by unknown2108 </script> ", "e": 14101, "s": 13070, "text": null }, { "code": null, "e": 14133, "s": 14101, "text": "Sum of heights of all Nodes = 8" }, { "code": null, "e": 14215, "s": 14135, "text": "Time Complexity: O(n) where n is the total number of nodes of the binary tree. " }, { "code": null, "e": 14225, "s": 14215, "text": "akash1295" }, { "code": null, "e": 14238, "s": 14225, "text": "prerna saini" }, { "code": null, "e": 14254, "s": 14238, "text": "PranchalKatiyar" }, { "code": null, "e": 14265, "s": 14254, "text": "andrew1234" }, { "code": null, "e": 14279, "s": 14265, "text": "princiraj1992" }, { "code": null, "e": 14292, "s": 14279, "text": "princi singh" }, { "code": null, "e": 14299, "s": 14292, "text": "be1398" }, { "code": null, "e": 14314, "s": 14299, "text": "mohit kumar 29" }, { "code": null, "e": 14324, "s": 14314, "text": "patel2127" }, { "code": null, "e": 14336, "s": 14324, "text": "unknown2108" }, { "code": null, "e": 14341, "s": 14336, "text": "Tree" }, { "code": null, "e": 14346, "s": 14341, "text": "Tree" } ]
Primitive and Reference value in JavaScript
08 Jan, 2021 In JavaScript, a variable may store two type of values, Primitive values or Reference values. This article will describe and help to compare both these type of values. 1. Primitive value: JavaScript provides six type of primitive values that includes Number, String, Boolean, Undefined, Symbol, and BigInt. The size of Primitive values are fixed, therefore JavaScript stores the primitive value in the call stack (Execution context). When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by Value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable. Let us take an example to understand primitive value: Primitive value Javascript let age = 30;let age1 = age; // Pointing to age console.log(`age = ${age} age1 = ${age1}`); age = 31; // Pointing to new address console.log(`age = ${age} age1 = ${age1}`); Output: age = 30 age1 = 30 age = 31 age1 = 30 2. Reference Value: JavaScript provides three types of Reference values that include Array, Object, and Function. The size of a reference value is dynamic therefore It is stored on Heap. When we access a reference value, we manipulate it through reference, not through its actual value that is stored. Thus, variables that are reference values are accessed by reference. When we assign a reference value from one variable to another, the value stored in the variable is also copied into the location of the new variable but the difference is that the values stored in both variables now are the address of the actual object stored on the heap. As a result, both variables are referencing the same object, So we can manipulate the original object from both the variable. Let us take an example to understand reference value: Reference value Javascript let info = { Name :"Abc", Age :10}console.log(`Name : ${info.Name} Age : ${info.Age}`); let info1 = info;info1.Age = 14; // Change the Age of original objectconsole.log(`Name : ${info.Name} Age : ${info.Age}`); Output: Name : Abc Age : 10 Name : Abc Age : 14 JavaScript-Misc Technical Scripter 2020 JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jan, 2021" }, { "code": null, "e": 220, "s": 52, "text": "In JavaScript, a variable may store two type of values, Primitive values or Reference values. This article will describe and help to compare both these type of values." }, { "code": null, "e": 486, "s": 220, "text": "1. Primitive value: JavaScript provides six type of primitive values that includes Number, String, Boolean, Undefined, Symbol, and BigInt. The size of Primitive values are fixed, therefore JavaScript stores the primitive value in the call stack (Execution context)." }, { "code": null, "e": 780, "s": 486, "text": "When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by Value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable." }, { "code": null, "e": 834, "s": 780, "text": "Let us take an example to understand primitive value:" }, { "code": null, "e": 850, "s": 834, "text": "Primitive value" }, { "code": null, "e": 861, "s": 850, "text": "Javascript" }, { "code": "let age = 30;let age1 = age; // Pointing to age console.log(`age = ${age} age1 = ${age1}`); age = 31; // Pointing to new address console.log(`age = ${age} age1 = ${age1}`);", "e": 1039, "s": 861, "text": null }, { "code": null, "e": 1047, "s": 1039, "text": "Output:" }, { "code": null, "e": 1089, "s": 1047, "text": " age = 30 age1 = 30\n age = 31 age1 = 30" }, { "code": null, "e": 1276, "s": 1089, "text": "2. Reference Value: JavaScript provides three types of Reference values that include Array, Object, and Function. The size of a reference value is dynamic therefore It is stored on Heap." }, { "code": null, "e": 1859, "s": 1276, "text": "When we access a reference value, we manipulate it through reference, not through its actual value that is stored. Thus, variables that are reference values are accessed by reference. When we assign a reference value from one variable to another, the value stored in the variable is also copied into the location of the new variable but the difference is that the values stored in both variables now are the address of the actual object stored on the heap. As a result, both variables are referencing the same object, So we can manipulate the original object from both the variable." }, { "code": null, "e": 1913, "s": 1859, "text": "Let us take an example to understand reference value:" }, { "code": null, "e": 1929, "s": 1913, "text": "Reference value" }, { "code": null, "e": 1940, "s": 1929, "text": "Javascript" }, { "code": "let info = { Name :\"Abc\", Age :10}console.log(`Name : ${info.Name} Age : ${info.Age}`); let info1 = info;info1.Age = 14; // Change the Age of original objectconsole.log(`Name : ${info.Name} Age : ${info.Age}`);", "e": 2158, "s": 1940, "text": null }, { "code": null, "e": 2167, "s": 2158, "text": "Output: " }, { "code": null, "e": 2207, "s": 2167, "text": "Name : Abc Age : 10\nName : Abc Age : 14" }, { "code": null, "e": 2223, "s": 2207, "text": "JavaScript-Misc" }, { "code": null, "e": 2247, "s": 2223, "text": "Technical Scripter 2020" }, { "code": null, "e": 2258, "s": 2247, "text": "JavaScript" }, { "code": null, "e": 2275, "s": 2258, "text": "Web Technologies" } ]
Python | Indexing a sublist
27 Mar, 2019 In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let’s discuss certain ways in which this can be performed. Method #1 : Using index() + list comprehensionThis method solves this problem in 2 parts, for the first part it generates a new list and then it performs indexing on it. # Python3 code to demonstrate# indexing of sublist # using list comprehension + index() # initializing test listtest_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] # printing original list print("The original list : " + str(test_list)) # using list comprehension + index()# indexing of sublistres = [ele for i, ele in test_list].index('For') # print resultprint("Index of nested element is : " + str(res)) The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] Index of nested element is : 1 Method #2 : Using next() + enumerate()This problem can be solved in an efficient manner using the combination of the above functions. The next function checks for the elements and enumerate functions separates the nested list elements. # Python3 code to demonstrate# indexing of sublist # using enumerate() + next() # initializing test listtest_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] # printing original list print("The original list : " + str(test_list)) # using enumerate() + next()# indexing of sublistres = next((i for i, (j, ele) in enumerate(test_list) if ele == 'For'), None) # print resultprint("Index of nested element is : " + str(res)) The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] Index of nested element is : 1 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2019" }, { "code": null, "e": 293, "s": 28, "text": "In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 463, "s": 293, "text": "Method #1 : Using index() + list comprehensionThis method solves this problem in 2 parts, for the first part it generates a new list and then it performs indexing on it." }, { "code": "# Python3 code to demonstrate# indexing of sublist # using list comprehension + index() # initializing test listtest_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] # printing original list print(\"The original list : \" + str(test_list)) # using list comprehension + index()# indexing of sublistres = [ele for i, ele in test_list].index('For') # print resultprint(\"Index of nested element is : \" + str(res))", "e": 874, "s": 463, "text": null }, { "code": null, "e": 967, "s": 874, "text": "The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]\nIndex of nested element is : 1\n" }, { "code": null, "e": 1205, "s": 969, "text": "Method #2 : Using next() + enumerate()This problem can be solved in an efficient manner using the combination of the above functions. The next function checks for the elements and enumerate functions separates the nested list elements." }, { "code": "# Python3 code to demonstrate# indexing of sublist # using enumerate() + next() # initializing test listtest_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] # printing original list print(\"The original list : \" + str(test_list)) # using enumerate() + next()# indexing of sublistres = next((i for i, (j, ele) in enumerate(test_list) if ele == 'For'), None) # print resultprint(\"Index of nested element is : \" + str(res))", "e": 1629, "s": 1205, "text": null }, { "code": null, "e": 1722, "s": 1629, "text": "The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]\nIndex of nested element is : 1\n" }, { "code": null, "e": 1743, "s": 1722, "text": "Python list-programs" }, { "code": null, "e": 1750, "s": 1743, "text": "Python" }, { "code": null, "e": 1766, "s": 1750, "text": "Python Programs" } ]
PyCairo – Setting Context Color
18 Feb, 2022 In this article, we will see how we can set context colors in pycairo Python. Pycairo is a Python module providing bindings for the Cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. Color can be set using RGBA model, RGBA stands for red green blue alpha. While it is sometimes described as a color space, it is actually the three-channel RGB color model supplemented with a fourth alpha channel. In order to this we will use set_source_rgba method with the Context object Syntax: context.set_source_rgba(0, 0, 0, 1) Argument: It takes color format in RGBA model Return: It returns None Example 1 : Python # importing pycairoimport cairo # creating a SVG surface# here geek007 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek007.svg", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) # setting color of the context context.set_source_rgba(0, 0, 0, 1) # setting of line width context.set_line_width(4) # move the context to x,y position context.move_to(40, 30) # creating a rectangle(square) context.rectangle(100, 100, 100, 100) # stroke out the color and width property context.stroke() # printing message when file is savedprint("File Saved") Setting color of the context context.set_source_rgba (0, 0, 0, 1) Output : Example 2 : Python3 # importing pycairoimport cairo # creating a SVG surface # here geek007 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek007.svg", 700, 700) as surface: # creating a cairo context object for SVG surface #using Context method context = cairo.Context(surface) # setting color of the context context.set_source_rgba(4, 0, 4, 0.5) # setting of line width context.set_line_width(40) # move the context to x,y position context.move_to(40, 30) #creating a rectangle(square) context.rectangle(100, 100, 100, 100) # stroke out the color and width property context.stroke() # printing message when file is savedprint("File Saved") Setting color of the context context.set_source_rgba (4, 0, 4, 0.5) Output : Example 3 : Python3 # importing pycairoimport cairo # creating a SVG surface# here geek007 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek007.svg", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) # setting color of the context context.set_source_rgba(180, 150, 0, 0.5) # setting of line width context.set_line_width(40) # move the context to x,y position context.move_to(40, 30) # creating a rectangle(square) context.rectangle(100, 100, 100, 100) # stroke out the color and width property context.stroke() # printing message when file is savedprint("File Saved") Setting color of the context context.set_source_rgba (180, 150, 0, 0.5) Output : saurabh1990aror Python-PyCairo Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2022" }, { "code": null, "e": 699, "s": 28, "text": "In this article, we will see how we can set context colors in pycairo Python. Pycairo is a Python module providing bindings for the Cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. Color can be set using RGBA model, RGBA stands for red green blue alpha. While it is sometimes described as a color space, it is actually the three-channel RGB color model supplemented with a fourth alpha channel." }, { "code": null, "e": 775, "s": 699, "text": "In order to this we will use set_source_rgba method with the Context object" }, { "code": null, "e": 819, "s": 775, "text": "Syntax: context.set_source_rgba(0, 0, 0, 1)" }, { "code": null, "e": 865, "s": 819, "text": "Argument: It takes color format in RGBA model" }, { "code": null, "e": 891, "s": 865, "text": "Return: It returns None " }, { "code": null, "e": 903, "s": 891, "text": "Example 1 :" }, { "code": null, "e": 910, "s": 903, "text": "Python" }, { "code": "# importing pycairoimport cairo # creating a SVG surface# here geek007 is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek007.svg\", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) # setting color of the context context.set_source_rgba(0, 0, 0, 1) # setting of line width context.set_line_width(4) # move the context to x,y position context.move_to(40, 30) # creating a rectangle(square) context.rectangle(100, 100, 100, 100) # stroke out the color and width property context.stroke() # printing message when file is savedprint(\"File Saved\")", "e": 1598, "s": 910, "text": null }, { "code": null, "e": 1627, "s": 1598, "text": "Setting color of the context" }, { "code": null, "e": 1665, "s": 1627, "text": " context.set_source_rgba (0, 0, 0, 1)" }, { "code": null, "e": 1674, "s": 1665, "text": "Output :" }, { "code": null, "e": 1686, "s": 1674, "text": "Example 2 :" }, { "code": null, "e": 1694, "s": 1686, "text": "Python3" }, { "code": "# importing pycairoimport cairo # creating a SVG surface # here geek007 is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek007.svg\", 700, 700) as surface: # creating a cairo context object for SVG surface #using Context method context = cairo.Context(surface) # setting color of the context context.set_source_rgba(4, 0, 4, 0.5) # setting of line width context.set_line_width(40) # move the context to x,y position context.move_to(40, 30) #creating a rectangle(square) context.rectangle(100, 100, 100, 100) # stroke out the color and width property context.stroke() # printing message when file is savedprint(\"File Saved\")", "e": 2416, "s": 1694, "text": null }, { "code": null, "e": 2445, "s": 2416, "text": "Setting color of the context" }, { "code": null, "e": 2487, "s": 2445, "text": " context.set_source_rgba (4, 0, 4, 0.5)" }, { "code": null, "e": 2496, "s": 2487, "text": "Output :" }, { "code": null, "e": 2508, "s": 2496, "text": "Example 3 :" }, { "code": null, "e": 2516, "s": 2508, "text": "Python3" }, { "code": "# importing pycairoimport cairo # creating a SVG surface# here geek007 is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek007.svg\", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) # setting color of the context context.set_source_rgba(180, 150, 0, 0.5) # setting of line width context.set_line_width(40) # move the context to x,y position context.move_to(40, 30) # creating a rectangle(square) context.rectangle(100, 100, 100, 100) # stroke out the color and width property context.stroke() # printing message when file is savedprint(\"File Saved\")", "e": 3211, "s": 2516, "text": null }, { "code": null, "e": 3240, "s": 3211, "text": "Setting color of the context" }, { "code": null, "e": 3283, "s": 3240, "text": "context.set_source_rgba (180, 150, 0, 0.5)" }, { "code": null, "e": 3292, "s": 3283, "text": "Output :" }, { "code": null, "e": 3308, "s": 3292, "text": "saurabh1990aror" }, { "code": null, "e": 3323, "s": 3308, "text": "Python-PyCairo" }, { "code": null, "e": 3330, "s": 3323, "text": "Python" } ]
How to make a loading gif in PyQT5?
02 Feb, 2021 PyQt5 is a GUI toolkit which can be used to develop GUI application in Python. It provides many modules that can help to build various components of the GUI application. pip install PyQt5 Gif Link: https://loading.io/ Import module Create window and labels Load GIF Start GIF using start() Add mechanism to stop GIF using stop() Execute code Example: Python3 import sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom PyQt5.QtGui import QMoviefrom PyQt5.QtCore import Qt class LoadingGif(object): def mainUI(self, FrontWindow): FrontWindow.setObjectName("FTwindow") FrontWindow.resize(320, 300) self.centralwidget = QtWidgets.QWidget(FrontWindow) self.centralwidget.setObjectName("main-widget") # Label Create self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(25, 25, 200, 200)) self.label.setMinimumSize(QtCore.QSize(250, 250)) self.label.setMaximumSize(QtCore.QSize(250, 250)) self.label.setObjectName("lb1") FrontWindow.setCentralWidget(self.centralwidget) # Loading the GIF self.movie = QMovie("loader.gif") self.label.setMovie(self.movie) self.startAnimation() # Start Animation def startAnimation(self): self.movie.start() # Stop Animation(According to need) def stopAnimation(self): self.movie.stop() app = QtWidgets.QApplication(sys.argv)window = QtWidgets.QMainWindow()demo = LoadingGif()demo.mainUI(window)window.show()sys.exit(app.exec_()) Output: The gif loading screen. Picked PyQt-exercise Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method 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.append() Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2021" }, { "code": null, "e": 198, "s": 28, "text": "PyQt5 is a GUI toolkit which can be used to develop GUI application in Python. It provides many modules that can help to build various components of the GUI application." }, { "code": null, "e": 216, "s": 198, "text": "pip install PyQt5" }, { "code": null, "e": 247, "s": 216, "text": "Gif Link: https://loading.io/" }, { "code": null, "e": 261, "s": 247, "text": "Import module" }, { "code": null, "e": 286, "s": 261, "text": "Create window and labels" }, { "code": null, "e": 295, "s": 286, "text": "Load GIF" }, { "code": null, "e": 320, "s": 295, "text": "Start GIF using start() " }, { "code": null, "e": 359, "s": 320, "text": "Add mechanism to stop GIF using stop()" }, { "code": null, "e": 372, "s": 359, "text": "Execute code" }, { "code": null, "e": 381, "s": 372, "text": "Example:" }, { "code": null, "e": 389, "s": 381, "text": "Python3" }, { "code": "import sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom PyQt5.QtGui import QMoviefrom PyQt5.QtCore import Qt class LoadingGif(object): def mainUI(self, FrontWindow): FrontWindow.setObjectName(\"FTwindow\") FrontWindow.resize(320, 300) self.centralwidget = QtWidgets.QWidget(FrontWindow) self.centralwidget.setObjectName(\"main-widget\") # Label Create self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(25, 25, 200, 200)) self.label.setMinimumSize(QtCore.QSize(250, 250)) self.label.setMaximumSize(QtCore.QSize(250, 250)) self.label.setObjectName(\"lb1\") FrontWindow.setCentralWidget(self.centralwidget) # Loading the GIF self.movie = QMovie(\"loader.gif\") self.label.setMovie(self.movie) self.startAnimation() # Start Animation def startAnimation(self): self.movie.start() # Stop Animation(According to need) def stopAnimation(self): self.movie.stop() app = QtWidgets.QApplication(sys.argv)window = QtWidgets.QMainWindow()demo = LoadingGif()demo.mainUI(window)window.show()sys.exit(app.exec_())", "e": 1569, "s": 389, "text": null }, { "code": null, "e": 1577, "s": 1569, "text": "Output:" }, { "code": null, "e": 1601, "s": 1577, "text": "The gif loading screen." }, { "code": null, "e": 1608, "s": 1601, "text": "Picked" }, { "code": null, "e": 1622, "s": 1608, "text": "PyQt-exercise" }, { "code": null, "e": 1629, "s": 1622, "text": "Python" }, { "code": null, "e": 1727, "s": 1629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1759, "s": 1727, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1780, "s": 1759, "text": "Python OOPs Concepts" }, { "code": null, "e": 1807, "s": 1780, "text": "Python Classes and Objects" }, { "code": null, "e": 1830, "s": 1807, "text": "Introduction To PYTHON" }, { "code": null, "e": 1861, "s": 1830, "text": "Python | os.path.join() method" }, { "code": null, "e": 1917, "s": 1861, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1959, "s": 1917, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2001, "s": 1959, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2036, "s": 2001, "text": "Python - Pandas dataframe.append()" } ]
How to add suffix to column names in R DataFrame ?
28 Apr, 2021 Each of the columns in a data frame is defined by a name, known as the column name. It may be of the type of numerical or string value. In this article, we will discuss how to add a suffix to column names in DataFrame in R Programming Language. In order to modify the column names, the paste function in R can be used. The paste() method, can be used for the concatenation of string vectors together to form a larger string or sentence. The string vector arguments are joined using the separator specified in the paste function. The changes have to be saved to the original string and are not retained on their own. The strings are concatenated in the order of specification in the method. The method is applied successively to each string in case we specify it over an R list object. Syntax: paste( colnames(df), suffix1, suffix2 , sep=) Parameter: colnames(df) – Column names of data frame suffix – suffix string to be added to each column name sep – separator to use between the strings Example R # declare data frame df <- data.frame(c1=c(1,2,4), c2=c("Ab","Cd","Ef"), c3=c(0.1,0.2,0.3)) print("Original DataFrame : ")print(df) print("Original col names")print(colnames(df)) # adding suffix to column names colnames(df) <- paste(colnames(df),"new",sep="_") print("New DataFrame : ")print(df) print("New col names")print(colnames(df)) Output [1] "Original DataFrame : " c1 c2 c3 1 1 Ab 0.1 2 2 Cd 0.2 3 4 Ef 0.3 [1] "Original col names" [1] "c1" "c2" "c3" [1] "New DataFrame : " c1_new c2_new c3_new 1 1 Ab 0.1 2 2 Cd 0.2 3 4 Ef 0.3 [1] "New col names" [1] "c1_new" "c2_new" "c3_new" Multiple suffixes can also be added to the column names, by specifying more than two argument strings in the method definition. Example R # declaring a data framedf <- data.frame(First = c(1,2,3,4) , Second = c("a","ab","cv","dsd"), Third=c(7:10)) # print original data frameprint ("Original DataFrame : ")print (df) # printing original colnames of # data frameoriginal_cols <- colnames(df)print ("Original column names ")print (original_cols) # adding suffix using the paste# function in Rcolnames(df) <- paste(original_cols,"1","modified",sep="-") # print changed data frameprint ("Modified DataFrame : ")print (df) Output [1] "Original DataFrame : " First Second Third 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 [1] "Original column names " [1] "First" "Second" "Third" [1] "Modified DataFrame : " First-1-modified Second-1-modified Third-1-modified 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 paste0 method is exactly alike like the paste method in functionality, but it does not provide a feature of customized separator between the string arguments. It automatically collapses the string arguments and concatenates them to produce a larger string without any spaces. Multiple suffixes can also be added using this approach. The method is applied successively to each string in case we specify it over an R list object. Syntax: paste0( colnames(df), suffix1, suffix2 ) Parameter : colnames(df) – Column names of data frame suffix1.. – suffix string to be added to each column name. The strings are concatenated using sep=””. Example: R # declaring a data framedf <- data.frame(c1 = c(1,2,3,4) , c2 = c("a","ab","cv","dsd")) # print original data frameprint ("Original DataFrame : ")print (df) # printing original colnames of # data frameoriginal_cols <- colnames(df)print ("Original column names ")print (original_cols) # adding suffix using the paste0 # function in Rcolnames(df) <- paste0(original_cols,"changed") # print changed data frameprint ("Modified DataFrame : ")print (df) Output [1] "Original DataFrame : " c1 c2 1 1 a 2 2 ab 3 3 cv 4 4 dsd [1] "Original column names " [1] "c1" "c2" [1] "Modified DataFrame : " c1changed c2changed 1 1 a 2 2 ab 3 3 cv 4 4 dsd Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 274, "s": 28, "text": "Each of the columns in a data frame is defined by a name, known as the column name. It may be of the type of numerical or string value. In this article, we will discuss how to add a suffix to column names in DataFrame in R Programming Language. " }, { "code": null, "e": 814, "s": 274, "text": "In order to modify the column names, the paste function in R can be used. The paste() method, can be used for the concatenation of string vectors together to form a larger string or sentence. The string vector arguments are joined using the separator specified in the paste function. The changes have to be saved to the original string and are not retained on their own. The strings are concatenated in the order of specification in the method. The method is applied successively to each string in case we specify it over an R list object." }, { "code": null, "e": 868, "s": 814, "text": "Syntax: paste( colnames(df), suffix1, suffix2 , sep=)" }, { "code": null, "e": 880, "s": 868, "text": "Parameter: " }, { "code": null, "e": 922, "s": 880, "text": "colnames(df) – Column names of data frame" }, { "code": null, "e": 977, "s": 922, "text": "suffix – suffix string to be added to each column name" }, { "code": null, "e": 1020, "s": 977, "text": "sep – separator to use between the strings" }, { "code": null, "e": 1028, "s": 1020, "text": "Example" }, { "code": null, "e": 1030, "s": 1028, "text": "R" }, { "code": "# declare data frame df <- data.frame(c1=c(1,2,4), c2=c(\"Ab\",\"Cd\",\"Ef\"), c3=c(0.1,0.2,0.3)) print(\"Original DataFrame : \")print(df) print(\"Original col names\")print(colnames(df)) # adding suffix to column names colnames(df) <- paste(colnames(df),\"new\",sep=\"_\") print(\"New DataFrame : \")print(df) print(\"New col names\")print(colnames(df))", "e": 1389, "s": 1030, "text": null }, { "code": null, "e": 1396, "s": 1389, "text": "Output" }, { "code": null, "e": 1680, "s": 1396, "text": "[1] \"Original DataFrame : \"\n c1 c2 c3\n1 1 Ab 0.1\n2 2 Cd 0.2\n3 4 Ef 0.3\n[1] \"Original col names\"\n[1] \"c1\" \"c2\" \"c3\"\n[1] \"New DataFrame : \"\n c1_new c2_new c3_new\n1 1 Ab 0.1\n2 2 Cd 0.2\n3 4 Ef 0.3\n[1] \"New col names\"\n[1] \"c1_new\" \"c2_new\" \"c3_new\"" }, { "code": null, "e": 1809, "s": 1680, "text": "Multiple suffixes can also be added to the column names, by specifying more than two argument strings in the method definition. " }, { "code": null, "e": 1817, "s": 1809, "text": "Example" }, { "code": null, "e": 1819, "s": 1817, "text": "R" }, { "code": "# declaring a data framedf <- data.frame(First = c(1,2,3,4) , Second = c(\"a\",\"ab\",\"cv\",\"dsd\"), Third=c(7:10)) # print original data frameprint (\"Original DataFrame : \")print (df) # printing original colnames of # data frameoriginal_cols <- colnames(df)print (\"Original column names \")print (original_cols) # adding suffix using the paste# function in Rcolnames(df) <- paste(original_cols,\"1\",\"modified\",sep=\"-\") # print changed data frameprint (\"Modified DataFrame : \")print (df)", "e": 2335, "s": 1819, "text": null }, { "code": null, "e": 2342, "s": 2335, "text": "Output" }, { "code": null, "e": 2830, "s": 2342, "text": "[1] \"Original DataFrame : \"\n First Second Third\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10\n[1] \"Original column names \"\n[1] \"First\" \"Second\" \"Third\"\n[1] \"Modified DataFrame : \"\n First-1-modified Second-1-modified Third-1-modified\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10" }, { "code": null, "e": 3259, "s": 2830, "text": "paste0 method is exactly alike like the paste method in functionality, but it does not provide a feature of customized separator between the string arguments. It automatically collapses the string arguments and concatenates them to produce a larger string without any spaces. Multiple suffixes can also be added using this approach. The method is applied successively to each string in case we specify it over an R list object. " }, { "code": null, "e": 3308, "s": 3259, "text": "Syntax: paste0( colnames(df), suffix1, suffix2 )" }, { "code": null, "e": 3320, "s": 3308, "text": "Parameter :" }, { "code": null, "e": 3362, "s": 3320, "text": "colnames(df) – Column names of data frame" }, { "code": null, "e": 3464, "s": 3362, "text": "suffix1.. – suffix string to be added to each column name. The strings are concatenated using sep=””." }, { "code": null, "e": 3473, "s": 3464, "text": "Example:" }, { "code": null, "e": 3475, "s": 3473, "text": "R" }, { "code": "# declaring a data framedf <- data.frame(c1 = c(1,2,3,4) , c2 = c(\"a\",\"ab\",\"cv\",\"dsd\")) # print original data frameprint (\"Original DataFrame : \")print (df) # printing original colnames of # data frameoriginal_cols <- colnames(df)print (\"Original column names \")print (original_cols) # adding suffix using the paste0 # function in Rcolnames(df) <- paste0(original_cols,\"changed\") # print changed data frameprint (\"Modified DataFrame : \")print (df)", "e": 3944, "s": 3475, "text": null }, { "code": null, "e": 3951, "s": 3944, "text": "Output" }, { "code": null, "e": 4203, "s": 3951, "text": "[1] \"Original DataFrame : \"\n c1 c2\n1 1 a\n2 2 ab\n3 3 cv\n4 4 dsd\n[1] \"Original column names \"\n[1] \"c1\" \"c2\"\n[1] \"Modified DataFrame : \"\n c1changed c2changed\n1 1 a\n2 2 ab\n3 3 cv\n4 4 dsd" }, { "code": null, "e": 4210, "s": 4203, "text": "Picked" }, { "code": null, "e": 4231, "s": 4210, "text": "R DataFrame-Programs" }, { "code": null, "e": 4243, "s": 4231, "text": "R-DataFrame" }, { "code": null, "e": 4254, "s": 4243, "text": "R Language" }, { "code": null, "e": 4265, "s": 4254, "text": "R Programs" } ]
HTTP headers | Cross-Origin-Resource-Policy
28 Nov, 2019 The Cross-Origin-Resource-Policy is an HTTP response-type header that allows the servers to protect against certain cross-origin or cross-site embedding of the returned source. It complements the Cross-Origin Read Blocking (A mechanism which is used to prevent some cross-origin reads), so it is especially valuable for resources that are not covered by CORB. This also serves as an additional layer to the Same-Origin Policy. This helps in mitigating speculative side-channel attacks as well as Cross-Site Script Inclusion attacks.The Cross Origin Resource Policy is the only way to protect the images from Spectre attacks or compromised renderers. However, because of a chrome bug, this response header can sometimes break file downloads and prevent the users from using Save as and Save image as on the resources. Syntax: Cross-Origin-Resource-Policy: same-site | same-origin | cross-site Directives: This header accepts three directives as mentioned above and describes below: same-site: This directive allowed users to read the resources only when the browser recognizes their requests from the same site (registrable domain). same-origin: This directive allowed users to read the resources only when the browser recognizes their requests from the same origin ([scheme, host, port]). cross-site: This directive allowed users requests from different sites can also read the resources. Note: If a header is set during the Cross-origin resource check, then the browser will automatically deny all the no-cors requests issued by different origin or site. Below examples illustrate the HTTP Cross-Origin-Resource-Policy: Examples: In the example below, only the requests that the browser recognizes as from the same site are allowed to read the resources.Cross-Origin-Resource-Policy: same-site Cross-Origin-Resource-Policy: same-site In the below example, only the requests that the browser recognizes as from the same origin are allowed to read the resources.Cross-Origin-Resource-Policy: same-origin Cross-Origin-Resource-Policy: same-origin Supported Browsers: The browsers are compatible with the HTTP Cross-Origin-Resources-Policy are listed below: Google Chrome Firefox Safari HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2019" }, { "code": null, "e": 678, "s": 28, "text": "The Cross-Origin-Resource-Policy is an HTTP response-type header that allows the servers to protect against certain cross-origin or cross-site embedding of the returned source. It complements the Cross-Origin Read Blocking (A mechanism which is used to prevent some cross-origin reads), so it is especially valuable for resources that are not covered by CORB. This also serves as an additional layer to the Same-Origin Policy. This helps in mitigating speculative side-channel attacks as well as Cross-Site Script Inclusion attacks.The Cross Origin Resource Policy is the only way to protect the images from Spectre attacks or compromised renderers." }, { "code": null, "e": 845, "s": 678, "text": "However, because of a chrome bug, this response header can sometimes break file downloads and prevent the users from using Save as and Save image as on the resources." }, { "code": null, "e": 853, "s": 845, "text": "Syntax:" }, { "code": null, "e": 920, "s": 853, "text": "Cross-Origin-Resource-Policy: same-site | same-origin | cross-site" }, { "code": null, "e": 1009, "s": 920, "text": "Directives: This header accepts three directives as mentioned above and describes below:" }, { "code": null, "e": 1160, "s": 1009, "text": "same-site: This directive allowed users to read the resources only when the browser recognizes their requests from the same site (registrable domain)." }, { "code": null, "e": 1317, "s": 1160, "text": "same-origin: This directive allowed users to read the resources only when the browser recognizes their requests from the same origin ([scheme, host, port])." }, { "code": null, "e": 1417, "s": 1317, "text": "cross-site: This directive allowed users requests from different sites can also read the resources." }, { "code": null, "e": 1584, "s": 1417, "text": "Note: If a header is set during the Cross-origin resource check, then the browser will automatically deny all the no-cors requests issued by different origin or site." }, { "code": null, "e": 1649, "s": 1584, "text": "Below examples illustrate the HTTP Cross-Origin-Resource-Policy:" }, { "code": null, "e": 1659, "s": 1649, "text": "Examples:" }, { "code": null, "e": 1823, "s": 1659, "text": "In the example below, only the requests that the browser recognizes as from the same site are allowed to read the resources.Cross-Origin-Resource-Policy: same-site" }, { "code": null, "e": 1863, "s": 1823, "text": "Cross-Origin-Resource-Policy: same-site" }, { "code": null, "e": 2031, "s": 1863, "text": "In the below example, only the requests that the browser recognizes as from the same origin are allowed to read the resources.Cross-Origin-Resource-Policy: same-origin" }, { "code": null, "e": 2073, "s": 2031, "text": "Cross-Origin-Resource-Policy: same-origin" }, { "code": null, "e": 2183, "s": 2073, "text": "Supported Browsers: The browsers are compatible with the HTTP Cross-Origin-Resources-Policy are listed below:" }, { "code": null, "e": 2197, "s": 2183, "text": "Google Chrome" }, { "code": null, "e": 2205, "s": 2197, "text": "Firefox" }, { "code": null, "e": 2212, "s": 2205, "text": "Safari" }, { "code": null, "e": 2225, "s": 2212, "text": "HTTP-headers" }, { "code": null, "e": 2232, "s": 2225, "text": "Picked" }, { "code": null, "e": 2249, "s": 2232, "text": "Web Technologies" } ]
PHP | is_uploaded_file( ) Function
08 Jun, 2018 The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST. This function can be used to ensure that a malicious user hasn’t tried to trick the script into working on files upon which it should not be working. Syntax: bool is_uploaded_file($file) Parameters Used: This function accepts single parameter $file. $file: It is a mandatory parameter which specifies the file. Return Value: It returns True if the $file uploaded via HTTP POST. It returns true on success or false in failure. For proper working, the function is_uploaded_file() needs an argument like $_FILES[‘userfile’][‘tmp_name’], – the name of the uploaded file on the clients machine $_FILES[‘userfile’][‘name’] does not work. Exceptions An E_WARNING is emitted on failure. The result of this function are cached and therefore the clearstatcache() function is used to clear the cache. is_uploaded_file() function returns false for non-existent files. Below programs illustrate the is_uploaded_file() function. Program 1: <?php// PHP program to illustrate is_uploaded_file() function.$myfile = "gfg.txt"; // checking whether the file is uploaded via HTTP POSTif (is_uploaded_file($file)) echo ("$file is uploaded via HTTP POST");else echo ("$file is not uploaded via HTTP POST");?> Output: gfg.txt is not uploaded via HTTP POST Program 2: <?php // checking whether the file is uploaded via HTTP POSTif (is_uploaded_file($_FILES['userfile']['gfg.txt'])) { echo "File ". $_FILES['userfile']['gfg.txt'] . " uploaded successfully.\n"; // displaying contents of the uploaded file echo "Contents of the file are :\n"; readfile($_FILES['userfile']['gfg.txt']);} else{ echo "File ". $_FILES['userfile']['gfg.txt'] . " not uploaded successfully.\n";}?> Output: File gfg.txt uploaded successfully. Contents of the file are : Portal for geeks! Reference:http://php.net/manual/en/function.is-uploaded-file.php PHP-file-handling PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2018" }, { "code": null, "e": 459, "s": 28, "text": "The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST. This function can be used to ensure that a malicious user hasn’t tried to trick the script into working on files upon which it should not be working." }, { "code": null, "e": 467, "s": 459, "text": "Syntax:" }, { "code": null, "e": 496, "s": 467, "text": "bool is_uploaded_file($file)" }, { "code": null, "e": 559, "s": 496, "text": "Parameters Used: This function accepts single parameter $file." }, { "code": null, "e": 620, "s": 559, "text": "$file: It is a mandatory parameter which specifies the file." }, { "code": null, "e": 941, "s": 620, "text": "Return Value: It returns True if the $file uploaded via HTTP POST. It returns true on success or false in failure. For proper working, the function is_uploaded_file() needs an argument like $_FILES[‘userfile’][‘tmp_name’], – the name of the uploaded file on the clients machine $_FILES[‘userfile’][‘name’] does not work." }, { "code": null, "e": 952, "s": 941, "text": "Exceptions" }, { "code": null, "e": 988, "s": 952, "text": "An E_WARNING is emitted on failure." }, { "code": null, "e": 1099, "s": 988, "text": "The result of this function are cached and therefore the clearstatcache() function is used to clear the cache." }, { "code": null, "e": 1165, "s": 1099, "text": "is_uploaded_file() function returns false for non-existent files." }, { "code": null, "e": 1224, "s": 1165, "text": "Below programs illustrate the is_uploaded_file() function." }, { "code": null, "e": 1235, "s": 1224, "text": "Program 1:" }, { "code": "<?php// PHP program to illustrate is_uploaded_file() function.$myfile = \"gfg.txt\"; // checking whether the file is uploaded via HTTP POSTif (is_uploaded_file($file)) echo (\"$file is uploaded via HTTP POST\");else echo (\"$file is not uploaded via HTTP POST\");?>", "e": 1502, "s": 1235, "text": null }, { "code": null, "e": 1510, "s": 1502, "text": "Output:" }, { "code": null, "e": 1549, "s": 1510, "text": "gfg.txt is not uploaded via HTTP POST\n" }, { "code": null, "e": 1560, "s": 1549, "text": "Program 2:" }, { "code": "<?php // checking whether the file is uploaded via HTTP POSTif (is_uploaded_file($_FILES['userfile']['gfg.txt'])) { echo \"File \". $_FILES['userfile']['gfg.txt'] . \" uploaded successfully.\\n\"; // displaying contents of the uploaded file echo \"Contents of the file are :\\n\"; readfile($_FILES['userfile']['gfg.txt']);} else{ echo \"File \". $_FILES['userfile']['gfg.txt'] . \" not uploaded successfully.\\n\";}?>", "e": 2044, "s": 1560, "text": null }, { "code": null, "e": 2052, "s": 2044, "text": "Output:" }, { "code": null, "e": 2134, "s": 2052, "text": "File gfg.txt uploaded successfully.\nContents of the file are :\nPortal for geeks!\n" }, { "code": null, "e": 2199, "s": 2134, "text": "Reference:http://php.net/manual/en/function.is-uploaded-file.php" }, { "code": null, "e": 2217, "s": 2199, "text": "PHP-file-handling" }, { "code": null, "e": 2221, "s": 2217, "text": "PHP" }, { "code": null, "e": 2238, "s": 2221, "text": "Web Technologies" }, { "code": null, "e": 2242, "s": 2238, "text": "PHP" } ]
Windows 10 Toast Notifications with Python
08 Jan, 2019 Python is a general-purpose language, can be used to develop both desktop and web applications. By using a package available in Python named win10toast , we can create desktop notifications. It is an easy way to get notified when some event occurs. The package is available in Pypi and it is installed using pip. pip install win10toast About show_toast() function: Syntax: show_toast(title=’Notification’, message=’Here comes the message’, icon_path=None, duration=5, threaded=False) Parameters:title: It contains notification title.message: It contains notification message.icon_path: It contains the path to .ico file.duration“: It specifies the notification destruction active duration. To create notifications we have to import the win10toast module. Then create an object to ToastNotifier class and by using the method show_toast we create a notification. It contains header or title of that notification, actual message, duration of that notification and icon for that notification. show_toast method is a instance of notification settings. Code #1: # import win10toast from win10toast import ToastNotifier # create an object to ToastNotifier classn = ToastNotifier() n.show_toast("GEEKSFORGEEKS", "You got notification", duration = 10, icon_path ="https://media.geeksforgeeks.org/wp-content/uploads/geeks.ico") Output: Code #2: # import win10toast from win10toast import ToastNotifier # create an object to ToastNotifier classn = ToastNotifier() n.show_toast("GEEKSFORGEEKS", "Notification body", duration = 20, icon_path ="https://media.geeksforgeeks.org/wp-content/uploads/geeks.ico") Output: python-utility Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jan, 2019" }, { "code": null, "e": 303, "s": 54, "text": "Python is a general-purpose language, can be used to develop both desktop and web applications. By using a package available in Python named win10toast , we can create desktop notifications. It is an easy way to get notified when some event occurs." }, { "code": null, "e": 367, "s": 303, "text": "The package is available in Pypi and it is installed using pip." }, { "code": null, "e": 390, "s": 367, "text": "pip install win10toast" }, { "code": null, "e": 419, "s": 390, "text": "About show_toast() function:" }, { "code": null, "e": 538, "s": 419, "text": "Syntax: show_toast(title=’Notification’, message=’Here comes the message’, icon_path=None, duration=5, threaded=False)" }, { "code": null, "e": 744, "s": 538, "text": "Parameters:title: It contains notification title.message: It contains notification message.icon_path: It contains the path to .ico file.duration“: It specifies the notification destruction active duration." }, { "code": null, "e": 1101, "s": 744, "text": "To create notifications we have to import the win10toast module. Then create an object to ToastNotifier class and by using the method show_toast we create a notification. It contains header or title of that notification, actual message, duration of that notification and icon for that notification. show_toast method is a instance of notification settings." }, { "code": null, "e": 1110, "s": 1101, "text": "Code #1:" }, { "code": "# import win10toast from win10toast import ToastNotifier # create an object to ToastNotifier classn = ToastNotifier() n.show_toast(\"GEEKSFORGEEKS\", \"You got notification\", duration = 10, icon_path =\"https://media.geeksforgeeks.org/wp-content/uploads/geeks.ico\")", "e": 1374, "s": 1110, "text": null }, { "code": null, "e": 1382, "s": 1374, "text": "Output:" }, { "code": null, "e": 1391, "s": 1382, "text": "Code #2:" }, { "code": "# import win10toast from win10toast import ToastNotifier # create an object to ToastNotifier classn = ToastNotifier() n.show_toast(\"GEEKSFORGEEKS\", \"Notification body\", duration = 20, icon_path =\"https://media.geeksforgeeks.org/wp-content/uploads/geeks.ico\")", "e": 1653, "s": 1391, "text": null }, { "code": null, "e": 1661, "s": 1653, "text": "Output:" }, { "code": null, "e": 1676, "s": 1661, "text": "python-utility" }, { "code": null, "e": 1683, "s": 1676, "text": "Python" }, { "code": null, "e": 1702, "s": 1683, "text": "Technical Scripter" }, { "code": null, "e": 1800, "s": 1702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1842, "s": 1800, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1864, "s": 1842, "text": "Enumerate() in Python" }, { "code": null, "e": 1890, "s": 1864, "text": "Python String | replace()" }, { "code": null, "e": 1922, "s": 1890, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1951, "s": 1922, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1978, "s": 1951, "text": "Python Classes and Objects" }, { "code": null, "e": 2014, "s": 1978, "text": "Convert integer to string in Python" }, { "code": null, "e": 2045, "s": 2014, "text": "Python | os.path.join() method" }, { "code": null, "e": 2066, "s": 2045, "text": "Python OOPs Concepts" } ]
Matplotlib.axis.Axis.zoom() function in Python
08 Jun, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. The Axis.zoom() function in axis module of matplotlib library is used to zoom in or out on axis . Syntax: Axis.zoom(self, direction) Parameters: This method accepts the following parameters. direction: This parameter is the value to zoom in (direction > 0) or zoom out (direction <= 0). Return value: This method does not return any value. Below examples illustrate the matplotlib.axis.Axis.zoom() function in matplotlib.axis: Example 1: Python3 # Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.plot([1, 2, 3]) ax.xaxis.zoom(3) ax.grid() fig.suptitle("""matplotlib.axis.Axis.zoom()function Example\n""", fontweight ="bold") plt.show() Output: Example 2: Python3 # Implementation of matplotlib functionfrom matplotlib.axis import Axisimport numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons fig, ax1 = plt.subplots() plt.subplots_adjust(bottom = 0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t) ax1.plot(t, s, lw = 2, color = 'green') ax1.xaxis.zoom(-2) ax1.grid() fig.suptitle("""matplotlib.axis.Axis.zoom()function Example\n""", fontweight ="bold") plt.show() Output: Matplotlib-Axis Class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 249, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack." }, { "code": null, "e": 347, "s": 249, "text": "The Axis.zoom() function in axis module of matplotlib library is used to zoom in or out on axis ." }, { "code": null, "e": 384, "s": 347, "text": "Syntax: Axis.zoom(self, direction) " }, { "code": null, "e": 443, "s": 384, "text": "Parameters: This method accepts the following parameters. " }, { "code": null, "e": 539, "s": 443, "text": "direction: This parameter is the value to zoom in (direction > 0) or zoom out (direction <= 0)." }, { "code": null, "e": 593, "s": 539, "text": "Return value: This method does not return any value. " }, { "code": null, "e": 681, "s": 593, "text": "Below examples illustrate the matplotlib.axis.Axis.zoom() function in matplotlib.axis: " }, { "code": null, "e": 692, "s": 681, "text": "Example 1:" }, { "code": null, "e": 700, "s": 692, "text": "Python3" }, { "code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.plot([1, 2, 3]) ax.xaxis.zoom(3) ax.grid() fig.suptitle(\"\"\"matplotlib.axis.Axis.zoom()function Example\\n\"\"\", fontweight =\"bold\") plt.show()", "e": 1010, "s": 700, "text": null }, { "code": null, "e": 1020, "s": 1010, "text": "Output: " }, { "code": null, "e": 1032, "s": 1020, "text": "Example 2: " }, { "code": null, "e": 1040, "s": 1032, "text": "Python3" }, { "code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons fig, ax1 = plt.subplots() plt.subplots_adjust(bottom = 0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t) ax1.plot(t, s, lw = 2, color = 'green') ax1.xaxis.zoom(-2) ax1.grid() fig.suptitle(\"\"\"matplotlib.axis.Axis.zoom()function Example\\n\"\"\", fontweight =\"bold\") plt.show()", "e": 1571, "s": 1040, "text": null }, { "code": null, "e": 1581, "s": 1571, "text": "Output: " }, { "code": null, "e": 1605, "s": 1583, "text": "Matplotlib-Axis Class" }, { "code": null, "e": 1623, "s": 1605, "text": "Python-matplotlib" }, { "code": null, "e": 1630, "s": 1623, "text": "Python" } ]
Java - Generics
It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements. You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods − All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). Following example illustrates how we can print an array of different type using a single Generic method − public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for(E element : inputArray) { System.out.printf("%s ", element); } System.out.println(); } public static void main(String args[]) { // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("Array integerArray contains:"); printArray(intArray); // pass an Integer array System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); // pass a Double array System.out.println("\nArray characterArray contains:"); printArray(charArray); // pass a Character array } } This will produce the following result − Array integerArray contains: 1 2 3 4 5 Array doubleArray contains: 1.1 2.2 3.3 4.4 Array characterArray contains: H E L L O There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound. Following example illustrates how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects − public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf("Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum("pear", "apple", "orange")); } } This will produce the following result − Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters. Following example illustrates how we can define a generic class − public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%d\n\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); } } This will produce the following result − Integer Value :10 String Value :Hello World 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": 2547, "s": 2377, "text": "It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering." }, { "code": null, "e": 2753, "s": 2547, "text": "Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively." }, { "code": null, "e": 2864, "s": 2753, "text": "Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time." }, { "code": null, "e": 3077, "s": 2864, "text": "Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements." }, { "code": null, "e": 3352, "s": 3077, "text": "You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods −" }, { "code": null, "e": 3521, "s": 3352, "text": "All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example)." }, { "code": null, "e": 3690, "s": 3521, "text": "All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example)." }, { "code": null, "e": 3878, "s": 3690, "text": "Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name." }, { "code": null, "e": 4066, "s": 3878, "text": "Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name." }, { "code": null, "e": 4252, "s": 4066, "text": "The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments." }, { "code": null, "e": 4438, "s": 4252, "text": "The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments." }, { "code": null, "e": 4616, "s": 4438, "text": "A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char)." }, { "code": null, "e": 4794, "s": 4616, "text": "A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char)." }, { "code": null, "e": 4900, "s": 4794, "text": "Following example illustrates how we can print an array of different type using a single Generic method −" }, { "code": null, "e": 5793, "s": 4900, "text": "public class GenericMethodTest {\n // generic method printArray\n public static < E > void printArray( E[] inputArray ) {\n // Display array elements\n for(E element : inputArray) {\n System.out.printf(\"%s \", element);\n }\n System.out.println();\n }\n\n public static void main(String args[]) {\n // Create arrays of Integer, Double and Character\n Integer[] intArray = { 1, 2, 3, 4, 5 };\n Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };\n Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };\n\n System.out.println(\"Array integerArray contains:\");\n printArray(intArray); // pass an Integer array\n\n System.out.println(\"\\nArray doubleArray contains:\");\n printArray(doubleArray); // pass a Double array\n\n System.out.println(\"\\nArray characterArray contains:\");\n printArray(charArray); // pass a Character array\n }\n}" }, { "code": null, "e": 5834, "s": 5793, "text": "This will produce the following result −" }, { "code": null, "e": 5963, "s": 5834, "text": "Array integerArray contains:\n1 2 3 4 5 \n\nArray doubleArray contains:\n1.1 2.2 3.3 4.4 \n\nArray characterArray contains:\nH E L L O\n" }, { "code": null, "e": 6239, "s": 5963, "text": "There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for." }, { "code": null, "e": 6370, "s": 6239, "text": "To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound." }, { "code": null, "e": 6599, "s": 6370, "text": "Following example illustrates how extends is used in a general sense to mean either \"extends\" (as in classes) or \"implements\" (as in interfaces). This example is Generic method to return the largest of three Comparable objects −" }, { "code": null, "e": 7474, "s": 6599, "text": "public class MaximumTest {\n // determines the largest of three Comparable objects\n \n public static <T extends Comparable<T>> T maximum(T x, T y, T z) {\n T max = x; // assume x is initially the largest\n \n if(y.compareTo(max) > 0) {\n max = y; // y is the largest so far\n }\n \n if(z.compareTo(max) > 0) {\n max = z; // z is the largest now \n }\n return max; // returns the largest object \n }\n \n public static void main(String args[]) {\n System.out.printf(\"Max of %d, %d and %d is %d\\n\\n\", \n 3, 4, 5, maximum( 3, 4, 5 ));\n\n System.out.printf(\"Max of %.1f,%.1f and %.1f is %.1f\\n\\n\",\n 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));\n\n System.out.printf(\"Max of %s, %s and %s is %s\\n\",\"pear\",\n \"apple\", \"orange\", maximum(\"pear\", \"apple\", \"orange\"));\n }\n}" }, { "code": null, "e": 7515, "s": 7474, "text": "This will produce the following result −" }, { "code": null, "e": 7609, "s": 7515, "text": "Max of 3, 4 and 5 is 5\n\nMax of 6.6,8.8 and 7.7 is 8.8\n\nMax of pear, apple and orange is pear\n" }, { "code": null, "e": 7749, "s": 7609, "text": "A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section." }, { "code": null, "e": 7994, "s": 7749, "text": "As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters." }, { "code": null, "e": 8060, "s": 7994, "text": "Following example illustrates how we can define a generic class −" }, { "code": null, "e": 8568, "s": 8060, "text": "public class Box<T> {\n private T t;\n\n public void add(T t) {\n this.t = t;\n }\n\n public T get() {\n return t;\n }\n\n public static void main(String[] args) {\n Box<Integer> integerBox = new Box<Integer>();\n Box<String> stringBox = new Box<String>();\n \n integerBox.add(new Integer(10));\n stringBox.add(new String(\"Hello World\"));\n\n System.out.printf(\"Integer Value :%d\\n\\n\", integerBox.get());\n System.out.printf(\"String Value :%s\\n\", stringBox.get());\n }\n}" }, { "code": null, "e": 8609, "s": 8568, "text": "This will produce the following result −" }, { "code": null, "e": 8654, "s": 8609, "text": "Integer Value :10\nString Value :Hello World\n" }, { "code": null, "e": 8687, "s": 8654, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8703, "s": 8687, "text": " Malhar Lathkar" }, { "code": null, "e": 8736, "s": 8703, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8752, "s": 8736, "text": " Malhar Lathkar" }, { "code": null, "e": 8787, "s": 8752, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8801, "s": 8787, "text": " Anadi Sharma" }, { "code": null, "e": 8835, "s": 8801, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 8849, "s": 8835, "text": " Tushar Kale" }, { "code": null, "e": 8886, "s": 8849, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8901, "s": 8886, "text": " Monica Mittal" }, { "code": null, "e": 8934, "s": 8901, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 8953, "s": 8934, "text": " Arnab Chakraborty" }, { "code": null, "e": 8960, "s": 8953, "text": " Print" }, { "code": null, "e": 8971, "s": 8960, "text": " Add Notes" } ]
C++ ios Library - Showpoint Function
It is used to sets the showpoint format flag for the str stream. When the showpoint format flag is set, the decimal point is always written for floating point values inserted into the stream (even for those whose decimal part is zero). Following the decimal point, as many digits as necessary are written to match the precision set for the stream (if any). Following is the declaration for std::showpoint function. ios_base& showpoint (ios_base& str); str − Stream object whose format flag is affected. It returns Argument str. Basic guarantee − if an exception is thrown, str is in a valid state. It modifies str. Concurrent access to the same stream object may cause data races. In below example explains about std::showpoint function. #include <iostream> int main () { double a = 30; double b = 10000.0; double pi = 3.1416; std::cout.precision (5); std::cout << std::showpoint << a << '\t' << b << '\t' << pi << '\n'; std::cout << std::noshowpoint << a << '\t' << b << '\t' << pi << '\n'; return 0; } Let us compile and run the above program, this will produce the following result − 30.000 10000. 3.1416 30 10000 3.1416 Print Add Notes Bookmark this page
[ { "code": null, "e": 2960, "s": 2603, "text": "It is used to sets the showpoint format flag for the str stream. When the showpoint format flag is set, the decimal point is always written for floating point values inserted into the stream (even for those whose decimal part is zero). Following the decimal point, as many digits as necessary are written to match the precision set for the stream (if any)." }, { "code": null, "e": 3018, "s": 2960, "text": "Following is the declaration for std::showpoint function." }, { "code": null, "e": 3055, "s": 3018, "text": "ios_base& showpoint (ios_base& str);" }, { "code": null, "e": 3106, "s": 3055, "text": "str − Stream object whose format flag is affected." }, { "code": null, "e": 3131, "s": 3106, "text": "It returns Argument str." }, { "code": null, "e": 3201, "s": 3131, "text": "Basic guarantee − if an exception is thrown, str is in a valid state." }, { "code": null, "e": 3284, "s": 3201, "text": "It modifies str. Concurrent access to the same stream object may cause data races." }, { "code": null, "e": 3341, "s": 3284, "text": "In below example explains about std::showpoint function." }, { "code": null, "e": 3631, "s": 3341, "text": "#include <iostream>\n\nint main () {\n double a = 30;\n double b = 10000.0;\n double pi = 3.1416;\n std::cout.precision (5);\n std::cout << std::showpoint << a << '\\t' << b << '\\t' << pi << '\\n';\n std::cout << std::noshowpoint << a << '\\t' << b << '\\t' << pi << '\\n';\n return 0;\n}" }, { "code": null, "e": 3714, "s": 3631, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3761, "s": 3714, "text": "30.000 10000. 3.1416\n30 10000 3.1416\n" }, { "code": null, "e": 3768, "s": 3761, "text": " Print" }, { "code": null, "e": 3779, "s": 3768, "text": " Add Notes" } ]
Inter Thread Communication With Condition() Method in Python - GeeksforGeeks
24 Jan, 2021 This article is based on how we use the Condition() method to implement Inter Thread Communication, let’s discuss this topic below -: Let’s have some brief discussion on Inter Thread Communication before talking about Condition() implementation for inter-thread communication, When any thread required something from another they will organize communication between them, and with this communication, they will fulfill their requirement. It means that it is a process of communicating between the threads for any kind of requirement. We can say that the implementation of inter-thread communication using the condition() method is the up-gradation of that event object used for inter-thread communication. Here Condition represents some type of state change between threads like ‘send notification’, ‘got notification’. See below how the condition object is creating:- Syntax : condition_object = threading.condition( ) In this scenario, threads can wait for that condition and once that condition executes then threads can modify according to that condition. In simple word, we can say that the condition object gave access to threads to wait until another thread give notification to them. Condition object is always correlated with lock (RLock) concept internally. Some following methods of Condition class we discuss below : release()acquire()notify()wait()notifyAll() release() acquire() notify() wait() notifyAll() release() Method: When the need of the condition object is fulfilled by threads then we will use the release() method which helps us to free the condition object from their tasks and suddenly releases the internal lock which was obtained by the threads. Syntax: condition_object.release() acquire() Method: When we want to obtain or takeover any condition object for inter-threading communication then we always used acquire() method. The acquire() method is compulsory when we want to implement inter-thread communication using condition class. When we use this method suddenly threads obtain the internal lock system. Syntax: condition_object.acquire() notify() Method: When we want to send a notification to only one thread that is in waiting state then we always use notify() method. Here if one thread wants to be condition object up-gradation then notify() is used. Syntax :condition_object.notify() wait(time) Method: The wait() method can be used to make a thread wait till the notification got and also till the given time will end. In simple words we can say that thread is to wait until the execution of the notify() method is not done. We can use time in it if we set a certain time then the execution will stop until time overs after that it will execute still the instructions are remaining. Syntax: condition_object.wait() Parameter:Time notifyAll() Method: Here the notifyAll() method is used to send notifications for all waiting threads. If all threads are waiting for condition object updating then notifyAll() will use. Syntax: condition_object.notifyAll() Now let’s take a simple example to show how acquire and release methods are used and how they work through the entire program -: Example 1: Python3 # code# import modules import threading import time obj1= threading.Condition() def task (): obj1.acquire() print('addition of 1 to 10 ') add= 0 for i in range ( 1 , 11 ): add = add+i print(add) obj1.release() print('the condition object is releases now') t1 = threading.Thread(target = task)t1.start() addition of 1 to 10 55 the condition object is releases now In the above example, we use acquire() and release() method which can be used to obtain or acquire the condition object and after the completion of tasks releases the condition object. First, we are importing the required modules, and then we create the condition object which is obj1 then we create and start the thread t1, In the task named function there where we used acquire() method from these we obtain the condition object and also from here internal lock of threads are started. After the completion of instructions at the last we release the condition object and also the internal lock of threads is released. Example 2: In this example we used other methods to explain how they work through the entire program:- Python3 # code # import modules import timefrom threading import *import random class appointment: def patient(self): condition_object.acquire() print('patient john waiting for appointment') condition_object.wait() # Thread is in waiting state print('successfully got the appointment') condition_object.release() def doctor(self): condition_object.acquire() print('doctor jarry checking the time for appointment') time=0 time=random.randint(1,13) print('time checked') print('oppointed time is {} PM'.format(time)) condition_object.notify() condition_object.release() condition_object = Condition()class_obj=appointment() T1 = Thread(target=class_obj.patient) T2 = Thread(target=class_obj.doctor) T1.start() T2.start() patient john waiting for appointment doctor jarry checking the time for appointment time checked oppointed time is 4 PM successfully got the appointment This is a simple example to explain the use of Condition() class and their methods in threading. Also, here we use an example of patient and doctor how patient and doctor first acquire the conditions and then how to notify them, and at last both also release the condition object. Let’s start first we create a class appointment which was having two functions which name as a patient() and doctor() and then we created two threads T1 and T2. With the help of the acquire() method, the doctor and patient both acquire the condition object in their first statement by this both the threads are internally locked. Now the patient has to wait for an appointment and got appointed after the execution of the wait() method doctor starting to check whether the time he chooses is it ok to go for an appointment or not and when the time is chosen by the doctor then it will notify to thread that is in waiting for the state by notify() method. Next after the notify() method, the patient got their notification and product both. Then after all this, both threads release the condition object by release() method and internal lock releases. Python-threading 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 Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24426, "s": 24292, "text": "This article is based on how we use the Condition() method to implement Inter Thread Communication, let’s discuss this topic below -:" }, { "code": null, "e": 24827, "s": 24426, "text": "Let’s have some brief discussion on Inter Thread Communication before talking about Condition() implementation for inter-thread communication, When any thread required something from another they will organize communication between them, and with this communication, they will fulfill their requirement. It means that it is a process of communicating between the threads for any kind of requirement. " }, { "code": null, "e": 25168, "s": 24827, "text": "We can say that the implementation of inter-thread communication using the condition() method is the up-gradation of that event object used for inter-thread communication. Here Condition represents some type of state change between threads like ‘send notification’, ‘got notification’. See below how the condition object is creating:- " }, { "code": null, "e": 25177, "s": 25168, "text": "Syntax :" }, { "code": null, "e": 25219, "s": 25177, "text": "condition_object = threading.condition( )" }, { "code": null, "e": 25567, "s": 25219, "text": "In this scenario, threads can wait for that condition and once that condition executes then threads can modify according to that condition. In simple word, we can say that the condition object gave access to threads to wait until another thread give notification to them. Condition object is always correlated with lock (RLock) concept internally." }, { "code": null, "e": 25628, "s": 25567, "text": "Some following methods of Condition class we discuss below :" }, { "code": null, "e": 25672, "s": 25628, "text": "release()acquire()notify()wait()notifyAll()" }, { "code": null, "e": 25682, "s": 25672, "text": "release()" }, { "code": null, "e": 25692, "s": 25682, "text": "acquire()" }, { "code": null, "e": 25701, "s": 25692, "text": "notify()" }, { "code": null, "e": 25708, "s": 25701, "text": "wait()" }, { "code": null, "e": 25720, "s": 25708, "text": "notifyAll()" }, { "code": null, "e": 25974, "s": 25720, "text": "release() Method: When the need of the condition object is fulfilled by threads then we will use the release() method which helps us to free the condition object from their tasks and suddenly releases the internal lock which was obtained by the threads." }, { "code": null, "e": 26009, "s": 25974, "text": "Syntax: condition_object.release()" }, { "code": null, "e": 26340, "s": 26009, "text": "acquire() Method: When we want to obtain or takeover any condition object for inter-threading communication then we always used acquire() method. The acquire() method is compulsory when we want to implement inter-thread communication using condition class. When we use this method suddenly threads obtain the internal lock system." }, { "code": null, "e": 26375, "s": 26340, "text": "Syntax: condition_object.acquire()" }, { "code": null, "e": 26592, "s": 26375, "text": "notify() Method: When we want to send a notification to only one thread that is in waiting state then we always use notify() method. Here if one thread wants to be condition object up-gradation then notify() is used." }, { "code": null, "e": 26664, "s": 26592, "text": "Syntax :condition_object.notify() " }, { "code": null, "e": 27064, "s": 26664, "text": "wait(time) Method: The wait() method can be used to make a thread wait till the notification got and also till the given time will end. In simple words we can say that thread is to wait until the execution of the notify() method is not done. We can use time in it if we set a certain time then the execution will stop until time overs after that it will execute still the instructions are remaining." }, { "code": null, "e": 27112, "s": 27064, "text": "Syntax: condition_object.wait()\nParameter:Time " }, { "code": null, "e": 27300, "s": 27112, "text": " notifyAll() Method: Here the notifyAll() method is used to send notifications for all waiting threads. If all threads are waiting for condition object updating then notifyAll() will use." }, { "code": null, "e": 27337, "s": 27300, "text": "Syntax: condition_object.notifyAll()" }, { "code": null, "e": 27466, "s": 27337, "text": "Now let’s take a simple example to show how acquire and release methods are used and how they work through the entire program -:" }, { "code": null, "e": 27477, "s": 27466, "text": "Example 1:" }, { "code": null, "e": 27485, "s": 27477, "text": "Python3" }, { "code": "# code# import modules import threading import time obj1= threading.Condition() def task (): obj1.acquire() print('addition of 1 to 10 ') add= 0 for i in range ( 1 , 11 ): add = add+i print(add) obj1.release() print('the condition object is releases now') t1 = threading.Thread(target = task)t1.start()", "e": 27808, "s": 27485, "text": null }, { "code": null, "e": 27869, "s": 27808, "text": "addition of 1 to 10 \n55\nthe condition object is releases now" }, { "code": null, "e": 28489, "s": 27869, "text": "In the above example, we use acquire() and release() method which can be used to obtain or acquire the condition object and after the completion of tasks releases the condition object. First, we are importing the required modules, and then we create the condition object which is obj1 then we create and start the thread t1, In the task named function there where we used acquire() method from these we obtain the condition object and also from here internal lock of threads are started. After the completion of instructions at the last we release the condition object and also the internal lock of threads is released." }, { "code": null, "e": 28500, "s": 28489, "text": "Example 2:" }, { "code": null, "e": 28592, "s": 28500, "text": "In this example we used other methods to explain how they work through the entire program:-" }, { "code": null, "e": 28600, "s": 28592, "text": "Python3" }, { "code": "# code # import modules import timefrom threading import *import random class appointment: def patient(self): condition_object.acquire() print('patient john waiting for appointment') condition_object.wait() # Thread is in waiting state print('successfully got the appointment') condition_object.release() def doctor(self): condition_object.acquire() print('doctor jarry checking the time for appointment') time=0 time=random.randint(1,13) print('time checked') print('oppointed time is {} PM'.format(time)) condition_object.notify() condition_object.release() condition_object = Condition()class_obj=appointment() T1 = Thread(target=class_obj.patient) T2 = Thread(target=class_obj.doctor) T1.start() T2.start()", "e": 29377, "s": 28600, "text": null }, { "code": null, "e": 29530, "s": 29377, "text": "patient john waiting for appointment\ndoctor jarry checking the time for appointment\ntime checked\noppointed time is 4 PM\nsuccessfully got the appointment" }, { "code": null, "e": 30663, "s": 29530, "text": "This is a simple example to explain the use of Condition() class and their methods in threading. Also, here we use an example of patient and doctor how patient and doctor first acquire the conditions and then how to notify them, and at last both also release the condition object. Let’s start first we create a class appointment which was having two functions which name as a patient() and doctor() and then we created two threads T1 and T2. With the help of the acquire() method, the doctor and patient both acquire the condition object in their first statement by this both the threads are internally locked. Now the patient has to wait for an appointment and got appointed after the execution of the wait() method doctor starting to check whether the time he chooses is it ok to go for an appointment or not and when the time is chosen by the doctor then it will notify to thread that is in waiting for the state by notify() method. Next after the notify() method, the patient got their notification and product both. Then after all this, both threads release the condition object by release() method and internal lock releases. " }, { "code": null, "e": 30680, "s": 30663, "text": "Python-threading" }, { "code": null, "e": 30687, "s": 30680, "text": "Python" }, { "code": null, "e": 30785, "s": 30687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30794, "s": 30785, "text": "Comments" }, { "code": null, "e": 30807, "s": 30794, "text": "Old Comments" }, { "code": null, "e": 30839, "s": 30807, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30895, "s": 30839, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30950, "s": 30895, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 30992, "s": 30950, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31034, "s": 30992, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31065, "s": 31034, "text": "Python | os.path.join() method" }, { "code": null, "e": 31104, "s": 31065, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31126, "s": 31104, "text": "Defaultdict in Python" }, { "code": null, "e": 31155, "s": 31126, "text": "Create a directory in Python" } ]
Naive Bayes Document Classification in Python | by Kelly Epley | Towards Data Science
Naive Bayes is a reasonably effective strategy for document classification tasks even though it is, as the name indicates, “naive.” Naive Bayes classification makes use of Bayes theorem to determine how probable it is that an item is a member of a category. If I have a document that contains the word “trust” or “virtue” or “knowledge,” what’s the probability that it falls in the category “ethics” rather than “epistemology?” Naive Bayes sorts items into categories based on whichever probability is highest. It’s “naive” because it treats the probability of each word appearing in a document as though it were independent of the probability of any other word appearing. This assumption is almost never true of any documents we’d wish to classify, which tend to follow rules of grammar, syntax, and communication. When we follow these rules, some words tend to be correlated with other words. Here, I devised what I thought would be a somewhat difficult classification task: sorting philosophy articles’ abstracts. I chose sub-disciplines that are distinct, but that have a significant amount of overlap: Epistemology and Ethics. Both employ the language of justification and reasons. They also intersect frequently (e.g. ethics of belief, moral knowledge, and so forth). In the end, Naive Bayes performed surprisingly well in classifying these documents. What is Naive Bayes Classification? Bayes Theorem Bayes theorem tells us that the probability of a hypothesis given some evidence is equal to the probability of the hypothesis multiplied by the probability of the evidence given the hypothesis, then divided by the probability of the evidence. Pr(H|E) = Pr(H) * Pr(E|H) / Pr(E) Since we are classifying documents, the “hypothesis” is: the document fits into category C. The “evidence” is the words W occurring in the document. Since classification tasks involve comparing two (or more) hypotheses, we can use the ratio form of Bayes theorem, which compares the numerators of the above formula (for Bayes aficionados: the prior times the likelihood) for each hypothesis: Pr(C1|W) / Pr(C2|W)= Pr(C1) * Pr(W|C1) / Pr(C2) * Pr(W|C2) Since there are many words in a document, the formula becomes: Pr(C1|W1, W2 ...Wn) / Pr(C2|W1, W2 ...Wn)= Pr(C1) * (Pr(W1|C1) * Pr(W2|C1) * ...Pr(Wn|C1)) / Pr(C2) * (Pr(W1|C2) * Pr(W2|C2) * ...Pr(Wn|C2)) For example, if I want to know whether a document containing the words “preheat the oven” is a member of the category “cookbooks” rather than “novels,” I’d compare this: Pr(cookbook) * Pr(“preheat”|cookbook) * Pr(“the”|cookbook) * Pr(“oven”|cookbook) To this: Pr(novel) * Pr(“preheat”|novel) * Pr(“the”|novel) * Pr(“oven”|novel) If the probability of its being a cookbook given the presence of the words in the document is greater than the probability of its being a novel, Naive Bayes returns “cookbook”. If it’s the other way around, Naive Bayes returns “novel”. A demonstration: Classifying philosophy papers by their abstracts Prepare the data Prepare the data The documents I will attempt to classify are article abstracts from a database called PhilPapers. Philpapers is a comprehensive database of research in philosophy. Since this database is curated by legions of topic editors, we can be reasonably confident that the document classifications given on the site are correct. I selected two philosophy subdisciplines from the site for a binary Naive Bayes classifier: ethics or epistemology. From each subdiscipline, I selected a topic. For ethics, I chose the topic “Varieties of Virtue Ethics” and for epistemology, I chose “Trust.” I collected 80 ethics and 80 epistemology abstracts. The head and tail of my initial DataFrame looked like this: To run a Naive Bayes classifier in Scikit Learn, the categories must be numeric, so I assigned the label 1 to all ethics abstracts and the label 0 to all epistemology abstracts (that is, not ethics): df[‘label’] = df[‘category’].apply(lambda x: 0 if x==’Epistemology’ else 1) 2. Split data into training and testing sets It’s important to hold back some data so that we can validate our model. For this, we can use Scikit Learn’s train_test_split. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df[‘abstract’], df[‘label’], random_state=1) 3. Convert abstracts into word count vectors A Naive Bayes classifier needs to be able to calculate how many times each word appears in each document and how many times it appears in each category. To make this possible, the data needs to look something like this: [0, 1, 0, ...] [1, 1, 1, ...] [0, 2, 0, ...] Each row represents a document, and each column represents a word. The first row might be a document that contains a zero for “preheat,” a one for “the” and a zero for “oven”. That means that the document contains one instance of the word “the”, but no “preheat” or “oven.” To get our abstracts in this format, we can use Scikit Learn’s CountVectorizer. CountVectorizer creates a vector of word counts for each abstract to form a matrix. Each index corresponds to a word and every word appearing in the abstracts is represented. from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer(strip_accents=’ascii’, token_pattern=u’(?ui)\\b\\w*[a-z]+\\w*\\b’, lowercase=True, stop_words=’english’)X_train_cv = cv.fit_transform(X_train)X_test_cv = cv.transform(X_test) We can use the strip_accents, token_pattern, lowercase, and stopwords arguments to exclude nonwords, numbers, articles, and other things that are not useful for predicting categories from our counts. For details, see the documentation. If you’d like to view the data and investigate the word counts, you can make a DataFrame of the word counts with the following code: word_freq_df = pd.DataFrame(X_train_cv.toarray(), columns=cv.get_feature_names())top_words_df = pd.DataFrame(word_freq.sum()).sort_values(0, ascending=False)``` 4. Fit the model and make predictions Now we’re ready to fit a Multinomial Naive Bayes classifier model to our training data and use it to predict the test data’s labels: from sklearn.naive_bayes import MultinomialNBnaive_bayes = MultinomialNB()naive_bayes.fit(X_train_cv, y_train)predictions = naive_bayes.predict(X_test_cv) 5. Check the results Let’s see how the model performed on the test data: from sklearn.metrics import accuracy_score, precision_score, recall_scoreprint(‘Accuracy score: ‘, accuracy_score(y_test, predictions))print(‘Precision score: ‘, precision_score(y_test, predictions))print(‘Recall score: ‘, recall_score(y_test, predictions)) To understand these scores, it helps to see a breakdown: from sklearn.metrics import confusion_matriximport matplotlib.pyplot as pltimport seaborn as snscm = confusion_matrix(y_test, predictions)sns.heatmap(cm, square=True, annot=True, cmap=’RdBu’, cbar=False,xticklabels=[‘epistemology’, ‘ethics’], yticklabels=[‘epistemology’, ‘ethics’])plt.xlabel(‘true label’)plt.ylabel(‘predicted label’) The accuracy score tells us: out of all of the identifications we made, how many were correct? true positives + true negatives / total observations: (18 + 19) / 40 The precision score tells us: out of all of the ethics identifications we made, how many were correct? true positives / (true positives + false positives): 18 / (18+2) The recall score tells us: out of all of the true cases of ethics, how many did we identify correctly? true positives / (true positives + false negatives): 18/(18+1) 6. Investigate the model’s misses To investigate the incorrect labels, we can put the actual labels and the predicted labels side-by-side in a DataFrame. testing_predictions = []for i in range(len(X_test)): if predictions[i] == 1: testing_predictions.append(‘Ethics’) else: testing_predictions.append(‘Epistemology’)check_df = pd.DataFrame({‘actual_label’: list(y_test), ‘prediction’: testing_predictions, ‘abstract’:list(X_test)})check_df.replace(to_replace=0, value=’Epistemology’, inplace=True)check_df.replace(to_replace=1, value=’Ethics’, inplace=True) Overall, my Naive Bayes classifier performed well on the test set. There were only three mismatched labels out of 40.
[ { "code": null, "e": 304, "s": 172, "text": "Naive Bayes is a reasonably effective strategy for document classification tasks even though it is, as the name indicates, “naive.”" }, { "code": null, "e": 683, "s": 304, "text": "Naive Bayes classification makes use of Bayes theorem to determine how probable it is that an item is a member of a category. If I have a document that contains the word “trust” or “virtue” or “knowledge,” what’s the probability that it falls in the category “ethics” rather than “epistemology?” Naive Bayes sorts items into categories based on whichever probability is highest." }, { "code": null, "e": 1067, "s": 683, "text": "It’s “naive” because it treats the probability of each word appearing in a document as though it were independent of the probability of any other word appearing. This assumption is almost never true of any documents we’d wish to classify, which tend to follow rules of grammar, syntax, and communication. When we follow these rules, some words tend to be correlated with other words." }, { "code": null, "e": 1530, "s": 1067, "text": "Here, I devised what I thought would be a somewhat difficult classification task: sorting philosophy articles’ abstracts. I chose sub-disciplines that are distinct, but that have a significant amount of overlap: Epistemology and Ethics. Both employ the language of justification and reasons. They also intersect frequently (e.g. ethics of belief, moral knowledge, and so forth). In the end, Naive Bayes performed surprisingly well in classifying these documents." }, { "code": null, "e": 1566, "s": 1530, "text": "What is Naive Bayes Classification?" }, { "code": null, "e": 1580, "s": 1566, "text": "Bayes Theorem" }, { "code": null, "e": 1823, "s": 1580, "text": "Bayes theorem tells us that the probability of a hypothesis given some evidence is equal to the probability of the hypothesis multiplied by the probability of the evidence given the hypothesis, then divided by the probability of the evidence." }, { "code": null, "e": 1857, "s": 1823, "text": "Pr(H|E) = Pr(H) * Pr(E|H) / Pr(E)" }, { "code": null, "e": 2006, "s": 1857, "text": "Since we are classifying documents, the “hypothesis” is: the document fits into category C. The “evidence” is the words W occurring in the document." }, { "code": null, "e": 2249, "s": 2006, "text": "Since classification tasks involve comparing two (or more) hypotheses, we can use the ratio form of Bayes theorem, which compares the numerators of the above formula (for Bayes aficionados: the prior times the likelihood) for each hypothesis:" }, { "code": null, "e": 2308, "s": 2249, "text": "Pr(C1|W) / Pr(C2|W)= Pr(C1) * Pr(W|C1) / Pr(C2) * Pr(W|C2)" }, { "code": null, "e": 2371, "s": 2308, "text": "Since there are many words in a document, the formula becomes:" }, { "code": null, "e": 2414, "s": 2371, "text": "Pr(C1|W1, W2 ...Wn) / Pr(C2|W1, W2 ...Wn)=" }, { "code": null, "e": 2464, "s": 2414, "text": "Pr(C1) * (Pr(W1|C1) * Pr(W2|C1) * ...Pr(Wn|C1)) /" }, { "code": null, "e": 2512, "s": 2464, "text": "Pr(C2) * (Pr(W1|C2) * Pr(W2|C2) * ...Pr(Wn|C2))" }, { "code": null, "e": 2682, "s": 2512, "text": "For example, if I want to know whether a document containing the words “preheat the oven” is a member of the category “cookbooks” rather than “novels,” I’d compare this:" }, { "code": null, "e": 2763, "s": 2682, "text": "Pr(cookbook) * Pr(“preheat”|cookbook) * Pr(“the”|cookbook) * Pr(“oven”|cookbook)" }, { "code": null, "e": 2772, "s": 2763, "text": "To this:" }, { "code": null, "e": 2841, "s": 2772, "text": "Pr(novel) * Pr(“preheat”|novel) * Pr(“the”|novel) * Pr(“oven”|novel)" }, { "code": null, "e": 3077, "s": 2841, "text": "If the probability of its being a cookbook given the presence of the words in the document is greater than the probability of its being a novel, Naive Bayes returns “cookbook”. If it’s the other way around, Naive Bayes returns “novel”." }, { "code": null, "e": 3143, "s": 3077, "text": "A demonstration: Classifying philosophy papers by their abstracts" }, { "code": null, "e": 3160, "s": 3143, "text": "Prepare the data" }, { "code": null, "e": 3177, "s": 3160, "text": "Prepare the data" }, { "code": null, "e": 3497, "s": 3177, "text": "The documents I will attempt to classify are article abstracts from a database called PhilPapers. Philpapers is a comprehensive database of research in philosophy. Since this database is curated by legions of topic editors, we can be reasonably confident that the document classifications given on the site are correct." }, { "code": null, "e": 3809, "s": 3497, "text": "I selected two philosophy subdisciplines from the site for a binary Naive Bayes classifier: ethics or epistemology. From each subdiscipline, I selected a topic. For ethics, I chose the topic “Varieties of Virtue Ethics” and for epistemology, I chose “Trust.” I collected 80 ethics and 80 epistemology abstracts." }, { "code": null, "e": 3869, "s": 3809, "text": "The head and tail of my initial DataFrame looked like this:" }, { "code": null, "e": 4069, "s": 3869, "text": "To run a Naive Bayes classifier in Scikit Learn, the categories must be numeric, so I assigned the label 1 to all ethics abstracts and the label 0 to all epistemology abstracts (that is, not ethics):" }, { "code": null, "e": 4145, "s": 4069, "text": "df[‘label’] = df[‘category’].apply(lambda x: 0 if x==’Epistemology’ else 1)" }, { "code": null, "e": 4190, "s": 4145, "text": "2. Split data into training and testing sets" }, { "code": null, "e": 4317, "s": 4190, "text": "It’s important to hold back some data so that we can validate our model. For this, we can use Scikit Learn’s train_test_split." }, { "code": null, "e": 4466, "s": 4317, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(df[‘abstract’], df[‘label’], random_state=1)" }, { "code": null, "e": 4511, "s": 4466, "text": "3. Convert abstracts into word count vectors" }, { "code": null, "e": 4731, "s": 4511, "text": "A Naive Bayes classifier needs to be able to calculate how many times each word appears in each document and how many times it appears in each category. To make this possible, the data needs to look something like this:" }, { "code": null, "e": 4746, "s": 4731, "text": "[0, 1, 0, ...]" }, { "code": null, "e": 4761, "s": 4746, "text": "[1, 1, 1, ...]" }, { "code": null, "e": 4776, "s": 4761, "text": "[0, 2, 0, ...]" }, { "code": null, "e": 5050, "s": 4776, "text": "Each row represents a document, and each column represents a word. The first row might be a document that contains a zero for “preheat,” a one for “the” and a zero for “oven”. That means that the document contains one instance of the word “the”, but no “preheat” or “oven.”" }, { "code": null, "e": 5305, "s": 5050, "text": "To get our abstracts in this format, we can use Scikit Learn’s CountVectorizer. CountVectorizer creates a vector of word counts for each abstract to form a matrix. Each index corresponds to a word and every word appearing in the abstracts is represented." }, { "code": null, "e": 5560, "s": 5305, "text": "from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer(strip_accents=’ascii’, token_pattern=u’(?ui)\\\\b\\\\w*[a-z]+\\\\w*\\\\b’, lowercase=True, stop_words=’english’)X_train_cv = cv.fit_transform(X_train)X_test_cv = cv.transform(X_test)" }, { "code": null, "e": 5796, "s": 5560, "text": "We can use the strip_accents, token_pattern, lowercase, and stopwords arguments to exclude nonwords, numbers, articles, and other things that are not useful for predicting categories from our counts. For details, see the documentation." }, { "code": null, "e": 5929, "s": 5796, "text": "If you’d like to view the data and investigate the word counts, you can make a DataFrame of the word counts with the following code:" }, { "code": null, "e": 6090, "s": 5929, "text": "word_freq_df = pd.DataFrame(X_train_cv.toarray(), columns=cv.get_feature_names())top_words_df = pd.DataFrame(word_freq.sum()).sort_values(0, ascending=False)```" }, { "code": null, "e": 6128, "s": 6090, "text": "4. Fit the model and make predictions" }, { "code": null, "e": 6261, "s": 6128, "text": "Now we’re ready to fit a Multinomial Naive Bayes classifier model to our training data and use it to predict the test data’s labels:" }, { "code": null, "e": 6416, "s": 6261, "text": "from sklearn.naive_bayes import MultinomialNBnaive_bayes = MultinomialNB()naive_bayes.fit(X_train_cv, y_train)predictions = naive_bayes.predict(X_test_cv)" }, { "code": null, "e": 6437, "s": 6416, "text": "5. Check the results" }, { "code": null, "e": 6489, "s": 6437, "text": "Let’s see how the model performed on the test data:" }, { "code": null, "e": 6747, "s": 6489, "text": "from sklearn.metrics import accuracy_score, precision_score, recall_scoreprint(‘Accuracy score: ‘, accuracy_score(y_test, predictions))print(‘Precision score: ‘, precision_score(y_test, predictions))print(‘Recall score: ‘, recall_score(y_test, predictions))" }, { "code": null, "e": 6804, "s": 6747, "text": "To understand these scores, it helps to see a breakdown:" }, { "code": null, "e": 7140, "s": 6804, "text": "from sklearn.metrics import confusion_matriximport matplotlib.pyplot as pltimport seaborn as snscm = confusion_matrix(y_test, predictions)sns.heatmap(cm, square=True, annot=True, cmap=’RdBu’, cbar=False,xticklabels=[‘epistemology’, ‘ethics’], yticklabels=[‘epistemology’, ‘ethics’])plt.xlabel(‘true label’)plt.ylabel(‘predicted label’)" }, { "code": null, "e": 7235, "s": 7140, "text": "The accuracy score tells us: out of all of the identifications we made, how many were correct?" }, { "code": null, "e": 7304, "s": 7235, "text": "true positives + true negatives / total observations: (18 + 19) / 40" }, { "code": null, "e": 7407, "s": 7304, "text": "The precision score tells us: out of all of the ethics identifications we made, how many were correct?" }, { "code": null, "e": 7472, "s": 7407, "text": "true positives / (true positives + false positives): 18 / (18+2)" }, { "code": null, "e": 7575, "s": 7472, "text": "The recall score tells us: out of all of the true cases of ethics, how many did we identify correctly?" }, { "code": null, "e": 7638, "s": 7575, "text": "true positives / (true positives + false negatives): 18/(18+1)" }, { "code": null, "e": 7672, "s": 7638, "text": "6. Investigate the model’s misses" }, { "code": null, "e": 7792, "s": 7672, "text": "To investigate the incorrect labels, we can put the actual labels and the predicted labels side-by-side in a DataFrame." }, { "code": null, "e": 8216, "s": 7792, "text": "testing_predictions = []for i in range(len(X_test)): if predictions[i] == 1: testing_predictions.append(‘Ethics’) else: testing_predictions.append(‘Epistemology’)check_df = pd.DataFrame({‘actual_label’: list(y_test), ‘prediction’: testing_predictions, ‘abstract’:list(X_test)})check_df.replace(to_replace=0, value=’Epistemology’, inplace=True)check_df.replace(to_replace=1, value=’Ethics’, inplace=True)" } ]
AI with Python – Deep Learning
Artificial Neural Network (ANN) it is an efficient computing system, whose central theme is borrowed from the analogy of biological neural networks. Neural networks are one type of model for machine learning. In the mid-1980s and early 1990s, much important architectural advancements were made in neural networks. In this chapter, you will learn more about Deep Learning, an approach of AI. Deep learning emerged from a decade’s explosive computational growth as a serious contender in the field. Thus, deep learning is a particular kind of machine learning whose algorithms are inspired by the structure and function of human brain. Deep learning is the most powerful machine learning technique these days. It is so powerful because they learn the best way to represent the problem while learning how to solve the problem. A comparison of Deep learning and Machine learning is given below − The first point of difference is based upon the performance of DL and ML when the scale of data increases. When the data is large, deep learning algorithms perform very well. Deep learning algorithms need high-end machines to work perfectly. On the other hand, machine learning algorithms can work on low-end machines too. Deep learning algorithms can extract high level features and try to learn from the same too. On the other hand, an expert is required to identify most of the features extracted by machine learning. Execution time depends upon the numerous parameters used in an algorithm. Deep learning has more parameters than machine learning algorithms. Hence, the execution time of DL algorithms, specially the training time, is much more than ML algorithms. But the testing time of DL algorithms is less than ML algorithms. Deep learning solves the problem end-to-end while machine learning uses the traditional way of solving the problem i.e. by breaking down it into parts. Convolutional neural networks are the same as ordinary neural networks because they are also made up of neurons that have learnable weights and biases. Ordinary neural networks ignore the structure of input data and all the data is converted into 1-D array before feeding it into the network. This process suits the regular data, however if the data contains images, the process may be cumbersome. CNN solves this problem easily. It takes the 2D structure of the images into account when they process them, which allows them to extract the properties specific to images. In this way, the main goal of CNNs is to go from the raw image data in the input layer to the correct class in the output layer. The only difference between an ordinary NNs and CNNs is in the treatment of input data and in the type of layers. Architecturally, the ordinary neural networks receive an input and transform it through a series of hidden layer. Every layer is connected to the other layer with the help of neurons. The main disadvantage of ordinary neural networks is that they do not scale well to full images. The architecture of CNNs have neurons arranged in 3 dimensions called width, height and depth. Each neuron in the current layer is connected to a small patch of the output from the previous layer. It is similar to overlaying a N×N filter on the input image. It uses M filters to be sure about getting all the details. These M filters are feature extractors which extract features like edges, corners, etc. Following layers are used to construct CNNs − Input Layer − It takes the raw image data as it is. Input Layer − It takes the raw image data as it is. Convolutional Layer − This layer is the core building block of CNNs that does most of the computations. This layer computes the convolutions between the neurons and the various patches in the input. Convolutional Layer − This layer is the core building block of CNNs that does most of the computations. This layer computes the convolutions between the neurons and the various patches in the input. Rectified Linear Unit Layer − It applies an activation function to the output of the previous layer. It adds non-linearity to the network so that it can generalize well to any type of function. Rectified Linear Unit Layer − It applies an activation function to the output of the previous layer. It adds non-linearity to the network so that it can generalize well to any type of function. Pooling Layer − Pooling helps us to keep only the important parts as we progress in the network. Pooling layer operates independently on every depth slice of the input and resizes it spatially. It uses the MAX function. Pooling Layer − Pooling helps us to keep only the important parts as we progress in the network. Pooling layer operates independently on every depth slice of the input and resizes it spatially. It uses the MAX function. Fully Connected layer/Output layer − This layer computes the output scores in the last layer. The resulting output is of the size 1×1×L , where L is the number training dataset classes. Fully Connected layer/Output layer − This layer computes the output scores in the last layer. The resulting output is of the size 1×1×L , where L is the number training dataset classes. You can use Keras, which is an high level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK or Theno. It is compatible with Python 2.7-3.6. You can learn more about it from https://keras.io/. Use the following commands to install keras − pip install keras On conda environment, you can use the following command − conda install –c conda-forge keras In this section, you will learn how to build a linear regressor using artificial neural networks. You can use KerasRegressor to achieve this. In this example, we are using the Boston house price dataset with 13 numerical for properties in Boston. The Python code for the same is shown here − Import all the required packages as shown − import numpy import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold Now, load our dataset which is saved in local directory. dataframe = pandas.read_csv("/Usrrs/admin/data.csv", delim_whitespace = True, header = None) dataset = dataframe.values Now, divide the data into input and output variables i.e. X and Y − X = dataset[:,0:13] Y = dataset[:,13] Since we use baseline neural networks, define the model − def baseline_model(): Now, create the model as follows − model_regressor = Sequential() model_regressor.add(Dense(13, input_dim = 13, kernel_initializer = 'normal', activation = 'relu')) model_regressor.add(Dense(1, kernel_initializer = 'normal')) Next, compile the model − model_regressor.compile(loss='mean_squared_error', optimizer='adam') return model_regressor Now, fix the random seed for reproducibility as follows − seed = 7 numpy.random.seed(seed) The Keras wrapper object for use in scikit-learn as a regression estimator is called KerasRegressor. In this section, we shall evaluate this model with standardize data set. estimator = KerasRegressor(build_fn = baseline_model, nb_epoch = 100, batch_size = 5, verbose = 0) kfold = KFold(n_splits = 10, random_state = seed) baseline_result = cross_val_score(estimator, X, Y, cv = kfold) print("Baseline: %.2f (%.2f) MSE" % (Baseline_result.mean(),Baseline_result.std())) The output of the code shown above would be the estimate of the model’s performance on the problem for unseen data. It will be the mean squared error, including the average and standard deviation across all 10 folds of the cross validation evaluation. Convolutional Neural Networks (CNNs) solve an image classification problem, that is to which class the input image belongs to. You can use Keras deep learning library. Note that we are using the training and testing data set of images of cats and dogs from following link https://www.kaggle.com/c/dogs-vs-cats/data. Import the important keras libraries and packages as shown − The following package called sequential will initialize the neural networks as sequential network. from keras.models import Sequential The following package called Conv2D is used to perform the convolution operation, the first step of CNN. from keras.layers import Conv2D The following package called MaxPoling2D is used to perform the pooling operation, the second step of CNN. from keras.layers import MaxPooling2D The following package called Flatten is the process of converting all the resultant 2D arrays into a single long continuous linear vector. from keras.layers import Flatten The following package called Dense is used to perform the full connection of the neural network, the fourth step of CNN. from keras.layers import Dense Now, create an object of the sequential class. S_classifier = Sequential() Now, next step is coding the convolution part. S_classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) Here relu is the rectifier function. Now, the next step of CNN is the pooling operation on the resultant feature maps after convolution part. S-classifier.add(MaxPooling2D(pool_size = (2, 2))) Now, convert all the pooled images into a continuous vector by using flattering − S_classifier.add(Flatten()) Next, create a fully connected layer. S_classifier.add(Dense(units = 128, activation = 'relu')) Here, 128 is the number of hidden units. It is a common practice to define the number of hidden units as the power of 2. Now, initialize the output layer as follows − S_classifier.add(Dense(units = 1, activation = 'sigmoid')) Now, compile the CNN, we have built − S_classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) Here optimizer parameter is to choose the stochastic gradient descent algorithm, loss parameter is to choose the loss function and metrics parameter is to choose the performance metric. Now, perform image augmentations and then fit the images to the neural networks − train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory(”/Users/admin/training_set”,target_size = (64, 64),batch_size = 32,class_mode = 'binary') test_set = test_datagen.flow_from_directory('test_set',target_size = (64, 64),batch_size = 32,class_mode = 'binary') Now, fit the data to the model we have created − classifier.fit_generator(training_set,steps_per_epoch = 8000,epochs = 25,validation_data = test_set,validation_steps = 2000) Here steps_per_epoch have the number of training images. Now as the model has been trained, we can use it for prediction as follows − from keras.preprocessing import image test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) result = classifier.predict(test_image) training_set.class_indices if result[0][0] == 1: prediction = 'dog' else: prediction = 'cat' 78 Lectures 7 hours Arnab Chakraborty 87 Lectures 9.5 hours DigiFisk (Programming Is Fun) 10 Lectures 1 hours Nikoloz Sanakoevi 15 Lectures 54 mins Mukund Kumar Mishra 11 Lectures 1 hours Gilad James, PhD 20 Lectures 2 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2597, "s": 2205, "text": "Artificial Neural Network (ANN) it is an efficient computing system, whose central theme is borrowed from the analogy of biological neural networks. Neural networks are one type of model for machine learning. In the mid-1980s and early 1990s, much important architectural advancements were made in neural networks. In this chapter, you will learn more about Deep Learning, an approach of AI." }, { "code": null, "e": 2840, "s": 2597, "text": "Deep learning emerged from a decade’s explosive computational growth as a serious contender in the field. Thus, deep learning is a particular kind of machine learning whose algorithms are inspired by the structure and function of human brain." }, { "code": null, "e": 3098, "s": 2840, "text": "Deep learning is the most powerful machine learning technique these days. It is so powerful because they learn the best way to represent the problem while learning how to solve the problem. A comparison of Deep learning and Machine learning is given below −" }, { "code": null, "e": 3273, "s": 3098, "text": "The first point of difference is based upon the performance of DL and ML when the scale of data increases. When the data is large, deep learning algorithms perform very well." }, { "code": null, "e": 3421, "s": 3273, "text": "Deep learning algorithms need high-end machines to work perfectly. On the other hand, machine learning algorithms can work on low-end machines too." }, { "code": null, "e": 3619, "s": 3421, "text": "Deep learning algorithms can extract high level features and try to learn from the same too. On the other hand, an expert is required to identify most of the features extracted by machine learning." }, { "code": null, "e": 3933, "s": 3619, "text": "Execution time depends upon the numerous parameters used in an algorithm. Deep learning has more parameters than machine learning algorithms. Hence, the execution time of DL algorithms, specially the training time, is much more than ML algorithms. But the testing time of DL algorithms is less than ML algorithms." }, { "code": null, "e": 4085, "s": 3933, "text": "Deep learning solves the problem end-to-end while machine learning uses the traditional way of solving the problem i.e. by breaking down it into parts." }, { "code": null, "e": 4483, "s": 4085, "text": "Convolutional neural networks are the same as ordinary neural networks because they are also made up of neurons that have learnable weights and biases. Ordinary neural networks ignore the structure of input data and all the data is converted into 1-D array before feeding it into the network. This process suits the regular data, however if the data contains images, the process may be cumbersome." }, { "code": null, "e": 4899, "s": 4483, "text": "CNN solves this problem easily. It takes the 2D structure of the images into account when they process them, which allows them to extract the properties specific to images. In this way, the main goal of CNNs is to go from the raw image data in the input layer to the correct class in the output layer. The only difference between an ordinary NNs and CNNs is in the treatment of input data and in the type of layers." }, { "code": null, "e": 5180, "s": 4899, "text": "Architecturally, the ordinary neural networks receive an input and transform it through a series of hidden layer. Every layer is connected to the other layer with the help of neurons. The main disadvantage of ordinary neural networks is that they do not scale well to full images." }, { "code": null, "e": 5586, "s": 5180, "text": "The architecture of CNNs have neurons arranged in 3 dimensions called width, height and depth. Each neuron in the current layer is connected to a small patch of the output from the previous layer. It is similar to overlaying a N×N filter on the input image. It uses M filters to be sure about getting all the details. These M filters are feature extractors which extract features like edges, corners, etc." }, { "code": null, "e": 5632, "s": 5586, "text": "Following layers are used to construct CNNs −" }, { "code": null, "e": 5684, "s": 5632, "text": "Input Layer − It takes the raw image data as it is." }, { "code": null, "e": 5736, "s": 5684, "text": "Input Layer − It takes the raw image data as it is." }, { "code": null, "e": 5935, "s": 5736, "text": "Convolutional Layer − This layer is the core building block of CNNs that does most of the computations. This layer computes the convolutions between the neurons and the various patches in the input." }, { "code": null, "e": 6134, "s": 5935, "text": "Convolutional Layer − This layer is the core building block of CNNs that does most of the computations. This layer computes the convolutions between the neurons and the various patches in the input." }, { "code": null, "e": 6328, "s": 6134, "text": "Rectified Linear Unit Layer − It applies an activation function to the output of the previous layer. It adds non-linearity to the network so that it can generalize well to any type of function." }, { "code": null, "e": 6522, "s": 6328, "text": "Rectified Linear Unit Layer − It applies an activation function to the output of the previous layer. It adds non-linearity to the network so that it can generalize well to any type of function." }, { "code": null, "e": 6742, "s": 6522, "text": "Pooling Layer − Pooling helps us to keep only the important parts as we progress in the network. Pooling layer operates independently on every depth slice of the input and resizes it spatially. It uses the MAX function." }, { "code": null, "e": 6962, "s": 6742, "text": "Pooling Layer − Pooling helps us to keep only the important parts as we progress in the network. Pooling layer operates independently on every depth slice of the input and resizes it spatially. It uses the MAX function." }, { "code": null, "e": 7148, "s": 6962, "text": "Fully Connected layer/Output layer − This layer computes the output scores in the last layer. The resulting output is of the size 1×1×L , where L is the number training dataset classes." }, { "code": null, "e": 7334, "s": 7148, "text": "Fully Connected layer/Output layer − This layer computes the output scores in the last layer. The resulting output is of the size 1×1×L , where L is the number training dataset classes." }, { "code": null, "e": 7565, "s": 7334, "text": "You can use Keras, which is an high level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK or Theno. It is compatible with Python 2.7-3.6. You can learn more about it from https://keras.io/." }, { "code": null, "e": 7611, "s": 7565, "text": "Use the following commands to install keras −" }, { "code": null, "e": 7630, "s": 7611, "text": "pip install keras\n" }, { "code": null, "e": 7688, "s": 7630, "text": "On conda environment, you can use the following command −" }, { "code": null, "e": 7724, "s": 7688, "text": "conda install –c conda-forge keras\n" }, { "code": null, "e": 8016, "s": 7724, "text": "In this section, you will learn how to build a linear regressor using artificial neural networks. You can use KerasRegressor to achieve this. In this example, we are using the Boston house price dataset with 13 numerical for properties in Boston. The Python code for the same is shown here −" }, { "code": null, "e": 8060, "s": 8016, "text": "Import all the required packages as shown −" }, { "code": null, "e": 8303, "s": 8060, "text": "import numpy\nimport pandas\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold" }, { "code": null, "e": 8360, "s": 8303, "text": "Now, load our dataset which is saved in local directory." }, { "code": null, "e": 8480, "s": 8360, "text": "dataframe = pandas.read_csv(\"/Usrrs/admin/data.csv\", delim_whitespace = True, header = None)\ndataset = dataframe.values" }, { "code": null, "e": 8548, "s": 8480, "text": "Now, divide the data into input and output variables i.e. X and Y −" }, { "code": null, "e": 8586, "s": 8548, "text": "X = dataset[:,0:13]\nY = dataset[:,13]" }, { "code": null, "e": 8644, "s": 8586, "text": "Since we use baseline neural networks, define the model −" }, { "code": null, "e": 8666, "s": 8644, "text": "def baseline_model():" }, { "code": null, "e": 8701, "s": 8666, "text": "Now, create the model as follows −" }, { "code": null, "e": 8896, "s": 8701, "text": "model_regressor = Sequential()\nmodel_regressor.add(Dense(13, input_dim = 13, kernel_initializer = 'normal', \n activation = 'relu'))\nmodel_regressor.add(Dense(1, kernel_initializer = 'normal'))" }, { "code": null, "e": 8922, "s": 8896, "text": "Next, compile the model −" }, { "code": null, "e": 9014, "s": 8922, "text": "model_regressor.compile(loss='mean_squared_error', optimizer='adam')\nreturn model_regressor" }, { "code": null, "e": 9072, "s": 9014, "text": "Now, fix the random seed for reproducibility as follows −" }, { "code": null, "e": 9105, "s": 9072, "text": "seed = 7\nnumpy.random.seed(seed)" }, { "code": null, "e": 9279, "s": 9105, "text": "The Keras wrapper object for use in scikit-learn as a regression estimator is called KerasRegressor. In this section, we shall evaluate this model with standardize data set." }, { "code": null, "e": 9575, "s": 9279, "text": "estimator = KerasRegressor(build_fn = baseline_model, nb_epoch = 100, batch_size = 5, verbose = 0)\nkfold = KFold(n_splits = 10, random_state = seed)\nbaseline_result = cross_val_score(estimator, X, Y, cv = kfold)\nprint(\"Baseline: %.2f (%.2f) MSE\" % (Baseline_result.mean(),Baseline_result.std()))" }, { "code": null, "e": 9827, "s": 9575, "text": "The output of the code shown above would be the estimate of the model’s performance on the problem for unseen data. It will be the mean squared error, including the average and standard deviation across all 10 folds of the cross validation evaluation." }, { "code": null, "e": 10143, "s": 9827, "text": "Convolutional Neural Networks (CNNs) solve an image classification problem, that is to which class the input image belongs to. You can use Keras deep learning library. Note that we are using the training and testing data set of images of cats and dogs from following link https://www.kaggle.com/c/dogs-vs-cats/data." }, { "code": null, "e": 10204, "s": 10143, "text": "Import the important keras libraries and packages as shown −" }, { "code": null, "e": 10303, "s": 10204, "text": "The following package called sequential will initialize the neural networks as sequential network." }, { "code": null, "e": 10339, "s": 10303, "text": "from keras.models import Sequential" }, { "code": null, "e": 10444, "s": 10339, "text": "The following package called Conv2D is used to perform the convolution operation, the first step of CNN." }, { "code": null, "e": 10476, "s": 10444, "text": "from keras.layers import Conv2D" }, { "code": null, "e": 10583, "s": 10476, "text": "The following package called MaxPoling2D is used to perform the pooling operation, the second step of CNN." }, { "code": null, "e": 10621, "s": 10583, "text": "from keras.layers import MaxPooling2D" }, { "code": null, "e": 10760, "s": 10621, "text": "The following package called Flatten is the process of converting all the resultant 2D arrays into a single long continuous linear vector." }, { "code": null, "e": 10793, "s": 10760, "text": "from keras.layers import Flatten" }, { "code": null, "e": 10914, "s": 10793, "text": "The following package called Dense is used to perform the full connection of the neural network, the fourth step of CNN." }, { "code": null, "e": 10945, "s": 10914, "text": "from keras.layers import Dense" }, { "code": null, "e": 10992, "s": 10945, "text": "Now, create an object of the sequential class." }, { "code": null, "e": 11020, "s": 10992, "text": "S_classifier = Sequential()" }, { "code": null, "e": 11067, "s": 11020, "text": "Now, next step is coding the convolution part." }, { "code": null, "e": 11152, "s": 11067, "text": "S_classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))" }, { "code": null, "e": 11189, "s": 11152, "text": "Here relu is the rectifier function." }, { "code": null, "e": 11294, "s": 11189, "text": "Now, the next step of CNN is the pooling operation on the resultant feature maps after convolution part." }, { "code": null, "e": 11345, "s": 11294, "text": "S-classifier.add(MaxPooling2D(pool_size = (2, 2)))" }, { "code": null, "e": 11427, "s": 11345, "text": "Now, convert all the pooled images into a continuous vector by using flattering −" }, { "code": null, "e": 11455, "s": 11427, "text": "S_classifier.add(Flatten())" }, { "code": null, "e": 11493, "s": 11455, "text": "Next, create a fully connected layer." }, { "code": null, "e": 11551, "s": 11493, "text": "S_classifier.add(Dense(units = 128, activation = 'relu'))" }, { "code": null, "e": 11672, "s": 11551, "text": "Here, 128 is the number of hidden units. It is a common practice to define the number of hidden units as the power of 2." }, { "code": null, "e": 11718, "s": 11672, "text": "Now, initialize the output layer as follows −" }, { "code": null, "e": 11777, "s": 11718, "text": "S_classifier.add(Dense(units = 1, activation = 'sigmoid'))" }, { "code": null, "e": 11815, "s": 11777, "text": "Now, compile the CNN, we have built −" }, { "code": null, "e": 11910, "s": 11815, "text": "S_classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])" }, { "code": null, "e": 12096, "s": 11910, "text": "Here optimizer parameter is to choose the stochastic gradient descent algorithm, loss parameter is to choose the loss function and metrics parameter is to choose the performance metric." }, { "code": null, "e": 12178, "s": 12096, "text": "Now, perform image augmentations and then fit the images to the neural networks −" }, { "code": null, "e": 12623, "s": 12178, "text": "train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2,\nzoom_range = 0.2,\nhorizontal_flip = True)\ntest_datagen = ImageDataGenerator(rescale = 1./255)\n\ntraining_set = \n train_datagen.flow_from_directory(”/Users/admin/training_set”,target_size = \n (64, 64),batch_size = 32,class_mode = 'binary')\n\ntest_set = \n test_datagen.flow_from_directory('test_set',target_size = \n (64, 64),batch_size = 32,class_mode = 'binary')" }, { "code": null, "e": 12672, "s": 12623, "text": "Now, fit the data to the model we have created −" }, { "code": null, "e": 12798, "s": 12672, "text": "classifier.fit_generator(training_set,steps_per_epoch = 8000,epochs = \n25,validation_data = test_set,validation_steps = 2000)" }, { "code": null, "e": 12855, "s": 12798, "text": "Here steps_per_epoch have the number of training images." }, { "code": null, "e": 12932, "s": 12855, "text": "Now as the model has been trained, we can use it for prediction as follows −" }, { "code": null, "e": 13306, "s": 12932, "text": "from keras.preprocessing import image\n\ntest_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', \ntarget_size = (64, 64))\n\ntest_image = image.img_to_array(test_image)\n\ntest_image = np.expand_dims(test_image, axis = 0)\n\nresult = classifier.predict(test_image)\n\ntraining_set.class_indices\n\nif result[0][0] == 1:\nprediction = 'dog'\n\nelse:\n prediction = 'cat'" }, { "code": null, "e": 13339, "s": 13306, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 13358, "s": 13339, "text": " Arnab Chakraborty" }, { "code": null, "e": 13393, "s": 13358, "text": "\n 87 Lectures \n 9.5 hours \n" }, { "code": null, "e": 13424, "s": 13393, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 13457, "s": 13424, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 13476, "s": 13457, "text": " Nikoloz Sanakoevi" }, { "code": null, "e": 13508, "s": 13476, "text": "\n 15 Lectures \n 54 mins\n" }, { "code": null, "e": 13529, "s": 13508, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 13562, "s": 13529, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 13580, "s": 13562, "text": " Gilad James, PhD" }, { "code": null, "e": 13613, "s": 13580, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 13631, "s": 13613, "text": " Gilad James, PhD" }, { "code": null, "e": 13638, "s": 13631, "text": " Print" }, { "code": null, "e": 13649, "s": 13638, "text": " Add Notes" } ]
Inorder Successor in BST | Practice | GeeksforGeeks
Given a BST, and a reference to a Node x in the BST. Find the Inorder Successor of the given node in the BST. Example 1: Input: 2 / \ 1 3 K(data of x) = 2 Output: 3 Explanation: Inorder traversal : 1 2 3 Hence, inorder successor of 2 is 3. Example 2: Input: 20 / \ 8 22 / \ 4 12 / \ 10 14 K(data of x) = 8 Output: 10 Explanation: Inorder traversal: 4 8 10 12 14 20 22 Hence, successor of 8 is 10. Your Task: You don't need to read input or print anything. Your task is to complete the function inOrderSuccessor(). This function takes the root node and the reference node as argument and returns the node that is inOrder successor of the reference node. If there is no successor, return null value. Expected Time Complexity: O(Height of the BST). Expected Auxiliary Space: O(1). Constraints: 1 <= N <= 1000, where N is number of nodes 0 utkarsh061 day ago Node * inOrderSuccessor(Node *root, Node *x) { Node* successor = NULL; while(root != NULL) { if(root->data <= x->data) root = root->right; else { successor = root; //might be a possible answer root = root->left; } } return successor; } 0 generalandy29973 days ago We can use Morris traversal to solve this problem, which is based on threaded binary tree. The time complexity is O(K), where x is Kth small number in BST. And the space complexity is O(1). def inorderSuccessor(self, root, x): isSuccessor = False while root: if root.left: # If left subtree exists, we have to create right threaded remember = root child = root.left # Find rightmost child in left subtree while child.right: child = child.right child.right = remember root = remember.left # Must remove left link or there will exist cycle remember.left = None else: # we only use right link to traversal if isSuccessor: return root if root.data == x.data: isSuccessor = True root = root.right return None 0 siddharthraja98496 days ago class Solution{ public: // returns the inorder successor of the Node x in BST (rooted at 'root') Node * inOrderSuccessor(Node *root, Node *x) { Node *ans=NULL; while(root!=NULL){ if(root->data==x->data) break; if(root->data>x->data){ ans=root; root=root->left; } else{ root=root->right; } } if(root->right==NULL) { return ans; } Node * p=root->right; while(p->left!=NULL)p=p->left; return p; //Your code here } }; 0 tanashah1 week ago void inorder(Node* root,queue<Node*>&q){ if(root==NULL){ return; } inorder(root->left,q); q.push(root); inorder(root->right,q); } Node * inOrderSuccessor(Node *root, Node *x) { //Your code here if(root==NULL){ return NULL; } queue<Node*>q; int temp; inorder(root,q); while(q.front()!=x){ q.pop();//je equal nahi te kadle } q.pop(); if(q.size()==0){ return NULL; } return q.front(); } 0 aryankhatana352 weeks ago C++ sol void inorder(Node *root, vector<Node*>&a){ if(root==NULL){ return; }https://practice.geeksforgeeks.org/problems/inorder-successor-in-bst/1/?page=1&difficulty[]=-2&difficulty[]=-1&difficulty[]=0&status[]=solved&status[]=unsolved&category[]=Binary%20Search%20Tree&sortBy=submissions# inorder(root->left,a); a.push_back(root); inorder(root->right,a); } public: // returns the inorder successor of the Node x in BST (rooted at 'root') Node * inOrderSuccessor(Node *root, Node *x) { //Your code here vector<Node*>ans; inorder(root,ans); for(int i=0;i<ans.size();i++){ if(ans[i]==x && i<ans.size()-1){ return ans[i+1]; } } return NULL; } +1 smeetgadhiya012 weeks ago SIMPLE JAVA SOLUTION TC : O(Height of Tree) SC : O(1) public Node inorderSuccessor(Node root,Node x) { Node successor = null; while(root != null){ if(x.data >= root.data){ root = root.right; }else{ successor = root; root = root.left; } } return successor; } +1 amishasahu3283 weeks ago Node * inOrderSuccessor(Node *root, Node *x) { //Your code here Node *successor = NULL; while(root) { if(root->data <= x->data) root = root->right; else { successor = root; root = root->left; } } return successor; } 0 ashutoshmulky73 weeks ago //MY accepted Java solution class Solution { // returns the inorder successor of the Node x in BST (rooted at 'root') public Node inorderSuccessor(Node root,Node x) { if(x.right!=null){ Node temp = x.right; while(temp.left!=null){ temp = temp.left; } return temp; } Node temp = root; Node succ = null; while(temp!=null){ if(temp.data>x.data){ succ=temp; temp=temp.left; } else if(temp.data<x.data){ temp=temp.right; } else{ break; } } return succ; } } 0 jaatgfg111 month ago void inorder(Node* root,queue<Node*>&s){ if(root==NULL){ return; } inorder(root->left,s); s.push(root); inorder(root->right,s); } Node * inOrderSuccessor(Node *root, Node *x){ queue<Node*>s; inorder(root,s); while(s.front()!=x){ s.pop(); } s.pop(); if(s.size()==0){ return NULL; } return s.front(); } +2 rajatgupta96961 month ago Node * inOrderSuccessor(Node *root, Node *x) { Node * successor=NULL; while(root!=NULL) { if(root->data > x->data) { successor=root; root=root->left; } else if(root->data <= x->data) { root=root->right; } } return successor; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 350, "s": 238, "text": "Given a BST, and a reference to a Node x in the BST. Find the Inorder Successor of the given node in the BST.\n " }, { "code": null, "e": 361, "s": 350, "text": "Example 1:" }, { "code": null, "e": 503, "s": 361, "text": "Input:\n 2\n / \\\n 1 3\nK(data of x) = 2\nOutput: 3 \nExplanation: \nInorder traversal : 1 2 3 \nHence, inorder successor of 2 is 3.\n" }, { "code": null, "e": 515, "s": 503, "text": "\nExample 2:" }, { "code": null, "e": 750, "s": 515, "text": "Input:\n 20\n / \\\n 8 22\n / \\\n 4 12\n / \\\n 10 14\nK(data of x) = 8\nOutput: 10\nExplanation:\nInorder traversal: 4 8 10 12 14 20 22\nHence, successor of 8 is 10." }, { "code": null, "e": 1053, "s": 752, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function inOrderSuccessor(). This function takes the root node and the reference node as argument and returns the node that is inOrder successor of the reference node. If there is no successor, return null value." }, { "code": null, "e": 1134, "s": 1053, "text": "\nExpected Time Complexity: O(Height of the BST).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1191, "s": 1134, "text": "\nConstraints:\n1 <= N <= 1000, where N is number of nodes" }, { "code": null, "e": 1193, "s": 1191, "text": "0" }, { "code": null, "e": 1212, "s": 1193, "text": "utkarsh061 day ago" }, { "code": null, "e": 1583, "s": 1212, "text": "Node * inOrderSuccessor(Node *root, Node *x)\n {\n Node* successor = NULL;\n \n while(root != NULL)\n {\n if(root->data <= x->data)\n root = root->right;\n else\n { successor = root; //might be a possible answer\n root = root->left;\n }\n }\n return successor;\n }" }, { "code": null, "e": 1585, "s": 1583, "text": "0" }, { "code": null, "e": 1611, "s": 1585, "text": "generalandy29973 days ago" }, { "code": null, "e": 1702, "s": 1611, "text": "We can use Morris traversal to solve this problem, which is based on threaded binary tree." }, { "code": null, "e": 1767, "s": 1702, "text": "The time complexity is O(K), where x is Kth small number in BST." }, { "code": null, "e": 1801, "s": 1767, "text": "And the space complexity is O(1)." }, { "code": null, "e": 2599, "s": 1801, "text": "def inorderSuccessor(self, root, x):\n\t\tisSuccessor = False\n \twhile root:\n if root.left:\n \t# If left subtree exists, we have to create right threaded\n remember = root\n child = root.left\n # Find rightmost child in left subtree\n while child.right:\n child = child.right\n child.right = remember\n root = remember.left\n # Must remove left link or there will exist cycle\n remember.left = None\n else:\n \t# we only use right link to traversal\n if isSuccessor: return root\n if root.data == x.data:\n isSuccessor = True\n root = root.right\n return None" }, { "code": null, "e": 2601, "s": 2599, "text": "0" }, { "code": null, "e": 2629, "s": 2601, "text": "siddharthraja98496 days ago" }, { "code": null, "e": 3295, "s": 2629, "text": "class Solution{\n public:\n // returns the inorder successor of the Node x in BST (rooted at 'root')\n Node * inOrderSuccessor(Node *root, Node *x)\n {\n Node *ans=NULL;\n \n while(root!=NULL){\n if(root->data==x->data)\n break;\n if(root->data>x->data){\n ans=root;\n root=root->left;\n }\n else{\n root=root->right;\n }\n }\n \n if(root->right==NULL)\n {\n return ans;\n }\n Node * p=root->right;\n while(p->left!=NULL)p=p->left;\n return p;\n //Your code here\n }\n};" }, { "code": null, "e": 3297, "s": 3295, "text": "0" }, { "code": null, "e": 3316, "s": 3297, "text": "tanashah1 week ago" }, { "code": null, "e": 3857, "s": 3316, "text": "void inorder(Node* root,queue<Node*>&q){ if(root==NULL){ return; } inorder(root->left,q); q.push(root); inorder(root->right,q); } Node * inOrderSuccessor(Node *root, Node *x) { //Your code here if(root==NULL){ return NULL; } queue<Node*>q; int temp; inorder(root,q); while(q.front()!=x){ q.pop();//je equal nahi te kadle } q.pop(); if(q.size()==0){ return NULL; } return q.front(); }" }, { "code": null, "e": 3859, "s": 3857, "text": "0" }, { "code": null, "e": 3885, "s": 3859, "text": "aryankhatana352 weeks ago" }, { "code": null, "e": 3893, "s": 3885, "text": "C++ sol" }, { "code": null, "e": 4660, "s": 3893, "text": " void inorder(Node *root, vector<Node*>&a){ if(root==NULL){ return; }https://practice.geeksforgeeks.org/problems/inorder-successor-in-bst/1/?page=1&difficulty[]=-2&difficulty[]=-1&difficulty[]=0&status[]=solved&status[]=unsolved&category[]=Binary%20Search%20Tree&sortBy=submissions# inorder(root->left,a); a.push_back(root); inorder(root->right,a); } public: // returns the inorder successor of the Node x in BST (rooted at 'root') Node * inOrderSuccessor(Node *root, Node *x) { //Your code here vector<Node*>ans; inorder(root,ans); for(int i=0;i<ans.size();i++){ if(ans[i]==x && i<ans.size()-1){ return ans[i+1]; } } return NULL; }" }, { "code": null, "e": 4663, "s": 4660, "text": "+1" }, { "code": null, "e": 4689, "s": 4663, "text": "smeetgadhiya012 weeks ago" }, { "code": null, "e": 4711, "s": 4689, "text": " SIMPLE JAVA SOLUTION" }, { "code": null, "e": 4734, "s": 4711, "text": "TC : O(Height of Tree)" }, { "code": null, "e": 4744, "s": 4734, "text": "SC : O(1)" }, { "code": null, "e": 5121, "s": 4746, "text": "public Node inorderSuccessor(Node root,Node x) { Node successor = null; while(root != null){ if(x.data >= root.data){ root = root.right; }else{ successor = root; root = root.left; } } return successor; }" }, { "code": null, "e": 5124, "s": 5121, "text": "+1" }, { "code": null, "e": 5149, "s": 5124, "text": "amishasahu3283 weeks ago" }, { "code": null, "e": 5517, "s": 5149, "text": "Node * inOrderSuccessor(Node *root, Node *x)\n {\n //Your code here\n Node *successor = NULL;\n while(root)\n {\n if(root->data <= x->data)\n root = root->right;\n else\n {\n successor = root;\n root = root->left;\n }\n }\n return successor;\n }" }, { "code": null, "e": 5519, "s": 5517, "text": "0" }, { "code": null, "e": 5545, "s": 5519, "text": "ashutoshmulky73 weeks ago" }, { "code": null, "e": 6310, "s": 5545, "text": "//MY accepted Java solution\nclass Solution\n{\n // returns the inorder successor of the Node x in BST (rooted at 'root')\npublic Node inorderSuccessor(Node root,Node x)\n {\n if(x.right!=null){\n Node temp = x.right;\n while(temp.left!=null){\n temp = temp.left;\n }\n return temp;\n }\n \n Node temp = root;\n Node succ = null;\n while(temp!=null){\n if(temp.data>x.data){\n succ=temp;\n temp=temp.left;\n }\n else if(temp.data<x.data){\n temp=temp.right;\n }\n else{\n break;\n }\n }\n return succ;\n }\n}" }, { "code": null, "e": 6312, "s": 6310, "text": "0" }, { "code": null, "e": 6333, "s": 6312, "text": "jaatgfg111 month ago" }, { "code": null, "e": 6763, "s": 6333, "text": " void inorder(Node* root,queue<Node*>&s){ if(root==NULL){ return; } inorder(root->left,s); s.push(root); inorder(root->right,s); } Node * inOrderSuccessor(Node *root, Node *x){ queue<Node*>s; inorder(root,s); while(s.front()!=x){ s.pop(); } s.pop(); if(s.size()==0){ return NULL; } return s.front(); }" }, { "code": null, "e": 6766, "s": 6763, "text": "+2" }, { "code": null, "e": 6792, "s": 6766, "text": "rajatgupta96961 month ago" }, { "code": null, "e": 7147, "s": 6792, "text": " Node * inOrderSuccessor(Node *root, Node *x) { Node * successor=NULL; while(root!=NULL) { if(root->data > x->data) { successor=root; root=root->left; } else if(root->data <= x->data) { root=root->right; } } return successor; }" }, { "code": null, "e": 7293, "s": 7147, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7329, "s": 7293, "text": " Login to access your submissions. " }, { "code": null, "e": 7339, "s": 7329, "text": "\nProblem\n" }, { "code": null, "e": 7349, "s": 7339, "text": "\nContest\n" }, { "code": null, "e": 7412, "s": 7349, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7560, "s": 7412, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7768, "s": 7560, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7874, "s": 7768, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
A Complete Logistic Regression Algorithm for Image Classification in Python From Scratch | by Rashida Nasrin Sucky | Towards Data Science
Logistic regression is very popular in machine learning and statistics. It can work on both binary and multiclass classification very well. I wrote tutorials on both binary and multiclass classification with logistic regression before. This article will be focused on image classification with logistic regression. If you are totally new to logistic regression, please go to this article first. This article has a detailed explanation of how a simple logistic regression algorithm works. towardsdatascience.com It will be helpful if you are familiar with logistic regression already. If not, I hope you will still understand the concepts here. I tried to explain it well. If you are reading this to learn, the only way is to run all the codes by yourself. The idea of this project is to develop and train a model that is able to take the pixel values of a digit and identify if it is an image of the digit one or not. The dataset that will be used in this tutorial is very commonly used in machine learning tutorials. The famous digits dataset. Each row of the dataset represents the flattened pixel values of a digit. I will show you in detail later. This dataset contains the pixel values of the digits from zero to nine. But because this tutorial is about binary classification, the goal of this model will be to return 1 if the digit is one and 0 otherwise. Please feel free to download the dataset from the link below to follow along: github.com Here I am importing the dataset: import pandas as pdimport numpy as npdf= pd.read_excel('ex3d1.xlsx', 'X', header=None)df.head() You can see that the dataset has 400 columns. That means each row has 400-pixel values and each row represents one digit. Let’s check some of the digits using the ‘imshow’ function of the matplotlib library. Notice that the pixel values of images are originally not one-dimensional. That’s why it was reshaped into a 20 x 20 two-dimensional array before passing into the ‘imshow’ function. import matplotlib.pyplot as pltplt.imshow(np.array(df.iloc[500, :]).reshape(20,20)) It’s one! Here I used the 500th row of the dataset. Here is another one using the 1750th row of the dataset: plt.imshow(np.array(X.iloc[1750, :]).reshape(20,20)) It’s three. Let’s check how many rows are in this dataset: len(df) Output: 5000 Labels are stored in a different sheet in this excel file. Here are the labels: df_y= pd.read_excel('ex3d1.xlsx', 'y', header=None)df_y.head() I am only showing the head of the dataset that brings the first five rows. Because this model will identify the digit 1 only, it will return 1 if the digit is 1 and 0 otherwise. So, in the label, I will keep only 1 and the rest of the digits will become zero. Let’s convert the rest of the digits as zeros. For that y = df_y[0]for i in range(len(y)): if y[i] != 1: y[i] = 0y = pd.DataFrame(y)y Out of these 5000 rows of data, 4000 rows will be used to train the model, and the remaining 1000 rows will be used to test the model. It is important for any machine learning or deep learning model to be tested by unseen data to the model. x_train = X.iloc[0:4000].Ty_train = y.iloc[0:4000].Tx_test = X.iloc[4000:].Ty_test = y.iloc[4000:].T Using .T, we are taking the transpose of each dataset. These training and test datasets are in DataFrame form. They need to be in an array format for the convenience of calculation. x_train = np.array(x_train)y_train = np.array(y_train)x_test = np.array(x_test)y_test = np.array(y_test) The training and test datasets are ready to be used in the model. This is the time to develop the model. Step 1: The logistic regression uses the basic linear regression formula that we all learned in high school: Y = AX + B Where Y is the output, X is the input or independent variable, A is the slope and B is the intercept. In logistic regression variables are expressed in this way: Formula 1 Here z is the output variable, x is the input variable. w and b will be initialized as zeros to start with and they will be modified by numbers of iterations while training the model. This output z is passed through a non-linear function. The commonly used nonlinear function is the sigmoid function that returns a value between 0 and 1. Formula 2 As a reminder, the formula for the sigmoid function is: Formula 3 This ‘a’ will be the final output that is the value in the ‘y_train’ or ‘y_test’. Here is the function to define the sigmoid function for later use: def sigmoid(z): s = 1/(1 + np.exp(-z)) return s As we mentioned before, w and b will be initialized as zeros. One w value will be initialized for each pixel value. Let’s define a function to initialize the zero value for w and b: def initialize_with_zeros(dim): w = np.zeros(shape=(dim, 1)) b = 0 return w, b Cost Function The cost function is a measure of a model that reflects how much the predicted output differs from the original output. Here is the formula for the cost function of one training example or one row of data: Formula 4 The average cost function for all the rows is: The aim of the model will be to lower the cost function value. Gradient descent We need to update the variables w and b of Formula 1. It would be initialized as zeros but they need to be updated later with more appropriate values. Gradient descent will help with that. Let’s see how. In Formula 4, we expressed the cost function as a function of ‘a’ and ‘y’. But it can be expressed as a function of ‘w’ and ‘b’ as well. Because ‘a’ is derived using ‘w’ and ‘b’. The formula for the differential ‘w’ and ‘b’ will be derived by taking the partial differentiation of cost function with respect to ‘w’ and ‘b’. Formula 5 and Formula 6 Now that we have all the formulas, let’s put it all together in a function called ‘propagate’: def propagate(w, b, X, Y): #Find the number of training data m = X.shape[1] #Calculate the predicted output A = sigmoid(np.dot(w.T, X) + b) #Calculate the cost function cost = -1/m * np.sum(Y*np.log(A) + (1-Y) * np.log(1-A)) #Calculate the gradients dw = 1/m * np.dot(X, (A-Y).T) db = 1/m * np.sum(A-Y) grads = {"dw": dw, "db": db} return grads, cost The propagate function calculates the predicted output that is ‘A’, cost function ‘cost’, and the gradients ‘dw’ and ‘db’. Using this function, we can now update ‘w’ and ‘b’ in Formula 1. That is the next step. Optimize the parameters to best fit the training data In this step, we will update the parameters which are the core of this model. The ‘propagate’ function will be run through a number of iterations. In each iteration, ‘w’ and ‘b’ will be updated. Below is a complete ‘optimize’ function. I explained each step in the code snippet. Please read carefully. A new term learning rate was introduced in this function. That’s not a calculated value. It is different for the different machine learning algorithms. Try a few different learning rates to see which works best. def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] #propagate function will run for a number of iterations for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads["dw"] db = grads["db"] #Updating w and b by deducting the dw #and db times learning rate from the previous #w and b w = w - learning_rate * dw b = b - learning_rate * db #Record the cost function value for each 100 iterations if i % 100 == 0: costs.append(cost) #The final updated parameters params = {"w": w, "b": b} #The final updated gradients grads = {"dw": dw, "db": db} return params, grads, costs We have the function to optimize the parameters. This is the time to predict the output: Explanation of each line of code is embedded in between the code snippet. Please read carefully to understand it well. def predict(w, b, X): m = X.shape[1] #Initializing an aray of zeros which has a size of the input #These zeros will be replaced by the predicted output Y_prediction = np.zeros((1, m)) w = w.reshape(X.shape[0], 1) #Calculating the predicted output using the Formula 1 #This will return the values from 0 to 1 A = sigmoid(np.dot(w.T, X) + b) #Iterating through A and predict an 1 if the value of A #is greater than 0.5 and zero otherwise for i in range(A.shape[1]): Y_prediction[:, i] = (A[:, i] > 0.5) * 1 return Y_prediction Final Model Putting all the functions together, the final model will look like this: def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5): #Initializing the w and b as zeros w, b = initialize_with_zeros(X_train.shape[0]) parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) w = parameters["w"] b = parameters["b"] # Predicting the output for both test and training set Y_prediction_test = predict(w, b, X_test) Y_prediction_train = predict(w, b, X_train) #Calculating the training and test set accuracy by comparing #the predicted output and the original output print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train" : Y_prediction_train, "w" : w, "b" : b, "learning_rate" : learning_rate, "num_iterations": num_iterations} return d The complete logistic regression model is ready! Using the model This is the time to use the model to see how well it works. Let’s pass our data that we prepared at the beginning to the model: d = model(train_x, train_y, test_x, test_y, num_iterations = 2000, learning_rate = 0.005) Output: train accuracy: 99.75 %test accuracy: 99.5 % Isn’t the accuracy just excellent! As you can see from the ‘model’ function that our final model returns a dictionary that contains the costs, final parameters, predicted outputs, learning rate, and the number of iterations used. Let’s see how cost function changed with each updated ‘w’s and ‘b’s: plt.figure(figsize=(7,5))plt.scatter(x = range(len(d['costs'])), y = d['costs'], color='black')plt.title('Scatter Plot of Cost Functions', fontsize=18)plt.ylabel('Costs', fontsize=12)plt.show() Look, with each iteration, the cost function went down as it should. That means with each iteration the parameters ‘w’ and ‘b’ kept refining towards perfection. If you could run all the code and could understand most of it, you just learned how a logistic regression works! Congratulations! If this model is not completely understandable to you yet, I suggest break down the functions and run each line of code individually. That should give you a better idea. Please feel free to ask questions in the comment section, if you have any problem. Feel free to follow me on Twitter and like my Facebook page.
[ { "code": null, "e": 487, "s": 172, "text": "Logistic regression is very popular in machine learning and statistics. It can work on both binary and multiclass classification very well. I wrote tutorials on both binary and multiclass classification with logistic regression before. This article will be focused on image classification with logistic regression." }, { "code": null, "e": 660, "s": 487, "text": "If you are totally new to logistic regression, please go to this article first. This article has a detailed explanation of how a simple logistic regression algorithm works." }, { "code": null, "e": 683, "s": 660, "text": "towardsdatascience.com" }, { "code": null, "e": 844, "s": 683, "text": "It will be helpful if you are familiar with logistic regression already. If not, I hope you will still understand the concepts here. I tried to explain it well." }, { "code": null, "e": 928, "s": 844, "text": "If you are reading this to learn, the only way is to run all the codes by yourself." }, { "code": null, "e": 1090, "s": 928, "text": "The idea of this project is to develop and train a model that is able to take the pixel values of a digit and identify if it is an image of the digit one or not." }, { "code": null, "e": 1324, "s": 1090, "text": "The dataset that will be used in this tutorial is very commonly used in machine learning tutorials. The famous digits dataset. Each row of the dataset represents the flattened pixel values of a digit. I will show you in detail later." }, { "code": null, "e": 1612, "s": 1324, "text": "This dataset contains the pixel values of the digits from zero to nine. But because this tutorial is about binary classification, the goal of this model will be to return 1 if the digit is one and 0 otherwise. Please feel free to download the dataset from the link below to follow along:" }, { "code": null, "e": 1623, "s": 1612, "text": "github.com" }, { "code": null, "e": 1656, "s": 1623, "text": "Here I am importing the dataset:" }, { "code": null, "e": 1752, "s": 1656, "text": "import pandas as pdimport numpy as npdf= pd.read_excel('ex3d1.xlsx', 'X', header=None)df.head()" }, { "code": null, "e": 2142, "s": 1752, "text": "You can see that the dataset has 400 columns. That means each row has 400-pixel values and each row represents one digit. Let’s check some of the digits using the ‘imshow’ function of the matplotlib library. Notice that the pixel values of images are originally not one-dimensional. That’s why it was reshaped into a 20 x 20 two-dimensional array before passing into the ‘imshow’ function." }, { "code": null, "e": 2226, "s": 2142, "text": "import matplotlib.pyplot as pltplt.imshow(np.array(df.iloc[500, :]).reshape(20,20))" }, { "code": null, "e": 2278, "s": 2226, "text": "It’s one! Here I used the 500th row of the dataset." }, { "code": null, "e": 2335, "s": 2278, "text": "Here is another one using the 1750th row of the dataset:" }, { "code": null, "e": 2388, "s": 2335, "text": "plt.imshow(np.array(X.iloc[1750, :]).reshape(20,20))" }, { "code": null, "e": 2400, "s": 2388, "text": "It’s three." }, { "code": null, "e": 2447, "s": 2400, "text": "Let’s check how many rows are in this dataset:" }, { "code": null, "e": 2455, "s": 2447, "text": "len(df)" }, { "code": null, "e": 2463, "s": 2455, "text": "Output:" }, { "code": null, "e": 2468, "s": 2463, "text": "5000" }, { "code": null, "e": 2548, "s": 2468, "text": "Labels are stored in a different sheet in this excel file. Here are the labels:" }, { "code": null, "e": 2611, "s": 2548, "text": "df_y= pd.read_excel('ex3d1.xlsx', 'y', header=None)df_y.head()" }, { "code": null, "e": 2918, "s": 2611, "text": "I am only showing the head of the dataset that brings the first five rows. Because this model will identify the digit 1 only, it will return 1 if the digit is 1 and 0 otherwise. So, in the label, I will keep only 1 and the rest of the digits will become zero. Let’s convert the rest of the digits as zeros." }, { "code": null, "e": 2927, "s": 2918, "text": "For that" }, { "code": null, "e": 3015, "s": 2927, "text": "y = df_y[0]for i in range(len(y)): if y[i] != 1: y[i] = 0y = pd.DataFrame(y)y" }, { "code": null, "e": 3256, "s": 3015, "text": "Out of these 5000 rows of data, 4000 rows will be used to train the model, and the remaining 1000 rows will be used to test the model. It is important for any machine learning or deep learning model to be tested by unseen data to the model." }, { "code": null, "e": 3357, "s": 3256, "text": "x_train = X.iloc[0:4000].Ty_train = y.iloc[0:4000].Tx_test = X.iloc[4000:].Ty_test = y.iloc[4000:].T" }, { "code": null, "e": 3539, "s": 3357, "text": "Using .T, we are taking the transpose of each dataset. These training and test datasets are in DataFrame form. They need to be in an array format for the convenience of calculation." }, { "code": null, "e": 3644, "s": 3539, "text": "x_train = np.array(x_train)y_train = np.array(y_train)x_test = np.array(x_test)y_test = np.array(y_test)" }, { "code": null, "e": 3749, "s": 3644, "text": "The training and test datasets are ready to be used in the model. This is the time to develop the model." }, { "code": null, "e": 3757, "s": 3749, "text": "Step 1:" }, { "code": null, "e": 3858, "s": 3757, "text": "The logistic regression uses the basic linear regression formula that we all learned in high school:" }, { "code": null, "e": 3869, "s": 3858, "text": "Y = AX + B" }, { "code": null, "e": 3971, "s": 3869, "text": "Where Y is the output, X is the input or independent variable, A is the slope and B is the intercept." }, { "code": null, "e": 4031, "s": 3971, "text": "In logistic regression variables are expressed in this way:" }, { "code": null, "e": 4041, "s": 4031, "text": "Formula 1" }, { "code": null, "e": 4225, "s": 4041, "text": "Here z is the output variable, x is the input variable. w and b will be initialized as zeros to start with and they will be modified by numbers of iterations while training the model." }, { "code": null, "e": 4379, "s": 4225, "text": "This output z is passed through a non-linear function. The commonly used nonlinear function is the sigmoid function that returns a value between 0 and 1." }, { "code": null, "e": 4389, "s": 4379, "text": "Formula 2" }, { "code": null, "e": 4445, "s": 4389, "text": "As a reminder, the formula for the sigmoid function is:" }, { "code": null, "e": 4455, "s": 4445, "text": "Formula 3" }, { "code": null, "e": 4537, "s": 4455, "text": "This ‘a’ will be the final output that is the value in the ‘y_train’ or ‘y_test’." }, { "code": null, "e": 4604, "s": 4537, "text": "Here is the function to define the sigmoid function for later use:" }, { "code": null, "e": 4658, "s": 4604, "text": "def sigmoid(z): s = 1/(1 + np.exp(-z)) return s" }, { "code": null, "e": 4840, "s": 4658, "text": "As we mentioned before, w and b will be initialized as zeros. One w value will be initialized for each pixel value. Let’s define a function to initialize the zero value for w and b:" }, { "code": null, "e": 4928, "s": 4840, "text": "def initialize_with_zeros(dim): w = np.zeros(shape=(dim, 1)) b = 0 return w, b" }, { "code": null, "e": 4942, "s": 4928, "text": "Cost Function" }, { "code": null, "e": 5148, "s": 4942, "text": "The cost function is a measure of a model that reflects how much the predicted output differs from the original output. Here is the formula for the cost function of one training example or one row of data:" }, { "code": null, "e": 5158, "s": 5148, "text": "Formula 4" }, { "code": null, "e": 5205, "s": 5158, "text": "The average cost function for all the rows is:" }, { "code": null, "e": 5268, "s": 5205, "text": "The aim of the model will be to lower the cost function value." }, { "code": null, "e": 5285, "s": 5268, "text": "Gradient descent" }, { "code": null, "e": 5489, "s": 5285, "text": "We need to update the variables w and b of Formula 1. It would be initialized as zeros but they need to be updated later with more appropriate values. Gradient descent will help with that. Let’s see how." }, { "code": null, "e": 5668, "s": 5489, "text": "In Formula 4, we expressed the cost function as a function of ‘a’ and ‘y’. But it can be expressed as a function of ‘w’ and ‘b’ as well. Because ‘a’ is derived using ‘w’ and ‘b’." }, { "code": null, "e": 5813, "s": 5668, "text": "The formula for the differential ‘w’ and ‘b’ will be derived by taking the partial differentiation of cost function with respect to ‘w’ and ‘b’." }, { "code": null, "e": 5837, "s": 5813, "text": "Formula 5 and Formula 6" }, { "code": null, "e": 5932, "s": 5837, "text": "Now that we have all the formulas, let’s put it all together in a function called ‘propagate’:" }, { "code": null, "e": 6348, "s": 5932, "text": "def propagate(w, b, X, Y): #Find the number of training data m = X.shape[1] #Calculate the predicted output A = sigmoid(np.dot(w.T, X) + b) #Calculate the cost function cost = -1/m * np.sum(Y*np.log(A) + (1-Y) * np.log(1-A)) #Calculate the gradients dw = 1/m * np.dot(X, (A-Y).T) db = 1/m * np.sum(A-Y) grads = {\"dw\": dw, \"db\": db} return grads, cost" }, { "code": null, "e": 6559, "s": 6348, "text": "The propagate function calculates the predicted output that is ‘A’, cost function ‘cost’, and the gradients ‘dw’ and ‘db’. Using this function, we can now update ‘w’ and ‘b’ in Formula 1. That is the next step." }, { "code": null, "e": 6613, "s": 6559, "text": "Optimize the parameters to best fit the training data" }, { "code": null, "e": 6915, "s": 6613, "text": "In this step, we will update the parameters which are the core of this model. The ‘propagate’ function will be run through a number of iterations. In each iteration, ‘w’ and ‘b’ will be updated. Below is a complete ‘optimize’ function. I explained each step in the code snippet. Please read carefully." }, { "code": null, "e": 7127, "s": 6915, "text": "A new term learning rate was introduced in this function. That’s not a calculated value. It is different for the different machine learning algorithms. Try a few different learning rates to see which works best." }, { "code": null, "e": 7959, "s": 7127, "text": "def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] #propagate function will run for a number of iterations for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads[\"dw\"] db = grads[\"db\"] #Updating w and b by deducting the dw #and db times learning rate from the previous #w and b w = w - learning_rate * dw b = b - learning_rate * db #Record the cost function value for each 100 iterations if i % 100 == 0: costs.append(cost) #The final updated parameters params = {\"w\": w, \"b\": b} #The final updated gradients grads = {\"dw\": dw, \"db\": db} return params, grads, costs" }, { "code": null, "e": 8048, "s": 7959, "text": "We have the function to optimize the parameters. This is the time to predict the output:" }, { "code": null, "e": 8167, "s": 8048, "text": "Explanation of each line of code is embedded in between the code snippet. Please read carefully to understand it well." }, { "code": null, "e": 8765, "s": 8167, "text": "def predict(w, b, X): m = X.shape[1] #Initializing an aray of zeros which has a size of the input #These zeros will be replaced by the predicted output Y_prediction = np.zeros((1, m)) w = w.reshape(X.shape[0], 1) #Calculating the predicted output using the Formula 1 #This will return the values from 0 to 1 A = sigmoid(np.dot(w.T, X) + b) #Iterating through A and predict an 1 if the value of A #is greater than 0.5 and zero otherwise for i in range(A.shape[1]): Y_prediction[:, i] = (A[:, i] > 0.5) * 1 return Y_prediction" }, { "code": null, "e": 8777, "s": 8765, "text": "Final Model" }, { "code": null, "e": 8850, "s": 8777, "text": "Putting all the functions together, the final model will look like this:" }, { "code": null, "e": 9919, "s": 8850, "text": "def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5): #Initializing the w and b as zeros w, b = initialize_with_zeros(X_train.shape[0]) parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) w = parameters[\"w\"] b = parameters[\"b\"] # Predicting the output for both test and training set Y_prediction_test = predict(w, b, X_test) Y_prediction_train = predict(w, b, X_train) #Calculating the training and test set accuracy by comparing #the predicted output and the original output print(\"train accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print(\"test accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {\"costs\": costs, \"Y_prediction_test\": Y_prediction_test, \"Y_prediction_train\" : Y_prediction_train, \"w\" : w, \"b\" : b, \"learning_rate\" : learning_rate, \"num_iterations\": num_iterations} return d" }, { "code": null, "e": 9968, "s": 9919, "text": "The complete logistic regression model is ready!" }, { "code": null, "e": 9984, "s": 9968, "text": "Using the model" }, { "code": null, "e": 10112, "s": 9984, "text": "This is the time to use the model to see how well it works. Let’s pass our data that we prepared at the beginning to the model:" }, { "code": null, "e": 10202, "s": 10112, "text": "d = model(train_x, train_y, test_x, test_y, num_iterations = 2000, learning_rate = 0.005)" }, { "code": null, "e": 10210, "s": 10202, "text": "Output:" }, { "code": null, "e": 10255, "s": 10210, "text": "train accuracy: 99.75 %test accuracy: 99.5 %" }, { "code": null, "e": 10290, "s": 10255, "text": "Isn’t the accuracy just excellent!" }, { "code": null, "e": 10554, "s": 10290, "text": "As you can see from the ‘model’ function that our final model returns a dictionary that contains the costs, final parameters, predicted outputs, learning rate, and the number of iterations used. Let’s see how cost function changed with each updated ‘w’s and ‘b’s:" }, { "code": null, "e": 10748, "s": 10554, "text": "plt.figure(figsize=(7,5))plt.scatter(x = range(len(d['costs'])), y = d['costs'], color='black')plt.title('Scatter Plot of Cost Functions', fontsize=18)plt.ylabel('Costs', fontsize=12)plt.show()" }, { "code": null, "e": 10909, "s": 10748, "text": "Look, with each iteration, the cost function went down as it should. That means with each iteration the parameters ‘w’ and ‘b’ kept refining towards perfection." }, { "code": null, "e": 11292, "s": 10909, "text": "If you could run all the code and could understand most of it, you just learned how a logistic regression works! Congratulations! If this model is not completely understandable to you yet, I suggest break down the functions and run each line of code individually. That should give you a better idea. Please feel free to ask questions in the comment section, if you have any problem." } ]
Area of squares formed by joining mid points repeatedly - GeeksforGeeks
19 Apr, 2021 Given a square having a side of length L. Another square form inside the first square by joining midpoint of the side of the first square. Now 3rd square is form inside 2nd one by joining midpoints of the side of the 2nd square and so on. You have 10 squares inside each other. and you are given side length of largest square.you have to find the area of these 10 squares. Examples: Input : L = 5, n = 10 Output :49.9512 Input : L = 2, n = 2 Output :7.99219 This article can be understand using diagram that depicts the whole problem. From the diagram- Area of outermost square will be given by L^2. Area of 2nd square-As length of 2nd square can be calculate using Pythagoras theorem., side for this square will be \\ Area of 3rd square- Similarly area of third square can be calculated, we get Area of 4th square- Similarly area of forth square can be calculated, we get Hence this form Geometric progression, having first term as L^2 and common ratio = 1/2. Now we have to find sum of first n terms of this GP. C++ Java Python 3 C# Javascript // C++ program to find Area of squares// formed by joining mid points repeatedly#include <bits/stdc++.h>#define ll long long intusing namespace std;int main(){ double L = 2, n = 10; double firstTerm = L * L; double ratio = 1 / 2.0; // apply GP sum formula double sum = firstTerm * (pow(ratio, 10) - 1) / (ratio - 1); cout << sum << endl; return 0;} // Java program to find Area of squares// formed by joining mid points repeatedlyimport java.util.*;import java.lang.*;import java.io.*;import java.lang.Math;/* Name of the class has to be "Main" only if the class is public. */class GFG{ public static void main (String[] args) throws java.lang.Exception { double L = 2, n = 10; double firstTerm = L * L; double ratio = 1 / 2.0; // apply GP sum formula double sum = firstTerm * (Math.pow(ratio, 10) - 1) / (ratio - 1); System.out.println(sum) ; }}// This code is contributed by Shrikant13 # Python3 program to find Area of squares# formed by joining mid points repeatedly if __name__=='__main__': L = 2 n = 10 firstTerm = L * L ratio = 1 / 2 # apply GP sum formula sum = firstTerm * ((ratio**10) - 1) / (ratio - 1) print(sum) # This code is contributed by# Sanjit_Prasad // C# program to find area of squares// formed by joining mid points repeatedlyusing System; // Name of the class has to be// "Main" only if the class is public.class GFG{ public static void Main(string[] args){ double L = 2; //double n = 10; double firstTerm = L * L; double ratio = 1 / 2.0; // Apply GP sum formula double sum = firstTerm * (Math.Pow(ratio, 10) - 1) / (ratio - 1); Console.Write(Math.Round(sum, 5));}} // This code is contributed by rutvik_56 <script> // Javascript program to find Area of squares// formed by joining mid points repeatedly var L = 2, n = 10; var firstTerm = L * L;var ratio = 1 / 2.0; // apply GP sum formulavar sum = firstTerm * (Math.pow(ratio, 10) - 1) / (ratio - 1);document.write( sum.toFixed(5) ); </script> 7.99219 Time Complexity: O(1) Sanjit_Prasad shrikanth13 rutvik_56 itsok Geometric Progression series Puzzles series Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Top 20 Puzzles Commonly Asked During SDE Interviews Puzzle 21 | (3 Ants and Triangle) Puzzle 18 | (Torch and Bridge) Container with Most Water Puzzle 16 | (100 Doors) Puzzle | Set 35 (2 Eggs and 100 Floors) Puzzle 24 | (10 Coins Puzzle) Puzzle 10 | (A Man with Medical Condition and 2 Pills) Puzzle 19 | (Poison and Rat)
[ { "code": null, "e": 26623, "s": 26595, "text": "\n19 Apr, 2021" }, { "code": null, "e": 26996, "s": 26623, "text": "Given a square having a side of length L. Another square form inside the first square by joining midpoint of the side of the first square. Now 3rd square is form inside 2nd one by joining midpoints of the side of the 2nd square and so on. You have 10 squares inside each other. and you are given side length of largest square.you have to find the area of these 10 squares." }, { "code": null, "e": 27007, "s": 26996, "text": "Examples: " }, { "code": null, "e": 27083, "s": 27007, "text": "Input : L = 5, n = 10\nOutput :49.9512\n\nInput : L = 2, n = 2\nOutput :7.99219" }, { "code": null, "e": 27162, "s": 27083, "text": "This article can be understand using diagram that depicts the whole problem. " }, { "code": null, "e": 27347, "s": 27162, "text": "From the diagram- Area of outermost square will be given by L^2. Area of 2nd square-As length of 2nd square can be calculate using Pythagoras theorem., side for this square will be \\\\ " }, { "code": null, "e": 27427, "s": 27349, "text": "Area of 3rd square- Similarly area of third square can be calculated, we get " }, { "code": null, "e": 27512, "s": 27434, "text": "Area of 4th square- Similarly area of forth square can be calculated, we get " }, { "code": null, "e": 27608, "s": 27519, "text": "Hence this form Geometric progression, having first term as L^2 and common ratio = 1/2. " }, { "code": null, "e": 27664, "s": 27610, "text": "Now we have to find sum of first n terms of this GP. " }, { "code": null, "e": 27670, "s": 27666, "text": "C++" }, { "code": null, "e": 27675, "s": 27670, "text": "Java" }, { "code": null, "e": 27684, "s": 27675, "text": "Python 3" }, { "code": null, "e": 27687, "s": 27684, "text": "C#" }, { "code": null, "e": 27698, "s": 27687, "text": "Javascript" }, { "code": "// C++ program to find Area of squares// formed by joining mid points repeatedly#include <bits/stdc++.h>#define ll long long intusing namespace std;int main(){ double L = 2, n = 10; double firstTerm = L * L; double ratio = 1 / 2.0; // apply GP sum formula double sum = firstTerm * (pow(ratio, 10) - 1) / (ratio - 1); cout << sum << endl; return 0;}", "e": 28072, "s": 27698, "text": null }, { "code": "// Java program to find Area of squares// formed by joining mid points repeatedlyimport java.util.*;import java.lang.*;import java.io.*;import java.lang.Math;/* Name of the class has to be \"Main\" only if the class is public. */class GFG{ public static void main (String[] args) throws java.lang.Exception { double L = 2, n = 10; double firstTerm = L * L; double ratio = 1 / 2.0; // apply GP sum formula double sum = firstTerm * (Math.pow(ratio, 10) - 1) / (ratio - 1); System.out.println(sum) ; }}// This code is contributed by Shrikant13", "e": 28658, "s": 28072, "text": null }, { "code": "# Python3 program to find Area of squares# formed by joining mid points repeatedly if __name__=='__main__': L = 2 n = 10 firstTerm = L * L ratio = 1 / 2 # apply GP sum formula sum = firstTerm * ((ratio**10) - 1) / (ratio - 1) print(sum) # This code is contributed by# Sanjit_Prasad", "e": 28960, "s": 28658, "text": null }, { "code": "// C# program to find area of squares// formed by joining mid points repeatedlyusing System; // Name of the class has to be// \"Main\" only if the class is public.class GFG{ public static void Main(string[] args){ double L = 2; //double n = 10; double firstTerm = L * L; double ratio = 1 / 2.0; // Apply GP sum formula double sum = firstTerm * (Math.Pow(ratio, 10) - 1) / (ratio - 1); Console.Write(Math.Round(sum, 5));}} // This code is contributed by rutvik_56", "e": 29502, "s": 28960, "text": null }, { "code": "<script> // Javascript program to find Area of squares// formed by joining mid points repeatedly var L = 2, n = 10; var firstTerm = L * L;var ratio = 1 / 2.0; // apply GP sum formulavar sum = firstTerm * (Math.pow(ratio, 10) - 1) / (ratio - 1);document.write( sum.toFixed(5) ); </script>", "e": 29790, "s": 29502, "text": null }, { "code": null, "e": 29798, "s": 29790, "text": "7.99219" }, { "code": null, "e": 29823, "s": 29800, "text": "Time Complexity: O(1) " }, { "code": null, "e": 29837, "s": 29823, "text": "Sanjit_Prasad" }, { "code": null, "e": 29849, "s": 29837, "text": "shrikanth13" }, { "code": null, "e": 29859, "s": 29849, "text": "rutvik_56" }, { "code": null, "e": 29865, "s": 29859, "text": "itsok" }, { "code": null, "e": 29887, "s": 29865, "text": "Geometric Progression" }, { "code": null, "e": 29894, "s": 29887, "text": "series" }, { "code": null, "e": 29902, "s": 29894, "text": "Puzzles" }, { "code": null, "e": 29909, "s": 29902, "text": "series" }, { "code": null, "e": 29917, "s": 29909, "text": "Puzzles" }, { "code": null, "e": 30015, "s": 29917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30047, "s": 30015, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 30099, "s": 30047, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 30133, "s": 30099, "text": "Puzzle 21 | (3 Ants and Triangle)" }, { "code": null, "e": 30164, "s": 30133, "text": "Puzzle 18 | (Torch and Bridge)" }, { "code": null, "e": 30190, "s": 30164, "text": "Container with Most Water" }, { "code": null, "e": 30214, "s": 30190, "text": "Puzzle 16 | (100 Doors)" }, { "code": null, "e": 30254, "s": 30214, "text": "Puzzle | Set 35 (2 Eggs and 100 Floors)" }, { "code": null, "e": 30284, "s": 30254, "text": "Puzzle 24 | (10 Coins Puzzle)" }, { "code": null, "e": 30339, "s": 30284, "text": "Puzzle 10 | (A Man with Medical Condition and 2 Pills)" } ]
Cellular Networks - GeeksforGeeks
16 Nov, 2018 Cellular Network is formed of some cells, cell covers a geographical region, has a base station analogous to 802.11 AP which helps mobile users attach to network and there is an air-interface of physical and link layer protocol between mobile and base station. All these base stations are connected to Mobile Switching Center which connects cells to wide area net, manages call setup and handles mobility. There is certain radio spectrum that is allocated to base station and to a particular region and that now needs to be shared. There are 2 techniques for sharing mobile-to-base station radio spectrum are: Combined FDMA/TDMA:It divide spectrum in frequency channel and divide each channel into time slots.Code Division Multiple Access (CDMA):It allows reuse of same spectrum over all cells. Net capacity improvement. Two frequency bands are used one of which is for forward channel (cell-site to subscriber) and one for reverse channel (sub to cell-site). Combined FDMA/TDMA:It divide spectrum in frequency channel and divide each channel into time slots. Code Division Multiple Access (CDMA):It allows reuse of same spectrum over all cells. Net capacity improvement. Two frequency bands are used one of which is for forward channel (cell-site to subscriber) and one for reverse channel (sub to cell-site). Cell Fundamentals –In practice cells are of arbitrary shape(close to a circle) because it has the same power on all sides and has same sensitivity on all sides, but putting up two three circles together may result in interleaving gaps or may intersect each other so in order to solve this problem we can use equilateral triangle, square or a regular hexagon in which hexagonal cell is close to a circle used for a system design.Co-channel reuse ratio is given by: DL/RL = Square root of (3N) Where, DL = Distance between co-channel cells RL = Cell Radius N = Cluster Size The number of cells in a cluster N determines the amount of co-channel interference and also the number of frequency channels available per cell. Cell Splitting –When number of subscribers in a given area increases allocation of more channels covered by that channel is necessary, which is done by cell splitting. A single small cell midway between two co-channel cells is introduced. Need for Cellular Hierarchy –Extending the coverage to the areas that are difficult to cover by a large cell. Increasing the capacity of the network for those areas that have a higher density of users. Increasing number of wireless devices and the communication between them. Cellular Hierarchy – Femtocells:Smallest unit of the hierarchy, these cells need to cover only a few meters where all devices are in the physical range of the uses.Picocells:Size of these networks is in the range of few tens of meters, e.g., WLANs.Microcells:Cover a range of hundreds of meters e.g. in urban areas to support PCS which is another kind of mobile technology.Macro cells:Cover areas in the order of several kilometers, e.g., cover metropolitan areas.Mega cells:Cover nationwide areas with ranges of hundreds of kilometers, e.g., used with satellites. Femtocells:Smallest unit of the hierarchy, these cells need to cover only a few meters where all devices are in the physical range of the uses. Picocells:Size of these networks is in the range of few tens of meters, e.g., WLANs. Microcells:Cover a range of hundreds of meters e.g. in urban areas to support PCS which is another kind of mobile technology. Macro cells:Cover areas in the order of several kilometers, e.g., cover metropolitan areas. Mega cells:Cover nationwide areas with ranges of hundreds of kilometers, e.g., used with satellites. Fixed Channel Allocation –For a particular channel the frequency band which is associated is fixed.Total number of channels is given by Nc = W/B Where, W = Bandwidth of the available spectrum, B = Bandwidth needed by each channels per cell, Cc = Nc/N where N is the cluster size Adjacent radio frequency bands are assigned to different cells. In analog each channel corresponds to one user while in digital each RF channel carries several time slots or codes (TDMA/CDMA). Simple to implement as traffic is uniform. Global System for Mobile (GSM) Communications –GSM uses 124 frequency channels, each of which uses an 8-slot Time Division Multiplexing (TDM) system. There is a frequency band which is also fixed. Transmitting and receiving does not happen in the same time slot because the GSM radios cannot transmit and receive at the same time and it takes time to switch from one to the other. A data frame is transmitted in 547 micro seconds, but a transmitter is only allowed to send one data frame every 4.615 micro seconds, since it is sharing the channel with seven other stations. The gross rate of each channel is 270, 833 bps divided among eight users, which gives 33.854 kbps gross. Control Channel (CC) –Apart from user channels there are some control channels which is used to manage the system. The broadcast control channel (BCC):It is a continuous stream of output from the base station’s identity and the channel status. All mobile stations monitor their signal strength to see when they moved into a new cell.The dedicated control channel (DCC):It is used for location updating, registration, and call setup. In particular, each base station maintains a database of mobile stations. Information needed to maintain this database and is sent on the dedicated control channel. The broadcast control channel (BCC):It is a continuous stream of output from the base station’s identity and the channel status. All mobile stations monitor their signal strength to see when they moved into a new cell. The dedicated control channel (DCC):It is used for location updating, registration, and call setup. In particular, each base station maintains a database of mobile stations. Information needed to maintain this database and is sent on the dedicated control channel. Common Control Channel –Three logical sub-channels: Is the paging channel, which the base station uses to announce incoming calls. Each mobile station monitors it continuously to watch for call it should answer.Is the random access channel that allows the users to request a slot on the dedicated control channel. If two requests collide, they are garbled and have to be retried later.Is the access grant channel which is the announced assigned slot. Is the paging channel, which the base station uses to announce incoming calls. Each mobile station monitors it continuously to watch for call it should answer. Is the random access channel that allows the users to request a slot on the dedicated control channel. If two requests collide, they are garbled and have to be retried later. Is the access grant channel which is the announced assigned slot. Computer Networks Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Types of Network Topology Socket Programming in Python TCP 3-Way Handshake Process Types of Transmission Media Implementation of Diffie-Hellman Algorithm
[ { "code": null, "e": 25499, "s": 25471, "text": "\n16 Nov, 2018" }, { "code": null, "e": 25905, "s": 25499, "text": "Cellular Network is formed of some cells, cell covers a geographical region, has a base station analogous to 802.11 AP which helps mobile users attach to network and there is an air-interface of physical and link layer protocol between mobile and base station. All these base stations are connected to Mobile Switching Center which connects cells to wide area net, manages call setup and handles mobility." }, { "code": null, "e": 26109, "s": 25905, "text": "There is certain radio spectrum that is allocated to base station and to a particular region and that now needs to be shared. There are 2 techniques for sharing mobile-to-base station radio spectrum are:" }, { "code": null, "e": 26459, "s": 26109, "text": "Combined FDMA/TDMA:It divide spectrum in frequency channel and divide each channel into time slots.Code Division Multiple Access (CDMA):It allows reuse of same spectrum over all cells. Net capacity improvement. Two frequency bands are used one of which is for forward channel (cell-site to subscriber) and one for reverse channel (sub to cell-site)." }, { "code": null, "e": 26559, "s": 26459, "text": "Combined FDMA/TDMA:It divide spectrum in frequency channel and divide each channel into time slots." }, { "code": null, "e": 26810, "s": 26559, "text": "Code Division Multiple Access (CDMA):It allows reuse of same spectrum over all cells. Net capacity improvement. Two frequency bands are used one of which is for forward channel (cell-site to subscriber) and one for reverse channel (sub to cell-site)." }, { "code": null, "e": 27274, "s": 26810, "text": "Cell Fundamentals –In practice cells are of arbitrary shape(close to a circle) because it has the same power on all sides and has same sensitivity on all sides, but putting up two three circles together may result in interleaving gaps or may intersect each other so in order to solve this problem we can use equilateral triangle, square or a regular hexagon in which hexagonal cell is close to a circle used for a system design.Co-channel reuse ratio is given by:" }, { "code": null, "e": 27384, "s": 27274, "text": "DL/RL = Square root of (3N)\nWhere, \nDL = Distance between co-channel cells\nRL = Cell Radius\nN = Cluster Size " }, { "code": null, "e": 27530, "s": 27384, "text": "The number of cells in a cluster N determines the amount of co-channel interference and also the number of frequency channels available per cell." }, { "code": null, "e": 27769, "s": 27530, "text": "Cell Splitting –When number of subscribers in a given area increases allocation of more channels covered by that channel is necessary, which is done by cell splitting. A single small cell midway between two co-channel cells is introduced." }, { "code": null, "e": 28045, "s": 27769, "text": "Need for Cellular Hierarchy –Extending the coverage to the areas that are difficult to cover by a large cell. Increasing the capacity of the network for those areas that have a higher density of users. Increasing number of wireless devices and the communication between them." }, { "code": null, "e": 28066, "s": 28045, "text": "Cellular Hierarchy –" }, { "code": null, "e": 28610, "s": 28066, "text": "Femtocells:Smallest unit of the hierarchy, these cells need to cover only a few meters where all devices are in the physical range of the uses.Picocells:Size of these networks is in the range of few tens of meters, e.g., WLANs.Microcells:Cover a range of hundreds of meters e.g. in urban areas to support PCS which is another kind of mobile technology.Macro cells:Cover areas in the order of several kilometers, e.g., cover metropolitan areas.Mega cells:Cover nationwide areas with ranges of hundreds of kilometers, e.g., used with satellites." }, { "code": null, "e": 28754, "s": 28610, "text": "Femtocells:Smallest unit of the hierarchy, these cells need to cover only a few meters where all devices are in the physical range of the uses." }, { "code": null, "e": 28839, "s": 28754, "text": "Picocells:Size of these networks is in the range of few tens of meters, e.g., WLANs." }, { "code": null, "e": 28965, "s": 28839, "text": "Microcells:Cover a range of hundreds of meters e.g. in urban areas to support PCS which is another kind of mobile technology." }, { "code": null, "e": 29057, "s": 28965, "text": "Macro cells:Cover areas in the order of several kilometers, e.g., cover metropolitan areas." }, { "code": null, "e": 29158, "s": 29057, "text": "Mega cells:Cover nationwide areas with ranges of hundreds of kilometers, e.g., used with satellites." }, { "code": null, "e": 29294, "s": 29158, "text": "Fixed Channel Allocation –For a particular channel the frequency band which is associated is fixed.Total number of channels is given by" }, { "code": null, "e": 29442, "s": 29294, "text": "Nc = W/B \nWhere, \nW = Bandwidth of the available spectrum, \nB = Bandwidth needed by each channels per cell, \nCc = Nc/N where N is the cluster size " }, { "code": null, "e": 29678, "s": 29442, "text": "Adjacent radio frequency bands are assigned to different cells. In analog each channel corresponds to one user while in digital each RF channel carries several time slots or codes (TDMA/CDMA). Simple to implement as traffic is uniform." }, { "code": null, "e": 30357, "s": 29678, "text": "Global System for Mobile (GSM) Communications –GSM uses 124 frequency channels, each of which uses an 8-slot Time Division Multiplexing (TDM) system. There is a frequency band which is also fixed. Transmitting and receiving does not happen in the same time slot because the GSM radios cannot transmit and receive at the same time and it takes time to switch from one to the other. A data frame is transmitted in 547 micro seconds, but a transmitter is only allowed to send one data frame every 4.615 micro seconds, since it is sharing the channel with seven other stations. The gross rate of each channel is 270, 833 bps divided among eight users, which gives 33.854 kbps gross." }, { "code": null, "e": 30472, "s": 30357, "text": "Control Channel (CC) –Apart from user channels there are some control channels which is used to manage the system." }, { "code": null, "e": 30955, "s": 30472, "text": "The broadcast control channel (BCC):It is a continuous stream of output from the base station’s identity and the channel status. All mobile stations monitor their signal strength to see when they moved into a new cell.The dedicated control channel (DCC):It is used for location updating, registration, and call setup. In particular, each base station maintains a database of mobile stations. Information needed to maintain this database and is sent on the dedicated control channel." }, { "code": null, "e": 31174, "s": 30955, "text": "The broadcast control channel (BCC):It is a continuous stream of output from the base station’s identity and the channel status. All mobile stations monitor their signal strength to see when they moved into a new cell." }, { "code": null, "e": 31439, "s": 31174, "text": "The dedicated control channel (DCC):It is used for location updating, registration, and call setup. In particular, each base station maintains a database of mobile stations. Information needed to maintain this database and is sent on the dedicated control channel." }, { "code": null, "e": 31491, "s": 31439, "text": "Common Control Channel –Three logical sub-channels:" }, { "code": null, "e": 31890, "s": 31491, "text": "Is the paging channel, which the base station uses to announce incoming calls. Each mobile station monitors it continuously to watch for call it should answer.Is the random access channel that allows the users to request a slot on the dedicated control channel. If two requests collide, they are garbled and have to be retried later.Is the access grant channel which is the announced assigned slot." }, { "code": null, "e": 32050, "s": 31890, "text": "Is the paging channel, which the base station uses to announce incoming calls. Each mobile station monitors it continuously to watch for call it should answer." }, { "code": null, "e": 32225, "s": 32050, "text": "Is the random access channel that allows the users to request a slot on the dedicated control channel. If two requests collide, they are garbled and have to be retried later." }, { "code": null, "e": 32291, "s": 32225, "text": "Is the access grant channel which is the announced assigned slot." }, { "code": null, "e": 32309, "s": 32291, "text": "Computer Networks" }, { "code": null, "e": 32328, "s": 32309, "text": "Technical Scripter" }, { "code": null, "e": 32346, "s": 32328, "text": "Computer Networks" }, { "code": null, "e": 32444, "s": 32346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32474, "s": 32444, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 32506, "s": 32474, "text": "Differences between TCP and UDP" }, { "code": null, "e": 32544, "s": 32506, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 32583, "s": 32544, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 32617, "s": 32583, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 32643, "s": 32617, "text": "Types of Network Topology" }, { "code": null, "e": 32672, "s": 32643, "text": "Socket Programming in Python" }, { "code": null, "e": 32700, "s": 32672, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 32728, "s": 32700, "text": "Types of Transmission Media" } ]
Angular ngx bootstrap Dropdowns Component - GeeksforGeeks
02 Sep, 2021 Angular ngx bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will see how to use Dropdowns in angular ngx bootstrap. Installation syntax: npm install ngx-bootstrap --save Approach: First, install the angular ngx bootstrap using the above-mentioned command. Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> <link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> Import Dropdowns component in module.ts In app.component.html, make a Dropdowns component. Serve the app using ng serve. Example 1: index.html <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <base href="/"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></head> <body class="mat-typography"> <app-root></app-root></body> </html> app.component.html <div class="btn-group" dropdown> <button id="button-basic" dropdownToggle type="button" class="btn btn-success dropdown-toggle" aria-controls="dropdown-basic"> Dropdown 1 </button> <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button-basic"> <li role="menuitem"> <a class="dropdown-item">gfg</a> </li> <li role="menuitem"> <a class="dropdown-item">geeks</a> </li> <li role="menuitem"> <a class="dropdown-item">GeeksforGeeks</a> </li> </ul></div> <div class="btn-group" dropdown> <button id="button-basic" dropdownToggle type="button" class="btn btn-danger dropdown-toggle" aria-controls="dropdown-basic"> Dropdown 2 </button> <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button-basic"> <li role="menuitem"> <a class="dropdown-item">gfg1</a> </li> <li role="menuitem"> <a class="dropdown-item">geeks1</a> </li> <li role="menuitem"> <a class="dropdown-item">GeeksforGeeks1</a> </li> </ul></div> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { BsDropdownModule } from 'ngx-bootstrap/dropdown'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, BsDropdownModule.forRoot() ]})export class AppModule { } Output: Reference: https://valor-software.com/ngx-bootstrap/dropdowns ysachin2314 Angular-ngx-bootstrap AngularJS Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Messages Component How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26539, "s": 26354, "text": "Angular ngx bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites." }, { "code": null, "e": 26615, "s": 26539, "text": "In this article, we will see how to use Dropdowns in angular ngx bootstrap." }, { "code": null, "e": 26636, "s": 26615, "text": "Installation syntax:" }, { "code": null, "e": 26670, "s": 26636, "text": "npm install ngx-bootstrap --save " }, { "code": null, "e": 26680, "s": 26670, "text": "Approach:" }, { "code": null, "e": 26757, "s": 26680, "text": "First, install the angular ngx bootstrap using the above-mentioned command. " }, { "code": null, "e": 26898, "s": 26759, "text": "Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 26999, "s": 26898, "text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 27039, "s": 26999, "text": "Import Dropdowns component in module.ts" }, { "code": null, "e": 27090, "s": 27039, "text": "In app.component.html, make a Dropdowns component." }, { "code": null, "e": 27120, "s": 27090, "text": "Serve the app using ng serve." }, { "code": null, "e": 27131, "s": 27120, "text": "Example 1:" }, { "code": null, "e": 27142, "s": 27131, "text": "index.html" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <base href=\"/\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\"> <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\"> <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\"> <link href=\"https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap\" rel=\"stylesheet\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"></head> <body class=\"mat-typography\"> <app-root></app-root></body> </html>", "e": 27836, "s": 27142, "text": null }, { "code": null, "e": 27855, "s": 27836, "text": "app.component.html" }, { "code": "<div class=\"btn-group\" dropdown> <button id=\"button-basic\" dropdownToggle type=\"button\" class=\"btn btn-success dropdown-toggle\" aria-controls=\"dropdown-basic\"> Dropdown 1 </button> <ul id=\"dropdown-basic\" *dropdownMenu class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"button-basic\"> <li role=\"menuitem\"> <a class=\"dropdown-item\">gfg</a> </li> <li role=\"menuitem\"> <a class=\"dropdown-item\">geeks</a> </li> <li role=\"menuitem\"> <a class=\"dropdown-item\">GeeksforGeeks</a> </li> </ul></div> <div class=\"btn-group\" dropdown> <button id=\"button-basic\" dropdownToggle type=\"button\" class=\"btn btn-danger dropdown-toggle\" aria-controls=\"dropdown-basic\"> Dropdown 2 </button> <ul id=\"dropdown-basic\" *dropdownMenu class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"button-basic\"> <li role=\"menuitem\"> <a class=\"dropdown-item\">gfg1</a> </li> <li role=\"menuitem\"> <a class=\"dropdown-item\">geeks1</a> </li> <li role=\"menuitem\"> <a class=\"dropdown-item\">GeeksforGeeks1</a> </li> </ul></div>", "e": 29116, "s": 27855, "text": null }, { "code": null, "e": 29130, "s": 29116, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { BsDropdownModule } from 'ngx-bootstrap/dropdown'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, BsDropdownModule.forRoot() ]})export class AppModule { }", "e": 29811, "s": 29130, "text": null }, { "code": null, "e": 29819, "s": 29811, "text": "Output:" }, { "code": null, "e": 29881, "s": 29819, "text": "Reference: https://valor-software.com/ngx-bootstrap/dropdowns" }, { "code": null, "e": 29893, "s": 29881, "text": "ysachin2314" }, { "code": null, "e": 29915, "s": 29893, "text": "Angular-ngx-bootstrap" }, { "code": null, "e": 29925, "s": 29915, "text": "AngularJS" }, { "code": null, "e": 29935, "s": 29925, "text": "Bootstrap" }, { "code": null, "e": 29952, "s": 29935, "text": "Web Technologies" }, { "code": null, "e": 30050, "s": 29952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30085, "s": 30050, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30120, "s": 30085, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 30144, "s": 30120, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 30197, "s": 30144, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 30232, "s": 30197, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 30282, "s": 30232, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 30311, "s": 30282, "text": "Form validation using jQuery" }, { "code": null, "e": 30352, "s": 30311, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 30408, "s": 30352, "text": "How to align navbar items to the right in Bootstrap 4 ?" } ]
p5.js | input() Function - GeeksforGeeks
17 Jan, 2020 The input() function is invoked whenever user input is detected on the element. It can be used to detect keystrokes or changes in the values of a slider. It can also be used to attach an event listener to an element. Syntax: input(fxn) Parameters: This function accepts a single parameter as mentioned above and described below. fxn: This is the callback function that would be called whenever input is detected. It can be passed ‘false’, which would prevent the previous firing function to stop firing. Below example illustrates the input() function in p5.js: Example: function setup() { createCanvas(600, 300); textSize(28); fill("green") text("Write in the input box to change the text", 10, 20); // create input box let inputElem = createInput(''); inputElem.input(onInput); inputElem.position(20, 40)} function onInput() { clear(); text("Write in the input box to change the text", 10, 20); fill("green") strokeWeight(10) rect(0, 80, 600, 100) // get the text entered fill("black") text(this.value(), 20, 120)} Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/input JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 44937, "s": 44909, "text": "\n17 Jan, 2020" }, { "code": null, "e": 45154, "s": 44937, "text": "The input() function is invoked whenever user input is detected on the element. It can be used to detect keystrokes or changes in the values of a slider. It can also be used to attach an event listener to an element." }, { "code": null, "e": 45162, "s": 45154, "text": "Syntax:" }, { "code": null, "e": 45173, "s": 45162, "text": "input(fxn)" }, { "code": null, "e": 45266, "s": 45173, "text": "Parameters: This function accepts a single parameter as mentioned above and described below." }, { "code": null, "e": 45441, "s": 45266, "text": "fxn: This is the callback function that would be called whenever input is detected. It can be passed ‘false’, which would prevent the previous firing function to stop firing." }, { "code": null, "e": 45498, "s": 45441, "text": "Below example illustrates the input() function in p5.js:" }, { "code": null, "e": 45507, "s": 45498, "text": "Example:" }, { "code": "function setup() { createCanvas(600, 300); textSize(28); fill(\"green\") text(\"Write in the input box to change the text\", 10, 20); // create input box let inputElem = createInput(''); inputElem.input(onInput); inputElem.position(20, 40)} function onInput() { clear(); text(\"Write in the input box to change the text\", 10, 20); fill(\"green\") strokeWeight(10) rect(0, 80, 600, 100) // get the text entered fill(\"black\") text(this.value(), 20, 120)}", "e": 45980, "s": 45507, "text": null }, { "code": null, "e": 45988, "s": 45980, "text": "Output:" }, { "code": null, "e": 46125, "s": 45988, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 46174, "s": 46125, "text": "Reference: https://p5js.org/reference/#/p5/input" }, { "code": null, "e": 46191, "s": 46174, "text": "JavaScript-p5.js" }, { "code": null, "e": 46202, "s": 46191, "text": "JavaScript" }, { "code": null, "e": 46219, "s": 46202, "text": "Web Technologies" }, { "code": null, "e": 46317, "s": 46219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46357, "s": 46317, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46402, "s": 46357, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46463, "s": 46402, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 46535, "s": 46463, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 46604, "s": 46535, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 46644, "s": 46604, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46677, "s": 46644, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 46722, "s": 46677, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46765, "s": 46722, "text": "How to fetch data from an API in ReactJS ?" } ]
How to name aggregate columns in PySpark DataFrame ? - GeeksforGeeks
17 Jun, 2021 In this article, we are going to see how to name aggregate columns in the Pyspark dataframe. We can do this by using alias after groupBy(). groupBy() is used to join two columns and it is used to aggregate the columns, alias is used to change the name of the new column which is formed by grouping data in columns. Syntax: dataframe.groupBy(“column_name1”) .agg(aggregate_function(“column_name2”).alias(“new_column_name”)) Where dataframe is the input dataframe aggregate function is used to group the column like sum(),avg(),count() new_column_name is the name of the new aggregate dcolumn alias is the keyword used to get the new column name Creating Dataframe for demonstration: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 10 row valuesdata =[["1","sravan","IT",45000], ["2","ojaswi","IT",30000], ["3","bobby","business",45000], ["4","rohith","IT",45000], ["5","gnanesh","business",120000], ["6","siva nagulu","sales",23000], ["7","bhanu","sales",34000], ["8","sireesha","business",456798], ["9","ravi","IT",230000], ["10","devi","business",100000], ] # specify column namescolumns=['ID','NAME','sector','salary'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) # display dataframedataframe.show() Output: Example 1: Python program to group the salary among different sectors and name as Employee_salary by sum aggregation. sum() function is available in pyspark.sql.functions package so we need to import it. Python3 # importing sum functionfrom pyspark.sql.functions import sum # group the salary among different sectors# and name as Employee_salary by sum aggregationdataframe.groupBy( "sector").agg(sum("salary").alias("Employee_salary")).show() Output: Example 2: Python program to group the salary among different sectors and name as Average_Employee_salary by average aggregation Syntax: avg(“column_name”) Python3 # importing avg functionfrom pyspark.sql.functions import avg # group the salary among different sectors# and name as Average_Employee_salary# by average aggregationdataframe.groupBy("sector") .agg(avg( "salary").alias("Average_Employee_salary")).show() Output: Example 3: Group the salary among different sectors and name as Total-People by count aggregation Python3 # importing count functionfrom pyspark.sql.functions import count # group the salary among different # sectors and name as Total-People# by count aggregationdataframe.groupBy("sector") .agg(count( "salary").alias("Total-People")).show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 26229, "s": 26201, "text": "\n17 Jun, 2021" }, { "code": null, "e": 26322, "s": 26229, "text": "In this article, we are going to see how to name aggregate columns in the Pyspark dataframe." }, { "code": null, "e": 26544, "s": 26322, "text": "We can do this by using alias after groupBy(). groupBy() is used to join two columns and it is used to aggregate the columns, alias is used to change the name of the new column which is formed by grouping data in columns." }, { "code": null, "e": 26652, "s": 26544, "text": "Syntax: dataframe.groupBy(“column_name1”) .agg(aggregate_function(“column_name2”).alias(“new_column_name”))" }, { "code": null, "e": 26659, "s": 26652, "text": "Where " }, { "code": null, "e": 26692, "s": 26659, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26764, "s": 26692, "text": "aggregate function is used to group the column like sum(),avg(),count()" }, { "code": null, "e": 26821, "s": 26764, "text": "new_column_name is the name of the new aggregate dcolumn" }, { "code": null, "e": 26874, "s": 26821, "text": "alias is the keyword used to get the new column name" }, { "code": null, "e": 26912, "s": 26874, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 26920, "s": 26912, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 10 row valuesdata =[[\"1\",\"sravan\",\"IT\",45000], [\"2\",\"ojaswi\",\"IT\",30000], [\"3\",\"bobby\",\"business\",45000], [\"4\",\"rohith\",\"IT\",45000], [\"5\",\"gnanesh\",\"business\",120000], [\"6\",\"siva nagulu\",\"sales\",23000], [\"7\",\"bhanu\",\"sales\",34000], [\"8\",\"sireesha\",\"business\",456798], [\"9\",\"ravi\",\"IT\",230000], [\"10\",\"devi\",\"business\",100000], ] # specify column namescolumns=['ID','NAME','sector','salary'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) # display dataframedataframe.show()", "e": 27762, "s": 26920, "text": null }, { "code": null, "e": 27770, "s": 27762, "text": "Output:" }, { "code": null, "e": 27974, "s": 27770, "text": "Example 1: Python program to group the salary among different sectors and name as Employee_salary by sum aggregation. sum() function is available in pyspark.sql.functions package so we need to import it." }, { "code": null, "e": 27982, "s": 27974, "text": "Python3" }, { "code": "# importing sum functionfrom pyspark.sql.functions import sum # group the salary among different sectors# and name as Employee_salary by sum aggregationdataframe.groupBy( \"sector\").agg(sum(\"salary\").alias(\"Employee_salary\")).show()", "e": 28217, "s": 27982, "text": null }, { "code": null, "e": 28225, "s": 28217, "text": "Output:" }, { "code": null, "e": 28355, "s": 28225, "text": "Example 2: Python program to group the salary among different sectors and name as Average_Employee_salary by average aggregation" }, { "code": null, "e": 28383, "s": 28355, "text": "Syntax: avg(“column_name”)" }, { "code": null, "e": 28391, "s": 28383, "text": "Python3" }, { "code": "# importing avg functionfrom pyspark.sql.functions import avg # group the salary among different sectors# and name as Average_Employee_salary# by average aggregationdataframe.groupBy(\"sector\") .agg(avg( \"salary\").alias(\"Average_Employee_salary\")).show()", "e": 28648, "s": 28391, "text": null }, { "code": null, "e": 28656, "s": 28648, "text": "Output:" }, { "code": null, "e": 28755, "s": 28656, "text": "Example 3: Group the salary among different sectors and name as Total-People by count aggregation" }, { "code": null, "e": 28763, "s": 28755, "text": "Python3" }, { "code": "# importing count functionfrom pyspark.sql.functions import count # group the salary among different # sectors and name as Total-People# by count aggregationdataframe.groupBy(\"sector\") .agg(count( \"salary\").alias(\"Total-People\")).show()", "e": 29003, "s": 28763, "text": null }, { "code": null, "e": 29011, "s": 29003, "text": "Output:" }, { "code": null, "e": 29018, "s": 29011, "text": "Picked" }, { "code": null, "e": 29033, "s": 29018, "text": "Python-Pyspark" }, { "code": null, "e": 29040, "s": 29033, "text": "Python" }, { "code": null, "e": 29138, "s": 29040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29156, "s": 29138, "text": "Python Dictionary" }, { "code": null, "e": 29188, "s": 29156, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29210, "s": 29188, "text": "Enumerate() in Python" }, { "code": null, "e": 29252, "s": 29210, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29282, "s": 29252, "text": "Iterate over a list in Python" }, { "code": null, "e": 29311, "s": 29282, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29355, "s": 29311, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29391, "s": 29355, "text": "Convert integer to string in Python" }, { "code": null, "e": 29428, "s": 29391, "text": "Create a Pandas DataFrame from Lists" } ]
How to compare two arrays in JavaScript ? - GeeksforGeeks
04 Dec, 2021 In this article, the task is to compare two arrays, & we need to check the length of both arrays that should be the same, the objects present in them are of the same type and each item in one array is equal to the counterpart in another array. By doing this, we can conclude both arrays are the same or not. JavaScript provides a function JSON.stringify() method in order to convert an object or array into a JSON string. By converting into JSON strings, we can directly check if the strings are equal or not. Example 1: This example uses the JSON.stringify() method to convert an object or array into a JSON string, then accordingly check for the given condition. If it satisfies the specific condition then it returns true otherwise, it will return false. Javascript <script> var a = [1, 2, 3, 5]; var b = [1, 2, 3, 5]; // Comparing both arrays using stringify if(JSON.stringify(a)==JSON.stringify(b)) document.write("True"); else document.write("False"); document.write('<br>'); var f=[1, 2, 4, 5]; if(JSON.stringify(a)==JSON.stringify(f)) document.write("True"); else document.write("False");</script> Output: True False Example 2: In this example, we manually check each and every item and return true if they are equal otherwise return false. Javascript <script> function isEqual() { var a = [1, 2, 3, 5]; var b = [1, 2, 3, 5]; // If length is not equal if(a.length!=b.length) return "False"; else { // Comparing each element of array for(var i=0;i<a.length;i++) if(a[i]!=b[i]) return "False"; return "True"; } } var v = isEqual(); document.write(v);</script> Output: True JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. bhaskargeeksforgeeks kapoorsagar226 javascript-array JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26708, "s": 26680, "text": "\n04 Dec, 2021" }, { "code": null, "e": 27218, "s": 26708, "text": "In this article, the task is to compare two arrays, & we need to check the length of both arrays that should be the same, the objects present in them are of the same type and each item in one array is equal to the counterpart in another array. By doing this, we can conclude both arrays are the same or not. JavaScript provides a function JSON.stringify() method in order to convert an object or array into a JSON string. By converting into JSON strings, we can directly check if the strings are equal or not." }, { "code": null, "e": 27466, "s": 27218, "text": "Example 1: This example uses the JSON.stringify() method to convert an object or array into a JSON string, then accordingly check for the given condition. If it satisfies the specific condition then it returns true otherwise, it will return false." }, { "code": null, "e": 27477, "s": 27466, "text": "Javascript" }, { "code": "<script> var a = [1, 2, 3, 5]; var b = [1, 2, 3, 5]; // Comparing both arrays using stringify if(JSON.stringify(a)==JSON.stringify(b)) document.write(\"True\"); else document.write(\"False\"); document.write('<br>'); var f=[1, 2, 4, 5]; if(JSON.stringify(a)==JSON.stringify(f)) document.write(\"True\"); else document.write(\"False\");</script>", "e": 27835, "s": 27477, "text": null }, { "code": null, "e": 27843, "s": 27835, "text": "Output:" }, { "code": null, "e": 27854, "s": 27843, "text": "True\nFalse" }, { "code": null, "e": 27978, "s": 27854, "text": "Example 2: In this example, we manually check each and every item and return true if they are equal otherwise return false." }, { "code": null, "e": 27989, "s": 27978, "text": "Javascript" }, { "code": "<script> function isEqual() { var a = [1, 2, 3, 5]; var b = [1, 2, 3, 5]; // If length is not equal if(a.length!=b.length) return \"False\"; else { // Comparing each element of array for(var i=0;i<a.length;i++) if(a[i]!=b[i]) return \"False\"; return \"True\"; } } var v = isEqual(); document.write(v);</script>", "e": 28353, "s": 27989, "text": null }, { "code": null, "e": 28361, "s": 28353, "text": "Output:" }, { "code": null, "e": 28366, "s": 28361, "text": "True" }, { "code": null, "e": 28585, "s": 28366, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 28606, "s": 28585, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28621, "s": 28606, "text": "kapoorsagar226" }, { "code": null, "e": 28638, "s": 28621, "text": "javascript-array" }, { "code": null, "e": 28659, "s": 28638, "text": "JavaScript-Questions" }, { "code": null, "e": 28666, "s": 28659, "text": "Picked" }, { "code": null, "e": 28677, "s": 28666, "text": "JavaScript" }, { "code": null, "e": 28694, "s": 28677, "text": "Web Technologies" }, { "code": null, "e": 28792, "s": 28694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28832, "s": 28792, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28877, "s": 28832, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28938, "s": 28877, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29010, "s": 28938, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29062, "s": 29010, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29102, "s": 29062, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29135, "s": 29102, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29180, "s": 29135, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29223, "s": 29180, "text": "How to fetch data from an API in ReactJS ?" } ]
Node.js | os.userInfo() Method - GeeksforGeeks
07 Aug, 2021 The os.userInfo() method is an inbuilt application programming interface of the os module which is used to get the information of currently effective user. Syntax: os.userInfo( options ) Parameters: This method accepts single parameter options which is optional parameter. It specifies the process options to be passed, and an object which contains encoding as a parameter returns. encoding: It specifies the character encoding for returned data. If it is set to ‘buffer’, then username, shell, homedir values will be buffer instances. Default value is ‘utf8’. Return Value: It returns an object that specifies the information about the current effective user, which contains username, uid, gid, shell, homedir like values. Note: On POSIX platform, this is generally a subset of password file contains username, uid, gid, shell, and homedir. Windows shell is set to null and uid, gid are -1. Below examples illustrate the use of os.userInfo() in Node.js: Example 1: Javascript // Node.js program to demonstrate the // os.userInfo() Method // Allocating os moduleconst os = require('os'); // Printing os.userInfo() valuestry { // Printing user information console.log(os.userInfo());} catch (err) { // Printing if any exception occurs console.log(": error occurred" + err);} Output: { uid: -1, gid: -1, username: 'gekcho', homedir: 'C:\\Users\\gekcho', shell: null } Example 2: Javascript // Node.js program to demonstrate the // os.userInfo() Method // Allocating os moduleconst os = require('os'); // Printing os.userInfo()try{ // Setting options for os.userInfo() // method var options = { encoding: 'buffer' }; // Printing user information console.log(os.userInfo(options));} catch(err){ // Printing exception if any console.log(": error occurred" + err);} Output: { uid: -1, gid: -1, username: <Buffer 6d 75 6b 75 6c>, homedir: <Buffer 43 3a 5c 55 73 65 72 73 5c 6d 75 6b 75 6c>, shell: null } Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/os.html#os_os_userinfo_options sweetyty anikaseth98 Node.js-os-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Mongoose | findByIdAndUpdate() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26149, "s": 26121, "text": "\n07 Aug, 2021" }, { "code": null, "e": 26305, "s": 26149, "text": "The os.userInfo() method is an inbuilt application programming interface of the os module which is used to get the information of currently effective user." }, { "code": null, "e": 26314, "s": 26305, "text": "Syntax: " }, { "code": null, "e": 26337, "s": 26314, "text": "os.userInfo( options )" }, { "code": null, "e": 26533, "s": 26337, "text": "Parameters: This method accepts single parameter options which is optional parameter. It specifies the process options to be passed, and an object which contains encoding as a parameter returns. " }, { "code": null, "e": 26712, "s": 26533, "text": "encoding: It specifies the character encoding for returned data. If it is set to ‘buffer’, then username, shell, homedir values will be buffer instances. Default value is ‘utf8’." }, { "code": null, "e": 26875, "s": 26712, "text": "Return Value: It returns an object that specifies the information about the current effective user, which contains username, uid, gid, shell, homedir like values." }, { "code": null, "e": 27043, "s": 26875, "text": "Note: On POSIX platform, this is generally a subset of password file contains username, uid, gid, shell, and homedir. Windows shell is set to null and uid, gid are -1." }, { "code": null, "e": 27106, "s": 27043, "text": "Below examples illustrate the use of os.userInfo() in Node.js:" }, { "code": null, "e": 27118, "s": 27106, "text": "Example 1: " }, { "code": null, "e": 27129, "s": 27118, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // os.userInfo() Method // Allocating os moduleconst os = require('os'); // Printing os.userInfo() valuestry { // Printing user information console.log(os.userInfo());} catch (err) { // Printing if any exception occurs console.log(\": error occurred\" + err);}", "e": 27443, "s": 27129, "text": null }, { "code": null, "e": 27452, "s": 27443, "text": "Output: " }, { "code": null, "e": 27544, "s": 27452, "text": "{ uid: -1,\n gid: -1,\n username: 'gekcho',\n homedir: 'C:\\\\Users\\\\gekcho',\n shell: null }" }, { "code": null, "e": 27556, "s": 27544, "text": "Example 2: " }, { "code": null, "e": 27567, "s": 27556, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // os.userInfo() Method // Allocating os moduleconst os = require('os'); // Printing os.userInfo()try{ // Setting options for os.userInfo() // method var options = { encoding: 'buffer' }; // Printing user information console.log(os.userInfo(options));} catch(err){ // Printing exception if any console.log(\": error occurred\" + err);}", "e": 27974, "s": 27567, "text": null }, { "code": null, "e": 27983, "s": 27974, "text": "Output: " }, { "code": null, "e": 28121, "s": 27983, "text": "{ uid: -1,\n gid: -1,\n username: <Buffer 6d 75 6b 75 6c>,\n homedir: <Buffer 43 3a 5c 55 73 65 72 73 5c 6d 75 6b 75 6c>,\n shell: null }" }, { "code": null, "e": 28205, "s": 28121, "text": "Note: The above program will compile and run by using the node filename.js command." }, { "code": null, "e": 28271, "s": 28205, "text": "Reference: https://nodejs.org/api/os.html#os_os_userinfo_options " }, { "code": null, "e": 28280, "s": 28271, "text": "sweetyty" }, { "code": null, "e": 28292, "s": 28280, "text": "anikaseth98" }, { "code": null, "e": 28310, "s": 28292, "text": "Node.js-os-module" }, { "code": null, "e": 28318, "s": 28310, "text": "Node.js" }, { "code": null, "e": 28335, "s": 28318, "text": "Web Technologies" }, { "code": null, "e": 28433, "s": 28335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28463, "s": 28433, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28520, "s": 28463, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28574, "s": 28520, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28611, "s": 28574, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28651, "s": 28611, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 28691, "s": 28651, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28736, "s": 28691, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28779, "s": 28736, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28829, "s": 28779, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to implement text Auto-complete feature using Ternary Search Tree - GeeksforGeeks
05 Aug, 2021 Given a set of strings S and a string patt the task is to autocomplete the string patt to strings from S that have patt as a prefix, using a Ternary Search Tree. If no string matches the given prefix, print “None”.Examples: Input: S = {“wallstreet”, “geeksforgeeks”, “wallmart”, “walmart”, “waldomort”, “word”], patt = “wall” Output: wallstreet wallmart Explanation: Only two strings {“wallstreet”, “wallmart”} from S matches with the given pattern “wall”.Input: S = {“word”, “wallstreet”, “wall”, “wallmart”, “walmart”, “waldo”, “won”}, patt = “geeks” Output: None Explanation: Since none of word of set matches with pattern so empty list will be printed. Trie Approach: Please refer this article to learn about the implementation using Trie data structure.Ternary Search Tree Approach Follow the steps below to solve the problem: Insert all the characters of the strings in S into the Ternary Search Tree based on the following conditions: If the character to be inserted is smaller than current node value, traverse the left subtree.If the character to be inserted is greater than current node value, traverse the right subtree to.If the character to be inserted is same as that of the current node value, traverse the equal subtree if it is not the end of the word. If so, mark the node as the end of the word. If the character to be inserted is smaller than current node value, traverse the left subtree.If the character to be inserted is greater than current node value, traverse the right subtree to.If the character to be inserted is same as that of the current node value, traverse the equal subtree if it is not the end of the word. If so, mark the node as the end of the word. If the character to be inserted is smaller than current node value, traverse the left subtree. If the character to be inserted is greater than current node value, traverse the right subtree to. If the character to be inserted is same as that of the current node value, traverse the equal subtree if it is not the end of the word. If so, mark the node as the end of the word. Follow a similar approach for extracting suggestions. Traverse the tree to search the given prefix patt following a similar traversal technique as mentioned above. If the given prefix is not found, print “None”. If the given prefix is found, traverse the tree from the node where the prefix ends. Traverse the left subtree and generate suggestions followed by the right and equal subtrees from every node . Every time a node is encountered which has the endofWord variable set, it denotes that a suggestion has been obtained. Insert that suggestion into words. Return words after generating all possible suggestions. Below is the implementation of the above approach: C++ // C++ Program to generate// autocompleted texts from// a given prefix using a// Ternary Search Tree#include <bits/stdc++.h>using namespace std; // Define the Node of the// treestruct Node { // Store the character // of a string char data; // Store the end of // word int end; // Left Subtree struct Node* left; // Equal Subtree struct Node* eq; // Right Subtree struct Node* right;}; // Function to create a NodeNode* createNode(char newData){ struct Node* newNode = new Node(); newNode->data = newData; newNode->end = 0; newNode->left = NULL; newNode->eq = NULL; newNode->right = NULL; return newNode;} // Function to insert a word// in the treevoid insert(Node** root, string word, int pos = 0){ // Base case if (!(*root)) *root = createNode(word[pos]); // If the current character is // less than root's data, then // it is inserted in the // left subtree if ((*root)->data > word[pos]) insert(&((*root)->left), word, pos); // If current character is // more than root's data, then // it is inserted in the right // subtree else if ((*root)->data < word[pos]) insert(&((*root)->right), word, pos); // If current character is same // as that of the root's data else { // If it is the end of word if (pos + 1 == word.size()) // Mark it as the // end of word (*root)->end = 1; // If it is not the end of // the string, then the // current character is // inserted in the equal subtree else insert(&((*root)->eq), word, pos + 1); }} // Function to traverse the ternary search treevoid traverse(Node* root, vector<string>& ret, char* buff, int depth = 0){ // Base case if (!root) return; // The left subtree is // traversed first traverse(root->left, ret, buff, depth); // Store the current character buff[depth] = root->data; // If the end of the string // is detected, store it in // the final ans if (root->end) { buff[depth + 1] = '\0'; ret.push_back(string(buff)); } // Traverse the equal subtree traverse(root->eq, ret, buff, depth + 1); // Traverse the right subtree traverse(root->right, ret, buff, depth);} // Utility function to find// all the wordsvector<string> util(Node* root, string pattern){ // Stores the words // to suggest char buffer[1001]; vector<string> ret; traverse(root, ret, buffer); if (root->end == 1) ret.push_back(pattern); return ret;} // Function to autocomplete// based on the given prefix// and return the suggestionsvector<string> autocomplete(Node* root, string pattern){ vector<string> words; int pos = 0; // If pattern is empty // return an empty list if (pattern.empty()) return words; // Iterating over the characters // of the pattern and find it's // corresponding node in the tree while (root && pos < pattern.length()) { // If current character is smaller if (root->data > pattern[pos]) // Search the left subtree root = root->left; // current character is greater else if (root->data < pattern[pos]) // Search right subtree root = root->right; // If current character is equal else if (root->data == pattern[pos]) { // Search equal subtree // since character is found, move to the next character in the pattern root = root->eq; pos++; } // If not found else return words; } // Search for all the words // from the current node words = util(root, pattern); return words;} // Function to print// suggested words void print(vector<string> sugg, string pat){ for (int i = 0; i < sugg.size(); i++) cout << pat << sugg[i].c_str() << "\n";} // Driver Codeint main(){ vector<string> S = { "wallstreet", "geeksforgeeks", "wallmart", "walmart", "waldormort", "word" }; Node* tree = NULL; // Insert the words in the // Ternary Search Tree for (string str : S) insert(&tree, str); string pat = "wall"; vector<string> sugg = autocomplete(tree, pat); if (sugg.size() == 0) cout << "None"; else print(sugg, pat); return 0;} wallmart wallstreet Time Complexity: O(L* log N) where L is length of longest word. The space is proportional to the length of the string to be stored.Auxiliary Space: O(N) PrasannaReddyIsireddy pankajsharmagfg Trees Trie Advanced Data Structure Algorithms Competitive Programming Data Structures Divide and Conquer Pattern Searching Recursion Searching Strings Tree Data Structures Searching Strings Recursion Divide and Conquer Tree Pattern Searching Trie Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Interval Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS How to write a Pseudo Code?
[ { "code": null, "e": 25731, "s": 25703, "text": "\n05 Aug, 2021" }, { "code": null, "e": 25957, "s": 25731, "text": "Given a set of strings S and a string patt the task is to autocomplete the string patt to strings from S that have patt as a prefix, using a Ternary Search Tree. If no string matches the given prefix, print “None”.Examples: " }, { "code": null, "e": 26392, "s": 25957, "text": "Input: S = {“wallstreet”, “geeksforgeeks”, “wallmart”, “walmart”, “waldomort”, “word”], patt = “wall” Output: wallstreet wallmart Explanation: Only two strings {“wallstreet”, “wallmart”} from S matches with the given pattern “wall”.Input: S = {“word”, “wallstreet”, “wall”, “wallmart”, “walmart”, “waldo”, “won”}, patt = “geeks” Output: None Explanation: Since none of word of set matches with pattern so empty list will be printed. " }, { "code": null, "e": 26571, "s": 26394, "text": "Trie Approach: Please refer this article to learn about the implementation using Trie data structure.Ternary Search Tree Approach Follow the steps below to solve the problem: " }, { "code": null, "e": 27054, "s": 26571, "text": "Insert all the characters of the strings in S into the Ternary Search Tree based on the following conditions: If the character to be inserted is smaller than current node value, traverse the left subtree.If the character to be inserted is greater than current node value, traverse the right subtree to.If the character to be inserted is same as that of the current node value, traverse the equal subtree if it is not the end of the word. If so, mark the node as the end of the word." }, { "code": null, "e": 27427, "s": 27054, "text": "If the character to be inserted is smaller than current node value, traverse the left subtree.If the character to be inserted is greater than current node value, traverse the right subtree to.If the character to be inserted is same as that of the current node value, traverse the equal subtree if it is not the end of the word. If so, mark the node as the end of the word." }, { "code": null, "e": 27522, "s": 27427, "text": "If the character to be inserted is smaller than current node value, traverse the left subtree." }, { "code": null, "e": 27621, "s": 27522, "text": "If the character to be inserted is greater than current node value, traverse the right subtree to." }, { "code": null, "e": 27802, "s": 27621, "text": "If the character to be inserted is same as that of the current node value, traverse the equal subtree if it is not the end of the word. If so, mark the node as the end of the word." }, { "code": null, "e": 27856, "s": 27802, "text": "Follow a similar approach for extracting suggestions." }, { "code": null, "e": 27966, "s": 27856, "text": "Traverse the tree to search the given prefix patt following a similar traversal technique as mentioned above." }, { "code": null, "e": 28014, "s": 27966, "text": "If the given prefix is not found, print “None”." }, { "code": null, "e": 28209, "s": 28014, "text": "If the given prefix is found, traverse the tree from the node where the prefix ends. Traverse the left subtree and generate suggestions followed by the right and equal subtrees from every node ." }, { "code": null, "e": 28363, "s": 28209, "text": "Every time a node is encountered which has the endofWord variable set, it denotes that a suggestion has been obtained. Insert that suggestion into words." }, { "code": null, "e": 28419, "s": 28363, "text": "Return words after generating all possible suggestions." }, { "code": null, "e": 28472, "s": 28419, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28476, "s": 28472, "text": "C++" }, { "code": "// C++ Program to generate// autocompleted texts from// a given prefix using a// Ternary Search Tree#include <bits/stdc++.h>using namespace std; // Define the Node of the// treestruct Node { // Store the character // of a string char data; // Store the end of // word int end; // Left Subtree struct Node* left; // Equal Subtree struct Node* eq; // Right Subtree struct Node* right;}; // Function to create a NodeNode* createNode(char newData){ struct Node* newNode = new Node(); newNode->data = newData; newNode->end = 0; newNode->left = NULL; newNode->eq = NULL; newNode->right = NULL; return newNode;} // Function to insert a word// in the treevoid insert(Node** root, string word, int pos = 0){ // Base case if (!(*root)) *root = createNode(word[pos]); // If the current character is // less than root's data, then // it is inserted in the // left subtree if ((*root)->data > word[pos]) insert(&((*root)->left), word, pos); // If current character is // more than root's data, then // it is inserted in the right // subtree else if ((*root)->data < word[pos]) insert(&((*root)->right), word, pos); // If current character is same // as that of the root's data else { // If it is the end of word if (pos + 1 == word.size()) // Mark it as the // end of word (*root)->end = 1; // If it is not the end of // the string, then the // current character is // inserted in the equal subtree else insert(&((*root)->eq), word, pos + 1); }} // Function to traverse the ternary search treevoid traverse(Node* root, vector<string>& ret, char* buff, int depth = 0){ // Base case if (!root) return; // The left subtree is // traversed first traverse(root->left, ret, buff, depth); // Store the current character buff[depth] = root->data; // If the end of the string // is detected, store it in // the final ans if (root->end) { buff[depth + 1] = '\\0'; ret.push_back(string(buff)); } // Traverse the equal subtree traverse(root->eq, ret, buff, depth + 1); // Traverse the right subtree traverse(root->right, ret, buff, depth);} // Utility function to find// all the wordsvector<string> util(Node* root, string pattern){ // Stores the words // to suggest char buffer[1001]; vector<string> ret; traverse(root, ret, buffer); if (root->end == 1) ret.push_back(pattern); return ret;} // Function to autocomplete// based on the given prefix// and return the suggestionsvector<string> autocomplete(Node* root, string pattern){ vector<string> words; int pos = 0; // If pattern is empty // return an empty list if (pattern.empty()) return words; // Iterating over the characters // of the pattern and find it's // corresponding node in the tree while (root && pos < pattern.length()) { // If current character is smaller if (root->data > pattern[pos]) // Search the left subtree root = root->left; // current character is greater else if (root->data < pattern[pos]) // Search right subtree root = root->right; // If current character is equal else if (root->data == pattern[pos]) { // Search equal subtree // since character is found, move to the next character in the pattern root = root->eq; pos++; } // If not found else return words; } // Search for all the words // from the current node words = util(root, pattern); return words;} // Function to print// suggested words void print(vector<string> sugg, string pat){ for (int i = 0; i < sugg.size(); i++) cout << pat << sugg[i].c_str() << \"\\n\";} // Driver Codeint main(){ vector<string> S = { \"wallstreet\", \"geeksforgeeks\", \"wallmart\", \"walmart\", \"waldormort\", \"word\" }; Node* tree = NULL; // Insert the words in the // Ternary Search Tree for (string str : S) insert(&tree, str); string pat = \"wall\"; vector<string> sugg = autocomplete(tree, pat); if (sugg.size() == 0) cout << \"None\"; else print(sugg, pat); return 0;}", "e": 33104, "s": 28476, "text": null }, { "code": null, "e": 33124, "s": 33104, "text": "wallmart\nwallstreet" }, { "code": null, "e": 33277, "s": 33124, "text": "Time Complexity: O(L* log N) where L is length of longest word. The space is proportional to the length of the string to be stored.Auxiliary Space: O(N)" }, { "code": null, "e": 33299, "s": 33277, "text": "PrasannaReddyIsireddy" }, { "code": null, "e": 33315, "s": 33299, "text": "pankajsharmagfg" }, { "code": null, "e": 33321, "s": 33315, "text": "Trees" }, { "code": null, "e": 33326, "s": 33321, "text": "Trie" }, { "code": null, "e": 33350, "s": 33326, "text": "Advanced Data Structure" }, { "code": null, "e": 33361, "s": 33350, "text": "Algorithms" }, { "code": null, "e": 33385, "s": 33361, "text": "Competitive Programming" }, { "code": null, "e": 33401, "s": 33385, "text": "Data Structures" }, { "code": null, "e": 33420, "s": 33401, "text": "Divide and Conquer" }, { "code": null, "e": 33438, "s": 33420, "text": "Pattern Searching" }, { "code": null, "e": 33448, "s": 33438, "text": "Recursion" }, { "code": null, "e": 33458, "s": 33448, "text": "Searching" }, { "code": null, "e": 33466, "s": 33458, "text": "Strings" }, { "code": null, "e": 33471, "s": 33466, "text": "Tree" }, { "code": null, "e": 33487, "s": 33471, "text": "Data Structures" }, { "code": null, "e": 33497, "s": 33487, "text": "Searching" }, { "code": null, "e": 33505, "s": 33497, "text": "Strings" }, { "code": null, "e": 33515, "s": 33505, "text": "Recursion" }, { "code": null, "e": 33534, "s": 33515, "text": "Divide and Conquer" }, { "code": null, "e": 33539, "s": 33534, "text": "Tree" }, { "code": null, "e": 33557, "s": 33539, "text": "Pattern Searching" }, { "code": null, "e": 33562, "s": 33557, "text": "Trie" }, { "code": null, "e": 33573, "s": 33562, "text": "Algorithms" }, { "code": null, "e": 33671, "s": 33573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33700, "s": 33671, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 33742, "s": 33700, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 33788, "s": 33742, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 33824, "s": 33788, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 33838, "s": 33824, "text": "Interval Tree" }, { "code": null, "e": 33887, "s": 33838, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33931, "s": 33887, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33956, "s": 33931, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33987, "s": 33956, "text": "Difference between BFS and DFS" } ]
LINQ | Projection Operator | SelectMany - GeeksforGeeks
21 May, 2019 In LINQ, projection is an operation which converts an object into the new form which holds only those properties which will be subsequently used. By using projection, a developer can create a new type which is built from each object. You are allowed to project property and conduct mathematical function on it, and you can also project the original object without transforming it. In LINQ, the following projection operations are available: SelectSelectMany Select SelectMany The SelectMany operator returns sequences of values which are based on the transformation function and then make them into one sequence. Or in other words, we can say, SelectMany operator is used when you want to select values from the multiple collections or if you want a result from the list of the lists and wants to display into a single sequence. SelectMany in Query Syntax: In Query Syntax, the working of SelectMany operator is achieved by using multiple from clause. As shown in the below example. Example: // C# program to find the languages// known by the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; } public List<string> emp_lang { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000, emp_lang = new List<string>{"C#", "VB"} }, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000, emp_lang = new List<string>{ "Java"} }, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000, emp_lang = new List<string>{ "C++", "SQL"} }, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000, emp_lang = new List<string>{"Python", "C", "PHP"} }, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000, emp_lang = new List<string>{"HTML", "JQuery"} }, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000, emp_lang = new List<string>{"JavaScript", "Perl"} }, }; // Query to find the languages // known by the employee var res = from e in emp from e2 in e.emp_lang select e2; Console.WriteLine("Languages known by all the employees are:"); foreach(var val in res) { Console.WriteLine(val); } }} Languages known by all the employees are: C# VB Java C++ SQL Python C PHP HTML JQuery JavaScript Perl SelectMany in Method Syntax: The SelectMany method is present in both the Queryable and Enumerable class and supported by both C# and VB.Net languages. Example: // C# program to find the languages// known by the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; } public List<string> emp_lang { get; set; }} public class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000, emp_lang = new List<string>{"C#", "VB"} }, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000, emp_lang = new List<string>{ "Java"} }, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000, emp_lang = new List<string>{ "C++", "SQL"} }, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000, emp_lang = new List<string>{"Python", "C", "PHP"} }, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000, emp_lang = new List<string>{"HTML", "JQuery"} }, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000, emp_lang = new List<string>{"JavaScript", "Perl"} }, }; // Finding the languages known by the employee // Using SelectMany method var res = emp.SelectMany(a => a.emp_lang); Console.WriteLine("Languages known by all the employees are:"); foreach(var val in res) { Console.WriteLine(val); } }} Languages known by all the employees are: C# VB Java C++ SQL Python C PHP HTML JQuery JavaScript Perl CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25663, "s": 25635, "text": "\n21 May, 2019" }, { "code": null, "e": 26044, "s": 25663, "text": "In LINQ, projection is an operation which converts an object into the new form which holds only those properties which will be subsequently used. By using projection, a developer can create a new type which is built from each object. You are allowed to project property and conduct mathematical function on it, and you can also project the original object without transforming it." }, { "code": null, "e": 26104, "s": 26044, "text": "In LINQ, the following projection operations are available:" }, { "code": null, "e": 26121, "s": 26104, "text": "SelectSelectMany" }, { "code": null, "e": 26128, "s": 26121, "text": "Select" }, { "code": null, "e": 26139, "s": 26128, "text": "SelectMany" }, { "code": null, "e": 26492, "s": 26139, "text": "The SelectMany operator returns sequences of values which are based on the transformation function and then make them into one sequence. Or in other words, we can say, SelectMany operator is used when you want to select values from the multiple collections or if you want a result from the list of the lists and wants to display into a single sequence." }, { "code": null, "e": 26646, "s": 26492, "text": "SelectMany in Query Syntax: In Query Syntax, the working of SelectMany operator is achieved by using multiple from clause. As shown in the below example." }, { "code": null, "e": 26655, "s": 26646, "text": "Example:" }, { "code": "// C# program to find the languages// known by the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; } public List<string> emp_lang { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000, emp_lang = new List<string>{\"C#\", \"VB\"} }, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000, emp_lang = new List<string>{ \"Java\"} }, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000, emp_lang = new List<string>{ \"C++\", \"SQL\"} }, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000, emp_lang = new List<string>{\"Python\", \"C\", \"PHP\"} }, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000, emp_lang = new List<string>{\"HTML\", \"JQuery\"} }, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000, emp_lang = new List<string>{\"JavaScript\", \"Perl\"} }, }; // Query to find the languages // known by the employee var res = from e in emp from e2 in e.emp_lang select e2; Console.WriteLine(\"Languages known by all the employees are:\"); foreach(var val in res) { Console.WriteLine(val); } }}", "e": 28769, "s": 26655, "text": null }, { "code": null, "e": 28872, "s": 28769, "text": "Languages known by all the employees are:\nC#\nVB\nJava\nC++\nSQL\nPython\nC\nPHP\nHTML\nJQuery\nJavaScript\nPerl\n" }, { "code": null, "e": 29024, "s": 28872, "text": "SelectMany in Method Syntax: The SelectMany method is present in both the Queryable and Enumerable class and supported by both C# and VB.Net languages." }, { "code": null, "e": 29033, "s": 29024, "text": "Example:" }, { "code": "// C# program to find the languages// known by the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; } public List<string> emp_lang { get; set; }} public class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000, emp_lang = new List<string>{\"C#\", \"VB\"} }, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000, emp_lang = new List<string>{ \"Java\"} }, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000, emp_lang = new List<string>{ \"C++\", \"SQL\"} }, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000, emp_lang = new List<string>{\"Python\", \"C\", \"PHP\"} }, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000, emp_lang = new List<string>{\"HTML\", \"JQuery\"} }, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000, emp_lang = new List<string>{\"JavaScript\", \"Perl\"} }, }; // Finding the languages known by the employee // Using SelectMany method var res = emp.SelectMany(a => a.emp_lang); Console.WriteLine(\"Languages known by all the employees are:\"); foreach(var val in res) { Console.WriteLine(val); } }}", "e": 31110, "s": 29033, "text": null }, { "code": null, "e": 31213, "s": 31110, "text": "Languages known by all the employees are:\nC#\nVB\nJava\nC++\nSQL\nPython\nC\nPHP\nHTML\nJQuery\nJavaScript\nPerl\n" }, { "code": null, "e": 31225, "s": 31213, "text": "CSharp LINQ" }, { "code": null, "e": 31228, "s": 31225, "text": "C#" }, { "code": null, "e": 31326, "s": 31228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31354, "s": 31326, "text": "C# Dictionary with examples" }, { "code": null, "e": 31369, "s": 31354, "text": "C# | Delegates" }, { "code": null, "e": 31392, "s": 31369, "text": "C# | Method Overriding" }, { "code": null, "e": 31414, "s": 31392, "text": "C# | Abstract Classes" }, { "code": null, "e": 31460, "s": 31414, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 31483, "s": 31460, "text": "Extension Method in C#" }, { "code": null, "e": 31505, "s": 31483, "text": "C# | Class and Object" }, { "code": null, "e": 31523, "s": 31505, "text": "C# | Constructors" }, { "code": null, "e": 31563, "s": 31523, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
How to find the minimum and maximum element of an Array using STL in C++? - GeeksforGeeks
18 Aug, 2021 Given an array arr[], find the minimum and maximum element of this array using STL in C++.Example: Input: arr[] = {1, 45, 54, 71, 76, 12} Output: min = 1, max = 76 Input: arr[] = {10, 7, 5, 4, 6, 12} Output: min = 4, max = 12 Approach: Min or Minimum element can be found with the help of *min_element() function provided in STL. Max or Maximum element can be found with the help of *max_element() function provided in STL. Syntax: *min_element (first, last); *max_element (first, last); To use *min_element() and *max_element() you must include “algorithm” as a header file. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. Below is the implementation of the above approach: CPP // C++ program to find the min and max element// of Array using sort() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the array int arr[] = { 1, 45, 54, 71, 76, 12 }; // Compute the sizes int n = sizeof(arr) / sizeof(arr[0]); // Print the array cout << "Array: "; for (int i = 0; i < n; i++) cout << arr[i] << " "; // Find the minimum element cout << "\nMin Element = " << *min_element(arr, arr + n); // Find the maximum element cout << "\nMax Element = " << *max_element(arr, arr + n); // Storing the pointer in an address int &min = *min_element(arr,arr+n ); int &max = *max_element(arr,arr+n ); cout<<"\nFinding the Element using address variable"; cout<<"\nMin Element = "<<min; cout<<"\nMax Element = "<<max; return 0;} Array: 1 45 54 71 76 12 Min Element = 1 Max Element = 76 Finding the Element using address variable Min Element = 1 Max Element = 76 shubhamlightning99 nagpalharshit31 nayakvarsha99 cpp-array STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25367, "s": 25339, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25467, "s": 25367, "text": "Given an array arr[], find the minimum and maximum element of this array using STL in C++.Example: " }, { "code": null, "e": 25595, "s": 25467, "text": "Input: arr[] = {1, 45, 54, 71, 76, 12}\nOutput: min = 1, max = 76\n\nInput: arr[] = {10, 7, 5, 4, 6, 12}\nOutput: min = 4, max = 12" }, { "code": null, "e": 25607, "s": 25595, "text": "Approach: " }, { "code": null, "e": 25701, "s": 25607, "text": "Min or Minimum element can be found with the help of *min_element() function provided in STL." }, { "code": null, "e": 25795, "s": 25701, "text": "Max or Maximum element can be found with the help of *max_element() function provided in STL." }, { "code": null, "e": 25805, "s": 25795, "text": "Syntax: " }, { "code": null, "e": 25862, "s": 25805, "text": "*min_element (first, last);\n\n*max_element (first, last);" }, { "code": null, "e": 25950, "s": 25862, "text": "To use *min_element() and *max_element() you must include “algorithm” as a header file." }, { "code": null, "e": 26114, "s": 25950, "text": "The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last." }, { "code": null, "e": 26166, "s": 26114, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26170, "s": 26166, "text": "CPP" }, { "code": "// C++ program to find the min and max element// of Array using sort() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the array int arr[] = { 1, 45, 54, 71, 76, 12 }; // Compute the sizes int n = sizeof(arr) / sizeof(arr[0]); // Print the array cout << \"Array: \"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; // Find the minimum element cout << \"\\nMin Element = \" << *min_element(arr, arr + n); // Find the maximum element cout << \"\\nMax Element = \" << *max_element(arr, arr + n); // Storing the pointer in an address int &min = *min_element(arr,arr+n ); int &max = *max_element(arr,arr+n ); cout<<\"\\nFinding the Element using address variable\"; cout<<\"\\nMin Element = \"<<min; cout<<\"\\nMax Element = \"<<max; return 0;}", "e": 27000, "s": 26170, "text": null }, { "code": null, "e": 27134, "s": 27000, "text": "Array: 1 45 54 71 76 12 \nMin Element = 1\nMax Element = 76\nFinding the Element using address variable\nMin Element = 1\nMax Element = 76" }, { "code": null, "e": 27153, "s": 27134, "text": "shubhamlightning99" }, { "code": null, "e": 27169, "s": 27153, "text": "nagpalharshit31" }, { "code": null, "e": 27183, "s": 27169, "text": "nayakvarsha99" }, { "code": null, "e": 27193, "s": 27183, "text": "cpp-array" }, { "code": null, "e": 27197, "s": 27193, "text": "STL" }, { "code": null, "e": 27201, "s": 27197, "text": "C++" }, { "code": null, "e": 27214, "s": 27201, "text": "C++ Programs" }, { "code": null, "e": 27218, "s": 27214, "text": "STL" }, { "code": null, "e": 27222, "s": 27218, "text": "CPP" }, { "code": null, "e": 27320, "s": 27222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27348, "s": 27320, "text": "Operator Overloading in C++" }, { "code": null, "e": 27368, "s": 27348, "text": "Polymorphism in C++" }, { "code": null, "e": 27401, "s": 27368, "text": "Friend class and function in C++" }, { "code": null, "e": 27425, "s": 27401, "text": "Sorting a vector in C++" }, { "code": null, "e": 27450, "s": 27425, "text": "std::string class in C++" }, { "code": null, "e": 27485, "s": 27450, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27529, "s": 27485, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27588, "s": 27529, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27614, "s": 27588, "text": "C++ Program for QuickSort" } ]
in_place module in Python - GeeksforGeeks
18 Jul, 2021 Sometimes, while working with Python files, we can have utility in which we wish to alter files without using system context or sys stdout. Such situation require reading/writing files inplace, i.e without using process resources. This can be achieved using the ein_place module in Python. This module – Doesn’t use sys.stdout, rather returns the new filehandler instance. Supports all filehandler methods. In case of exception, the original file is retained, helping in atomicity. Creation of temporary files doesn’t hit other files opened. Simply run this command to install the required module pip install in_place Now to actually get the job done use in_place() method of this module. Syntax: in_place.InPlace(filename, mode=t, backup=None, backup_ext=None, delay_open=False, move_first=False) Parameter: filename : Location of file to open and edit inplace.mode : Mode with which to open file. Options are byte (b) and text(t). In case its open in byte more, read and write happens in bytes. In text mode, R & W happens in string. Defaults to text mode.backup : Path to save original file after the end of process in case to keep backup of original file.backup_ext : Created backup of with name – filename + backup_ext, of original file before editing. delay_open : In case set to True, it will only open file after calling open(), whereas by default its open as soon as class is initiated.move_first : If set to True, the input file is sent to temporary location and output is edited in place first. By default this process takes place after calling of close() or when process ends. Using this function the file in use is first opened and a required task is performed on it. Given below is the simplest implementation for the same. Example 1 : Input: Original Content Python3 import in_place # using inplace() to perform same file edit.with in_place.InPlace('gfg_inplace') as f: for line in f: # reversing cases while writing in file, inplace f.write(''.join(char.upper() if char.islower() else char.lower() for char in line)) Output : Output of file after code execution.- Alters cases. It is also possible to first back up the data of the existing file onto some other file and then make the required changes to the file. For this the name of the file by which you want to create a back-up is given as an value to backup argument. Example 2 : Input: Output of file after code execution.- Alters cases. Python3 import in_place # using inplace() to perform same file edit.# backs up original file in given path.with in_place.InPlace('gfg_inplace', backup='origin_gfg_inplace') as f: for line in f: # reversing cases while writing in file, inplace f.write(''.join(char.upper() if char.islower() else char.lower() for char in line)) Output : After code execution, inplace changes. Backup of original contents is created in new file. The alternative to the above method is the use fo keyword backup_ext. Onto this just pass the extra word to differentiate the existing file from. Example 3: Input: Python3 import in_place # using inplace() to perform same file edit.# adds extension to file and creates backupwith in_place.InPlace('gfg_inplace', backup_ext='-original') as f: for line in f: # reversing cases while writing in file, inplace f.write(''.join(char.upper() if char.islower() else char.lower() for char in line)) Output : After code execution, inplace changes. Created backup of original file, adding given extension. python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n18 Jul, 2021" }, { "code": null, "e": 25841, "s": 25537, "text": "Sometimes, while working with Python files, we can have utility in which we wish to alter files without using system context or sys stdout. Such situation require reading/writing files inplace, i.e without using process resources. This can be achieved using the ein_place module in Python. This module –" }, { "code": null, "e": 25910, "s": 25841, "text": "Doesn’t use sys.stdout, rather returns the new filehandler instance." }, { "code": null, "e": 25944, "s": 25910, "text": "Supports all filehandler methods." }, { "code": null, "e": 26019, "s": 25944, "text": "In case of exception, the original file is retained, helping in atomicity." }, { "code": null, "e": 26079, "s": 26019, "text": "Creation of temporary files doesn’t hit other files opened." }, { "code": null, "e": 26134, "s": 26079, "text": "Simply run this command to install the required module" }, { "code": null, "e": 26155, "s": 26134, "text": "pip install in_place" }, { "code": null, "e": 26226, "s": 26155, "text": "Now to actually get the job done use in_place() method of this module." }, { "code": null, "e": 26234, "s": 26226, "text": "Syntax:" }, { "code": null, "e": 26335, "s": 26234, "text": "in_place.InPlace(filename, mode=t, backup=None, backup_ext=None, delay_open=False, move_first=False)" }, { "code": null, "e": 26346, "s": 26335, "text": "Parameter:" }, { "code": null, "e": 27127, "s": 26346, "text": "filename : Location of file to open and edit inplace.mode : Mode with which to open file. Options are byte (b) and text(t). In case its open in byte more, read and write happens in bytes. In text mode, R & W happens in string. Defaults to text mode.backup : Path to save original file after the end of process in case to keep backup of original file.backup_ext : Created backup of with name – filename + backup_ext, of original file before editing. delay_open : In case set to True, it will only open file after calling open(), whereas by default its open as soon as class is initiated.move_first : If set to True, the input file is sent to temporary location and output is edited in place first. By default this process takes place after calling of close() or when process ends." }, { "code": null, "e": 27276, "s": 27127, "text": "Using this function the file in use is first opened and a required task is performed on it. Given below is the simplest implementation for the same." }, { "code": null, "e": 27288, "s": 27276, "text": "Example 1 :" }, { "code": null, "e": 27295, "s": 27288, "text": "Input:" }, { "code": null, "e": 27312, "s": 27295, "text": "Original Content" }, { "code": null, "e": 27320, "s": 27312, "text": "Python3" }, { "code": "import in_place # using inplace() to perform same file edit.with in_place.InPlace('gfg_inplace') as f: for line in f: # reversing cases while writing in file, inplace f.write(''.join(char.upper() if char.islower() else char.lower() for char in line))", "e": 27614, "s": 27320, "text": null }, { "code": null, "e": 27623, "s": 27614, "text": "Output :" }, { "code": null, "e": 27675, "s": 27623, "text": "Output of file after code execution.- Alters cases." }, { "code": null, "e": 27920, "s": 27675, "text": "It is also possible to first back up the data of the existing file onto some other file and then make the required changes to the file. For this the name of the file by which you want to create a back-up is given as an value to backup argument." }, { "code": null, "e": 27933, "s": 27920, "text": "Example 2 : " }, { "code": null, "e": 27940, "s": 27933, "text": "Input:" }, { "code": null, "e": 27992, "s": 27940, "text": "Output of file after code execution.- Alters cases." }, { "code": null, "e": 28000, "s": 27992, "text": "Python3" }, { "code": "import in_place # using inplace() to perform same file edit.# backs up original file in given path.with in_place.InPlace('gfg_inplace', backup='origin_gfg_inplace') as f: for line in f: # reversing cases while writing in file, inplace f.write(''.join(char.upper() if char.islower() else char.lower() for char in line))", "e": 28362, "s": 28000, "text": null }, { "code": null, "e": 28372, "s": 28362, "text": "Output : " }, { "code": null, "e": 28411, "s": 28372, "text": "After code execution, inplace changes." }, { "code": null, "e": 28463, "s": 28411, "text": "Backup of original contents is created in new file." }, { "code": null, "e": 28609, "s": 28463, "text": "The alternative to the above method is the use fo keyword backup_ext. Onto this just pass the extra word to differentiate the existing file from." }, { "code": null, "e": 28620, "s": 28609, "text": "Example 3:" }, { "code": null, "e": 28627, "s": 28620, "text": "Input:" }, { "code": null, "e": 28635, "s": 28627, "text": "Python3" }, { "code": "import in_place # using inplace() to perform same file edit.# adds extension to file and creates backupwith in_place.InPlace('gfg_inplace', backup_ext='-original') as f: for line in f: # reversing cases while writing in file, inplace f.write(''.join(char.upper() if char.islower() else char.lower() for char in line))", "e": 28996, "s": 28635, "text": null }, { "code": null, "e": 29006, "s": 28996, "text": "Output : " }, { "code": null, "e": 29045, "s": 29006, "text": "After code execution, inplace changes." }, { "code": null, "e": 29102, "s": 29045, "text": "Created backup of original file, adding given extension." }, { "code": null, "e": 29117, "s": 29102, "text": "python-modules" }, { "code": null, "e": 29124, "s": 29117, "text": "Python" }, { "code": null, "e": 29222, "s": 29124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29254, "s": 29222, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29296, "s": 29254, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29338, "s": 29296, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29365, "s": 29338, "text": "Python Classes and Objects" }, { "code": null, "e": 29421, "s": 29365, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29443, "s": 29421, "text": "Defaultdict in Python" }, { "code": null, "e": 29482, "s": 29443, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29513, "s": 29482, "text": "Python | os.path.join() method" }, { "code": null, "e": 29542, "s": 29513, "text": "Create a directory in Python" } ]
Implementation of Locally Weighted Linear Regression - GeeksforGeeks
12 Dec, 2021 LOESS or LOWESS are non-parametric regression methods that combine multiple regression models in a k-nearest-neighbor-based meta-model. LOESS combines much of the simplicity of linear least squares regression with the flexibility of nonlinear regression. It does this by fitting simple models to localized subsets of the data to build up a function that describes the variation in the data, point by point. This algorithm is used for making predictions when there exists a non-linear relationship between the features. Locally weighted linear regression is a supervised learning algorithm. It a non-parametric algorithm. doneThere exists No training phase. All the work is done during the testing phase/while making predictions. Suppose we want to evaluate the hypothesis function h at a certain query point x. For linear regression we would do the following: For locally weighted linear regression we will instead do the following: where w(i) is a is a non-negative “weight” associated with training point x(i). A higher “preference” is given to the points in the training set lying in the vicinity of x than the points lying far away from x. so For x(i) lying closer to the query point x, the value of w(i) is large, while for x(i) lying far away from x the value of w(i) is small. w(i) can be chosen as – Directly using closed Form solution to find parameters- Code: Importing Libraries : python import numpy as npimport matplotlib.pyplot as pltimport pandas as pd plt.style.use("seaborn") Code: Loading Data : python # Loading CSV files from local storagedfx = pd.read_csv('weightedX_LOWES.csv')dfy = pd.read_csv('weightedY_LOWES.csv')# Getting data from DataFrame Object and storing in numpy n-dim arraysX = dfx.valuesY = dfy.values Output: Code: Function to calculate weight matrix : python # function to calculate W weight diagonal Matrix used in calculation of predictionsdef get_WeightMatrix_for_LOWES(query_point, Training_examples, Bandwidth): # M is the No of training examples M = Training_examples.shape[0] # Initialising W with identity matrix W = np.mat(np.eye(M)) # calculating weights for query points for i in range(M): xi = Training_examples[i] denominator = (-2 * Bandwidth * Bandwidth) W[i, i] = np.exp(np.dot((xi-query_point), (xi-query_point).T)/denominator) return W Code: Making Predictions: python # function to make predictionsdef predict(training_examples, Y, query_x, Bandwidth): M = Training_examples.shape[0] all_ones = np.ones((M, 1)) X_ = np.hstack((training_examples, all_ones)) qx = np.mat([query_x, 1]) W = get_WeightMatrix_for_LOWES(qx, X_, Bandwidth) # calculating parameter theta theta = np.linalg.pinv(X_.T*(W * X_))*(X_.T*(W * Y)) # calculating predictions pred = np.dot(qx, theta) return theta, pred Code: Visualise Predictions : python # visualise predicted values with respect# to original target values Bandwidth = 0.1X_test = np.linspace(-2, 2, 20)Y_test = []for query in X_test: theta, pred = predict(X, Y, query, Bandwidth) Y_test.append(pred[0][0])horizontal_axis = np.array(X)vertical_axis = np.array(Y)plt.title("Tau / Bandwidth Param %.2f"% Bandwidth)plt.scatter(horizontal_axis, vertical_axis)Y_test = np.array(Y_test)plt.scatter(X_test, Y_test, color ='red')plt.show() surinderdawra388 sooda367 avtarkumar719 Regression Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network Support Vector Machine Algorithm Python | Decision tree implementation 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": 25905, "s": 25877, "text": "\n12 Dec, 2021" }, { "code": null, "e": 26314, "s": 25905, "text": "LOESS or LOWESS are non-parametric regression methods that combine multiple regression models in a k-nearest-neighbor-based meta-model. LOESS combines much of the simplicity of linear least squares regression with the flexibility of nonlinear regression. It does this by fitting simple models to localized subsets of the data to build up a function that describes the variation in the data, point by point. " }, { "code": null, "e": 26426, "s": 26314, "text": "This algorithm is used for making predictions when there exists a non-linear relationship between the features." }, { "code": null, "e": 26497, "s": 26426, "text": "Locally weighted linear regression is a supervised learning algorithm." }, { "code": null, "e": 26528, "s": 26497, "text": "It a non-parametric algorithm." }, { "code": null, "e": 26636, "s": 26528, "text": "doneThere exists No training phase. All the work is done during the testing phase/while making predictions." }, { "code": null, "e": 27307, "s": 26636, "text": "Suppose we want to evaluate the hypothesis function h at a certain query point x. For linear regression we would do the following: For locally weighted linear regression we will instead do the following: where w(i) is a is a non-negative “weight” associated with training point x(i). A higher “preference” is given to the points in the training set lying in the vicinity of x than the points lying far away from x. so For x(i) lying closer to the query point x, the value of w(i) is large, while for x(i) lying far away from x the value of w(i) is small. w(i) can be chosen as – Directly using closed Form solution to find parameters- Code: Importing Libraries : " }, { "code": null, "e": 27314, "s": 27307, "text": "python" }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd plt.style.use(\"seaborn\")", "e": 27408, "s": 27314, "text": null }, { "code": null, "e": 27431, "s": 27408, "text": "Code: Loading Data : " }, { "code": null, "e": 27438, "s": 27431, "text": "python" }, { "code": "# Loading CSV files from local storagedfx = pd.read_csv('weightedX_LOWES.csv')dfy = pd.read_csv('weightedY_LOWES.csv')# Getting data from DataFrame Object and storing in numpy n-dim arraysX = dfx.valuesY = dfy.values", "e": 27655, "s": 27438, "text": null }, { "code": null, "e": 27665, "s": 27655, "text": "Output: " }, { "code": null, "e": 27710, "s": 27665, "text": "Code: Function to calculate weight matrix : " }, { "code": null, "e": 27717, "s": 27710, "text": "python" }, { "code": "# function to calculate W weight diagonal Matrix used in calculation of predictionsdef get_WeightMatrix_for_LOWES(query_point, Training_examples, Bandwidth): # M is the No of training examples M = Training_examples.shape[0] # Initialising W with identity matrix W = np.mat(np.eye(M)) # calculating weights for query points for i in range(M): xi = Training_examples[i] denominator = (-2 * Bandwidth * Bandwidth) W[i, i] = np.exp(np.dot((xi-query_point), (xi-query_point).T)/denominator) return W", "e": 28230, "s": 27717, "text": null }, { "code": null, "e": 28258, "s": 28230, "text": "Code: Making Predictions: " }, { "code": null, "e": 28265, "s": 28258, "text": "python" }, { "code": "# function to make predictionsdef predict(training_examples, Y, query_x, Bandwidth): M = Training_examples.shape[0] all_ones = np.ones((M, 1)) X_ = np.hstack((training_examples, all_ones)) qx = np.mat([query_x, 1]) W = get_WeightMatrix_for_LOWES(qx, X_, Bandwidth) # calculating parameter theta theta = np.linalg.pinv(X_.T*(W * X_))*(X_.T*(W * Y)) # calculating predictions pred = np.dot(qx, theta) return theta, pred", "e": 28693, "s": 28265, "text": null }, { "code": null, "e": 28724, "s": 28693, "text": "Code: Visualise Predictions : " }, { "code": null, "e": 28731, "s": 28724, "text": "python" }, { "code": "# visualise predicted values with respect# to original target values Bandwidth = 0.1X_test = np.linspace(-2, 2, 20)Y_test = []for query in X_test: theta, pred = predict(X, Y, query, Bandwidth) Y_test.append(pred[0][0])horizontal_axis = np.array(X)vertical_axis = np.array(Y)plt.title(\"Tau / Bandwidth Param %.2f\"% Bandwidth)plt.scatter(horizontal_axis, vertical_axis)Y_test = np.array(Y_test)plt.scatter(X_test, Y_test, color ='red')plt.show()", "e": 29177, "s": 28731, "text": null }, { "code": null, "e": 29194, "s": 29177, "text": "surinderdawra388" }, { "code": null, "e": 29203, "s": 29194, "text": "sooda367" }, { "code": null, "e": 29217, "s": 29203, "text": "avtarkumar719" }, { "code": null, "e": 29228, "s": 29217, "text": "Regression" }, { "code": null, "e": 29245, "s": 29228, "text": "Machine Learning" }, { "code": null, "e": 29252, "s": 29245, "text": "Python" }, { "code": null, "e": 29269, "s": 29252, "text": "Machine Learning" }, { "code": null, "e": 29367, "s": 29269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29407, "s": 29367, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 29447, "s": 29407, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29488, "s": 29447, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29521, "s": 29488, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29559, "s": 29521, "text": "Python | Decision tree implementation" }, { "code": null, "e": 29587, "s": 29559, "text": "Read JSON file using Python" }, { "code": null, "e": 29637, "s": 29587, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29659, "s": 29637, "text": "Python map() function" } ]
How to Send Automated Email Messages in Python - GeeksforGeeks
31 Aug, 2021 In this article, we are going to see how to send automated email messages which involve delivering text messages, essential photos, and important files, among other things. in Python. We’ll be using two libraries for this: email, and smtplib, as well as the MIMEMultipart object. This object has multiple subclasses; these subclasses will be used to build our email message. MIMEText: It consists of simple text. This will be the body of the email. MIMEImage: This would allow us to add images to our emails. MIMEAudio: If we wish to add audio files, we may do it easily with the help of this subclass. MIMEApplication: This can be used to add anything or any other attachments. Step 1: Import the following modules Python3 from email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartimport smtplibimport os Step 2: Let’s set up a connection to our email server. Provide the server address and port number to initiate our SMTP connection Then we’ll use smtp.ehlo to send an EHLO (Extended Hello) command. Now, we’ll use smtp.starttls to enable transport layer security (TLS) encryption. Python3 smtp = smtplib.SMTP('smtp.gmail.com', 587)smtp.ehlo()smtp.starttls()smtp.login('[email protected]', 'Your Password') Step 3: Now, built the message content. Assign the MIMEMultipart object to the msg variable after initializing it. The MIMEText function will be used to attach text. Python3 msg = MIMEMultipart()msg['Subject'] = subjectmsg.attach(MIMEText(text)) Step 4: Let’s look at how to attach pictures and multiple attachments. Attaching Images: First, read the image as binary data. Attach the image data to MIMEMultipart using MIMEImage, we add the given filename use os.basename Python3 img_data = open(one_img, 'rb').read()msg.attach(MIMEImage(img_data, name=os.path.basename(one_img))) Attaching Several Files: Read in the attachment using MIMEApplication. Then we edit the attached file metadata. Finally, add the attachment to our message object. Python3 with open(one_attachment, 'rb') as f: file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment; \ filename="{os.path.basename(one_attachment)}"' msg.attach(file) Step 5: The last step is to send the email. Make a list of all the emails you want to send. Then, by using the sendmail function, pass parameters such as from where, to where, and the message content. At last, just quit the server connection. Python3 to = ["[email protected]", "[email protected]", "[email protected]"]smtp.sendmail(from_addr="Your Login Email", to_addrs=to, msg=msg.as_string())smtp.quit() Below is the full implementation: Python3 # Import the following modulefrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartimport smtplibimport os # initialize connection to our# email server, we will use gmail heresmtp = smtplib.SMTP('smtp.gmail.com', 587)smtp.ehlo()smtp.starttls() # Login with your email and passwordsmtp.login('Your Email', 'Your Password') # send our email message 'msg' to our bossdef message(subject="Python Notification", text="", img=None, attachment=None): # build message contents msg = MIMEMultipart() # Add Subject msg['Subject'] = subject # Add text contents msg.attach(MIMEText(text)) # Check if we have anything # given in the img parameter if img is not None: # Check whether we have the lists of images or not! if type(img) is not list: # if it isn't a list, make it one img = [img] # Now iterate through our list for one_img in img: # read the image binary data img_data = open(one_img, 'rb').read() # Attach the image data to MIMEMultipart # using MIMEImage, we add the given filename use os.basename msg.attach(MIMEImage(img_data, name=os.path.basename(one_img))) # We do the same for # attachments as we did for images if attachment is not None: # Check whether we have the # lists of attachments or not! if type(attachment) is not list: # if it isn't a list, make it one attachment = [attachment] for one_attachment in attachment: with open(one_attachment, 'rb') as f: # Read in the attachment # using MIMEApplication file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment;\ filename="{os.path.basename(one_attachment)}"' # At last, Add the attachment to our message object msg.attach(file) return msg # Call the message functionmsg = message("Good!", "Hi there!", r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg", r"C:\Users\Dell\Desktop\slack.py") # Make a list of emails, where you wanna send mailto = ["[email protected]", "[email protected]", "[email protected]"] # Provide some data to the sendmail function!smtp.sendmail(from_addr="[email protected]", to_addrs=to, msg=msg.as_string()) # Finally, don't forget to close the connectionsmtp.quit() Output: For scheduling the mail, we will make use of the schedule package in python. It is very lightweight and easy to use. Install the module pip install schedule The below function will call the function mail every 2 seconds. schedule.every(2).seconds.do(mail) This will call the function mail every 10 minutes. schedule.every(10).minutes.do(mail) This will call the function in every hour. schedule.every().hour.do(mail) Calling every day at 10:30 AM. schedule.every().day.at("10:30").do(mail) Calling a particular day. schedule.every().monday.do(mail) Below is the implementation: Python3 import scheduleimport timefrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartimport smtplibimport os # send our email message 'msg' to our bossdef message(subject="Python Notification", text="", img=None, attachment=None): # build message contents msg = MIMEMultipart() # Add Subject msg['Subject'] = subject # Add text contents msg.attach(MIMEText(text)) # Check if we have anything # given in the img parameter if img is not None: # Check whether we have the # lists of images or not! if type(img) is not list: # if it isn't a list, make it one img = [img] # Now iterate through our list for one_img in img: # read the image binary data img_data = open(one_img, 'rb').read() # Attach the image data to MIMEMultipart # using MIMEImage, # we add the given filename use os.basename msg.attach(MIMEImage(img_data, name=os.path.basename(one_img))) # We do the same for attachments # as we did for images if attachment is not None: # Check whether we have the # lists of attachments or not! if type(attachment) is not list: # if it isn't a list, make it one attachment = [attachment] for one_attachment in attachment: with open(one_attachment, 'rb') as f: # Read in the attachment using MIMEApplication file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment;\ filename="{os.path.basename(one_attachment)}"' # At last, Add the attachment to our message object msg.attach(file) return msg def mail(): # initialize connection to our email server, # we will use gmail here smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() # Login with your email and password smtp.login('Email', 'Password') # Call the message function msg = message("Good!", "Hi there!", r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg", r"C:\Users\Dell\Desktop\slack.py") # Make a list of emails, where you wanna send mail to = ["[email protected]", "[email protected]", "[email protected]"] # Provide some data to the sendmail function! smtp.sendmail(from_addr="[email protected]", to_addrs=to, msg=msg.as_string()) # Finally, don't forget to close the connection smtp.quit() schedule.every(2).seconds.do(mail)schedule.every(10).minutes.do(mail)schedule.every().hour.do(mail)schedule.every().day.at("10:30").do(mail)schedule.every(5).to(10).minutes.do(mail)schedule.every().monday.do(mail)schedule.every().wednesday.at("13:15").do(mail)schedule.every().minute.at(":17").do(mail) while True: schedule.run_pending() time.sleep(1) Output: Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25748, "s": 25563, "text": "In this article, we are going to see how to send automated email messages which involve delivering text messages, essential photos, and important files, among other things. in Python. " }, { "code": null, "e": 25939, "s": 25748, "text": "We’ll be using two libraries for this: email, and smtplib, as well as the MIMEMultipart object. This object has multiple subclasses; these subclasses will be used to build our email message." }, { "code": null, "e": 26013, "s": 25939, "text": "MIMEText: It consists of simple text. This will be the body of the email." }, { "code": null, "e": 26073, "s": 26013, "text": "MIMEImage: This would allow us to add images to our emails." }, { "code": null, "e": 26167, "s": 26073, "text": "MIMEAudio: If we wish to add audio files, we may do it easily with the help of this subclass." }, { "code": null, "e": 26243, "s": 26167, "text": "MIMEApplication: This can be used to add anything or any other attachments." }, { "code": null, "e": 26280, "s": 26243, "text": "Step 1: Import the following modules" }, { "code": null, "e": 26288, "s": 26280, "text": "Python3" }, { "code": "from email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartimport smtplibimport os", "e": 26482, "s": 26288, "text": null }, { "code": null, "e": 26537, "s": 26482, "text": "Step 2: Let’s set up a connection to our email server." }, { "code": null, "e": 26612, "s": 26537, "text": "Provide the server address and port number to initiate our SMTP connection" }, { "code": null, "e": 26679, "s": 26612, "text": "Then we’ll use smtp.ehlo to send an EHLO (Extended Hello) command." }, { "code": null, "e": 26761, "s": 26679, "text": "Now, we’ll use smtp.starttls to enable transport layer security (TLS) encryption." }, { "code": null, "e": 26769, "s": 26761, "text": "Python3" }, { "code": "smtp = smtplib.SMTP('smtp.gmail.com', 587)smtp.ehlo()smtp.starttls()smtp.login('[email protected]', 'Your Password')", "e": 26887, "s": 26769, "text": null }, { "code": null, "e": 26927, "s": 26887, "text": "Step 3: Now, built the message content." }, { "code": null, "e": 27002, "s": 26927, "text": "Assign the MIMEMultipart object to the msg variable after initializing it." }, { "code": null, "e": 27053, "s": 27002, "text": "The MIMEText function will be used to attach text." }, { "code": null, "e": 27061, "s": 27053, "text": "Python3" }, { "code": "msg = MIMEMultipart()msg['Subject'] = subjectmsg.attach(MIMEText(text))", "e": 27133, "s": 27061, "text": null }, { "code": null, "e": 27204, "s": 27133, "text": "Step 4: Let’s look at how to attach pictures and multiple attachments." }, { "code": null, "e": 27223, "s": 27204, "text": "Attaching Images: " }, { "code": null, "e": 27261, "s": 27223, "text": "First, read the image as binary data." }, { "code": null, "e": 27359, "s": 27261, "text": "Attach the image data to MIMEMultipart using MIMEImage, we add the given filename use os.basename" }, { "code": null, "e": 27367, "s": 27359, "text": "Python3" }, { "code": "img_data = open(one_img, 'rb').read()msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))", "e": 27489, "s": 27367, "text": null }, { "code": null, "e": 27514, "s": 27489, "text": "Attaching Several Files:" }, { "code": null, "e": 27560, "s": 27514, "text": "Read in the attachment using MIMEApplication." }, { "code": null, "e": 27601, "s": 27560, "text": "Then we edit the attached file metadata." }, { "code": null, "e": 27652, "s": 27601, "text": "Finally, add the attachment to our message object." }, { "code": null, "e": 27660, "s": 27652, "text": "Python3" }, { "code": "with open(one_attachment, 'rb') as f: file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment; \\ filename=\"{os.path.basename(one_attachment)}\"' msg.attach(file)", "e": 27904, "s": 27660, "text": null }, { "code": null, "e": 27948, "s": 27904, "text": "Step 5: The last step is to send the email." }, { "code": null, "e": 27996, "s": 27948, "text": "Make a list of all the emails you want to send." }, { "code": null, "e": 28105, "s": 27996, "text": "Then, by using the sendmail function, pass parameters such as from where, to where, and the message content." }, { "code": null, "e": 28147, "s": 28105, "text": "At last, just quit the server connection." }, { "code": null, "e": 28155, "s": 28147, "text": "Python3" }, { "code": "to = [\"[email protected]\", \"[email protected]\", \"[email protected]\"]smtp.sendmail(from_addr=\"Your Login Email\", to_addrs=to, msg=msg.as_string())smtp.quit()", "e": 28313, "s": 28155, "text": null }, { "code": null, "e": 28347, "s": 28313, "text": "Below is the full implementation:" }, { "code": null, "e": 28355, "s": 28347, "text": "Python3" }, { "code": "# Import the following modulefrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartimport smtplibimport os # initialize connection to our# email server, we will use gmail heresmtp = smtplib.SMTP('smtp.gmail.com', 587)smtp.ehlo()smtp.starttls() # Login with your email and passwordsmtp.login('Your Email', 'Your Password') # send our email message 'msg' to our bossdef message(subject=\"Python Notification\", text=\"\", img=None, attachment=None): # build message contents msg = MIMEMultipart() # Add Subject msg['Subject'] = subject # Add text contents msg.attach(MIMEText(text)) # Check if we have anything # given in the img parameter if img is not None: # Check whether we have the lists of images or not! if type(img) is not list: # if it isn't a list, make it one img = [img] # Now iterate through our list for one_img in img: # read the image binary data img_data = open(one_img, 'rb').read() # Attach the image data to MIMEMultipart # using MIMEImage, we add the given filename use os.basename msg.attach(MIMEImage(img_data, name=os.path.basename(one_img))) # We do the same for # attachments as we did for images if attachment is not None: # Check whether we have the # lists of attachments or not! if type(attachment) is not list: # if it isn't a list, make it one attachment = [attachment] for one_attachment in attachment: with open(one_attachment, 'rb') as f: # Read in the attachment # using MIMEApplication file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment;\\ filename=\"{os.path.basename(one_attachment)}\"' # At last, Add the attachment to our message object msg.attach(file) return msg # Call the message functionmsg = message(\"Good!\", \"Hi there!\", r\"C:\\Users\\Dell\\Downloads\\Garbage\\Cartoon.jpg\", r\"C:\\Users\\Dell\\Desktop\\slack.py\") # Make a list of emails, where you wanna send mailto = [\"[email protected]\", \"[email protected]\", \"[email protected]\"] # Provide some data to the sendmail function!smtp.sendmail(from_addr=\"[email protected]\", to_addrs=to, msg=msg.as_string()) # Finally, don't forget to close the connectionsmtp.quit()", "e": 31159, "s": 28355, "text": null }, { "code": null, "e": 31168, "s": 31159, "text": "Output: " }, { "code": null, "e": 31286, "s": 31168, "text": "For scheduling the mail, we will make use of the schedule package in python. It is very lightweight and easy to use. " }, { "code": null, "e": 31306, "s": 31286, "text": "Install the module " }, { "code": null, "e": 31327, "s": 31306, "text": "pip install schedule" }, { "code": null, "e": 31391, "s": 31327, "text": "The below function will call the function mail every 2 seconds." }, { "code": null, "e": 31427, "s": 31391, "text": "schedule.every(2).seconds.do(mail) " }, { "code": null, "e": 31478, "s": 31427, "text": "This will call the function mail every 10 minutes." }, { "code": null, "e": 31514, "s": 31478, "text": "schedule.every(10).minutes.do(mail)" }, { "code": null, "e": 31557, "s": 31514, "text": "This will call the function in every hour." }, { "code": null, "e": 31588, "s": 31557, "text": "schedule.every().hour.do(mail)" }, { "code": null, "e": 31619, "s": 31588, "text": "Calling every day at 10:30 AM." }, { "code": null, "e": 31661, "s": 31619, "text": "schedule.every().day.at(\"10:30\").do(mail)" }, { "code": null, "e": 31687, "s": 31661, "text": "Calling a particular day." }, { "code": null, "e": 31720, "s": 31687, "text": "schedule.every().monday.do(mail)" }, { "code": null, "e": 31749, "s": 31720, "text": "Below is the implementation:" }, { "code": null, "e": 31757, "s": 31749, "text": "Python3" }, { "code": "import scheduleimport timefrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.application import MIMEApplicationfrom email.mime.multipart import MIMEMultipartimport smtplibimport os # send our email message 'msg' to our bossdef message(subject=\"Python Notification\", text=\"\", img=None, attachment=None): # build message contents msg = MIMEMultipart() # Add Subject msg['Subject'] = subject # Add text contents msg.attach(MIMEText(text)) # Check if we have anything # given in the img parameter if img is not None: # Check whether we have the # lists of images or not! if type(img) is not list: # if it isn't a list, make it one img = [img] # Now iterate through our list for one_img in img: # read the image binary data img_data = open(one_img, 'rb').read() # Attach the image data to MIMEMultipart # using MIMEImage, # we add the given filename use os.basename msg.attach(MIMEImage(img_data, name=os.path.basename(one_img))) # We do the same for attachments # as we did for images if attachment is not None: # Check whether we have the # lists of attachments or not! if type(attachment) is not list: # if it isn't a list, make it one attachment = [attachment] for one_attachment in attachment: with open(one_attachment, 'rb') as f: # Read in the attachment using MIMEApplication file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment;\\ filename=\"{os.path.basename(one_attachment)}\"' # At last, Add the attachment to our message object msg.attach(file) return msg def mail(): # initialize connection to our email server, # we will use gmail here smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() # Login with your email and password smtp.login('Email', 'Password') # Call the message function msg = message(\"Good!\", \"Hi there!\", r\"C:\\Users\\Dell\\Downloads\\Garbage\\Cartoon.jpg\", r\"C:\\Users\\Dell\\Desktop\\slack.py\") # Make a list of emails, where you wanna send mail to = [\"[email protected]\", \"[email protected]\", \"[email protected]\"] # Provide some data to the sendmail function! smtp.sendmail(from_addr=\"[email protected]\", to_addrs=to, msg=msg.as_string()) # Finally, don't forget to close the connection smtp.quit() schedule.every(2).seconds.do(mail)schedule.every(10).minutes.do(mail)schedule.every().hour.do(mail)schedule.every().day.at(\"10:30\").do(mail)schedule.every(5).to(10).minutes.do(mail)schedule.every().monday.do(mail)schedule.every().wednesday.at(\"13:15\").do(mail)schedule.every().minute.at(\":17\").do(mail) while True: schedule.run_pending() time.sleep(1)", "e": 35008, "s": 31757, "text": null }, { "code": null, "e": 35016, "s": 35008, "text": "Output:" }, { "code": null, "e": 35023, "s": 35016, "text": "Picked" }, { "code": null, "e": 35038, "s": 35023, "text": "python-utility" }, { "code": null, "e": 35045, "s": 35038, "text": "Python" }, { "code": null, "e": 35143, "s": 35045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35175, "s": 35143, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 35217, "s": 35175, "text": "Check if element exists in list in Python" }, { "code": null, "e": 35259, "s": 35217, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 35286, "s": 35259, "text": "Python Classes and Objects" }, { "code": null, "e": 35342, "s": 35286, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 35381, "s": 35342, "text": "Python | Get unique values from a list" }, { "code": null, "e": 35403, "s": 35381, "text": "Defaultdict in Python" }, { "code": null, "e": 35434, "s": 35403, "text": "Python | os.path.join() method" }, { "code": null, "e": 35463, "s": 35434, "text": "Create a directory in Python" } ]
Python | Convert String to tuple list - GeeksforGeeks
24 Jun, 2020 Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace()This is a brute force method to perform this task. In this, we perform the task of extracting and remaking the tuples to list in a loop using split() and replace() functionalities. # Python3 code to demonstrate working of# Convert String to tuple list# using loop + replace() + split() # initializing string test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)" # printing original string print("The original string is : " + test_str) # Convert String to tuple list# using loop + replace() + split()res = []temp = []for token in test_str.split(", "): num = int(token.replace("(", "").replace(")", "")) temp.append(num) if ")" in token: res.append(tuple(temp)) temp = [] # printing resultprint("List after conversion from string : " + str(res)) The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6) List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)] Method #2: Using eval()This inbuilt function can also be used to perform this task. This function internally evaluates the string and returns the converted list of tuples as desired. # Python3 code to demonstrate working of# Convert String to tuple list# using eval() # initializing string test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)" # printing original string print("The original string is : " + test_str) # Convert String to tuple list# using eval()res = list(eval(test_str)) # printing resultprint("List after conversion from string : " + str(res)) The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6) List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)] nidhi_biet Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary How to print without newline in Python? Python | Convert string dictionary to dictionary
[ { "code": null, "e": 25757, "s": 25729, "text": "\n24 Jun, 2020" }, { "code": null, "e": 26000, "s": 25757, "text": "Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26225, "s": 26000, "text": "Method #1 : Using loop + split() + replace()This is a brute force method to perform this task. In this, we perform the task of extracting and remaking the tuples to list in a loop using split() and replace() functionalities." }, { "code": "# Python3 code to demonstrate working of# Convert String to tuple list# using loop + replace() + split() # initializing string test_str = \"(1, 3, 4), (5, 6, 4), (1, 3, 6)\" # printing original string print(\"The original string is : \" + test_str) # Convert String to tuple list# using loop + replace() + split()res = []temp = []for token in test_str.split(\", \"): num = int(token.replace(\"(\", \"\").replace(\")\", \"\")) temp.append(num) if \")\" in token: res.append(tuple(temp)) temp = [] # printing resultprint(\"List after conversion from string : \" + str(res))", "e": 26804, "s": 26225, "text": null }, { "code": null, "e": 26932, "s": 26804, "text": "The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6)\nList after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)]\n" }, { "code": null, "e": 27117, "s": 26934, "text": "Method #2: Using eval()This inbuilt function can also be used to perform this task. This function internally evaluates the string and returns the converted list of tuples as desired." }, { "code": "# Python3 code to demonstrate working of# Convert String to tuple list# using eval() # initializing string test_str = \"(1, 3, 4), (5, 6, 4), (1, 3, 6)\" # printing original string print(\"The original string is : \" + test_str) # Convert String to tuple list# using eval()res = list(eval(test_str)) # printing resultprint(\"List after conversion from string : \" + str(res))", "e": 27491, "s": 27117, "text": null }, { "code": null, "e": 27619, "s": 27491, "text": "The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6)\nList after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)]\n" }, { "code": null, "e": 27630, "s": 27619, "text": "nidhi_biet" }, { "code": null, "e": 27653, "s": 27630, "text": "Python string-programs" }, { "code": null, "e": 27660, "s": 27653, "text": "Python" }, { "code": null, "e": 27676, "s": 27660, "text": "Python Programs" }, { "code": null, "e": 27774, "s": 27676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27792, "s": 27774, "text": "Python Dictionary" }, { "code": null, "e": 27824, "s": 27792, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27846, "s": 27824, "text": "Enumerate() in Python" }, { "code": null, "e": 27888, "s": 27846, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27914, "s": 27888, "text": "Python String | replace()" }, { "code": null, "e": 27936, "s": 27914, "text": "Defaultdict in Python" }, { "code": null, "e": 27975, "s": 27936, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28013, "s": 27975, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 28053, "s": 28013, "text": "How to print without newline in Python?" } ]
How to create a MySQL table with InnoDB engine table?
To create a table with InnoDB engine, we can use the ENGINE command. Here is the query to create a table. mysql> create table EmployeeRecords - > ( - > EmpId int, - > EmpName varchar(100), - > EmpAge int, - > EmpSalary float - > )ENGINE=INNODB; Query OK, 0 rows affected (0.46 sec) We have set the ENGINE as INNODB above. Check the full description about the table using the DESC command. mysql> DESC EmployeeRecords; The following is the output. +-----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+-------+ | EmpId | int(11) | YES | | NULL | | | EmpName | varchar(100) | YES | | NULL | | | EmpAge | int(11) | YES | | NULL | | | EmpSalary | float | YES | | NULL | | +-----------+--------------+------+-----+---------+-------+ 4 rows in set (0.05 sec) To check if the table is created with InnoDB. mysql> SHOW TABLE STATUS FROM business LIKE 'EmployeeRecords'; Here is the output − +-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | employeerecords | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-10-22 15:22:01 | NULL | NULL | utf8mb4_unicode_ci | NULL | | | +-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ 1 row in set (0.10 sec) In the above output, the “Engine” is visible as “InnoDB”.
[ { "code": null, "e": 1168, "s": 1062, "text": "To create a table with InnoDB engine, we can use the ENGINE command. Here is the query to create a table." }, { "code": null, "e": 1344, "s": 1168, "text": "mysql> create table EmployeeRecords\n- > (\n- > EmpId int,\n- > EmpName varchar(100),\n- > EmpAge int,\n- > EmpSalary float\n- > )ENGINE=INNODB;\nQuery OK, 0 rows affected (0.46 sec)" }, { "code": null, "e": 1384, "s": 1344, "text": "We have set the ENGINE as INNODB above." }, { "code": null, "e": 1451, "s": 1384, "text": "Check the full description about the table using the DESC command." }, { "code": null, "e": 1480, "s": 1451, "text": "mysql> DESC EmployeeRecords;" }, { "code": null, "e": 1509, "s": 1480, "text": "The following is the output." }, { "code": null, "e": 2014, "s": 1509, "text": "+-----------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------+--------------+------+-----+---------+-------+\n| EmpId | int(11) | YES | | NULL | |\n| EmpName | varchar(100) | YES | | NULL | |\n| EmpAge | int(11) | YES | | NULL | |\n| EmpSalary | float | YES | | NULL | |\n+-----------+--------------+------+-----+---------+-------+\n4 rows in set (0.05 sec)" }, { "code": null, "e": 2060, "s": 2014, "text": "To check if the table is created with InnoDB." }, { "code": null, "e": 2123, "s": 2060, "text": "mysql> SHOW TABLE STATUS FROM business LIKE 'EmployeeRecords';" }, { "code": null, "e": 2144, "s": 2123, "text": "Here is the output −" }, { "code": null, "e": 3327, "s": 2144, "text": "+-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| employeerecords | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-10-22 15:22:01 | NULL | NULL | utf8mb4_unicode_ci | NULL | | |\n+-----------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n1 row in set (0.10 sec)" }, { "code": null, "e": 3385, "s": 3327, "text": "In the above output, the “Engine” is visible as “InnoDB”." } ]
Add only numeric values present in a list in Python
We have a Python list which contains both string and numbers. In this article we will see how to sum up the numbers present in such list by ignoring the strings. The isinstance function can be used to filter out only the numbers from the elements in the list. Then we apply and the sum function and get the final result. Live Demo listA = [1,14,'Mon','Tue',23,'Wed',14,-4] #Given dlist print("Given list: ",listA) # Add the numeric values res = sum(filter(lambda i: isinstance(i, int), listA)) print ("Sum of numbers in listA: ", res) Running the above code gives us the following result − Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4] Sum of numbers in listA: 48 It is a similar approach as a wall except that we don't use filter rather we use the follow and the is instance condition. Then apply the sum function. Live Demo listA = [1,14,'Mon','Tue',23,'Wed',14,-4] #Given dlist print("Given list: ",listA) # Add the numeric values res = sum([x for x in listA if isinstance(x, int)]) print ("Sum of numbers in listA: ", res) Running the above code gives us the following result − Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4] Sum of numbers in listA: 48
[ { "code": null, "e": 1224, "s": 1062, "text": "We have a Python list which contains both string and numbers. In this article we will see how to sum up the numbers present in such list by ignoring the strings." }, { "code": null, "e": 1383, "s": 1224, "text": "The isinstance function can be used to filter out only the numbers from the elements in the list. Then we apply and the sum function and get the final result." }, { "code": null, "e": 1394, "s": 1383, "text": " Live Demo" }, { "code": null, "e": 1598, "s": 1394, "text": "listA = [1,14,'Mon','Tue',23,'Wed',14,-4]\n#Given dlist\nprint(\"Given list: \",listA)\n# Add the numeric values\nres = sum(filter(lambda i: isinstance(i, int), listA))\nprint (\"Sum of numbers in listA: \", res)" }, { "code": null, "e": 1653, "s": 1598, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1734, "s": 1653, "text": "Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]\nSum of numbers in listA: 48" }, { "code": null, "e": 1886, "s": 1734, "text": "It is a similar approach as a wall except that we don't use filter rather we use the follow and the is instance condition. Then apply the sum function." }, { "code": null, "e": 1897, "s": 1886, "text": " Live Demo" }, { "code": null, "e": 2098, "s": 1897, "text": "listA = [1,14,'Mon','Tue',23,'Wed',14,-4]\n#Given dlist\nprint(\"Given list: \",listA)\n# Add the numeric values\nres = sum([x for x in listA if isinstance(x, int)])\nprint (\"Sum of numbers in listA: \", res)" }, { "code": null, "e": 2153, "s": 2098, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2234, "s": 2153, "text": "Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]\nSum of numbers in listA: 48" } ]
Calculating median of an array JavaScript
We are required to write a JavaScript function that takes in an array of Numbers and returns its median. The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average. First, we will sort the array, if its size is even, we will need extra logic to deal with two middle numbers. In these cases, we will need to return the average of those two numbers. const arr = [4, 6, 2, 45, 2, 78, 5, 89, 34, 6]; const findMedian = (arr = []) => { const sorted = arr.slice().sort((a, b) => { return a - b; }); if(sorted.length % 2 === 0){ const first = sorted[sorted.length / 2 - 1]; const second = sorted[sorted.length / 2]; return (first + second) / 2; } else{ const mid = Math.floor(sorted.length / 2); return sorted[mid]; }; }; console.log(findMedian(arr)); And the output in the console will be − 6
[ { "code": null, "e": 1167, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of Numbers and returns its median." }, { "code": null, "e": 1316, "s": 1167, "text": "The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average." }, { "code": null, "e": 1426, "s": 1316, "text": "First, we will sort the array, if its size is even, we will need extra logic to deal with two middle numbers." }, { "code": null, "e": 1499, "s": 1426, "text": "In these cases, we will need to return the average of those two numbers." }, { "code": null, "e": 1950, "s": 1499, "text": "const arr = [4, 6, 2, 45, 2, 78, 5, 89, 34, 6];\nconst findMedian = (arr = []) => {\n const sorted = arr.slice().sort((a, b) => {\n return a - b;\n });\n if(sorted.length % 2 === 0){\n const first = sorted[sorted.length / 2 - 1];\n const second = sorted[sorted.length / 2];\n return (first + second) / 2;\n }\n else{\n const mid = Math.floor(sorted.length / 2);\n return sorted[mid];\n };\n};\nconsole.log(findMedian(arr));" }, { "code": null, "e": 1990, "s": 1950, "text": "And the output in the console will be −" }, { "code": null, "e": 1992, "s": 1990, "text": "6" } ]
Build an Application to translate English to Hindi in Python - GeeksforGeeks
15 Feb, 2022 In these articles, We are going to write python scripts to translate English word to Hindi word and bind it with the GUI application. We are using the English-to-Hindi module to translate the English word to the Hindi word. Installation: Run this code into your terminal: pip install English-to-Hindi Approach: Import English to Hindi modules. Create an object of EngtoHindi() by passing the message. Use convert() methods for the translation. Example: Python3 # importing the modulefrom english to hindi.englishtohindi import EngtoHindi # message to be translatedmessage = "Yes, I am geeks" # creating a EngtoHindi() objectres = EngtoHindi(message) # displaying the translationprint(res.convert) Output: हां, मैं गीक्स हूं English to Hindi Translator Application with Tkinter: This Script implements the above Implementation into a GUI. Python3 # import modulesfrom tkinter import *from englishtohindi.englishtohindi import EngtoHindi # user define functiondef eng_to_hindi(): trans = EngtoHindi(str(e.get())) res = trans.convert result.set(res) # object of tkinter# and background set for greymaster = Tk()master.configure(bg = 'light grey') # Variable Classes in tkinterresult = StringVar(); # Creating label for each information# name using widget LabelLabel(master, text="Enter Text : " , bg = "light grey").grid(row = 0, sticky = W)Label(master, text="Result :", bg = "light grey").grid(row = 3, sticky = W) # Creating label for class variable# name using widget EntryLabel(master, text="", textvariable=result,bg = "light grey").grid(row = 3, column = 1, sticky = W) e = Entry(master, width = 100)e.grid(row = 0, column = 1) # creating a button using the widget # Button that will call the submit functionb = Button(master, text = "Show", command = eng_to_hindi, bg = "Blue")b.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5,) mainloop() Output: manikarora059 nnr223442 kk9826225 bijeshkumarch Python Tkinter-exercises Python-tkinter python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24353, "s": 24325, "text": "\n15 Feb, 2022" }, { "code": null, "e": 24577, "s": 24353, "text": "In these articles, We are going to write python scripts to translate English word to Hindi word and bind it with the GUI application. We are using the English-to-Hindi module to translate the English word to the Hindi word." }, { "code": null, "e": 24591, "s": 24577, "text": "Installation:" }, { "code": null, "e": 24625, "s": 24591, "text": "Run this code into your terminal:" }, { "code": null, "e": 24654, "s": 24625, "text": "pip install English-to-Hindi" }, { "code": null, "e": 24664, "s": 24654, "text": "Approach:" }, { "code": null, "e": 24697, "s": 24664, "text": "Import English to Hindi modules." }, { "code": null, "e": 24754, "s": 24697, "text": "Create an object of EngtoHindi() by passing the message." }, { "code": null, "e": 24797, "s": 24754, "text": "Use convert() methods for the translation." }, { "code": null, "e": 24806, "s": 24797, "text": "Example:" }, { "code": null, "e": 24814, "s": 24806, "text": "Python3" }, { "code": "# importing the modulefrom english to hindi.englishtohindi import EngtoHindi # message to be translatedmessage = \"Yes, I am geeks\" # creating a EngtoHindi() objectres = EngtoHindi(message) # displaying the translationprint(res.convert)", "e": 25050, "s": 24814, "text": null }, { "code": null, "e": 25059, "s": 25050, "text": "Output: " }, { "code": null, "e": 25078, "s": 25059, "text": "हां, मैं गीक्स हूं" }, { "code": null, "e": 25193, "s": 25078, "text": "English to Hindi Translator Application with Tkinter: This Script implements the above Implementation into a GUI. " }, { "code": null, "e": 25201, "s": 25193, "text": "Python3" }, { "code": "# import modulesfrom tkinter import *from englishtohindi.englishtohindi import EngtoHindi # user define functiondef eng_to_hindi(): trans = EngtoHindi(str(e.get())) res = trans.convert result.set(res) # object of tkinter# and background set for greymaster = Tk()master.configure(bg = 'light grey') # Variable Classes in tkinterresult = StringVar(); # Creating label for each information# name using widget LabelLabel(master, text=\"Enter Text : \" , bg = \"light grey\").grid(row = 0, sticky = W)Label(master, text=\"Result :\", bg = \"light grey\").grid(row = 3, sticky = W) # Creating label for class variable# name using widget EntryLabel(master, text=\"\", textvariable=result,bg = \"light grey\").grid(row = 3, column = 1, sticky = W) e = Entry(master, width = 100)e.grid(row = 0, column = 1) # creating a button using the widget # Button that will call the submit functionb = Button(master, text = \"Show\", command = eng_to_hindi, bg = \"Blue\")b.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5,) mainloop()", "e": 26369, "s": 25201, "text": null }, { "code": null, "e": 26378, "s": 26369, "text": "Output: " }, { "code": null, "e": 26392, "s": 26378, "text": "manikarora059" }, { "code": null, "e": 26402, "s": 26392, "text": "nnr223442" }, { "code": null, "e": 26412, "s": 26402, "text": "kk9826225" }, { "code": null, "e": 26426, "s": 26412, "text": "bijeshkumarch" }, { "code": null, "e": 26451, "s": 26426, "text": "Python Tkinter-exercises" }, { "code": null, "e": 26466, "s": 26451, "text": "Python-tkinter" }, { "code": null, "e": 26481, "s": 26466, "text": "python-utility" }, { "code": null, "e": 26488, "s": 26481, "text": "Python" }, { "code": null, "e": 26586, "s": 26488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26595, "s": 26586, "text": "Comments" }, { "code": null, "e": 26608, "s": 26595, "text": "Old Comments" }, { "code": null, "e": 26626, "s": 26608, "text": "Python Dictionary" }, { "code": null, "e": 26661, "s": 26626, "text": "Read a file line by line in Python" }, { "code": null, "e": 26683, "s": 26661, "text": "Enumerate() in Python" }, { "code": null, "e": 26715, "s": 26683, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26745, "s": 26715, "text": "Iterate over a list in Python" }, { "code": null, "e": 26787, "s": 26745, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26830, "s": 26787, "text": "Python program to convert a list to string" }, { "code": null, "e": 26856, "s": 26830, "text": "Python String | replace()" }, { "code": null, "e": 26900, "s": 26856, "text": "Reading and Writing to text files in Python" } ]
Angular PrimeNG BlockUI Component - GeeksforGeeks
24 Aug, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the BlockUI component in Angular PrimeNG. BlockUI component: It is used to block the component or the whole page. Properties: blocked: It is used to control the blocked state. It is of the boolean data type, the default value is false. target: It is used to define the name of the local ng-template variable referring to another component. It is of string data type, the default value documents. baseZIndex: It is used to define the base z-Index value to use in layering. It is of number data type, the default value is 0. autoZIndex: It is used to whether to automatically manage the layering. It is of boolean data type, the default value is true. styleClass: It is used to define the style class of the component. It is of string data type, the default value is false. Styling: p-blockui: It is the masking element. p-blockui-document: It is the masking element in full-screen mode. Creating Angular application & module installation: Step 1: Create an Angular application using the following command.ng new appname Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory.npm install primeng --save npm install primeicons --save Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use the blockUI component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG BlockUI Component</h5><p-blockUI [blocked]="gfg"></p-blockUI> <button type="button" pButton pRipple label="Click here to block" (click)="geeks()"></button> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html",})export class AppComponent { gfg: boolean = false; geeks() { this.gfg = true; setTimeout(() => { this.gfg = false; }, 3000); }} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { ButtonModule } from "primeng/button";import { BlockUIModule } from "primeng/blockui";import { PanelModule } from "primeng/panel"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, BlockUIModule, ButtonModule, PanelModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to block a panel in the message component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG BlockUI Component</h5> <button type="button" pButton pRipple label="Click Here to Block" (click)="gfg=true"></button><button type="button" pButton pRipple label="Click Here to Unblock" (click)="gfg=false"></button> <p-blockUI [target]="geeks" [blocked]="gfg"> <i class="pi pi-lock" style="font-size: 3rem"></i></p-blockUI><p-panel #geeks header="BlockUI" styleClass="p-mt-4"> <p class="p-m-0"> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-panel> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html",})export class AppComponent { gfg: boolean = false;} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { ButtonModule } from "primeng/button";import { BlockUIModule } from "primeng/blockui";import { PanelModule } from "primeng/panel"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, BlockUIModule, ButtonModule, PanelModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/blockui Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n24 Aug, 2021" }, { "code": null, "e": 26747, "s": 26464, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the BlockUI component in Angular PrimeNG." }, { "code": null, "e": 26819, "s": 26747, "text": "BlockUI component: It is used to block the component or the whole page." }, { "code": null, "e": 26831, "s": 26819, "text": "Properties:" }, { "code": null, "e": 26941, "s": 26831, "text": "blocked: It is used to control the blocked state. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27101, "s": 26941, "text": "target: It is used to define the name of the local ng-template variable referring to another component. It is of string data type, the default value documents." }, { "code": null, "e": 27228, "s": 27101, "text": "baseZIndex: It is used to define the base z-Index value to use in layering. It is of number data type, the default value is 0." }, { "code": null, "e": 27355, "s": 27228, "text": "autoZIndex: It is used to whether to automatically manage the layering. It is of boolean data type, the default value is true." }, { "code": null, "e": 27477, "s": 27355, "text": "styleClass: It is used to define the style class of the component. It is of string data type, the default value is false." }, { "code": null, "e": 27486, "s": 27477, "text": "Styling:" }, { "code": null, "e": 27524, "s": 27486, "text": "p-blockui: It is the masking element." }, { "code": null, "e": 27591, "s": 27524, "text": "p-blockui-document: It is the masking element in full-screen mode." }, { "code": null, "e": 27645, "s": 27593, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 27726, "s": 27645, "text": "Step 1: Create an Angular application using the following command.ng new appname" }, { "code": null, "e": 27793, "s": 27726, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 27808, "s": 27793, "text": "ng new appname" }, { "code": null, "e": 27915, "s": 27808, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname" }, { "code": null, "e": 28012, "s": 27915, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28023, "s": 28012, "text": "cd appname" }, { "code": null, "e": 28128, "s": 28023, "text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28177, "s": 28128, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28234, "s": 28177, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28286, "s": 28234, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 28370, "s": 28288, "text": "Example 1: This is the basic example that shows how to use the blockUI component." }, { "code": null, "e": 28389, "s": 28370, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG BlockUI Component</h5><p-blockUI [blocked]=\"gfg\"></p-blockUI> <button type=\"button\" pButton pRipple label=\"Click here to block\" (click)=\"geeks()\"></button>", "e": 28585, "s": 28389, "text": null }, { "code": null, "e": 28602, "s": 28585, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"app-root\", templateUrl: \"./app.component.html\",})export class AppComponent { gfg: boolean = false; geeks() { this.gfg = true; setTimeout(() => { this.gfg = false; }, 3000); }}", "e": 28867, "s": 28602, "text": null }, { "code": null, "e": 28881, "s": 28867, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { ButtonModule } from \"primeng/button\";import { BlockUIModule } from \"primeng/blockui\";import { PanelModule } from \"primeng/panel\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, BlockUIModule, ButtonModule, PanelModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29524, "s": 28881, "text": null }, { "code": null, "e": 29532, "s": 29524, "text": "Output:" }, { "code": null, "e": 29620, "s": 29532, "text": "Example 2: In this example, we will know how to block a panel in the message component." }, { "code": null, "e": 29639, "s": 29620, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG BlockUI Component</h5> <button type=\"button\" pButton pRipple label=\"Click Here to Block\" (click)=\"gfg=true\"></button><button type=\"button\" pButton pRipple label=\"Click Here to Unblock\" (click)=\"gfg=false\"></button> <p-blockUI [target]=\"geeks\" [blocked]=\"gfg\"> <i class=\"pi pi-lock\" style=\"font-size: 3rem\"></i></p-blockUI><p-panel #geeks header=\"BlockUI\" styleClass=\"p-mt-4\"> <p class=\"p-m-0\"> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-panel>", "e": 30285, "s": 29639, "text": null }, { "code": null, "e": 30302, "s": 30285, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"app-root\", templateUrl: \"./app.component.html\",})export class AppComponent { gfg: boolean = false;}", "e": 30473, "s": 30302, "text": null }, { "code": null, "e": 30487, "s": 30473, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { ButtonModule } from \"primeng/button\";import { BlockUIModule } from \"primeng/blockui\";import { PanelModule } from \"primeng/panel\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, BlockUIModule, ButtonModule, PanelModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31130, "s": 30487, "text": null }, { "code": null, "e": 31138, "s": 31130, "text": "Output:" }, { "code": null, "e": 31199, "s": 31138, "text": "Reference: https://primefaces.org/primeng/showcase/#/blockui" }, { "code": null, "e": 31215, "s": 31199, "text": "Angular-PrimeNG" }, { "code": null, "e": 31225, "s": 31215, "text": "AngularJS" }, { "code": null, "e": 31242, "s": 31225, "text": "Web Technologies" }, { "code": null, "e": 31340, "s": 31242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31375, "s": 31340, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31410, "s": 31375, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31445, "s": 31410, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31469, "s": 31445, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31522, "s": 31469, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31562, "s": 31522, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31595, "s": 31562, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31640, "s": 31595, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31683, "s": 31640, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if strings are rotations of each other or not | Set 2 - GeeksforGeeks
14 Apr, 2021 Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm’s lps (longest proper prefix which is also suffix) construction, which will help in finding the longest match of the prefix of string b and suffix of string a. By which we will know the rotating point, from this point match the characters. If all the characters are matched, then it is a rotation, else not.Below is the basic implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to check if// two strings are rotations// of each other#include<bits/stdc++.h>using namespace std;bool isRotation(string a, string b){ int n = a.length(); int m = b.length(); if (n != m) return false; // create lps[] that // will hold the longest // prefix suffix values // for pattern int lps[n]; // length of the previous // longest prefix suffix int len = 0; int i = 1; // lps[0] is always 0 lps[0] = 0; // the loop calculates // lps[i] for i = 1 to n-1 while (i < n) { if (a[i] == b[len]) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // Match from that rotating // point for (int k = lps[n - 1]; k < m; ++k) { if (b[k] != a[i++]) return false; } return true;} // Driver codeint main(){ string s1 = "ABACD"; string s2 = "CDABA"; cout << (isRotation(s1, s2) ? "1" : "0");} // This code is contributed by Chitranayal // Java program to check if two strings are rotations// of each other.import java.util.*;import java.lang.*;import java.io.*;class stringMatching { public static boolean isRotation(String a, String b) { int n = a.length(); int m = b.length(); if (n != m) return false; // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[n]; // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to n-1 while (i < n) { if (a.charAt(i) == b.charAt(len)) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // match from that rotating point for (int k = lps[n - 1]; k < m; ++k) { if (b.charAt(k) != a.charAt(i++)) return false; } return true; } // Driver code public static void main(String[] args) { String s1 = "ABACD"; String s2 = "CDABA"; System.out.println(isRotation(s1, s2) ? "1" : "0"); }} # Python program to check if# two strings are rotations# of each otherdef isRotation(a: str, b: str) -> bool: n = len(a) m = len(b) if (n != m): return False # create lps[] that # will hold the longest # prefix suffix values # for pattern lps = [0 for _ in range(n)] # length of the previous # longest prefix suffix length = 0 i = 1 # lps[0] is always 0 lps[0] = 0 # the loop calculates # lps[i] for i = 1 to n-1 while (i < n): if (a[i] == b[length]): length += 1 lps[i] = length i += 1 else: if (length == 0): lps[i] = 0 i += 1 else: length = lps[length - 1] i = 0 # Match from that rotating # point for k in range(lps[n - 1], m): if (b[k] != a[i]): return False i += 1 return True # Driver codeif __name__ == "__main__": s1 = "ABACD" s2 = "CDABA" print("1" if isRotation(s1, s2) else "0") # This code is contributed by sanjeev2552 // C# program to check if// two strings are rotations// of each other.using System; class GFG{public static bool isRotation(string a, string b){ int n = a.Length; int m = b.Length; if (n != m) return false; // create lps[] that will // hold the longest prefix // suffix values for pattern int []lps = new int[n]; // length of the previous // longest prefix suffix int len = 0; int i = 1; // lps[0] is always 0 lps[0] = 0; // the loop calculates // lps[i] for i = 1 to n-1 while (i < n) { if (a[i] == b[len]) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // match from that // rotating point for (int k = lps[n - 1]; k < m; ++k) { if (b[k] != a[i++]) return false; } return true;} // Driver codepublic static void Main(){ string s1 = "ABACD"; string s2 = "CDABA"; Console.WriteLine(isRotation(s1, s2) ? "1" : "0");}} // This code is contributed// by anuj_67. <script> // javascript program to check if two strings are rotations// of each other.function isRotation(a, b){ var n = a.length; var m = b.length; if (n != m) return false; // create lps that will hold the longest // prefix suffix values for pattern var lps = Array.from({length: n}, (_, i) => 0); // length of the previous longest prefix suffix var len = 0; var i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to n-1 while (i < n) { if (a.charAt(i) == b.charAt(len)) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // match from that rotating point for (k = lps[n - 1]; k < m; ++k) { if (b.charAt(k) != a.charAt(i++)) return false; } return true;} // Driver codevar s1 = "ABACD";var s2 = "CDABA";document.write(isRotation(s1, s2) ? "1" : "0"); // This code is contributed by shikhasingrajput.</script> Output: 1 Time Complexity: O(n) Auxiliary Space: O(n) vt_m ukasp sanjeev2552 shikhasingrajput rotation Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check if a string contains uppercase, lowercase, special characters and numeric values Pattern Searching using Suffix Tree Finite Automata algorithm for Pattern Searching Remove leading zeros from a Number given as a string String matching where one string contains wildcard characters Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 25202, "s": 25174, "text": "\n14 Apr, 2021" }, { "code": null, "e": 25280, "s": 25202, "text": "Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: " }, { "code": null, "e": 25351, "s": 25280, "text": "Input : ABACD, CDABA\nOutput : True\n\nInput : GEEKS, EKSGE\nOutput : True" }, { "code": null, "e": 25859, "s": 25351, "text": "We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm’s lps (longest proper prefix which is also suffix) construction, which will help in finding the longest match of the prefix of string b and suffix of string a. By which we will know the rotating point, from this point match the characters. If all the characters are matched, then it is a rotation, else not.Below is the basic implementation of the above approach. " }, { "code": null, "e": 25863, "s": 25859, "text": "C++" }, { "code": null, "e": 25868, "s": 25863, "text": "Java" }, { "code": null, "e": 25876, "s": 25868, "text": "Python3" }, { "code": null, "e": 25879, "s": 25876, "text": "C#" }, { "code": null, "e": 25890, "s": 25879, "text": "Javascript" }, { "code": "// C++ program to check if// two strings are rotations// of each other#include<bits/stdc++.h>using namespace std;bool isRotation(string a, string b){ int n = a.length(); int m = b.length(); if (n != m) return false; // create lps[] that // will hold the longest // prefix suffix values // for pattern int lps[n]; // length of the previous // longest prefix suffix int len = 0; int i = 1; // lps[0] is always 0 lps[0] = 0; // the loop calculates // lps[i] for i = 1 to n-1 while (i < n) { if (a[i] == b[len]) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // Match from that rotating // point for (int k = lps[n - 1]; k < m; ++k) { if (b[k] != a[i++]) return false; } return true;} // Driver codeint main(){ string s1 = \"ABACD\"; string s2 = \"CDABA\"; cout << (isRotation(s1, s2) ? \"1\" : \"0\");} // This code is contributed by Chitranayal", "e": 26947, "s": 25890, "text": null }, { "code": "// Java program to check if two strings are rotations// of each other.import java.util.*;import java.lang.*;import java.io.*;class stringMatching { public static boolean isRotation(String a, String b) { int n = a.length(); int m = b.length(); if (n != m) return false; // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[n]; // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to n-1 while (i < n) { if (a.charAt(i) == b.charAt(len)) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // match from that rotating point for (int k = lps[n - 1]; k < m; ++k) { if (b.charAt(k) != a.charAt(i++)) return false; } return true; } // Driver code public static void main(String[] args) { String s1 = \"ABACD\"; String s2 = \"CDABA\"; System.out.println(isRotation(s1, s2) ? \"1\" : \"0\"); }}", "e": 28323, "s": 26947, "text": null }, { "code": "# Python program to check if# two strings are rotations# of each otherdef isRotation(a: str, b: str) -> bool: n = len(a) m = len(b) if (n != m): return False # create lps[] that # will hold the longest # prefix suffix values # for pattern lps = [0 for _ in range(n)] # length of the previous # longest prefix suffix length = 0 i = 1 # lps[0] is always 0 lps[0] = 0 # the loop calculates # lps[i] for i = 1 to n-1 while (i < n): if (a[i] == b[length]): length += 1 lps[i] = length i += 1 else: if (length == 0): lps[i] = 0 i += 1 else: length = lps[length - 1] i = 0 # Match from that rotating # point for k in range(lps[n - 1], m): if (b[k] != a[i]): return False i += 1 return True # Driver codeif __name__ == \"__main__\": s1 = \"ABACD\" s2 = \"CDABA\" print(\"1\" if isRotation(s1, s2) else \"0\") # This code is contributed by sanjeev2552", "e": 29383, "s": 28323, "text": null }, { "code": "// C# program to check if// two strings are rotations// of each other.using System; class GFG{public static bool isRotation(string a, string b){ int n = a.Length; int m = b.Length; if (n != m) return false; // create lps[] that will // hold the longest prefix // suffix values for pattern int []lps = new int[n]; // length of the previous // longest prefix suffix int len = 0; int i = 1; // lps[0] is always 0 lps[0] = 0; // the loop calculates // lps[i] for i = 1 to n-1 while (i < n) { if (a[i] == b[len]) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // match from that // rotating point for (int k = lps[n - 1]; k < m; ++k) { if (b[k] != a[i++]) return false; } return true;} // Driver codepublic static void Main(){ string s1 = \"ABACD\"; string s2 = \"CDABA\"; Console.WriteLine(isRotation(s1, s2) ? \"1\" : \"0\");}} // This code is contributed// by anuj_67.", "e": 30662, "s": 29383, "text": null }, { "code": "<script> // javascript program to check if two strings are rotations// of each other.function isRotation(a, b){ var n = a.length; var m = b.length; if (n != m) return false; // create lps that will hold the longest // prefix suffix values for pattern var lps = Array.from({length: n}, (_, i) => 0); // length of the previous longest prefix suffix var len = 0; var i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to n-1 while (i < n) { if (a.charAt(i) == b.charAt(len)) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // match from that rotating point for (k = lps[n - 1]; k < m; ++k) { if (b.charAt(k) != a.charAt(i++)) return false; } return true;} // Driver codevar s1 = \"ABACD\";var s2 = \"CDABA\";document.write(isRotation(s1, s2) ? \"1\" : \"0\"); // This code is contributed by shikhasingrajput.</script>", "e": 31781, "s": 30662, "text": null }, { "code": null, "e": 31791, "s": 31781, "text": "Output: " }, { "code": null, "e": 31793, "s": 31791, "text": "1" }, { "code": null, "e": 31837, "s": 31793, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 31842, "s": 31837, "text": "vt_m" }, { "code": null, "e": 31848, "s": 31842, "text": "ukasp" }, { "code": null, "e": 31860, "s": 31848, "text": "sanjeev2552" }, { "code": null, "e": 31877, "s": 31860, "text": "shikhasingrajput" }, { "code": null, "e": 31886, "s": 31877, "text": "rotation" }, { "code": null, "e": 31904, "s": 31886, "text": "Pattern Searching" }, { "code": null, "e": 31912, "s": 31904, "text": "Strings" }, { "code": null, "e": 31920, "s": 31912, "text": "Strings" }, { "code": null, "e": 31938, "s": 31920, "text": "Pattern Searching" }, { "code": null, "e": 32036, "s": 31938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32045, "s": 32036, "text": "Comments" }, { "code": null, "e": 32058, "s": 32045, "text": "Old Comments" }, { "code": null, "e": 32145, "s": 32058, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 32181, "s": 32145, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 32229, "s": 32181, "text": "Finite Automata algorithm for Pattern Searching" }, { "code": null, "e": 32282, "s": 32229, "text": "Remove leading zeros from a Number given as a string" }, { "code": null, "e": 32344, "s": 32282, "text": "String matching where one string contains wildcard characters" }, { "code": null, "e": 32369, "s": 32344, "text": "Reverse a string in Java" }, { "code": null, "e": 32415, "s": 32369, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32449, "s": 32415, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32464, "s": 32449, "text": "C++ Data Types" } ]
Check if there exist two elements in an array whose sum is equal to the sum of rest of the array - GeeksforGeeks
27 Sep, 2021 We have an array of integers and we have to find two such elements in the array such that sum of these two elements is equal to the sum of rest of elements in array. Examples: Input : arr[] = {2, 11, 5, 1, 4, 7} Output : Elements are 4 and 11 Note that 4 + 11 = 2 + 5 + 1 + 7 Input : arr[] = {2, 4, 2, 1, 11, 15} Output : Elements do not exist A simple solution is to consider every pair one by one, find its sum and compare the sum with sum of rest of the elements. If we find a pair whose sum is equal to rest of elements, we print the pair and return true. Time complexity of this solution is O(n3) An efficient solution is to find sum of all array elements. Let this sum be “sum”. Now the task reduces to finding a pair with sum equals to sum/2. Another optimization is, a pair can exist only if the sum of whole array is even because we are basically dividing it into two parts with equal sum.1- Find the sum of whole array. Let this sum be “sum” 2- If sum is odd, return false. 3- Find a pair with sum equals to “sum/2” using hashing based method discussed here as method 2. If a pair is found, print it and return true. 4- If no pair exists, return false. Below is the implementation of above steps. C++ Java Python3 C# PHP Javascript // C++ program to find whether two elements exist// whose sum is equal to sum of rest of the elements.#include<bits/stdc++.h>using namespace std; // Function to check whether two elements exist// whose sum is equal to sum of rest of the elements.bool checkPair(int arr[],int n){ // Find sum of whole array int sum = 0; for (int i=0; i<n; i++) sum += arr[i]; // If sum of array is not even than we can not // divide it into two part if (sum%2 != 0) return false; sum = sum/2; // For each element arr[i], see if there is // another element with value sum - arr[i] unordered_set<int> s; for (int i=0; i<n; i++) { int val = sum-arr[i]; // If element exist than return the pair if (s.find(val) != s.end()) { printf("Pair elements are %d and %d\n", arr[i], val); return true; } s.insert(arr[i]); } return false;} // Driver program.int main(){ int arr[] = {2, 11, 5, 1, 4, 7}; int n = sizeof(arr)/sizeof(arr[0]); if (checkPair(arr, n) == false) printf("No pair found"); return 0;} // Java program to find whether two elements exist// whose sum is equal to sum of rest of the elements.import java.util.*; class GFG{ // Function to check whether two elements exist // whose sum is equal to sum of rest of the elements. static boolean checkPair(int arr[], int n) { // Find sum of whole array int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } // If sum of array is not even than we can not // divide it into two part if (sum % 2 != 0) { return false; } sum = sum / 2; // For each element arr[i], see if there is // another element with value sum - arr[i] HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { int val = sum - arr[i]; // If element exist than return the pair if (s.contains(val) && val == (int) s.toArray()[s.size() - 1]) { System.out.printf("Pair elements are %d and %d\n", arr[i], val); return true; } s.add(arr[i]); } return false; } // Driver program. public static void main(String[] args) { int arr[] = {2, 11, 5, 1, 4, 7}; int n = arr.length; if (checkPair(arr, n) == false) { System.out.printf("No pair found"); } }} /* This code contributed by PrinciRaj1992 */ # Python3 program to find whether# two elements exist whose sum is# equal to sum of rest of the elements. # Function to check whether two# elements exist whose sum is equal# to sum of rest of the elements.def checkPair(arr, n): s = set() sum = 0 # Find sum of whole array for i in range(n): sum += arr[i] # / If sum of array is not # even than we can not # divide it into two part if sum % 2 != 0: return False sum = sum / 2 # For each element arr[i], see if # there is another element with # value sum - arr[i] for i in range(n): val = sum - arr[i] if arr[i] not in s: s.add(arr[i]) # If element exist than # return the pair if val in s: print("Pair elements are", arr[i], "and", int(val)) # Driver Codearr = [2, 11, 5, 1, 4, 7]n = len(arr)if checkPair(arr, n) == False: print("No pair found") # This code is contributed# by Shrikant13 // C# program to find whether two elements exist// whose sum is equal to sum of rest of the elements.using System;using System.Collections.Generic; class GFG{ // Function to check whether two elements exist // whose sum is equal to sum of rest of the elements. static bool checkPair(int []arr, int n) { // Find sum of whole array int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } // If sum of array is not even than we can not // divide it into two part if (sum % 2 != 0) { return false; } sum = sum / 2; // For each element arr[i], see if there is // another element with value sum - arr[i] HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { int val = sum - arr[i]; // If element exist than return the pair if (s.Contains(val)) { Console.Write("Pair elements are {0} and {1}\n", arr[i], val); return true; } s.Add(arr[i]); } return false; } // Driver code public static void Main(String[] args) { int []arr = {2, 11, 5, 1, 4, 7}; int n = arr.Length; if (checkPair(arr, n) == false) { Console.Write("No pair found"); } }} // This code contributed by Rajput-Ji <?php// PHP program to find whether two elements exist// whose sum is equal to sum of rest of the elements. // Function to check whether two elements exist// whose sum is equal to sum of rest of the elements.function checkPair(&$arr, $n){ // Find sum of whole array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // If sum of array is not even than we // can not divide it into two part if ($sum % 2 != 0) return false; $sum = $sum / 2; // For each element arr[i], see if there is // another element with value sum - arr[i] $s = array(); for ($i = 0; $i < $n; $i++) { $val = $sum - $arr[$i]; // If element exist than return the pair if (array_search($val, $s)) { echo "Pair elements are " . $arr[$i] . " and " . $val . "\n"; return true; } array_push($s, $arr[$i]); } return false;} // Driver Code$arr = array(2, 11, 5, 1, 4, 7);$n = sizeof($arr);if (checkPair($arr, $n) == false) echo "No pair found"; // This code is contributed by ita_c?> <script> // Javascript program to find// whether two elements exist// whose sum is equal to sum of rest// of the elements. // Function to check whether // two elements exist // whose sum is equal to sum of // rest of the elements. function checkPair(arr,n) { // Find sum of whole array let sum = 0; for (let i = 0; i < n; i++) { sum += arr[i]; } // If sum of array is not even than we can not // divide it into two part if (sum % 2 != 0) { return false; } sum = Math.floor(sum / 2); // For each element arr[i], see if there is // another element with value sum - arr[i] let s = new Set(); for (let i = 0; i < n; i++) { let val = sum - arr[i]; // If element exist than return the pair if(!s.has(arr[i])) { s.add(arr[i]) } if (s.has(val) ) { document.write("Pair elements are "+ arr[i]+" and "+ val+"<br>"); return true; } s.add(arr[i]); } return false; } // Driver program. let arr=[2, 11, 5, 1, 4, 7]; let n = arr.length; if (checkPair(arr, n) == false) { document.write("No pair found"); } // This code is contributed by rag2127 </script> Output: Pair elements are 4 and 11 Time complexity : O(n). unordered_set is implemented using hashing. Time complexity hash search and insert is assumed as O(1) here. This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 ukasp princiraj1992 Rajput-Ji rag2127 simmytarika5 Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26585, "s": 26557, "text": "\n27 Sep, 2021" }, { "code": null, "e": 26752, "s": 26585, "text": "We have an array of integers and we have to find two such elements in the array such that sum of these two elements is equal to the sum of rest of elements in array. " }, { "code": null, "e": 26763, "s": 26752, "text": "Examples: " }, { "code": null, "e": 26935, "s": 26763, "text": "Input : arr[] = {2, 11, 5, 1, 4, 7}\nOutput : Elements are 4 and 11\nNote that 4 + 11 = 2 + 5 + 1 + 7\n\nInput : arr[] = {2, 4, 2, 1, 11, 15}\nOutput : Elements do not exist " }, { "code": null, "e": 27193, "s": 26935, "text": "A simple solution is to consider every pair one by one, find its sum and compare the sum with sum of rest of the elements. If we find a pair whose sum is equal to rest of elements, we print the pair and return true. Time complexity of this solution is O(n3)" }, { "code": null, "e": 27754, "s": 27193, "text": "An efficient solution is to find sum of all array elements. Let this sum be “sum”. Now the task reduces to finding a pair with sum equals to sum/2. Another optimization is, a pair can exist only if the sum of whole array is even because we are basically dividing it into two parts with equal sum.1- Find the sum of whole array. Let this sum be “sum” 2- If sum is odd, return false. 3- Find a pair with sum equals to “sum/2” using hashing based method discussed here as method 2. If a pair is found, print it and return true. 4- If no pair exists, return false." }, { "code": null, "e": 27798, "s": 27754, "text": "Below is the implementation of above steps." }, { "code": null, "e": 27802, "s": 27798, "text": "C++" }, { "code": null, "e": 27807, "s": 27802, "text": "Java" }, { "code": null, "e": 27815, "s": 27807, "text": "Python3" }, { "code": null, "e": 27818, "s": 27815, "text": "C#" }, { "code": null, "e": 27822, "s": 27818, "text": "PHP" }, { "code": null, "e": 27833, "s": 27822, "text": "Javascript" }, { "code": "// C++ program to find whether two elements exist// whose sum is equal to sum of rest of the elements.#include<bits/stdc++.h>using namespace std; // Function to check whether two elements exist// whose sum is equal to sum of rest of the elements.bool checkPair(int arr[],int n){ // Find sum of whole array int sum = 0; for (int i=0; i<n; i++) sum += arr[i]; // If sum of array is not even than we can not // divide it into two part if (sum%2 != 0) return false; sum = sum/2; // For each element arr[i], see if there is // another element with value sum - arr[i] unordered_set<int> s; for (int i=0; i<n; i++) { int val = sum-arr[i]; // If element exist than return the pair if (s.find(val) != s.end()) { printf(\"Pair elements are %d and %d\\n\", arr[i], val); return true; } s.insert(arr[i]); } return false;} // Driver program.int main(){ int arr[] = {2, 11, 5, 1, 4, 7}; int n = sizeof(arr)/sizeof(arr[0]); if (checkPair(arr, n) == false) printf(\"No pair found\"); return 0;}", "e": 28986, "s": 27833, "text": null }, { "code": "// Java program to find whether two elements exist// whose sum is equal to sum of rest of the elements.import java.util.*; class GFG{ // Function to check whether two elements exist // whose sum is equal to sum of rest of the elements. static boolean checkPair(int arr[], int n) { // Find sum of whole array int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } // If sum of array is not even than we can not // divide it into two part if (sum % 2 != 0) { return false; } sum = sum / 2; // For each element arr[i], see if there is // another element with value sum - arr[i] HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { int val = sum - arr[i]; // If element exist than return the pair if (s.contains(val) && val == (int) s.toArray()[s.size() - 1]) { System.out.printf(\"Pair elements are %d and %d\\n\", arr[i], val); return true; } s.add(arr[i]); } return false; } // Driver program. public static void main(String[] args) { int arr[] = {2, 11, 5, 1, 4, 7}; int n = arr.length; if (checkPair(arr, n) == false) { System.out.printf(\"No pair found\"); } }} /* This code contributed by PrinciRaj1992 */", "e": 30482, "s": 28986, "text": null }, { "code": "# Python3 program to find whether# two elements exist whose sum is# equal to sum of rest of the elements. # Function to check whether two# elements exist whose sum is equal# to sum of rest of the elements.def checkPair(arr, n): s = set() sum = 0 # Find sum of whole array for i in range(n): sum += arr[i] # / If sum of array is not # even than we can not # divide it into two part if sum % 2 != 0: return False sum = sum / 2 # For each element arr[i], see if # there is another element with # value sum - arr[i] for i in range(n): val = sum - arr[i] if arr[i] not in s: s.add(arr[i]) # If element exist than # return the pair if val in s: print(\"Pair elements are\", arr[i], \"and\", int(val)) # Driver Codearr = [2, 11, 5, 1, 4, 7]n = len(arr)if checkPair(arr, n) == False: print(\"No pair found\") # This code is contributed# by Shrikant13", "e": 31470, "s": 30482, "text": null }, { "code": "// C# program to find whether two elements exist// whose sum is equal to sum of rest of the elements.using System;using System.Collections.Generic; class GFG{ // Function to check whether two elements exist // whose sum is equal to sum of rest of the elements. static bool checkPair(int []arr, int n) { // Find sum of whole array int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } // If sum of array is not even than we can not // divide it into two part if (sum % 2 != 0) { return false; } sum = sum / 2; // For each element arr[i], see if there is // another element with value sum - arr[i] HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { int val = sum - arr[i]; // If element exist than return the pair if (s.Contains(val)) { Console.Write(\"Pair elements are {0} and {1}\\n\", arr[i], val); return true; } s.Add(arr[i]); } return false; } // Driver code public static void Main(String[] args) { int []arr = {2, 11, 5, 1, 4, 7}; int n = arr.Length; if (checkPair(arr, n) == false) { Console.Write(\"No pair found\"); } }} // This code contributed by Rajput-Ji", "e": 32906, "s": 31470, "text": null }, { "code": "<?php// PHP program to find whether two elements exist// whose sum is equal to sum of rest of the elements. // Function to check whether two elements exist// whose sum is equal to sum of rest of the elements.function checkPair(&$arr, $n){ // Find sum of whole array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // If sum of array is not even than we // can not divide it into two part if ($sum % 2 != 0) return false; $sum = $sum / 2; // For each element arr[i], see if there is // another element with value sum - arr[i] $s = array(); for ($i = 0; $i < $n; $i++) { $val = $sum - $arr[$i]; // If element exist than return the pair if (array_search($val, $s)) { echo \"Pair elements are \" . $arr[$i] . \" and \" . $val . \"\\n\"; return true; } array_push($s, $arr[$i]); } return false;} // Driver Code$arr = array(2, 11, 5, 1, 4, 7);$n = sizeof($arr);if (checkPair($arr, $n) == false) echo \"No pair found\"; // This code is contributed by ita_c?>", "e": 34039, "s": 32906, "text": null }, { "code": "<script> // Javascript program to find// whether two elements exist// whose sum is equal to sum of rest// of the elements. // Function to check whether // two elements exist // whose sum is equal to sum of // rest of the elements. function checkPair(arr,n) { // Find sum of whole array let sum = 0; for (let i = 0; i < n; i++) { sum += arr[i]; } // If sum of array is not even than we can not // divide it into two part if (sum % 2 != 0) { return false; } sum = Math.floor(sum / 2); // For each element arr[i], see if there is // another element with value sum - arr[i] let s = new Set(); for (let i = 0; i < n; i++) { let val = sum - arr[i]; // If element exist than return the pair if(!s.has(arr[i])) { s.add(arr[i]) } if (s.has(val) ) { document.write(\"Pair elements are \"+ arr[i]+\" and \"+ val+\"<br>\"); return true; } s.add(arr[i]); } return false; } // Driver program. let arr=[2, 11, 5, 1, 4, 7]; let n = arr.length; if (checkPair(arr, n) == false) { document.write(\"No pair found\"); } // This code is contributed by rag2127 </script>", "e": 35498, "s": 34039, "text": null }, { "code": null, "e": 35507, "s": 35498, "text": "Output: " }, { "code": null, "e": 35534, "s": 35507, "text": "Pair elements are 4 and 11" }, { "code": null, "e": 35666, "s": 35534, "text": "Time complexity : O(n). unordered_set is implemented using hashing. Time complexity hash search and insert is assumed as O(1) here." }, { "code": null, "e": 36087, "s": 35666, "text": "This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36099, "s": 36087, "text": "shrikanth13" }, { "code": null, "e": 36105, "s": 36099, "text": "ukasp" }, { "code": null, "e": 36119, "s": 36105, "text": "princiraj1992" }, { "code": null, "e": 36129, "s": 36119, "text": "Rajput-Ji" }, { "code": null, "e": 36137, "s": 36129, "text": "rag2127" }, { "code": null, "e": 36150, "s": 36137, "text": "simmytarika5" }, { "code": null, "e": 36157, "s": 36150, "text": "Arrays" }, { "code": null, "e": 36167, "s": 36157, "text": "Searching" }, { "code": null, "e": 36174, "s": 36167, "text": "Arrays" }, { "code": null, "e": 36184, "s": 36174, "text": "Searching" }, { "code": null, "e": 36282, "s": 36184, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36350, "s": 36282, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36394, "s": 36350, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36442, "s": 36394, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36465, "s": 36442, "text": "Introduction to Arrays" }, { "code": null, "e": 36497, "s": 36465, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36511, "s": 36497, "text": "Binary Search" }, { "code": null, "e": 36579, "s": 36511, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36593, "s": 36579, "text": "Linear Search" }, { "code": null, "e": 36641, "s": 36593, "text": "Search an element in a sorted and rotated array" } ]
Wand Python - Introduction and Installation - GeeksforGeeks
15 May, 2020 Imagemagick is a tool developed to convert images from one format to another. Due to a versatile range of image formats and its precise and simple working, it has a huge community support. We can get images from pdf files.Wand is a binding developed for python by Imagemagick.wWand opens and manipulate images. Wand provides a large number of functions for image manipulation. Uses of Wand Library:1. Read/Write images of different formats2. Converting images from one form to another3. Scaling and Cropping4. Add simple effects to image5. Add Special effects to images6. Transform images7. Other color Enhancements Installation:Using pip:Wand can be easily installed by running $ pip install Wand in a terminal oR Command Prompt. Installation on Linux:we can install Wand in Linux by running the below command sudo apt-get install libmagickwand-dev If we need SVG, WMF, OpenEXR, DjVu, and Graphviz support we have to install libmagickcore5-extra as well, to install libmagickcore5-extra run, sudo apt-get install libmagickcore5-extra in your terminal. Installation on Mac:We can simply install wand by using brew command as below brew install imagemagick in terminal. Installation on Windows:You could build ImageMagick by yourself, but it requires a build toolchain like Visual Studio to compile it. The easiest way is simply downloading a prebuilt binary of ImageMagick for your architecture (win32 or win64). You can download it from here. Below is a simple use case example of Wand library where we write python code to convert image from jpeg format to pngExample: from __future__ import print_functionfrom wand.image import Image with Image(filename ='koala.jpeg') as img: with img.convert('png') as converted: converted.save(filename ='png_koala.png') Output: Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Check if element exists in list in Python
[ { "code": null, "e": 26127, "s": 26099, "text": "\n15 May, 2020" }, { "code": null, "e": 26504, "s": 26127, "text": "Imagemagick is a tool developed to convert images from one format to another. Due to a versatile range of image formats and its precise and simple working, it has a huge community support. We can get images from pdf files.Wand is a binding developed for python by Imagemagick.wWand opens and manipulate images. Wand provides a large number of functions for image manipulation." }, { "code": null, "e": 26743, "s": 26504, "text": "Uses of Wand Library:1. Read/Write images of different formats2. Converting images from one form to another3. Scaling and Cropping4. Add simple effects to image5. Add Special effects to images6. Transform images7. Other color Enhancements" }, { "code": null, "e": 26806, "s": 26743, "text": "Installation:Using pip:Wand can be easily installed by running" }, { "code": null, "e": 26825, "s": 26806, "text": "$ pip install Wand" }, { "code": null, "e": 26858, "s": 26825, "text": "in a terminal oR Command Prompt." }, { "code": null, "e": 26938, "s": 26858, "text": "Installation on Linux:we can install Wand in Linux by running the below command" }, { "code": null, "e": 26977, "s": 26938, "text": "sudo apt-get install libmagickwand-dev" }, { "code": null, "e": 27120, "s": 26977, "text": "If we need SVG, WMF, OpenEXR, DjVu, and Graphviz support we have to install libmagickcore5-extra as well, to install libmagickcore5-extra run," }, { "code": null, "e": 27162, "s": 27120, "text": "sudo apt-get install libmagickcore5-extra" }, { "code": null, "e": 27180, "s": 27162, "text": "in your terminal." }, { "code": null, "e": 27258, "s": 27180, "text": "Installation on Mac:We can simply install wand by using brew command as below" }, { "code": null, "e": 27284, "s": 27258, "text": " brew install imagemagick" }, { "code": null, "e": 27297, "s": 27284, "text": "in terminal." }, { "code": null, "e": 27572, "s": 27297, "text": "Installation on Windows:You could build ImageMagick by yourself, but it requires a build toolchain like Visual Studio to compile it. The easiest way is simply downloading a prebuilt binary of ImageMagick for your architecture (win32 or win64). You can download it from here." }, { "code": null, "e": 27699, "s": 27572, "text": "Below is a simple use case example of Wand library where we write python code to convert image from jpeg format to pngExample:" }, { "code": "from __future__ import print_functionfrom wand.image import Image with Image(filename ='koala.jpeg') as img: with img.convert('png') as converted: converted.save(filename ='png_koala.png')", "e": 27899, "s": 27699, "text": null }, { "code": null, "e": 27907, "s": 27899, "text": "Output:" }, { "code": null, "e": 27914, "s": 27907, "text": "Python" }, { "code": null, "e": 28012, "s": 27914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28030, "s": 28012, "text": "Python Dictionary" }, { "code": null, "e": 28065, "s": 28030, "text": "Read a file line by line in Python" }, { "code": null, "e": 28097, "s": 28065, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28119, "s": 28097, "text": "Enumerate() in Python" }, { "code": null, "e": 28161, "s": 28119, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28191, "s": 28161, "text": "Iterate over a list in Python" }, { "code": null, "e": 28217, "s": 28191, "text": "Python String | replace()" }, { "code": null, "e": 28261, "s": 28217, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28290, "s": 28261, "text": "*args and **kwargs in Python" } ]
How to Connect Data Points on Boxplot with Lines in R? - GeeksforGeeks
10 Oct, 2021 In this article, we will discuss how to connect paired points in box plot in ggplot2 in R Programming Language. Boxplots with data points help us to visualize the summary information between distributions. For example, we may have two quantitative variables corresponding to two different categories and would like to connect those data points by lines. So to do this we have to load the tidyverse library Syntax: library(tidyverse) Here is a basic box plot with lines joining paired points. R # load tidyverselibrary(tidyverse) # create dataframesample_data < - data.frame(value=c(1, 2, 3, 4, 4, 5, 6, 7, 9, 11, 1.5, 2.3, 2.5, 3.4, 4.5, 5.5, 6.5, 7.5, 9.5, 12.5), category=c('A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'), paired=c(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9)) # create plot using ggplot() and geom_boxplot() functionsggplot(sample_data, aes(category, value, fill=category)) +geom_boxplot()+ # geom_point() is used to make points at data valuesgeom_point()+ # geom_line() joins the paired datapointsgeom_line(aes(group=paired)) Output: We can change the color and width of the joining segment by using the color and size property of geom_line(). Syntax: ggplot(aes( x, y )) + geom_boxplot()+geom_point( aes( fill ), size, shape ) + geom_line( aes( group ), size, color, alpha ) Parameters: group: the variable that has pairs to be joined. color: the variable that categorizes points alpha: determines the transparency size: determines the size shape: determines the shape fill: determines the fill color Example: R # load tidyverselibrary(tidyverse) # create dataframesample_data <- data.frame( value = c(1,2,3,4,4,5,6, 7,9,11,1.5,2.3,2.5,3.4, 4.5,5.5,6.5,7.5,9.5,12.5), category = c('A','B','A','B','A', 'B','A','B','A','B', 'A','B','A','B','A', 'B','A','B','A','B'), paired = c(0,0,1,1,2,2,3,3,4,4, 5,5,6,6,7,7,8,8,9,9)) # create plot using ggplot() and geom_boxplot() functionsggplot(sample_data, aes(category,value, fill=category)) + geom_boxplot()+ # geom_line() joins the paired datapoints # color and size parameters are used to customize line geom_line(aes(group = paired), size=2, color='gray', alpha=0.6)+ # geom_point() is used to make points at data values # fill and size parameters are used to customize point geom_point(aes(fill=category,group=paired),size=5,shape=21) Output: We can convert the joining line into ridged line by using linetype property. Every property that works on a line plot also works in this line. Syntax: ggplot(aes( x, y )) + geom_boxplot()+geom_point() + geom_line( aes( group ), linetype ) Parameters group: the variable that has pairs to be joined. linetype: determines the type of line Example: R # load tidyverselibrary(tidyverse) # create dataframesample_data <- data.frame( value = c(1,2,3,4,4,5,6, 7,9,11,1.5,2.3,2.5,3.4, 4.5,5.5,6.5,7.5,9.5,12.5), category = c('A','B','A','B','A', 'B','A','B','A','B', 'A','B','A','B','A', 'B','A','B','A','B'), paired = c(0,0,1,1,2,2,3,3,4,4, 5,5,6,6,7,7,8,8,9,9)) # create plot using ggplot() and geom_boxplot() functionggplot(sample_data, aes(category,value, fill=category)) + geom_boxplot()+ # linetype parameter is used to customize the joining line geom_line(aes(group = paired), linetype=2, size=1.3)+ # geom_point() is used to plot data points on boxplotgeom_point(aes(fill=category,group=paired),size=5,shape=21) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n10 Oct, 2021" }, { "code": null, "e": 24963, "s": 24851, "text": "In this article, we will discuss how to connect paired points in box plot in ggplot2 in R Programming Language." }, { "code": null, "e": 25257, "s": 24963, "text": "Boxplots with data points help us to visualize the summary information between distributions. For example, we may have two quantitative variables corresponding to two different categories and would like to connect those data points by lines. So to do this we have to load the tidyverse library" }, { "code": null, "e": 25265, "s": 25257, "text": "Syntax:" }, { "code": null, "e": 25284, "s": 25265, "text": "library(tidyverse)" }, { "code": null, "e": 25343, "s": 25284, "text": "Here is a basic box plot with lines joining paired points." }, { "code": null, "e": 25345, "s": 25343, "text": "R" }, { "code": "# load tidyverselibrary(tidyverse) # create dataframesample_data < - data.frame(value=c(1, 2, 3, 4, 4, 5, 6, 7, 9, 11, 1.5, 2.3, 2.5, 3.4, 4.5, 5.5, 6.5, 7.5, 9.5, 12.5), category=c('A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'), paired=c(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9)) # create plot using ggplot() and geom_boxplot() functionsggplot(sample_data, aes(category, value, fill=category)) +geom_boxplot()+ # geom_point() is used to make points at data valuesgeom_point()+ # geom_line() joins the paired datapointsgeom_line(aes(group=paired))", "e": 26239, "s": 25345, "text": null }, { "code": null, "e": 26247, "s": 26239, "text": "Output:" }, { "code": null, "e": 26359, "s": 26247, "text": "We can change the color and width of the joining segment by using the color and size property of geom_line(). " }, { "code": null, "e": 26367, "s": 26359, "text": "Syntax:" }, { "code": null, "e": 26491, "s": 26367, "text": "ggplot(aes( x, y )) + geom_boxplot()+geom_point( aes( fill ), size, shape ) + geom_line( aes( group ), size, color, alpha )" }, { "code": null, "e": 26503, "s": 26491, "text": "Parameters:" }, { "code": null, "e": 26552, "s": 26503, "text": "group: the variable that has pairs to be joined." }, { "code": null, "e": 26596, "s": 26552, "text": "color: the variable that categorizes points" }, { "code": null, "e": 26631, "s": 26596, "text": "alpha: determines the transparency" }, { "code": null, "e": 26657, "s": 26631, "text": "size: determines the size" }, { "code": null, "e": 26685, "s": 26657, "text": "shape: determines the shape" }, { "code": null, "e": 26717, "s": 26685, "text": "fill: determines the fill color" }, { "code": null, "e": 26726, "s": 26717, "text": "Example:" }, { "code": null, "e": 26728, "s": 26726, "text": "R" }, { "code": "# load tidyverselibrary(tidyverse) # create dataframesample_data <- data.frame( value = c(1,2,3,4,4,5,6, 7,9,11,1.5,2.3,2.5,3.4, 4.5,5.5,6.5,7.5,9.5,12.5), category = c('A','B','A','B','A', 'B','A','B','A','B', 'A','B','A','B','A', 'B','A','B','A','B'), paired = c(0,0,1,1,2,2,3,3,4,4, 5,5,6,6,7,7,8,8,9,9)) # create plot using ggplot() and geom_boxplot() functionsggplot(sample_data, aes(category,value, fill=category)) + geom_boxplot()+ # geom_line() joins the paired datapoints # color and size parameters are used to customize line geom_line(aes(group = paired), size=2, color='gray', alpha=0.6)+ # geom_point() is used to make points at data values # fill and size parameters are used to customize point geom_point(aes(fill=category,group=paired),size=5,shape=21)", "e": 27844, "s": 26728, "text": null }, { "code": null, "e": 27852, "s": 27844, "text": "Output:" }, { "code": null, "e": 27995, "s": 27852, "text": "We can convert the joining line into ridged line by using linetype property. Every property that works on a line plot also works in this line." }, { "code": null, "e": 28003, "s": 27995, "text": "Syntax:" }, { "code": null, "e": 28091, "s": 28003, "text": "ggplot(aes( x, y )) + geom_boxplot()+geom_point() + geom_line( aes( group ), linetype )" }, { "code": null, "e": 28102, "s": 28091, "text": "Parameters" }, { "code": null, "e": 28151, "s": 28102, "text": "group: the variable that has pairs to be joined." }, { "code": null, "e": 28189, "s": 28151, "text": "linetype: determines the type of line" }, { "code": null, "e": 28198, "s": 28189, "text": "Example:" }, { "code": null, "e": 28200, "s": 28198, "text": "R" }, { "code": "# load tidyverselibrary(tidyverse) # create dataframesample_data <- data.frame( value = c(1,2,3,4,4,5,6, 7,9,11,1.5,2.3,2.5,3.4, 4.5,5.5,6.5,7.5,9.5,12.5), category = c('A','B','A','B','A', 'B','A','B','A','B', 'A','B','A','B','A', 'B','A','B','A','B'), paired = c(0,0,1,1,2,2,3,3,4,4, 5,5,6,6,7,7,8,8,9,9)) # create plot using ggplot() and geom_boxplot() functionggplot(sample_data, aes(category,value, fill=category)) + geom_boxplot()+ # linetype parameter is used to customize the joining line geom_line(aes(group = paired), linetype=2, size=1.3)+ # geom_point() is used to plot data points on boxplotgeom_point(aes(fill=category,group=paired),size=5,shape=21)", "e": 29203, "s": 28200, "text": null }, { "code": null, "e": 29211, "s": 29203, "text": "Output:" }, { "code": null, "e": 29218, "s": 29211, "text": "Picked" }, { "code": null, "e": 29227, "s": 29218, "text": "R-ggplot" }, { "code": null, "e": 29238, "s": 29227, "text": "R Language" }, { "code": null, "e": 29336, "s": 29238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29345, "s": 29336, "text": "Comments" }, { "code": null, "e": 29358, "s": 29345, "text": "Old Comments" }, { "code": null, "e": 29410, "s": 29358, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29448, "s": 29410, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29483, "s": 29448, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29541, "s": 29483, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29590, "s": 29541, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29633, "s": 29590, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29683, "s": 29633, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29700, "s": 29683, "text": "R - if statement" }, { "code": null, "e": 29737, "s": 29700, "text": "How to import an Excel File into R ?" } ]
GANscapes: Create Impressionist Paintings with AI | Towards Data Science
This is my third article on experimenting with Generative Adversarial Networks (GANs) to create fine art. The first two articles focused on creating abstract art by using image augmentation, but this one focuses on creating Impressionist landscape paintings. I posted all of the source code for GANscapes on GitHub and posted the original paintings on Kaggle. You can create new landscape paintings using the Google Colab here. There have been several projects and papers that show how to use GANs to create landscape paintings. There’s Drew Flaherty’s master’s thesis from the Queensland University of Technology entitled “Artistic approaches to machine learning,” where he used the original StyleGAN [1]. Alice Xue created SAPGAN described in her paper, “End-to-End Chinese Landscape Painting Creation Using Generative Adversarial Networks” [2]. And Bingchen Liu, et al. created a Lightweight GAN in their paper, “Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis” [3]. Below is a sample of paintings from StyleGAN, SAPGAN, Lightweight GAN, and GANscapes. GANscapes is a system for creating new Impressionist landscape paintings using the latest advances in AI. Here’s a diagram that shows the main system components. Here is a brief, high-level overview of the components used in GANscapes. I’ll discuss the details of each component later in the article. I gathered images of Impressionist landscape paintings from WikiArt.org [4] and processed the images to adjust the aspect ratio. I then used the CLIP model [5] from OpenAI to filter the images to keep the “good ones.” I used these images to train StyleGAN2 ADA [6] from NVidia, which has a generator and discriminator network. The generator creates new images starting with random “latent” vectors for form and style and tries to fool the discriminator into thinking the output images are real. Before the real and the generated images are fed into the discriminator, they are modified slightly with the Adaptive Discriminator Augmentation (ADA) module that creates visual diversity in the pictures. I use CLIP again to filter the output images based on a user-supplied text query. And I use the generator again to create an image with a mix of style and form selected by the user. As the final step, I post-process the final images to adust the aspect ratios. Be sure to check out the image gallery in the appendix at the end of the article to see more results. I started by scraping landscape paintings from WikiArt.org using a custom python script in the Colab here. The script goes through each artist on the site alphabetically. It checks to see if the artist is tagged as part of the “Impressionism” art movement and if they were born after 1800 and died before 1950. The script then loops through all of the artists’ paintings, looking for ones in the “landscape” genre available in the public domain. The script then downloads each qualified image using the artist and painting name as the filename, i.e., claude-monet_landscape-at-giverny-1.jpg. The system found about 5,300 paintings that matched these criteria. Here is a sample of Impressionist paintings from WikiArt.org. You will notice from the sample of paintings above that they have varying aspect ratios, e.g., some of the images are a lot wider than others. Because the GAN systems work more efficiently with perfectly square images, the source images' aspect ratios need to be adjusted. Three techniques are commonly used to make the adjustments, each with pros and cons. I’ll use Landscape at Valery-sur-Somme by Degas as an example to show the different methods. The “letterbox” format in the first image above keeps the image uncut and unsqueezed, but black bars are added above and below to make the image have a square shape. The issue with the letterbox format is that the entire image is effectively resized down, losing resolution, and the black parts are “wasted” in the GAN training. The second image is in the “center cut” format, which is cropped to keep just the image's square center. The issue with the center cut format is the significant loss of imagery on the left and the right. The third image is squeezed horizontally to be square. The issue with the squeezed format is that the objects in the painting are distorted. For example, in this image, the windmill just got a lot thinner. And each painting will be squeezed by a different amount, depending on the original aspect ratio. For this project, I came up with a hybrid technique that seems to be a good compromise. My hybrid solution requires first determining the average aspect ratio of all the original paintings, which for the dataset is 1.27:1. Next, I crop each image into a 1.27:1 aspect ratio, pulling out a center rectangle. I then squeeze the cropped images horizontally into a square format with a resolution of 1024 x 1024 pixels and use the resulting images for my training dataset. When the GAN produces square output images, I scale them back out to be 1.27:1 to match the original format. The result of this process will be synthetically generated images that are free of distortion. This “center rectangle” format seems to be a good compromise between the center cut and squeezed formats, especially since the original landscape paintings are in, well, landscape format. However, this method would not work well with a mix of landscape and portrait-formatted images as it would tend towards the center cut format. The source code is in the Colab here. Just because a painting is tagged on WikiArt as being a landscape from an Impressionist painter doesn't mean that it’s a good representation of such a painting. In my previous project for generating abstract art with a GAN, I “hand chose” the source images, which was quite time-consuming (and made me feel a little “judgy”). For this project, I used a new open-source AI system called CLIP from OpenAI [5] to do the image filtering. OpenAI designed two models, an image encoder and a text encoder. They trained the two models on a dataset of images with corresponding phrases. The goal of the models is to have the encoded images match the encoded phrases. Once trained, the image encoder system converts images to embeddings, lists of 512 floating-point numbers that capture the images' general features. The text encoder converts a text phrase to similar a embedding that can be compared to image embeddings for a semantic search. For GANscapes, I compare the embedding from the phrase “impressionist landscape painting” to the embeddings from the 5,300 paintings to find the images that best match the phrase. The source code is in the Colab here. Below are the top 24 images that match the phrase “impressionist landscape painting,” according to CLIP. Not bad! There seem to be many depictions of trees and water, but they vary in painting style. And below are the bottom 24 images according to CLIP. OK, I can see why CLIP doesn't think these images match the phrase “impressionist landscape painting.” Except for the two grayscale images on the left, most of them are of people, buildings, abstractions, etc. I took a look at the images near the 5,000 mark, and they seemed to be decent. So of the 5,314 images, I moved the bottom 314 into a folder called “Salon des Refusés” and kept them out of the training. In 2014, Ian Goodfellow and his coauthors at the Université de Montréal presented a paper on GANs [7]. They came up with a way to train two Artificial Neural Networks (ANNs) that compete with each other to create realistic images. As I explained at the beginning of this article, the first ANN is called the generator, and the second is called the discriminator. The generator tries to create realistic output. The discriminator tries to discern real images from the training set from the fake images from the generator. During the training, both ANNs gradually improve, and the results are surprisingly good. Last year, I created a project called MachineRay that uses Nvidia’s StyleGAN2 to create abstract artwork based on 20th-century paintings in the public domain. Since then, Nvidia has released a new version of their AI model, StyleGAN2 ADA, designed to yield better results when generating images from a limited dataset. One of the significant improvements in StyleGAN2 ADA is dynamically changing the amount of image augmentation during training. I wrote about this improvement back in January 2020. towardsdatascience.com I trained the GAN on Google Colab Pro for about three weeks. Because the Colab times out every 24 hours, I kept the results on my Google Drive and pick up where it left off. Here is the command I used to kick off the training: !python stylegan2-ada/train.py --aug=ada --mirror=1--metrics=none --snap=1 --gpus=1 \--data=/content/drive/MyDrive/GANscapes/dataset_1024 \--outdir=/content/drive/MyDrive/GANscapes/models_1024 I noticed an issue with the ADA variable p, which determines how much image augmentation is used during training. Because the p value always starts at zero, it takes the system a while each day to climb back up to around 0.2. I fixed this in my fork of StyleGAN2 ADA to allow p to be set when the augmentation is set to ADA (the implementation in NVidia’s repo will throw an error if p is set when using ADA.) Here’s the command I used on subsequent restarts. !python stylegan2-ada/train.py --aug=ada --p 0.186 --mirror=1 \--metrics=none --snap=1 --gpus=1 \--data=/content/drive/MyDrive/GANscapes/dataset_1024 \--outdir=/content/drive/MyDrive/GANscapes/models_1024 \--resume=/content/drive/MyDrive/GANscapes/models_1024/00020-dataset_1024-mirror-auto1-ada-p0.183-resumecustom/network-snapshot-000396.pkl I replaced 0.186 with the last used p value and the resume path to the previously saved model. Here are some samples from the trained GANscapes system. Nice! Some of the generated paintings look more abstract than others, but overall, the quality seems pretty good. The system tends to depict natural items well, like trees, water, clouds, etc. However, it seems to be struggling a bit with buildings, boats, and other human-made objects. I put the CLIP model to work again to filter the output images. The system generates 1,000 images and is fed into CLIP to get the image embeddings. The user can type in a prompt, like “Impressionist painting of autumn woods,” which gets transformed into a CLIP text embedding. The system compares the image embeddings to the text embedding and finds the top matches. Here are the top 6 paintings that match the “autumn woods” prompt. Not only does the system find suitable matches for the prompt, but the overall quality seems to have improved, too. This is because the CLIP system is effectively rating the paintings by how closely they match the phrase, “Impressionist painting of autumn woods.” CLIP will filter out any of the “funky” images. Did you ever wonder why NVidia named their model StyleGAN? Why the word “style” in the name? The answer is in the architecture. Not only does the model learn how to create new images based on a set of training images, it learns how to create images with different styles based on the training dataset. And you can effectively copy the “style” from one image and paste it into a second image, creating a third image that retains the form of the first but adopts the style of the second. This is called style mixing. I built a Google Colab that demonstrates how style mixing looks for GANscapes. It’s based on the style_mixing.py script from NVidia. The Colab renders seven landscapes for their form and three landscapes for their style. It then shows a grid of 21 landscapes that mix each form with each style. Note that the thumbnails are scaled up horizontally to have a 1:127 aspect ratio. As you can see, the form images are presented at the top from left to right, labeled F1 to F7. The style images are present at the left from top to bottom, labeled S1 to S3. The images in the 7x3 grid are mixtures of the form and style images. You can see how the trees are placed in roughly the same locations within the images for each of the seven forms, and the paintings rendered with different styles use the same color palette and look as if they were painted at a different time in the year. I perform two post-processing steps, a mild contrast adjustment and image resizing, to restore the original aspect ratio. Here’s the code. import numpy as npimport PIL# convert the image to use floating pointimg_fp = images[generation_indices[0]].astype(np.float32)# stretch the red channel by 0.1% at each endr_min = np.percentile(img_fp[:,:,0:1], 0.1)r_max = np.percentile(img_fp[:,:,0:1], 99.9)img_fp[:,:,0:1] = (img_fp[:,:,0:1]-r_min) * 255.0 / (r_max-r_min)# stretch the green channel by 0.1% at each endg_min = np.percentile(img_fp[:,:,1:2], 0.1)g_max = np.percentile(img_fp[:,:,1:2], 99.9)img_fp[:,:,1:2] = (img_fp[:,:,1:2]-g_min) * 255.0 / (g_max-g_min)# stretch the blue channel by 0.1% at each endb_min = np.percentile(img_fp[:,:,2:3], 0.1)b_max = np.percentile(img_fp[:,:,2:3], 99.9)img_fp[:,:,2:3] = (img_fp[:,:,2:3]-b_min) * 255.0 / (b_max-b_min)# convert the image back to integer, after rounding and clippingimg_int = np.clip(np.round(img_fp), 0, 255).astype(np.uint8)# convert to the image to PIL and resize to fix the aspect ratioimg_pil=PIL.Image.fromarray(img_int)img_pil=img_pil.resize((1024, int(1024/1.2718))) The first part of the code converts the image to floating-point, finds the 0.1% min and the 0.99% max of each channel, and scales up the contrast. This is akin to Adjust Levels feature in Photoshop. The second part of the code converts the image back to use integers and resizes it to have a 1.27 to 1 aspect ratio. Here are three of the style-mixed paintings, before and after post-processing. You can click on each image for a closer look. The quality of the landscape paintings created by GANscapes can be attributed to the StyleGAN2 ADA and CLIP models. By design, StyleGAN2 ADA can be trained on a limited dataset to produce excellent results. Note that GANs produce images that flow continuously from image to image. Unless the input images are labeled to be in categories, there are no hard breaks between the results. If the input latent vectors change a little, the resultant image will change a little. If the vectors change a lot, the image will change a lot. This means that the system is effectively morphing from one scene to all possible neighbors. Sometimes these “in-between” images have odd artifacts, like a tree partially dissolved to a cloud. This is where CLIP comes in. Because it’s rating images by how much they match the text query, i.e., “Impressionist landscape painting,” it tends to pick fully formed images that don’t have odd artifacts. The CLIP model effectively solves the partial morphing problem with unlabeled GANs. There are several different ways to improve and extend this project. First, the paintings' quality could be improved using a technique called Learning Transfer [8]. This could be done by first training the GAN on photographs of landscapes and then continue the training on landscape paintings. I could probably improve the text-to-image generation by running through multiple iterations of StyleGAN → CLIP → StyleGAN → CLIP, etc. This could either be done with a genetic algorithm like in CLIPGLaSS [9] or gradient descent and backpropagation. This is the same method used to train ANNs, as described in Victor Perez’s article on Medium [10]. Finally, the recent press about how Non-Fungible Tokens (NFTs) can be used to verify the owner of digital files made me think of a possible NFT-GAN hybrid. Instead of buying ownership of a single JPEG file, a prospective collector could bid on a range of latent vectors that generate variations of images and/or styles in a trained GAN. Hey, you read it here first, folks! The 5,000 abstract paintings I collected can be found on Kaggle here. All source code for this project is available on GitHub. Images of the paintings on Kaggle and the source code are released under the CC BY-SA license. I want to thank Jennifer Lim and Oliver Strimpel for their help with this article. [1] D. Flaherty, “Artistic approaches to machine learning,” May 22, 2020, Queensland University of Technology, Masters Thesis, https://eprints.qut.edu.au/200191/1/Drew_Flaherty_Thesis.pdf [2] A. Xu, “End-to-End Chinese Landscape Painting Creation UsingGenerative Adversarial Networks”, November 11, 2020, https://openaccess.thecvf.com/content/WACV2021/papers/Xue_End-to-End_Chinese_Landscape_Painting_Creation_Using_Generative_Adversarial_Networks_WACV_2021_paper.pdf [3] B. Liu, Y Zhu, K. Song, A. Elgammal, “Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis,” January 12, 2021, https://arxiv.org/pdf/2101.04775.pdf [4] WikiArt, December 26, 2008, https://www.wikiart.org [5] A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark, et al., “Learning Transferable Visual Models From Natural Language Supervision,” January 5, 2021, https://cdn.openai.com/papers/Learning_Transferable_Visual_Models_From_Natural_Language_Supervision.pdf [6] T. Karras, M. Aittala, J. Hellsten, S. Laine, J. Lehtinen, and T. Aila, “Training Generative Adversarial Networks with Limited Data.”, October 7, 2020, https://arxiv.org/pdf/2006.06676.pdf [7] I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D.Warde-Farley, S. Ozair, A. Courville, Y. Bengio, “Generative Adversarial Networks,” June 10, 2014, https://arxiv.org/pdf/1406.2661.pdf [8] S. Bozinovskim, and A. Fulgosi, “The influence of pattern similarity and transfer learning upon training of a base perceptron B2.” Proceedings of Symposium Informatica, 3–121–5, 1976 [9] F. Galatolo, M.G.C.A. Cimino, and G. Vaglini, “Generating images from caption and vice versa via CLIP-Guided Generative Latent Space Search,” February 26, 2021, https://arxiv.org/pdf/2102.01645.pdf [10] V. Perez, “Generating Images from Prompts using CLIP and StyleGAN,” Feb 6, 2021, https://towardsdatascience.com/generating-images-from-prompts-using-clip-and-stylegan-1f9ed495ddda Here is a collection of finished paintings. Note that you can click to zoom in on any of the images. To get unlimited access to all articles on Medium, become a member for $5/month. Non-members can only read three locked stories each month. Some rights reserved
[ { "code": null, "e": 430, "s": 171, "text": "This is my third article on experimenting with Generative Adversarial Networks (GANs) to create fine art. The first two articles focused on creating abstract art by using image augmentation, but this one focuses on creating Impressionist landscape paintings." }, { "code": null, "e": 599, "s": 430, "text": "I posted all of the source code for GANscapes on GitHub and posted the original paintings on Kaggle. You can create new landscape paintings using the Google Colab here." }, { "code": null, "e": 1179, "s": 599, "text": "There have been several projects and papers that show how to use GANs to create landscape paintings. There’s Drew Flaherty’s master’s thesis from the Queensland University of Technology entitled “Artistic approaches to machine learning,” where he used the original StyleGAN [1]. Alice Xue created SAPGAN described in her paper, “End-to-End Chinese Landscape Painting Creation Using Generative Adversarial Networks” [2]. And Bingchen Liu, et al. created a Lightweight GAN in their paper, “Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis” [3]." }, { "code": null, "e": 1265, "s": 1179, "text": "Below is a sample of paintings from StyleGAN, SAPGAN, Lightweight GAN, and GANscapes." }, { "code": null, "e": 1427, "s": 1265, "text": "GANscapes is a system for creating new Impressionist landscape paintings using the latest advances in AI. Here’s a diagram that shows the main system components." }, { "code": null, "e": 1566, "s": 1427, "text": "Here is a brief, high-level overview of the components used in GANscapes. I’ll discuss the details of each component later in the article." }, { "code": null, "e": 1784, "s": 1566, "text": "I gathered images of Impressionist landscape paintings from WikiArt.org [4] and processed the images to adjust the aspect ratio. I then used the CLIP model [5] from OpenAI to filter the images to keep the “good ones.”" }, { "code": null, "e": 2266, "s": 1784, "text": "I used these images to train StyleGAN2 ADA [6] from NVidia, which has a generator and discriminator network. The generator creates new images starting with random “latent” vectors for form and style and tries to fool the discriminator into thinking the output images are real. Before the real and the generated images are fed into the discriminator, they are modified slightly with the Adaptive Discriminator Augmentation (ADA) module that creates visual diversity in the pictures." }, { "code": null, "e": 2527, "s": 2266, "text": "I use CLIP again to filter the output images based on a user-supplied text query. And I use the generator again to create an image with a mix of style and form selected by the user. As the final step, I post-process the final images to adust the aspect ratios." }, { "code": null, "e": 2629, "s": 2527, "text": "Be sure to check out the image gallery in the appendix at the end of the article to see more results." }, { "code": null, "e": 3289, "s": 2629, "text": "I started by scraping landscape paintings from WikiArt.org using a custom python script in the Colab here. The script goes through each artist on the site alphabetically. It checks to see if the artist is tagged as part of the “Impressionism” art movement and if they were born after 1800 and died before 1950. The script then loops through all of the artists’ paintings, looking for ones in the “landscape” genre available in the public domain. The script then downloads each qualified image using the artist and painting name as the filename, i.e., claude-monet_landscape-at-giverny-1.jpg. The system found about 5,300 paintings that matched these criteria." }, { "code": null, "e": 3351, "s": 3289, "text": "Here is a sample of Impressionist paintings from WikiArt.org." }, { "code": null, "e": 3802, "s": 3351, "text": "You will notice from the sample of paintings above that they have varying aspect ratios, e.g., some of the images are a lot wider than others. Because the GAN systems work more efficiently with perfectly square images, the source images' aspect ratios need to be adjusted. Three techniques are commonly used to make the adjustments, each with pros and cons. I’ll use Landscape at Valery-sur-Somme by Degas as an example to show the different methods." }, { "code": null, "e": 4131, "s": 3802, "text": "The “letterbox” format in the first image above keeps the image uncut and unsqueezed, but black bars are added above and below to make the image have a square shape. The issue with the letterbox format is that the entire image is effectively resized down, losing resolution, and the black parts are “wasted” in the GAN training." }, { "code": null, "e": 4335, "s": 4131, "text": "The second image is in the “center cut” format, which is cropped to keep just the image's square center. The issue with the center cut format is the significant loss of imagery on the left and the right." }, { "code": null, "e": 4639, "s": 4335, "text": "The third image is squeezed horizontally to be square. The issue with the squeezed format is that the objects in the painting are distorted. For example, in this image, the windmill just got a lot thinner. And each painting will be squeezed by a different amount, depending on the original aspect ratio." }, { "code": null, "e": 4727, "s": 4639, "text": "For this project, I came up with a hybrid technique that seems to be a good compromise." }, { "code": null, "e": 5312, "s": 4727, "text": "My hybrid solution requires first determining the average aspect ratio of all the original paintings, which for the dataset is 1.27:1. Next, I crop each image into a 1.27:1 aspect ratio, pulling out a center rectangle. I then squeeze the cropped images horizontally into a square format with a resolution of 1024 x 1024 pixels and use the resulting images for my training dataset. When the GAN produces square output images, I scale them back out to be 1.27:1 to match the original format. The result of this process will be synthetically generated images that are free of distortion." }, { "code": null, "e": 5681, "s": 5312, "text": "This “center rectangle” format seems to be a good compromise between the center cut and squeezed formats, especially since the original landscape paintings are in, well, landscape format. However, this method would not work well with a mix of landscape and portrait-formatted images as it would tend towards the center cut format. The source code is in the Colab here." }, { "code": null, "e": 6115, "s": 5681, "text": "Just because a painting is tagged on WikiArt as being a landscape from an Impressionist painter doesn't mean that it’s a good representation of such a painting. In my previous project for generating abstract art with a GAN, I “hand chose” the source images, which was quite time-consuming (and made me feel a little “judgy”). For this project, I used a new open-source AI system called CLIP from OpenAI [5] to do the image filtering." }, { "code": null, "e": 6339, "s": 6115, "text": "OpenAI designed two models, an image encoder and a text encoder. They trained the two models on a dataset of images with corresponding phrases. The goal of the models is to have the encoded images match the encoded phrases." }, { "code": null, "e": 6615, "s": 6339, "text": "Once trained, the image encoder system converts images to embeddings, lists of 512 floating-point numbers that capture the images' general features. The text encoder converts a text phrase to similar a embedding that can be compared to image embeddings for a semantic search." }, { "code": null, "e": 6833, "s": 6615, "text": "For GANscapes, I compare the embedding from the phrase “impressionist landscape painting” to the embeddings from the 5,300 paintings to find the images that best match the phrase. The source code is in the Colab here." }, { "code": null, "e": 6938, "s": 6833, "text": "Below are the top 24 images that match the phrase “impressionist landscape painting,” according to CLIP." }, { "code": null, "e": 7087, "s": 6938, "text": "Not bad! There seem to be many depictions of trees and water, but they vary in painting style. And below are the bottom 24 images according to CLIP." }, { "code": null, "e": 7297, "s": 7087, "text": "OK, I can see why CLIP doesn't think these images match the phrase “impressionist landscape painting.” Except for the two grayscale images on the left, most of them are of people, buildings, abstractions, etc." }, { "code": null, "e": 7500, "s": 7297, "text": "I took a look at the images near the 5,000 mark, and they seemed to be decent. So of the 5,314 images, I moved the bottom 314 into a folder called “Salon des Refusés” and kept them out of the training." }, { "code": null, "e": 8112, "s": 7500, "text": "In 2014, Ian Goodfellow and his coauthors at the Université de Montréal presented a paper on GANs [7]. They came up with a way to train two Artificial Neural Networks (ANNs) that compete with each other to create realistic images. As I explained at the beginning of this article, the first ANN is called the generator, and the second is called the discriminator. The generator tries to create realistic output. The discriminator tries to discern real images from the training set from the fake images from the generator. During the training, both ANNs gradually improve, and the results are surprisingly good." }, { "code": null, "e": 8431, "s": 8112, "text": "Last year, I created a project called MachineRay that uses Nvidia’s StyleGAN2 to create abstract artwork based on 20th-century paintings in the public domain. Since then, Nvidia has released a new version of their AI model, StyleGAN2 ADA, designed to yield better results when generating images from a limited dataset." }, { "code": null, "e": 8611, "s": 8431, "text": "One of the significant improvements in StyleGAN2 ADA is dynamically changing the amount of image augmentation during training. I wrote about this improvement back in January 2020." }, { "code": null, "e": 8634, "s": 8611, "text": "towardsdatascience.com" }, { "code": null, "e": 8861, "s": 8634, "text": "I trained the GAN on Google Colab Pro for about three weeks. Because the Colab times out every 24 hours, I kept the results on my Google Drive and pick up where it left off. Here is the command I used to kick off the training:" }, { "code": null, "e": 9054, "s": 8861, "text": "!python stylegan2-ada/train.py --aug=ada --mirror=1--metrics=none --snap=1 --gpus=1 \\--data=/content/drive/MyDrive/GANscapes/dataset_1024 \\--outdir=/content/drive/MyDrive/GANscapes/models_1024" }, { "code": null, "e": 9464, "s": 9054, "text": "I noticed an issue with the ADA variable p, which determines how much image augmentation is used during training. Because the p value always starts at zero, it takes the system a while each day to climb back up to around 0.2. I fixed this in my fork of StyleGAN2 ADA to allow p to be set when the augmentation is set to ADA (the implementation in NVidia’s repo will throw an error if p is set when using ADA.)" }, { "code": null, "e": 9514, "s": 9464, "text": "Here’s the command I used on subsequent restarts." }, { "code": null, "e": 9858, "s": 9514, "text": "!python stylegan2-ada/train.py --aug=ada --p 0.186 --mirror=1 \\--metrics=none --snap=1 --gpus=1 \\--data=/content/drive/MyDrive/GANscapes/dataset_1024 \\--outdir=/content/drive/MyDrive/GANscapes/models_1024 \\--resume=/content/drive/MyDrive/GANscapes/models_1024/00020-dataset_1024-mirror-auto1-ada-p0.183-resumecustom/network-snapshot-000396.pkl" }, { "code": null, "e": 9953, "s": 9858, "text": "I replaced 0.186 with the last used p value and the resume path to the previously saved model." }, { "code": null, "e": 10010, "s": 9953, "text": "Here are some samples from the trained GANscapes system." }, { "code": null, "e": 10297, "s": 10010, "text": "Nice! Some of the generated paintings look more abstract than others, but overall, the quality seems pretty good. The system tends to depict natural items well, like trees, water, clouds, etc. However, it seems to be struggling a bit with buildings, boats, and other human-made objects." }, { "code": null, "e": 10731, "s": 10297, "text": "I put the CLIP model to work again to filter the output images. The system generates 1,000 images and is fed into CLIP to get the image embeddings. The user can type in a prompt, like “Impressionist painting of autumn woods,” which gets transformed into a CLIP text embedding. The system compares the image embeddings to the text embedding and finds the top matches. Here are the top 6 paintings that match the “autumn woods” prompt." }, { "code": null, "e": 11043, "s": 10731, "text": "Not only does the system find suitable matches for the prompt, but the overall quality seems to have improved, too. This is because the CLIP system is effectively rating the paintings by how closely they match the phrase, “Impressionist painting of autumn woods.” CLIP will filter out any of the “funky” images." }, { "code": null, "e": 11558, "s": 11043, "text": "Did you ever wonder why NVidia named their model StyleGAN? Why the word “style” in the name? The answer is in the architecture. Not only does the model learn how to create new images based on a set of training images, it learns how to create images with different styles based on the training dataset. And you can effectively copy the “style” from one image and paste it into a second image, creating a third image that retains the form of the first but adopts the style of the second. This is called style mixing." }, { "code": null, "e": 11935, "s": 11558, "text": "I built a Google Colab that demonstrates how style mixing looks for GANscapes. It’s based on the style_mixing.py script from NVidia. The Colab renders seven landscapes for their form and three landscapes for their style. It then shows a grid of 21 landscapes that mix each form with each style. Note that the thumbnails are scaled up horizontally to have a 1:127 aspect ratio." }, { "code": null, "e": 12435, "s": 11935, "text": "As you can see, the form images are presented at the top from left to right, labeled F1 to F7. The style images are present at the left from top to bottom, labeled S1 to S3. The images in the 7x3 grid are mixtures of the form and style images. You can see how the trees are placed in roughly the same locations within the images for each of the seven forms, and the paintings rendered with different styles use the same color palette and look as if they were painted at a different time in the year." }, { "code": null, "e": 12574, "s": 12435, "text": "I perform two post-processing steps, a mild contrast adjustment and image resizing, to restore the original aspect ratio. Here’s the code." }, { "code": null, "e": 13567, "s": 12574, "text": "import numpy as npimport PIL# convert the image to use floating pointimg_fp = images[generation_indices[0]].astype(np.float32)# stretch the red channel by 0.1% at each endr_min = np.percentile(img_fp[:,:,0:1], 0.1)r_max = np.percentile(img_fp[:,:,0:1], 99.9)img_fp[:,:,0:1] = (img_fp[:,:,0:1]-r_min) * 255.0 / (r_max-r_min)# stretch the green channel by 0.1% at each endg_min = np.percentile(img_fp[:,:,1:2], 0.1)g_max = np.percentile(img_fp[:,:,1:2], 99.9)img_fp[:,:,1:2] = (img_fp[:,:,1:2]-g_min) * 255.0 / (g_max-g_min)# stretch the blue channel by 0.1% at each endb_min = np.percentile(img_fp[:,:,2:3], 0.1)b_max = np.percentile(img_fp[:,:,2:3], 99.9)img_fp[:,:,2:3] = (img_fp[:,:,2:3]-b_min) * 255.0 / (b_max-b_min)# convert the image back to integer, after rounding and clippingimg_int = np.clip(np.round(img_fp), 0, 255).astype(np.uint8)# convert to the image to PIL and resize to fix the aspect ratioimg_pil=PIL.Image.fromarray(img_int)img_pil=img_pil.resize((1024, int(1024/1.2718)))" }, { "code": null, "e": 13766, "s": 13567, "text": "The first part of the code converts the image to floating-point, finds the 0.1% min and the 0.99% max of each channel, and scales up the contrast. This is akin to Adjust Levels feature in Photoshop." }, { "code": null, "e": 13962, "s": 13766, "text": "The second part of the code converts the image back to use integers and resizes it to have a 1.27 to 1 aspect ratio. Here are three of the style-mixed paintings, before and after post-processing." }, { "code": null, "e": 14009, "s": 13962, "text": "You can click on each image for a closer look." }, { "code": null, "e": 14125, "s": 14009, "text": "The quality of the landscape paintings created by GANscapes can be attributed to the StyleGAN2 ADA and CLIP models." }, { "code": null, "e": 14731, "s": 14125, "text": "By design, StyleGAN2 ADA can be trained on a limited dataset to produce excellent results. Note that GANs produce images that flow continuously from image to image. Unless the input images are labeled to be in categories, there are no hard breaks between the results. If the input latent vectors change a little, the resultant image will change a little. If the vectors change a lot, the image will change a lot. This means that the system is effectively morphing from one scene to all possible neighbors. Sometimes these “in-between” images have odd artifacts, like a tree partially dissolved to a cloud." }, { "code": null, "e": 15020, "s": 14731, "text": "This is where CLIP comes in. Because it’s rating images by how much they match the text query, i.e., “Impressionist landscape painting,” it tends to pick fully formed images that don’t have odd artifacts. The CLIP model effectively solves the partial morphing problem with unlabeled GANs." }, { "code": null, "e": 15089, "s": 15020, "text": "There are several different ways to improve and extend this project." }, { "code": null, "e": 15314, "s": 15089, "text": "First, the paintings' quality could be improved using a technique called Learning Transfer [8]. This could be done by first training the GAN on photographs of landscapes and then continue the training on landscape paintings." }, { "code": null, "e": 15663, "s": 15314, "text": "I could probably improve the text-to-image generation by running through multiple iterations of StyleGAN → CLIP → StyleGAN → CLIP, etc. This could either be done with a genetic algorithm like in CLIPGLaSS [9] or gradient descent and backpropagation. This is the same method used to train ANNs, as described in Victor Perez’s article on Medium [10]." }, { "code": null, "e": 16036, "s": 15663, "text": "Finally, the recent press about how Non-Fungible Tokens (NFTs) can be used to verify the owner of digital files made me think of a possible NFT-GAN hybrid. Instead of buying ownership of a single JPEG file, a prospective collector could bid on a range of latent vectors that generate variations of images and/or styles in a trained GAN. Hey, you read it here first, folks!" }, { "code": null, "e": 16258, "s": 16036, "text": "The 5,000 abstract paintings I collected can be found on Kaggle here. All source code for this project is available on GitHub. Images of the paintings on Kaggle and the source code are released under the CC BY-SA license." }, { "code": null, "e": 16341, "s": 16258, "text": "I want to thank Jennifer Lim and Oliver Strimpel for their help with this article." }, { "code": null, "e": 16529, "s": 16341, "text": "[1] D. Flaherty, “Artistic approaches to machine learning,” May 22, 2020, Queensland University of Technology, Masters Thesis, https://eprints.qut.edu.au/200191/1/Drew_Flaherty_Thesis.pdf" }, { "code": null, "e": 16809, "s": 16529, "text": "[2] A. Xu, “End-to-End Chinese Landscape Painting Creation UsingGenerative Adversarial Networks”, November 11, 2020, https://openaccess.thecvf.com/content/WACV2021/papers/Xue_End-to-End_Chinese_Landscape_Painting_Creation_Using_Generative_Adversarial_Networks_WACV_2021_paper.pdf" }, { "code": null, "e": 16994, "s": 16809, "text": "[3] B. Liu, Y Zhu, K. Song, A. Elgammal, “Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis,” January 12, 2021, https://arxiv.org/pdf/2101.04775.pdf" }, { "code": null, "e": 17050, "s": 16994, "text": "[4] WikiArt, December 26, 2008, https://www.wikiart.org" }, { "code": null, "e": 17366, "s": 17050, "text": "[5] A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark, et al., “Learning Transferable Visual Models From Natural Language Supervision,” January 5, 2021, https://cdn.openai.com/papers/Learning_Transferable_Visual_Models_From_Natural_Language_Supervision.pdf" }, { "code": null, "e": 17559, "s": 17366, "text": "[6] T. Karras, M. Aittala, J. Hellsten, S. Laine, J. Lehtinen, and T. Aila, “Training Generative Adversarial Networks with Limited Data.”, October 7, 2020, https://arxiv.org/pdf/2006.06676.pdf" }, { "code": null, "e": 17750, "s": 17559, "text": "[7] I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D.Warde-Farley, S. Ozair, A. Courville, Y. Bengio, “Generative Adversarial Networks,” June 10, 2014, https://arxiv.org/pdf/1406.2661.pdf" }, { "code": null, "e": 17937, "s": 17750, "text": "[8] S. Bozinovskim, and A. Fulgosi, “The influence of pattern similarity and transfer learning upon training of a base perceptron B2.” Proceedings of Symposium Informatica, 3–121–5, 1976" }, { "code": null, "e": 18139, "s": 17937, "text": "[9] F. Galatolo, M.G.C.A. Cimino, and G. Vaglini, “Generating images from caption and vice versa via CLIP-Guided Generative Latent Space Search,” February 26, 2021, https://arxiv.org/pdf/2102.01645.pdf" }, { "code": null, "e": 18324, "s": 18139, "text": "[10] V. Perez, “Generating Images from Prompts using CLIP and StyleGAN,” Feb 6, 2021, https://towardsdatascience.com/generating-images-from-prompts-using-clip-and-stylegan-1f9ed495ddda" }, { "code": null, "e": 18425, "s": 18324, "text": "Here is a collection of finished paintings. Note that you can click to zoom in on any of the images." }, { "code": null, "e": 18565, "s": 18425, "text": "To get unlimited access to all articles on Medium, become a member for $5/month. Non-members can only read three locked stories each month." } ]
String slicing in Python to rotate a string
A string is given, our task is to slicing the string into two way. One is clockwise and another anticlockwise. 1. Left (Or anticlockwise) rotate the given string by d elements (where d <= n). 2. Right (Or clockwise) rotate the given string by d elements (where d <= n). Input: string = "pythonprogram" d = 2 Output: Left Rotation: thonprogrampy Right Rotation: ampythonprogr Step 1: Enter string. Step 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ]. Step 3: Now concatenate these two parts second + first accordingly. def rotate(input,d): # Slice string in two parts for left and right Lfirst = input[0 : d] Lsecond = input[d :] Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] print ("Left Rotation : ", (Lsecond + Lfirst) ) print ("Right Rotation : ", (Rsecond + Rfirst) ) # Driver program if __name__ == "__main__": str = input("Enter String ::>") d=2 rotate(str,d) Enter String ::> pythonprogram Left Rotation: thonprogrampy Right Rotation: ampythonprogr
[ { "code": null, "e": 1173, "s": 1062, "text": "A string is given, our task is to slicing the string into two way. One is clockwise and another anticlockwise." }, { "code": null, "e": 1254, "s": 1173, "text": "1. Left (Or anticlockwise) rotate the given string by d elements (where d <= n)." }, { "code": null, "e": 1332, "s": 1254, "text": "2. Right (Or clockwise) rotate the given string by d elements (where d <= n)." }, { "code": null, "e": 1437, "s": 1332, "text": "Input: string = \"pythonprogram\"\nd = 2\nOutput: Left Rotation: thonprogrampy\nRight Rotation: ampythonprogr" }, { "code": null, "e": 1724, "s": 1437, "text": "Step 1: Enter string.\nStep 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ].\nStep 3: Now concatenate these two parts second + first accordingly." }, { "code": null, "e": 2131, "s": 1724, "text": "def rotate(input,d):\n # Slice string in two parts for left and right\n Lfirst = input[0 : d]\n Lsecond = input[d :]\n Rfirst = input[0 : len(input)-d]\n Rsecond = input[len(input)-d : ]\n print (\"Left Rotation : \", (Lsecond + Lfirst) )\n print (\"Right Rotation : \", (Rsecond + Rfirst) )\n # Driver program\n if __name__ == \"__main__\":\n str = input(\"Enter String ::>\")\nd=2\nrotate(str,d)" }, { "code": null, "e": 2221, "s": 2131, "text": "Enter String ::> pythonprogram\nLeft Rotation: thonprogrampy\nRight Rotation: ampythonprogr" } ]
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
21 Jun, 2022 The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Although it’s a loophole in C++, yes it’s possible through pointers. Example 1: CPP // CPP Program to initialize the private members and display// them without using member functions #include <bits/stdc++.h>using namespace std; class Test {private: int data; public: Test() { data = 0; } int getData() { return data; }}; int main(){ Test t; int* ptr = (int*)&t; *ptr = 10; cout << t.getData(); return 0;} 10 Example 2: CPP // CPP Program to initialize the private members and display// them without using member functions#include <bits/stdc++.h>using namespace std; class A {private: int x; int y;}; // Driver Codeint main(){ A a; int* p = (int*)&a; *p = 3; p++; *p = 9; p--; cout << endl << "x = " << *p; p++; cout << endl << "y = " << *p; return 0;} x = 3 y = 9 Explanation: In the above program, a is an object of class A. The address of the object is assigned to integer pointer p by applying typecasting. The pointer p points to private member x. The integer value is assigned to *p, that is, x. Address of object a is increased and by accessing the memory location value 9 is assigned to y. The p– statement sets the memory location of x. Using the cout statement contains of x is displayed.Example 3: CPP // CPP Program to initialize and// display private members// using pointers#include <bits/stdc++.h>using namespace std; class A {private: int x; int y;}; class B : public A {public: int z; void show(int* k) { cout << "x = " << *k << " y = " << *(k + 1) << " z = " << *(k + 2); }}; int main(){ // object declaration B b; // pointer declaration int* p; // address of z is assigned to p p = &b.z; // initialization of z *p = 3; // points to previous location p--; // initialization of y *p = 4; // points to previous location p--; // initialization of x *p = 5; // passing address of x to function show() b.show(p); return 0;} x = 5 y = 4 z = 3 Note: In the above way of accessing private data members is not at all a recommended way of accessing members and should never be used. Also, it doesn’t mean that the encapsulation doesn’t work in C++. The idea of making private members is to avoid accidental changes. The above change to data is not accidental. It’s an intentionally written code to fool the compiler. Time Complexity : O(1) Auxiliary Space: O(1) This article is contributed by Ashish Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. auspicious_boy anshikajain26 tarakki100 cpp-class cpp-friend C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 468, "s": 54, "text": "The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Although it’s a loophole in C++, yes it’s possible through pointers." }, { "code": null, "e": 479, "s": 468, "text": "Example 1:" }, { "code": null, "e": 483, "s": 479, "text": "CPP" }, { "code": "// CPP Program to initialize the private members and display// them without using member functions #include <bits/stdc++.h>using namespace std; class Test {private: int data; public: Test() { data = 0; } int getData() { return data; }}; int main(){ Test t; int* ptr = (int*)&t; *ptr = 10; cout << t.getData(); return 0;}", "e": 828, "s": 483, "text": null }, { "code": null, "e": 831, "s": 828, "text": "10" }, { "code": null, "e": 843, "s": 831, "text": "Example 2: " }, { "code": null, "e": 847, "s": 843, "text": "CPP" }, { "code": "// CPP Program to initialize the private members and display// them without using member functions#include <bits/stdc++.h>using namespace std; class A {private: int x; int y;}; // Driver Codeint main(){ A a; int* p = (int*)&a; *p = 3; p++; *p = 9; p--; cout << endl << \"x = \" << *p; p++; cout << endl << \"y = \" << *p; return 0;}", "e": 1212, "s": 847, "text": null }, { "code": null, "e": 1224, "s": 1212, "text": "x = 3\ny = 9" }, { "code": null, "e": 1669, "s": 1224, "text": "Explanation: In the above program, a is an object of class A. The address of the object is assigned to integer pointer p by applying typecasting. The pointer p points to private member x. The integer value is assigned to *p, that is, x. Address of object a is increased and by accessing the memory location value 9 is assigned to y. The p– statement sets the memory location of x. Using the cout statement contains of x is displayed.Example 3: " }, { "code": null, "e": 1673, "s": 1669, "text": "CPP" }, { "code": "// CPP Program to initialize and// display private members// using pointers#include <bits/stdc++.h>using namespace std; class A {private: int x; int y;}; class B : public A {public: int z; void show(int* k) { cout << \"x = \" << *k << \" y = \" << *(k + 1) << \" z = \" << *(k + 2); }}; int main(){ // object declaration B b; // pointer declaration int* p; // address of z is assigned to p p = &b.z; // initialization of z *p = 3; // points to previous location p--; // initialization of y *p = 4; // points to previous location p--; // initialization of x *p = 5; // passing address of x to function show() b.show(p); return 0;}", "e": 2417, "s": 1673, "text": null }, { "code": null, "e": 2435, "s": 2417, "text": "x = 5 y = 4 z = 3" }, { "code": null, "e": 2807, "s": 2437, "text": "Note: In the above way of accessing private data members is not at all a recommended way of accessing members and should never be used. Also, it doesn’t mean that the encapsulation doesn’t work in C++. The idea of making private members is to avoid accidental changes. The above change to data is not accidental. It’s an intentionally written code to fool the compiler." }, { "code": null, "e": 2830, "s": 2807, "text": "Time Complexity : O(1)" }, { "code": null, "e": 2852, "s": 2830, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3022, "s": 2852, "text": "This article is contributed by Ashish Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3037, "s": 3022, "text": "auspicious_boy" }, { "code": null, "e": 3051, "s": 3037, "text": "anshikajain26" }, { "code": null, "e": 3062, "s": 3051, "text": "tarakki100" }, { "code": null, "e": 3072, "s": 3062, "text": "cpp-class" }, { "code": null, "e": 3083, "s": 3072, "text": "cpp-friend" }, { "code": null, "e": 3094, "s": 3083, "text": "C Language" }, { "code": null, "e": 3098, "s": 3094, "text": "C++" }, { "code": null, "e": 3102, "s": 3098, "text": "CPP" } ]
std::minmax() and std::minmax_element() in C++ STL
15 Jun, 2017 C++ defined functions to get smallest and largest elements among 2 or in a container using different functions. But there are also functions that are used to get both smallest and largest element using a single function, “minmax()” function achieves this task for us. This function is defined in “algorithm” header file. This article would deal in its implementation and other related functions. minmax(a, b): This function returns a pair, in which 1st element is of minimum of the two elements and the 2nd element is maximum of 2 elements.minmax(array of elements): This function returns similarly as 1st version. Only difference is that in this version, the accepted argument is a list of integers/strings among which maximum and minimum are obtained. Useful in cases when we need to find maximum and minimum elements in list without sorting.// C++ code to demonstrate the working of minmax() #include<iostream>#include<algorithm>using namespace std; int main(){ // declaring pair to catch the return valuepair<int, int> mnmx; // Using minmax(a, b) mnmx = minmax(53, 23); // printing minimum and maximum valuescout << "The minimum value obtained is : ";cout << mnmx.first;cout << "\nThe maximum value obtained is : ";cout << mnmx.second ; // Using minmax((array of elements) mnmx = minmax({2, 5, 1, 6, 3}); // printing minimum and maximum values.cout << "\n\nThe minimum value obtained is : ";cout << mnmx.first;cout << "\nThe maximum value obtained is : ";cout << mnmx.second; }Output:The minimum value obtained is : 23 The maximum value obtained is : 53 The minimum value obtained is : 1 The maximum value obtained is : 6 minmax_element(): This purpose of this function is same as above functions i.e to find minimum and maximum element. But it differs in return type and accepted argument. This function accepts start and end pointer as its argument and is used to find maximum and minimum element in a range. This function returns pair pointer, whose 1st element points to the position of minimum element in the range and 2nd element points to the position of maximum element in the range. If there are more than 1 minimum numbers, then the 1st element points to first occurring element. If there are more than 1 maximum numbers, then the 2nd element points to last occurring element.// C++ code to demonstrate the working of minmax_element() #include<iostream>#include<algorithm>#include<vector>using namespace std; int main(){ // initializing vector of integers vector<int> vi = { 5, 3, 4, 4, 3, 5, 3 }; // declaring pair pointer to catch the return value pair<vector<int>::iterator, vector<int>::iterator> mnmx; // using minmax_element() to find // minimum and maximum element // between 0th and 3rd number mnmx = minmax_element(vi.begin(), vi.begin() + 4); // printing position of minimum and maximum values. cout << "The minimum value position obtained is : "; cout << mnmx.first - vi.begin() << endl; cout << "The maximum value position obtained is : "; cout << mnmx.second - vi.begin() << endl; cout << endl; // using duplicated // prints 1 and 5 respectively mnmx = minmax_element(vi.begin(), vi.end()); // printing position of minimum and maximum values. cout << "The minimum value position obtained is : "; cout << mnmx.first - vi.begin() << endl; cout << "The maximum value position obtained is : "; cout << mnmx.second - vi.begin()<< endl; }Output:The minimum value position obtained is : 1 The maximum value position obtained is : 0 The minimum value position obtained is : 1 The maximum value position obtained is : 5 minmax(a, b): This function returns a pair, in which 1st element is of minimum of the two elements and the 2nd element is maximum of 2 elements. minmax(array of elements): This function returns similarly as 1st version. Only difference is that in this version, the accepted argument is a list of integers/strings among which maximum and minimum are obtained. Useful in cases when we need to find maximum and minimum elements in list without sorting.// C++ code to demonstrate the working of minmax() #include<iostream>#include<algorithm>using namespace std; int main(){ // declaring pair to catch the return valuepair<int, int> mnmx; // Using minmax(a, b) mnmx = minmax(53, 23); // printing minimum and maximum valuescout << "The minimum value obtained is : ";cout << mnmx.first;cout << "\nThe maximum value obtained is : ";cout << mnmx.second ; // Using minmax((array of elements) mnmx = minmax({2, 5, 1, 6, 3}); // printing minimum and maximum values.cout << "\n\nThe minimum value obtained is : ";cout << mnmx.first;cout << "\nThe maximum value obtained is : ";cout << mnmx.second; }Output:The minimum value obtained is : 23 The maximum value obtained is : 53 The minimum value obtained is : 1 The maximum value obtained is : 6 // C++ code to demonstrate the working of minmax() #include<iostream>#include<algorithm>using namespace std; int main(){ // declaring pair to catch the return valuepair<int, int> mnmx; // Using minmax(a, b) mnmx = minmax(53, 23); // printing minimum and maximum valuescout << "The minimum value obtained is : ";cout << mnmx.first;cout << "\nThe maximum value obtained is : ";cout << mnmx.second ; // Using minmax((array of elements) mnmx = minmax({2, 5, 1, 6, 3}); // printing minimum and maximum values.cout << "\n\nThe minimum value obtained is : ";cout << mnmx.first;cout << "\nThe maximum value obtained is : ";cout << mnmx.second; } Output: The minimum value obtained is : 23 The maximum value obtained is : 53 The minimum value obtained is : 1 The maximum value obtained is : 6 minmax_element(): This purpose of this function is same as above functions i.e to find minimum and maximum element. But it differs in return type and accepted argument. This function accepts start and end pointer as its argument and is used to find maximum and minimum element in a range. This function returns pair pointer, whose 1st element points to the position of minimum element in the range and 2nd element points to the position of maximum element in the range. If there are more than 1 minimum numbers, then the 1st element points to first occurring element. If there are more than 1 maximum numbers, then the 2nd element points to last occurring element.// C++ code to demonstrate the working of minmax_element() #include<iostream>#include<algorithm>#include<vector>using namespace std; int main(){ // initializing vector of integers vector<int> vi = { 5, 3, 4, 4, 3, 5, 3 }; // declaring pair pointer to catch the return value pair<vector<int>::iterator, vector<int>::iterator> mnmx; // using minmax_element() to find // minimum and maximum element // between 0th and 3rd number mnmx = minmax_element(vi.begin(), vi.begin() + 4); // printing position of minimum and maximum values. cout << "The minimum value position obtained is : "; cout << mnmx.first - vi.begin() << endl; cout << "The maximum value position obtained is : "; cout << mnmx.second - vi.begin() << endl; cout << endl; // using duplicated // prints 1 and 5 respectively mnmx = minmax_element(vi.begin(), vi.end()); // printing position of minimum and maximum values. cout << "The minimum value position obtained is : "; cout << mnmx.first - vi.begin() << endl; cout << "The maximum value position obtained is : "; cout << mnmx.second - vi.begin()<< endl; }Output:The minimum value position obtained is : 1 The maximum value position obtained is : 0 The minimum value position obtained is : 1 The maximum value position obtained is : 5 // C++ code to demonstrate the working of minmax_element() #include<iostream>#include<algorithm>#include<vector>using namespace std; int main(){ // initializing vector of integers vector<int> vi = { 5, 3, 4, 4, 3, 5, 3 }; // declaring pair pointer to catch the return value pair<vector<int>::iterator, vector<int>::iterator> mnmx; // using minmax_element() to find // minimum and maximum element // between 0th and 3rd number mnmx = minmax_element(vi.begin(), vi.begin() + 4); // printing position of minimum and maximum values. cout << "The minimum value position obtained is : "; cout << mnmx.first - vi.begin() << endl; cout << "The maximum value position obtained is : "; cout << mnmx.second - vi.begin() << endl; cout << endl; // using duplicated // prints 1 and 5 respectively mnmx = minmax_element(vi.begin(), vi.end()); // printing position of minimum and maximum values. cout << "The minimum value position obtained is : "; cout << mnmx.first - vi.begin() << endl; cout << "The maximum value position obtained is : "; cout << mnmx.second - vi.begin()<< endl; } Output: The minimum value position obtained is : 1 The maximum value position obtained is : 0 The minimum value position obtained is : 1 The maximum value position obtained is : 5 This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2017" }, { "code": null, "e": 448, "s": 52, "text": "C++ defined functions to get smallest and largest elements among 2 or in a container using different functions. But there are also functions that are used to get both smallest and largest element using a single function, “minmax()” function achieves this task for us. This function is defined in “algorithm” header file. This article would deal in its implementation and other related functions." }, { "code": null, "e": 3782, "s": 448, "text": "minmax(a, b): This function returns a pair, in which 1st element is of minimum of the two elements and the 2nd element is maximum of 2 elements.minmax(array of elements): This function returns similarly as 1st version. Only difference is that in this version, the accepted argument is a list of integers/strings among which maximum and minimum are obtained. Useful in cases when we need to find maximum and minimum elements in list without sorting.// C++ code to demonstrate the working of minmax() #include<iostream>#include<algorithm>using namespace std; int main(){ // declaring pair to catch the return valuepair<int, int> mnmx; // Using minmax(a, b) mnmx = minmax(53, 23); // printing minimum and maximum valuescout << \"The minimum value obtained is : \";cout << mnmx.first;cout << \"\\nThe maximum value obtained is : \";cout << mnmx.second ; // Using minmax((array of elements) mnmx = minmax({2, 5, 1, 6, 3}); // printing minimum and maximum values.cout << \"\\n\\nThe minimum value obtained is : \";cout << mnmx.first;cout << \"\\nThe maximum value obtained is : \";cout << mnmx.second; }Output:The minimum value obtained is : 23\nThe maximum value obtained is : 53\n\nThe minimum value obtained is : 1\nThe maximum value obtained is : 6\nminmax_element(): This purpose of this function is same as above functions i.e to find minimum and maximum element. But it differs in return type and accepted argument. This function accepts start and end pointer as its argument and is used to find maximum and minimum element in a range. This function returns pair pointer, whose 1st element points to the position of minimum element in the range and 2nd element points to the position of maximum element in the range. If there are more than 1 minimum numbers, then the 1st element points to first occurring element. If there are more than 1 maximum numbers, then the 2nd element points to last occurring element.// C++ code to demonstrate the working of minmax_element() #include<iostream>#include<algorithm>#include<vector>using namespace std; int main(){ // initializing vector of integers vector<int> vi = { 5, 3, 4, 4, 3, 5, 3 }; // declaring pair pointer to catch the return value pair<vector<int>::iterator, vector<int>::iterator> mnmx; // using minmax_element() to find // minimum and maximum element // between 0th and 3rd number mnmx = minmax_element(vi.begin(), vi.begin() + 4); // printing position of minimum and maximum values. cout << \"The minimum value position obtained is : \"; cout << mnmx.first - vi.begin() << endl; cout << \"The maximum value position obtained is : \"; cout << mnmx.second - vi.begin() << endl; cout << endl; // using duplicated // prints 1 and 5 respectively mnmx = minmax_element(vi.begin(), vi.end()); // printing position of minimum and maximum values. cout << \"The minimum value position obtained is : \"; cout << mnmx.first - vi.begin() << endl; cout << \"The maximum value position obtained is : \"; cout << mnmx.second - vi.begin()<< endl; }Output:The minimum value position obtained is : 1\nThe maximum value position obtained is : 0\n\nThe minimum value position obtained is : 1\nThe maximum value position obtained is : 5\n" }, { "code": null, "e": 3927, "s": 3782, "text": "minmax(a, b): This function returns a pair, in which 1st element is of minimum of the two elements and the 2nd element is maximum of 2 elements." }, { "code": null, "e": 5045, "s": 3927, "text": "minmax(array of elements): This function returns similarly as 1st version. Only difference is that in this version, the accepted argument is a list of integers/strings among which maximum and minimum are obtained. Useful in cases when we need to find maximum and minimum elements in list without sorting.// C++ code to demonstrate the working of minmax() #include<iostream>#include<algorithm>using namespace std; int main(){ // declaring pair to catch the return valuepair<int, int> mnmx; // Using minmax(a, b) mnmx = minmax(53, 23); // printing minimum and maximum valuescout << \"The minimum value obtained is : \";cout << mnmx.first;cout << \"\\nThe maximum value obtained is : \";cout << mnmx.second ; // Using minmax((array of elements) mnmx = minmax({2, 5, 1, 6, 3}); // printing minimum and maximum values.cout << \"\\n\\nThe minimum value obtained is : \";cout << mnmx.first;cout << \"\\nThe maximum value obtained is : \";cout << mnmx.second; }Output:The minimum value obtained is : 23\nThe maximum value obtained is : 53\n\nThe minimum value obtained is : 1\nThe maximum value obtained is : 6\n" }, { "code": "// C++ code to demonstrate the working of minmax() #include<iostream>#include<algorithm>using namespace std; int main(){ // declaring pair to catch the return valuepair<int, int> mnmx; // Using minmax(a, b) mnmx = minmax(53, 23); // printing minimum and maximum valuescout << \"The minimum value obtained is : \";cout << mnmx.first;cout << \"\\nThe maximum value obtained is : \";cout << mnmx.second ; // Using minmax((array of elements) mnmx = minmax({2, 5, 1, 6, 3}); // printing minimum and maximum values.cout << \"\\n\\nThe minimum value obtained is : \";cout << mnmx.first;cout << \"\\nThe maximum value obtained is : \";cout << mnmx.second; }", "e": 5713, "s": 5045, "text": null }, { "code": null, "e": 5721, "s": 5713, "text": "Output:" }, { "code": null, "e": 5861, "s": 5721, "text": "The minimum value obtained is : 23\nThe maximum value obtained is : 53\n\nThe minimum value obtained is : 1\nThe maximum value obtained is : 6\n" }, { "code": null, "e": 7934, "s": 5861, "text": "minmax_element(): This purpose of this function is same as above functions i.e to find minimum and maximum element. But it differs in return type and accepted argument. This function accepts start and end pointer as its argument and is used to find maximum and minimum element in a range. This function returns pair pointer, whose 1st element points to the position of minimum element in the range and 2nd element points to the position of maximum element in the range. If there are more than 1 minimum numbers, then the 1st element points to first occurring element. If there are more than 1 maximum numbers, then the 2nd element points to last occurring element.// C++ code to demonstrate the working of minmax_element() #include<iostream>#include<algorithm>#include<vector>using namespace std; int main(){ // initializing vector of integers vector<int> vi = { 5, 3, 4, 4, 3, 5, 3 }; // declaring pair pointer to catch the return value pair<vector<int>::iterator, vector<int>::iterator> mnmx; // using minmax_element() to find // minimum and maximum element // between 0th and 3rd number mnmx = minmax_element(vi.begin(), vi.begin() + 4); // printing position of minimum and maximum values. cout << \"The minimum value position obtained is : \"; cout << mnmx.first - vi.begin() << endl; cout << \"The maximum value position obtained is : \"; cout << mnmx.second - vi.begin() << endl; cout << endl; // using duplicated // prints 1 and 5 respectively mnmx = minmax_element(vi.begin(), vi.end()); // printing position of minimum and maximum values. cout << \"The minimum value position obtained is : \"; cout << mnmx.first - vi.begin() << endl; cout << \"The maximum value position obtained is : \"; cout << mnmx.second - vi.begin()<< endl; }Output:The minimum value position obtained is : 1\nThe maximum value position obtained is : 0\n\nThe minimum value position obtained is : 1\nThe maximum value position obtained is : 5\n" }, { "code": "// C++ code to demonstrate the working of minmax_element() #include<iostream>#include<algorithm>#include<vector>using namespace std; int main(){ // initializing vector of integers vector<int> vi = { 5, 3, 4, 4, 3, 5, 3 }; // declaring pair pointer to catch the return value pair<vector<int>::iterator, vector<int>::iterator> mnmx; // using minmax_element() to find // minimum and maximum element // between 0th and 3rd number mnmx = minmax_element(vi.begin(), vi.begin() + 4); // printing position of minimum and maximum values. cout << \"The minimum value position obtained is : \"; cout << mnmx.first - vi.begin() << endl; cout << \"The maximum value position obtained is : \"; cout << mnmx.second - vi.begin() << endl; cout << endl; // using duplicated // prints 1 and 5 respectively mnmx = minmax_element(vi.begin(), vi.end()); // printing position of minimum and maximum values. cout << \"The minimum value position obtained is : \"; cout << mnmx.first - vi.begin() << endl; cout << \"The maximum value position obtained is : \"; cout << mnmx.second - vi.begin()<< endl; }", "e": 9163, "s": 7934, "text": null }, { "code": null, "e": 9171, "s": 9163, "text": "Output:" }, { "code": null, "e": 9345, "s": 9171, "text": "The minimum value position obtained is : 1\nThe maximum value position obtained is : 0\n\nThe minimum value position obtained is : 1\nThe maximum value position obtained is : 5\n" }, { "code": null, "e": 9646, "s": 9345, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 9771, "s": 9646, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9775, "s": 9771, "text": "STL" }, { "code": null, "e": 9779, "s": 9775, "text": "C++" }, { "code": null, "e": 9783, "s": 9779, "text": "STL" }, { "code": null, "e": 9787, "s": 9783, "text": "CPP" } ]
Tailwind CSS Margin
23 Mar, 2022 This class accepts lots of values in tailwind CSS in which all the properties are covered as in the class form. It is the alternative to the CSS Margin Property. This class is used to create space around the element, outside any defined border. We can set different margins for individual sides(top, right, bottom, left). It is important to add border properties to implement margin classes. There are lots of CSS properties used for margin like CSS padding-top, CSS padding-bottom, CSS padding-right, CSS padding-left, etc. Margin Classes: m-0: This class is used to define the margin on all sides. -m-0: This class is used to define the negative margin on all the sides. my-0: This class is used to define margin on the y-axis i.e margin-top and margin-bottom. -my-0: This class is used to define negative margin on the y-axis i.e margin-top and margin-bottom. mx-0: This class is used to define margin on the x-axis i.e margin-left and margin-right. -mx-0: This class is used to add a negative margin on right. mt-0: This class is specially used to add a margin on top. -mt-0: This class is specially used to add a negative margin on top. mr-0: This class is specially used to add a margin on right. -mr-0: This class is specially used to add a negative margin on right. mb-0: This class is specially used to add a margin on the bottom. -mb-0: This class is specially used to add a negative margin on the bottom. ml-0: This class is specially used to add a margin on left. -ml-0: This class is specially used to add a negative margin on left. Note: You can change the number “0” with the valid “rem” values. m-0: This class is used to define the margin on all sides. Syntax: <element class="m-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="m-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: -m-0: This class is used to define the negative margin on all the sides. Syntax: <element class="-m-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="-m-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: my-0: This class Is used to define margin on the y-axis i.e margin-top and margin-bottom. Syntax: <element class="my-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="my-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: -my-0: This class is used to define negative margin on the y-axis i.e margin-top and margin-bottom. Syntax: <element class="-my-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="-my-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: mx-0: This class is used to define margin on the x-axis i.e margin-left and margin-right. Syntax: <element class="mx-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="mx-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: -mx-0: This class is used to define negative margin on the x-axis i.e margin-left and margin-right. Syntax: <element class="-mx-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="-mx-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: mt-0: This class is specially used to add a margin on top. Syntax: <element class="mt-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="mt-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: -mt-0: This class is specially used to add a negative margin on top. Syntax: <element class="-mt-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class="flex justify-center"> <div class="m-8 bg-green-300 w-24 h-24"> <div class="-mt-4 border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: Tailwind CSS Tailwind-Spacing Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Mar, 2022" }, { "code": null, "e": 577, "s": 52, "text": "This class accepts lots of values in tailwind CSS in which all the properties are covered as in the class form. It is the alternative to the CSS Margin Property. This class is used to create space around the element, outside any defined border. We can set different margins for individual sides(top, right, bottom, left). It is important to add border properties to implement margin classes. There are lots of CSS properties used for margin like CSS padding-top, CSS padding-bottom, CSS padding-right, CSS padding-left, etc." }, { "code": null, "e": 593, "s": 577, "text": "Margin Classes:" }, { "code": null, "e": 652, "s": 593, "text": "m-0: This class is used to define the margin on all sides." }, { "code": null, "e": 725, "s": 652, "text": "-m-0: This class is used to define the negative margin on all the sides." }, { "code": null, "e": 815, "s": 725, "text": "my-0: This class is used to define margin on the y-axis i.e margin-top and margin-bottom." }, { "code": null, "e": 915, "s": 815, "text": "-my-0: This class is used to define negative margin on the y-axis i.e margin-top and margin-bottom." }, { "code": null, "e": 1005, "s": 915, "text": "mx-0: This class is used to define margin on the x-axis i.e margin-left and margin-right." }, { "code": null, "e": 1066, "s": 1005, "text": "-mx-0: This class is used to add a negative margin on right." }, { "code": null, "e": 1125, "s": 1066, "text": "mt-0: This class is specially used to add a margin on top." }, { "code": null, "e": 1194, "s": 1125, "text": "-mt-0: This class is specially used to add a negative margin on top." }, { "code": null, "e": 1255, "s": 1194, "text": "mr-0: This class is specially used to add a margin on right." }, { "code": null, "e": 1326, "s": 1255, "text": "-mr-0: This class is specially used to add a negative margin on right." }, { "code": null, "e": 1392, "s": 1326, "text": "mb-0: This class is specially used to add a margin on the bottom." }, { "code": null, "e": 1468, "s": 1392, "text": "-mb-0: This class is specially used to add a negative margin on the bottom." }, { "code": null, "e": 1528, "s": 1468, "text": "ml-0: This class is specially used to add a margin on left." }, { "code": null, "e": 1598, "s": 1528, "text": "-ml-0: This class is specially used to add a negative margin on left." }, { "code": null, "e": 1663, "s": 1598, "text": "Note: You can change the number “0” with the valid “rem” values." }, { "code": null, "e": 1722, "s": 1663, "text": "m-0: This class is used to define the margin on all sides." }, { "code": null, "e": 1730, "s": 1722, "text": "Syntax:" }, { "code": null, "e": 1765, "s": 1730, "text": "<element class=\"m-0\">...</element>" }, { "code": null, "e": 1774, "s": 1765, "text": "Example:" }, { "code": null, "e": 1779, "s": 1774, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"m-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 2300, "s": 1779, "text": null }, { "code": null, "e": 2308, "s": 2300, "text": "Output:" }, { "code": null, "e": 2381, "s": 2308, "text": "-m-0: This class is used to define the negative margin on all the sides." }, { "code": null, "e": 2389, "s": 2381, "text": "Syntax:" }, { "code": null, "e": 2425, "s": 2389, "text": "<element class=\"-m-0\">...</element>" }, { "code": null, "e": 2434, "s": 2425, "text": "Example:" }, { "code": null, "e": 2439, "s": 2434, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"-m-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 2961, "s": 2439, "text": null }, { "code": null, "e": 2969, "s": 2961, "text": "Output:" }, { "code": null, "e": 3059, "s": 2969, "text": "my-0: This class Is used to define margin on the y-axis i.e margin-top and margin-bottom." }, { "code": null, "e": 3067, "s": 3059, "text": "Syntax:" }, { "code": null, "e": 3103, "s": 3067, "text": "<element class=\"my-0\">...</element>" }, { "code": null, "e": 3112, "s": 3103, "text": "Example:" }, { "code": null, "e": 3117, "s": 3112, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"my-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 3639, "s": 3117, "text": null }, { "code": null, "e": 3647, "s": 3639, "text": "Output:" }, { "code": null, "e": 3747, "s": 3647, "text": "-my-0: This class is used to define negative margin on the y-axis i.e margin-top and margin-bottom." }, { "code": null, "e": 3755, "s": 3747, "text": "Syntax:" }, { "code": null, "e": 3792, "s": 3755, "text": "<element class=\"-my-0\">...</element>" }, { "code": null, "e": 3801, "s": 3792, "text": "Example:" }, { "code": null, "e": 3806, "s": 3801, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"-my-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 4329, "s": 3806, "text": null }, { "code": null, "e": 4337, "s": 4329, "text": "Output:" }, { "code": null, "e": 4427, "s": 4337, "text": "mx-0: This class is used to define margin on the x-axis i.e margin-left and margin-right." }, { "code": null, "e": 4435, "s": 4427, "text": "Syntax:" }, { "code": null, "e": 4471, "s": 4435, "text": "<element class=\"mx-0\">...</element>" }, { "code": null, "e": 4480, "s": 4471, "text": "Example:" }, { "code": null, "e": 4485, "s": 4480, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"mx-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 5007, "s": 4485, "text": null }, { "code": null, "e": 5015, "s": 5007, "text": "Output:" }, { "code": null, "e": 5115, "s": 5015, "text": "-mx-0: This class is used to define negative margin on the x-axis i.e margin-left and margin-right." }, { "code": null, "e": 5123, "s": 5115, "text": "Syntax:" }, { "code": null, "e": 5160, "s": 5123, "text": "<element class=\"-mx-0\">...</element>" }, { "code": null, "e": 5169, "s": 5160, "text": "Example:" }, { "code": null, "e": 5174, "s": 5169, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"-mx-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 5697, "s": 5174, "text": null }, { "code": null, "e": 5705, "s": 5697, "text": "Output:" }, { "code": null, "e": 5764, "s": 5705, "text": "mt-0: This class is specially used to add a margin on top." }, { "code": null, "e": 5772, "s": 5764, "text": "Syntax:" }, { "code": null, "e": 5808, "s": 5772, "text": "<element class=\"mt-0\">...</element>" }, { "code": null, "e": 5817, "s": 5808, "text": "Example:" }, { "code": null, "e": 5822, "s": 5817, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"mt-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 6344, "s": 5822, "text": null }, { "code": null, "e": 6352, "s": 6344, "text": "Output:" }, { "code": null, "e": 6421, "s": 6352, "text": "-mt-0: This class is specially used to add a negative margin on top." }, { "code": null, "e": 6429, "s": 6421, "text": "Syntax:" }, { "code": null, "e": 6466, "s": 6429, "text": "<element class=\"-mt-0\">...</element>" }, { "code": null, "e": 6475, "s": 6466, "text": "Example:" }, { "code": null, "e": 6480, "s": 6475, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Margin Class</b> <div class=\"flex justify-center\"> <div class=\"m-8 bg-green-300 w-24 h-24\"> <div class=\"-mt-4 border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 7003, "s": 6480, "text": null }, { "code": null, "e": 7011, "s": 7003, "text": "Output:" }, { "code": null, "e": 7024, "s": 7011, "text": "Tailwind CSS" }, { "code": null, "e": 7041, "s": 7024, "text": "Tailwind-Spacing" }, { "code": null, "e": 7058, "s": 7041, "text": "Web Technologies" } ]
reflect.FieldByName() Function in Golang with Examples
03 May, 2020 Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByName() Function in Golang is used to get the struct field with the given name. To access this function, one needs to imports the reflect package in the program. Syntax: func (v Value) FieldByName(name string) Value Parameters: This function accept only single parameters. name: This parameter is the string type. Return Value: This function returns the struct field with the given name. Below examples illustrate the use of the above method in Golang: Example 1: // Golang program to illustrate// reflect.FieldByName() Function package main import ( "fmt" "reflect") type Struct1 struct { Var1 string Var2 string Var3 float64 Var4 float64} // Main function func main() { NewMap := make(map[string]*Struct1) NewMap["abc"] = &Struct1{"abc", "def", 1.0, 2.0} subvalMetric := "Var1" for _, Value:= range NewMap { s := reflect.ValueOf(&Value).Elem() println(s.String()) println(s.Elem().String()) // use of FieldByName() method metric := s.Elem().FieldByName(subvalMetric).Interface() fmt.Println(metric) } } Output: <*main.Struct1 Value> <main.Struct1 Value> abc Example 2: // Golang program to illustrate// reflect.FieldByName() Function package main import ( "fmt" "reflect") // Main function func main() { type t struct { N int } var n = t{76} fmt.Println(n.N) // use of FieldByName() method reflect.ValueOf(&n).Elem().FieldByName("N").SetInt(4) fmt.Println(n.N) } Output: 76 4 Golang-reflect Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2020" }, { "code": null, "e": 383, "s": 28, "text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByName() Function in Golang is used to get the struct field with the given name. To access this function, one needs to imports the reflect package in the program." }, { "code": null, "e": 391, "s": 383, "text": "Syntax:" }, { "code": null, "e": 438, "s": 391, "text": "func (v Value) FieldByName(name string) Value\n" }, { "code": null, "e": 495, "s": 438, "text": "Parameters: This function accept only single parameters." }, { "code": null, "e": 536, "s": 495, "text": "name: This parameter is the string type." }, { "code": null, "e": 610, "s": 536, "text": "Return Value: This function returns the struct field with the given name." }, { "code": null, "e": 675, "s": 610, "text": "Below examples illustrate the use of the above method in Golang:" }, { "code": null, "e": 686, "s": 675, "text": "Example 1:" }, { "code": "// Golang program to illustrate// reflect.FieldByName() Function package main import ( \"fmt\" \"reflect\") type Struct1 struct { Var1 string Var2 string Var3 float64 Var4 float64} // Main function func main() { NewMap := make(map[string]*Struct1) NewMap[\"abc\"] = &Struct1{\"abc\", \"def\", 1.0, 2.0} subvalMetric := \"Var1\" for _, Value:= range NewMap { s := reflect.ValueOf(&Value).Elem() println(s.String()) println(s.Elem().String()) // use of FieldByName() method metric := s.Elem().FieldByName(subvalMetric).Interface() fmt.Println(metric) } } ", "e": 1359, "s": 686, "text": null }, { "code": null, "e": 1367, "s": 1359, "text": "Output:" }, { "code": null, "e": 1415, "s": 1367, "text": "<*main.Struct1 Value>\n<main.Struct1 Value>\nabc\n" }, { "code": null, "e": 1426, "s": 1415, "text": "Example 2:" }, { "code": "// Golang program to illustrate// reflect.FieldByName() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { type t struct { N int } var n = t{76} fmt.Println(n.N) // use of FieldByName() method reflect.ValueOf(&n).Elem().FieldByName(\"N\").SetInt(4) fmt.Println(n.N) }", "e": 1773, "s": 1426, "text": null }, { "code": null, "e": 1781, "s": 1773, "text": "Output:" }, { "code": null, "e": 1787, "s": 1781, "text": "76\n4\n" }, { "code": null, "e": 1802, "s": 1787, "text": "Golang-reflect" }, { "code": null, "e": 1814, "s": 1802, "text": "Go Language" } ]
Writing power function for large numbers
28 May, 2021 We have given two numbers x and n which are base and exponent respectively. Write a function to compute x^n where 1 <= x, n <= 10000 and overflow may happenExamples: Input : x = 5, n = 20 Output : 95367431640625 Input : x = 2, n = 100 Output : 1267650600228229401496703205376 In the above example, 2^100 has 31 digits and it is not possible to store these digits even if we use long long int which can store maximum 18 digits. The idea behind is that multiply x, n times and store result in res[] array. Here is the algorithm for finding power of a number.Power(n) 1. Create an array res[] of MAX size and store x in res[] array and initialize res_size as the number of digits in x. 2. Do following for all numbers from i=2 to n .....Multiply x with res[] and update res[] and res_size to store the multiplication result.Multiply(res[], x) 1. Initialize carry as 0. 2. Do following for i=0 to res_size-1 ....a. Find prod = res[i]*x+carry. ....b. Store last digit of prod in res[i] and remaining digits in carry. 3. Store all digits of carry in res[] and increase res_size by number of digits. C++ Java Python3 C# PHP Javascript // C++ program to compute// factorial of big numbers#include <iostream>using namespace std; // Maximum number of digits in// output#define MAX 100000 // This function multiplies x// with the number represented by res[].// res_size is size of res[] or// number of digits in the number// represented by res[]. This function// uses simple school mathematics// for multiplication.// This function may value of res_size// and returns the new value of res_sizeint multiply(int x, int res[], int res_size) { // Initialize carryint carry = 0; // One by one multiply n with// individual digits of res[]for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10;} // Put carry in res and// increase result sizewhile (carry) { res[res_size] = carry % 10; carry = carry / 10; res_size++;}return res_size;} // This function finds// power of a number xvoid power(int x, int n){ //printing value "1" for power = 0if(n == 0 ){ cout<<"1"; return;} int res[MAX];int res_size = 0;int temp = x; // Initialize resultwhile (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10;} // Multiply x n times// (x^n = x*x*x....n times)for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); cout << x << "^" << n << " = ";for (int i = res_size - 1; i >= 0; i--) cout << res[i];} // Driver programint main() {int exponent = 100;int base = 20;power(base, exponent);return 0;} // Java program to compute// factorial of big numbersclass GFG {// Maximum number of digits in// outputstatic final int MAX = 100000; // This function multiplies x// with the number represented by res[].// res_size is size of res[] or// number of digits in the number// represented by res[]. This function// uses simple school mathematics// for multiplication.// This function may value of res_size// and returns the new value of res_sizestatic int multiply(int x, int res[], int res_size) { // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10; } // Put carry in res and // increase result size while (carry > 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size;} // This function finds// power of a number xstatic void power(int x, int n) { //printing value "1" for power = 0 if(n == 0 ){ System.out.print("1"); return;} int res[] = new int[MAX]; int res_size = 0; int temp = x; // Initialize result while (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10; } // Multiply x n times // (x^n = x*x*x....n times) for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); System.out.print(x + "^" + n + " = "); for (int i = res_size - 1; i >= 0; i--) System.out.print(res[i]);}// Driver codepublic static void main(String[] args) { int exponent = 100; int base = 2; power(base, exponent);}}// This code is contributed by Anant Agarwal. # Python program to compute# factorial of big numbers # Maximum number of digits in# outputMAX=100000 # This function multiplies x# with the number represented by res[].# res_size is size of res[] or# number of digits in the number# represented by res[]. This function# uses simple school mathematics# for multiplication.# This function may value of res_size# and returns the new value of res_sizedef multiply(x, res, res_size): # Initialize carry carry = 0 # One by one multiply n with # individual digits of res[] for i in range(res_size): prod = res[i] * x + carry # Store last digit of # 'prod' in res[] res[i] = prod % 10 # Put rest in carry carry = prod // 10 # Put carry in res and # increase result size while (carry): res[res_size] = carry % 10 carry = carry // 10 res_size+=1 return res_size # This function finds# power of a number xdef power(x,n): # printing value "1" for power = 0 if (n == 0) : print("1") return res=[0 for i in range(MAX)] res_size = 0 temp = x # Initialize result while (temp != 0): res[res_size] = temp % 10; res_size+=1 temp = temp // 10 # Multiply x n times # (x^n = x*x*x....n times) for i in range(2, n + 1): res_size = multiply(x, res, res_size) print(x , "^" , n , " = ",end="") for i in range(res_size - 1, -1, -1): print(res[i], end="") # Driver program exponent = 100base = 2power(base, exponent) # This code is contributed# by Anant Agarwal. // C# program to compute// factorial of big numbersusing System; class GFG { // Maximum number of digits in // output static int MAX = 100000; // This function multiplies x // with the number represented by res[]. // res_size is size of res[] or // number of digits in the number // represented by res[]. This function // uses simple school mathematics // for multiplication. // This function may value of res_size // and returns the new value of res_size static int multiply(int x, int []res, int res_size) { // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10; } // Put carry in res and // increase result size while (carry > 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // This function finds // power of a number x static void power(int x, int n) { //printing value "1" for power = 0 if(n == 0 ){ Console.Write("1"); return; } int []res = new int[MAX]; int res_size = 0; int temp = x; // Initialize result while (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10; } // Multiply x n times // (x^n = x*x*x....n times) for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); Console.Write(x + "^" + n + " = "); for (int i = res_size - 1; i >= 0; i--) Console.Write(res[i]); } // Driver code public static void Main() { int exponent = 100; int b_ase = 2; power(b_ase, exponent); }} // This code is contributed by vt_m. <?php// PHP program to compute// factorial of big numbers // Maximum number of// digits in output // This function multiplies// x with the number represented// by res[]. res_size is size of// res[] or number of digits in// the number represented by res[].// This function uses simple school// mathematics for multiplication.// This function may value of// res_size and returns the new// value of res_sizefunction multiply($x, $res){ // Initialize carry$carry = 0;$res_size = count($res); // One by one multiply// n with individual// digits of res[]for ($i = 0; $i < $res_size; $i++){ $prod = $res[$i] * $x + $carry; // Store last digit of // 'prod' in res[] $res[$i] = $prod % 10; // Put rest in carry $carry = (int)($prod / 10);} // Put carry in res and// increase result sizewhile ($carry){ if($carry % 10) $res[$res_size++] = $carry % 10; $carry = (int)($carry / 10);}return $res;} // This function finds// power of a number xfunction power($x, $n){ //printing value "1" for power = 0 if($n == 0 ){ echo "1"; return; }$res_size = 0;$res = array();$temp = $x; // Initialize resultwhile ($temp != 0){ $res[$res_size++] = $temp % 10; $temp = $temp / 10;} // Multiply x n times// (x^n = x*x*x....n times)for ($i = 2; $i <= $n; $i++) $res = multiply($x, $res); echo $x . "^" . $n . " = ";$O = 0;for ($i = count($res) - 1; $i >= 0; $i--, $O++)if($res[$i])break;for ($i = count($res) - $O - 1; $i >= 0; $i--) echo $res[$i];} // Driver Code$exponent = 100;$base = 2;power($base, $exponent); // This code is contributed// by mits?> <script> // Javascript program to compute// factorial of big numbers // Maximum number of digits in// outputlet MAX = 100000 // This function multiplies x// with the number represented by res[].// res_size is size of res[] or// number of digits in the number// represented by res[]. This function// uses simple school mathematics// for multiplication.// This function may value of res_size// and returns the new value of res_sizefunction multiply( x, res, res_size) { // Initialize carrylet carry = 0; // One by one multiply n with// individual digits of res[]for (let i = 0; i < res_size; i++) { let prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = Math.floor(prod / 10);} // Put carry in res and// increase result sizewhile (carry) { res[res_size] = carry % 10; carry = Math.floor(carry / 10); res_size++;}return res_size;} // This function finds// power of a number xfunction power( x, n){ //printing value "1" for power = 0if(n == 0 ){ document.write("1"); return;} let res = new Array(MAX);let res_size = 0;let temp = x; // Initialize resultwhile (temp != 0) { res[res_size++] = temp % 10; temp = Math.floor(temp / 10);} // Multiply x n times// (x^n = x*x*x....n times)for (let i = 2; i <= n; i++) res_size = multiply(x, res, res_size); document.write( x + "^" + n + " = ");for (let i = res_size - 1; i >= 0; i--) document.write(res[i]);} // Driver Code let exponent = 100;let base = 2;power(base, exponent); </script> Output: 2^100 = 1267650600228229401496703205376 Mithun Kumar AmanBhagat arorapranav23 jana_sayantan large-numbers maths-power Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 May, 2021" }, { "code": null, "e": 222, "s": 54, "text": "We have given two numbers x and n which are base and exponent respectively. Write a function to compute x^n where 1 <= x, n <= 10000 and overflow may happenExamples: " }, { "code": null, "e": 333, "s": 222, "text": "Input : x = 5, n = 20\nOutput : 95367431640625\n\nInput : x = 2, n = 100\nOutput : 1267650600228229401496703205376" }, { "code": null, "e": 1154, "s": 335, "text": "In the above example, 2^100 has 31 digits and it is not possible to store these digits even if we use long long int which can store maximum 18 digits. The idea behind is that multiply x, n times and store result in res[] array. Here is the algorithm for finding power of a number.Power(n) 1. Create an array res[] of MAX size and store x in res[] array and initialize res_size as the number of digits in x. 2. Do following for all numbers from i=2 to n .....Multiply x with res[] and update res[] and res_size to store the multiplication result.Multiply(res[], x) 1. Initialize carry as 0. 2. Do following for i=0 to res_size-1 ....a. Find prod = res[i]*x+carry. ....b. Store last digit of prod in res[i] and remaining digits in carry. 3. Store all digits of carry in res[] and increase res_size by number of digits. " }, { "code": null, "e": 1160, "s": 1156, "text": "C++" }, { "code": null, "e": 1165, "s": 1160, "text": "Java" }, { "code": null, "e": 1173, "s": 1165, "text": "Python3" }, { "code": null, "e": 1176, "s": 1173, "text": "C#" }, { "code": null, "e": 1180, "s": 1176, "text": "PHP" }, { "code": null, "e": 1191, "s": 1180, "text": "Javascript" }, { "code": "// C++ program to compute// factorial of big numbers#include <iostream>using namespace std; // Maximum number of digits in// output#define MAX 100000 // This function multiplies x// with the number represented by res[].// res_size is size of res[] or// number of digits in the number// represented by res[]. This function// uses simple school mathematics// for multiplication.// This function may value of res_size// and returns the new value of res_sizeint multiply(int x, int res[], int res_size) { // Initialize carryint carry = 0; // One by one multiply n with// individual digits of res[]for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10;} // Put carry in res and// increase result sizewhile (carry) { res[res_size] = carry % 10; carry = carry / 10; res_size++;}return res_size;} // This function finds// power of a number xvoid power(int x, int n){ //printing value \"1\" for power = 0if(n == 0 ){ cout<<\"1\"; return;} int res[MAX];int res_size = 0;int temp = x; // Initialize resultwhile (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10;} // Multiply x n times// (x^n = x*x*x....n times)for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); cout << x << \"^\" << n << \" = \";for (int i = res_size - 1; i >= 0; i--) cout << res[i];} // Driver programint main() {int exponent = 100;int base = 20;power(base, exponent);return 0;}", "e": 2711, "s": 1191, "text": null }, { "code": "// Java program to compute// factorial of big numbersclass GFG {// Maximum number of digits in// outputstatic final int MAX = 100000; // This function multiplies x// with the number represented by res[].// res_size is size of res[] or// number of digits in the number// represented by res[]. This function// uses simple school mathematics// for multiplication.// This function may value of res_size// and returns the new value of res_sizestatic int multiply(int x, int res[], int res_size) { // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10; } // Put carry in res and // increase result size while (carry > 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size;} // This function finds// power of a number xstatic void power(int x, int n) { //printing value \"1\" for power = 0 if(n == 0 ){ System.out.print(\"1\"); return;} int res[] = new int[MAX]; int res_size = 0; int temp = x; // Initialize result while (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10; } // Multiply x n times // (x^n = x*x*x....n times) for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); System.out.print(x + \"^\" + n + \" = \"); for (int i = res_size - 1; i >= 0; i--) System.out.print(res[i]);}// Driver codepublic static void main(String[] args) { int exponent = 100; int base = 2; power(base, exponent);}}// This code is contributed by Anant Agarwal.", "e": 4445, "s": 2711, "text": null }, { "code": "# Python program to compute# factorial of big numbers # Maximum number of digits in# outputMAX=100000 # This function multiplies x# with the number represented by res[].# res_size is size of res[] or# number of digits in the number# represented by res[]. This function# uses simple school mathematics# for multiplication.# This function may value of res_size# and returns the new value of res_sizedef multiply(x, res, res_size): # Initialize carry carry = 0 # One by one multiply n with # individual digits of res[] for i in range(res_size): prod = res[i] * x + carry # Store last digit of # 'prod' in res[] res[i] = prod % 10 # Put rest in carry carry = prod // 10 # Put carry in res and # increase result size while (carry): res[res_size] = carry % 10 carry = carry // 10 res_size+=1 return res_size # This function finds# power of a number xdef power(x,n): # printing value \"1\" for power = 0 if (n == 0) : print(\"1\") return res=[0 for i in range(MAX)] res_size = 0 temp = x # Initialize result while (temp != 0): res[res_size] = temp % 10; res_size+=1 temp = temp // 10 # Multiply x n times # (x^n = x*x*x....n times) for i in range(2, n + 1): res_size = multiply(x, res, res_size) print(x , \"^\" , n , \" = \",end=\"\") for i in range(res_size - 1, -1, -1): print(res[i], end=\"\") # Driver program exponent = 100base = 2power(base, exponent) # This code is contributed# by Anant Agarwal.", "e": 6029, "s": 4445, "text": null }, { "code": "// C# program to compute// factorial of big numbersusing System; class GFG { // Maximum number of digits in // output static int MAX = 100000; // This function multiplies x // with the number represented by res[]. // res_size is size of res[] or // number of digits in the number // represented by res[]. This function // uses simple school mathematics // for multiplication. // This function may value of res_size // and returns the new value of res_size static int multiply(int x, int []res, int res_size) { // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10; } // Put carry in res and // increase result size while (carry > 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // This function finds // power of a number x static void power(int x, int n) { //printing value \"1\" for power = 0 if(n == 0 ){ Console.Write(\"1\"); return; } int []res = new int[MAX]; int res_size = 0; int temp = x; // Initialize result while (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10; } // Multiply x n times // (x^n = x*x*x....n times) for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); Console.Write(x + \"^\" + n + \" = \"); for (int i = res_size - 1; i >= 0; i--) Console.Write(res[i]); } // Driver code public static void Main() { int exponent = 100; int b_ase = 2; power(b_ase, exponent); }} // This code is contributed by vt_m.", "e": 8158, "s": 6029, "text": null }, { "code": "<?php// PHP program to compute// factorial of big numbers // Maximum number of// digits in output // This function multiplies// x with the number represented// by res[]. res_size is size of// res[] or number of digits in// the number represented by res[].// This function uses simple school// mathematics for multiplication.// This function may value of// res_size and returns the new// value of res_sizefunction multiply($x, $res){ // Initialize carry$carry = 0;$res_size = count($res); // One by one multiply// n with individual// digits of res[]for ($i = 0; $i < $res_size; $i++){ $prod = $res[$i] * $x + $carry; // Store last digit of // 'prod' in res[] $res[$i] = $prod % 10; // Put rest in carry $carry = (int)($prod / 10);} // Put carry in res and// increase result sizewhile ($carry){ if($carry % 10) $res[$res_size++] = $carry % 10; $carry = (int)($carry / 10);}return $res;} // This function finds// power of a number xfunction power($x, $n){ //printing value \"1\" for power = 0 if($n == 0 ){ echo \"1\"; return; }$res_size = 0;$res = array();$temp = $x; // Initialize resultwhile ($temp != 0){ $res[$res_size++] = $temp % 10; $temp = $temp / 10;} // Multiply x n times// (x^n = x*x*x....n times)for ($i = 2; $i <= $n; $i++) $res = multiply($x, $res); echo $x . \"^\" . $n . \" = \";$O = 0;for ($i = count($res) - 1; $i >= 0; $i--, $O++)if($res[$i])break;for ($i = count($res) - $O - 1; $i >= 0; $i--) echo $res[$i];} // Driver Code$exponent = 100;$base = 2;power($base, $exponent); // This code is contributed// by mits?>", "e": 9780, "s": 8158, "text": null }, { "code": "<script> // Javascript program to compute// factorial of big numbers // Maximum number of digits in// outputlet MAX = 100000 // This function multiplies x// with the number represented by res[].// res_size is size of res[] or// number of digits in the number// represented by res[]. This function// uses simple school mathematics// for multiplication.// This function may value of res_size// and returns the new value of res_sizefunction multiply( x, res, res_size) { // Initialize carrylet carry = 0; // One by one multiply n with// individual digits of res[]for (let i = 0; i < res_size; i++) { let prod = res[i] * x + carry; // Store last digit of // 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = Math.floor(prod / 10);} // Put carry in res and// increase result sizewhile (carry) { res[res_size] = carry % 10; carry = Math.floor(carry / 10); res_size++;}return res_size;} // This function finds// power of a number xfunction power( x, n){ //printing value \"1\" for power = 0if(n == 0 ){ document.write(\"1\"); return;} let res = new Array(MAX);let res_size = 0;let temp = x; // Initialize resultwhile (temp != 0) { res[res_size++] = temp % 10; temp = Math.floor(temp / 10);} // Multiply x n times// (x^n = x*x*x....n times)for (let i = 2; i <= n; i++) res_size = multiply(x, res, res_size); document.write( x + \"^\" + n + \" = \");for (let i = res_size - 1; i >= 0; i--) document.write(res[i]);} // Driver Code let exponent = 100;let base = 2;power(base, exponent); </script>", "e": 11326, "s": 9780, "text": null }, { "code": null, "e": 11336, "s": 11326, "text": "Output: " }, { "code": null, "e": 11376, "s": 11336, "text": "2^100 = 1267650600228229401496703205376" }, { "code": null, "e": 11391, "s": 11378, "text": "Mithun Kumar" }, { "code": null, "e": 11402, "s": 11391, "text": "AmanBhagat" }, { "code": null, "e": 11416, "s": 11402, "text": "arorapranav23" }, { "code": null, "e": 11430, "s": 11416, "text": "jana_sayantan" }, { "code": null, "e": 11444, "s": 11430, "text": "large-numbers" }, { "code": null, "e": 11456, "s": 11444, "text": "maths-power" }, { "code": null, "e": 11469, "s": 11456, "text": "Mathematical" }, { "code": null, "e": 11482, "s": 11469, "text": "Mathematical" } ]
numpy.random.laplace() in Python
15 Jul, 2020 With the help of numpy.random.laplace() method, we can get the random samples of Laplace or double exponential distribution having specific mean and scale value and returns the random samples by using this method. laplace distribution Syntax : numpy.random.laplace(loc=0.0, scale=1.0, size=None) Return : Return the random samples as numpy array. Example #1 : In this example we can see that by using numpy.random.laplace() method, we are able to get the random samples of laplace or double exponential distribution and return the random samples by using this method. Python3 # import numpy import numpy as npimport matplotlib.pyplot as plt # Using numpy.random.laplace() methodgfg = np.random.laplace(1.45, 15, 1000) count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show() Output : Example #2 : Python3 # import numpy import numpy as npimport matplotlib.pyplot as plt # Using numpy.random.laplace() methodgfg = np.random.laplace(0.5, 12.45, 1000)gfg1 = np.random.laplace(gfg, 12.45, 1000) count, bins, ignored = plt.hist(gfg1, 40, density = True)plt.show() Output : Python numpy-Random 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 How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python OOPs Concepts Introduction To PYTHON Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jul, 2020" }, { "code": null, "e": 242, "s": 28, "text": "With the help of numpy.random.laplace() method, we can get the random samples of Laplace or double exponential distribution having specific mean and scale value and returns the random samples by using this method." }, { "code": null, "e": 263, "s": 242, "text": "laplace distribution" }, { "code": null, "e": 324, "s": 263, "text": "Syntax : numpy.random.laplace(loc=0.0, scale=1.0, size=None)" }, { "code": null, "e": 375, "s": 324, "text": "Return : Return the random samples as numpy array." }, { "code": null, "e": 388, "s": 375, "text": "Example #1 :" }, { "code": null, "e": 596, "s": 388, "text": "In this example we can see that by using numpy.random.laplace() method, we are able to get the random samples of laplace or double exponential distribution and return the random samples by using this method." }, { "code": null, "e": 604, "s": 596, "text": "Python3" }, { "code": "# import numpy import numpy as npimport matplotlib.pyplot as plt # Using numpy.random.laplace() methodgfg = np.random.laplace(1.45, 15, 1000) count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()", "e": 815, "s": 604, "text": null }, { "code": null, "e": 824, "s": 815, "text": "Output :" }, { "code": null, "e": 837, "s": 824, "text": "Example #2 :" }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": "# import numpy import numpy as npimport matplotlib.pyplot as plt # Using numpy.random.laplace() methodgfg = np.random.laplace(0.5, 12.45, 1000)gfg1 = np.random.laplace(gfg, 12.45, 1000) count, bins, ignored = plt.hist(gfg1, 40, density = True)plt.show()", "e": 1101, "s": 845, "text": null }, { "code": null, "e": 1110, "s": 1101, "text": "Output :" }, { "code": null, "e": 1130, "s": 1110, "text": "Python numpy-Random" }, { "code": null, "e": 1143, "s": 1130, "text": "Python-numpy" }, { "code": null, "e": 1150, "s": 1143, "text": "Python" }, { "code": null, "e": 1248, "s": 1150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1266, "s": 1248, "text": "Python Dictionary" }, { "code": null, "e": 1308, "s": 1266, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1330, "s": 1308, "text": "Enumerate() in Python" }, { "code": null, "e": 1365, "s": 1330, "text": "Read a file line by line in Python" }, { "code": null, "e": 1397, "s": 1365, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1423, "s": 1397, "text": "Python String | replace()" }, { "code": null, "e": 1452, "s": 1423, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1473, "s": 1452, "text": "Python OOPs Concepts" }, { "code": null, "e": 1496, "s": 1473, "text": "Introduction To PYTHON" } ]