title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Port Security in Computer Network
15 Mar, 2022 Attackers’ task is comparatively very easy when they can enter the network they want to attack. Ethernet LANs are very much vulnerable to attack as the switch ports are open to use by default. Various attacks such as Dos attack at layer 2, address spoofing can take place. If the administrator has control over the network then obviously the network is safe. To take total control over the switch ports, the user can use a feature called port-security. If somehow prevent an unauthorized user to use these ports, then the security will increase up to a great extent at layer 2. Users can secure a port in two steps: Limiting the number of MAC addresses to a single switch port, i.e if more than the limit, Mac addresses are learned from a single port then appropriate action will be taken.If unauthorized access is observed, the traffic should be discarded by using any of the options, or more appropriately, the user should generate a log message so that unauthorized access can be easily observed. Limiting the number of MAC addresses to a single switch port, i.e if more than the limit, Mac addresses are learned from a single port then appropriate action will be taken. If unauthorized access is observed, the traffic should be discarded by using any of the options, or more appropriately, the user should generate a log message so that unauthorized access can be easily observed. Port security – Switches learn MAC addresses when the frame is forwarded through a switch port. By using port security, users can limit the number of MAC addresses that can be learned to a port, set static MAC addresses, and set penalties for that port if it is used by an unauthorized user. Users can either use restrict, shut down or protect port-security commands. Let’s discuss these violation modes: protect – This mode drops the packets with unknown source mac addresses until you remove enough secure mac addresses to drop below the maximum value. restrict – This mode performs the same function as protecting, i.e drops packets until enough secure mac addresses are removed to drop below the maximum value. In addition to this, it will generate a log message, increment the counter value, and will also send an SNMP trap. shut down – This mode is mostly preferred as compared to other modes as it shut down the port immediately if unauthorized access is done. It will also generate a log, increment counter value, and send an SNMP trap. This port will remain in a shutdown state until the administrator will perform the β€œno shutdown” command. Sticky – This is not a violation mode. By using the sticky command, the user provides static Mac address security without typing the absolute Mac address. For example, if user provides a maximum limit of 2 then the first 2 Mac addresses learned on that port will be placed in the running configuration. After the 2nd learned Mac address, if the 3rd user wants to access then the appropriate action will be taken according to the violation mode applied. Note – The port security will work on access port only i.e to enable port security, the user first has to make it an access port. Configuration – Applying port-security on fa0/1 interface of switch .first, convert the port to an access port and will enable port-security. S1(config)#int fa0/1 S1(config-if)#switchport mode access S1(config-if)#switchport port-security Use sticky command so that it will learn the Mac address dynamically and will provide the limit and the appropriate action that should be taken. S1(config-if)#switchport port-security mac-address sticky S1(config-if)#switchport port-security maximum 2 S1(config-if)#switchport port-security violation shutdown If the user wants to provide a static entry, then configure that by starting its Mac address. S1(config-if)#switchport port-security S1(config-if)#switchport port-security violation shutdown S1(config-if)#switchport port-security mac-address aa.bb.cc.dd.ee.ff vivekpal23123451254 Pushpender007 kalrap615 23603vaibhav2021 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2022" }, { "code": null, "e": 607, "s": 28, "text": "Attackers’ task is comparatively very easy when they can enter the network they want to attack. Ethernet LANs are very much vulnerable to attack as the switch ports are open to use by default. Various attacks such as Dos attack at layer 2, address spoofing can take place. If the administrator has control over the network then obviously the network is safe. To take total control over the switch ports, the user can use a feature called port-security. If somehow prevent an unauthorized user to use these ports, then the security will increase up to a great extent at layer 2. " }, { "code": null, "e": 646, "s": 607, "text": "Users can secure a port in two steps: " }, { "code": null, "e": 1030, "s": 646, "text": "Limiting the number of MAC addresses to a single switch port, i.e if more than the limit, Mac addresses are learned from a single port then appropriate action will be taken.If unauthorized access is observed, the traffic should be discarded by using any of the options, or more appropriately, the user should generate a log message so that unauthorized access can be easily observed." }, { "code": null, "e": 1204, "s": 1030, "text": "Limiting the number of MAC addresses to a single switch port, i.e if more than the limit, Mac addresses are learned from a single port then appropriate action will be taken." }, { "code": null, "e": 1415, "s": 1204, "text": "If unauthorized access is observed, the traffic should be discarded by using any of the options, or more appropriately, the user should generate a log message so that unauthorized access can be easily observed." }, { "code": null, "e": 1784, "s": 1415, "text": "Port security – Switches learn MAC addresses when the frame is forwarded through a switch port. By using port security, users can limit the number of MAC addresses that can be learned to a port, set static MAC addresses, and set penalties for that port if it is used by an unauthorized user. Users can either use restrict, shut down or protect port-security commands. " }, { "code": null, "e": 1822, "s": 1784, "text": "Let’s discuss these violation modes: " }, { "code": null, "e": 1972, "s": 1822, "text": "protect – This mode drops the packets with unknown source mac addresses until you remove enough secure mac addresses to drop below the maximum value." }, { "code": null, "e": 2247, "s": 1972, "text": "restrict – This mode performs the same function as protecting, i.e drops packets until enough secure mac addresses are removed to drop below the maximum value. In addition to this, it will generate a log message, increment the counter value, and will also send an SNMP trap." }, { "code": null, "e": 2568, "s": 2247, "text": "shut down – This mode is mostly preferred as compared to other modes as it shut down the port immediately if unauthorized access is done. It will also generate a log, increment counter value, and send an SNMP trap. This port will remain in a shutdown state until the administrator will perform the β€œno shutdown” command." }, { "code": null, "e": 3021, "s": 2568, "text": "Sticky – This is not a violation mode. By using the sticky command, the user provides static Mac address security without typing the absolute Mac address. For example, if user provides a maximum limit of 2 then the first 2 Mac addresses learned on that port will be placed in the running configuration. After the 2nd learned Mac address, if the 3rd user wants to access then the appropriate action will be taken according to the violation mode applied." }, { "code": null, "e": 3152, "s": 3021, "text": "Note – The port security will work on access port only i.e to enable port security, the user first has to make it an access port. " }, { "code": null, "e": 3295, "s": 3152, "text": "Configuration – Applying port-security on fa0/1 interface of switch .first, convert the port to an access port and will enable port-security. " }, { "code": null, "e": 3392, "s": 3295, "text": "S1(config)#int fa0/1\nS1(config-if)#switchport mode access\nS1(config-if)#switchport port-security" }, { "code": null, "e": 3539, "s": 3392, "text": "Use sticky command so that it will learn the Mac address dynamically and will provide the limit and the appropriate action that should be taken. " }, { "code": null, "e": 3704, "s": 3539, "text": "S1(config-if)#switchport port-security mac-address sticky\nS1(config-if)#switchport port-security\nmaximum 2\nS1(config-if)#switchport port-security violation shutdown" }, { "code": null, "e": 3800, "s": 3704, "text": "If the user wants to provide a static entry, then configure that by starting its Mac address. " }, { "code": null, "e": 3967, "s": 3800, "text": "S1(config-if)#switchport port-security \nS1(config-if)#switchport port-security violation shutdown\nS1(config-if)#switchport port-security mac-address aa.bb.cc.dd.ee.ff" }, { "code": null, "e": 3989, "s": 3969, "text": "vivekpal23123451254" }, { "code": null, "e": 4003, "s": 3989, "text": "Pushpender007" }, { "code": null, "e": 4013, "s": 4003, "text": "kalrap615" }, { "code": null, "e": 4030, "s": 4013, "text": "23603vaibhav2021" }, { "code": null, "e": 4048, "s": 4030, "text": "Computer Networks" }, { "code": null, "e": 4066, "s": 4048, "text": "Computer Networks" } ]
Avoid wrapping flex-items in Bootstrap
Use the flex-nowrap class in Bootstrap 4 to avoid wrapping the flex items. Here you can see the difference between wrap and nowrap βˆ’ Above the flex-items are not wrapped. This is achieved using the flex-nowrap class in Bootstrap 4 βˆ’ <div class="d-flex flex-nowrap bg-primary"> <div class="p-2 border">One</div> <div class="p-2 border">Two</div> <div class="p-2 border">Three</div> <div class="p-2 border">Four</div> <div class="p-2 border">Five</div> <div class="p-2 border">Six</div> <div class="p-2 border">Seven</div> <div class="p-2 border">Eight</div> <div class="p-2 border">Nine</div> </div> The following is an example to avoid wrapping flex items βˆ’ Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-3"> <h3>FLEX WRAP AND NOWRAP</h3> <p>Flex items will wrap</p> <div class="d-flex flex-wrap bg-primary"> <div class="p-2 border">One</div> <div class="p-2 border">Two</div> <div class="p-2 border">Three</div> <div class="p-2 border">Four</div> <div class="p-2 border">Five</div> <div class="p-2 border">Six</div> <div class="p-2 border">Seven</div> <div class="p-2 border">Eight</div> <div class="p-2 border">Nine</div> </div><br> <p>Flex items won't wrap</p> <div class="d-flex flex-nowrap bg-primary"> <div class="p-2 border">One</div> <div class="p-2 border">Two</div> <div class="p-2 border">Three</div> <div class="p-2 border">Four</div> <div class="p-2 border">Five</div> <div class="p-2 border">Six</div> <div class="p-2 border">Seven</div> <div class="p-2 border">Eight</div> <div class="p-2 border">Nine</div> </div><br> </div> </body> </html>
[ { "code": null, "e": 1262, "s": 1187, "text": "Use the flex-nowrap class in Bootstrap 4 to avoid wrapping the flex items." }, { "code": null, "e": 1320, "s": 1262, "text": "Here you can see the difference between wrap and nowrap βˆ’" }, { "code": null, "e": 1420, "s": 1320, "text": "Above the flex-items are not wrapped. This is achieved using the flex-nowrap class in Bootstrap 4 βˆ’" }, { "code": null, "e": 1804, "s": 1420, "text": "<div class=\"d-flex flex-nowrap bg-primary\">\n <div class=\"p-2 border\">One</div>\n <div class=\"p-2 border\">Two</div>\n <div class=\"p-2 border\">Three</div>\n <div class=\"p-2 border\">Four</div>\n <div class=\"p-2 border\">Five</div>\n <div class=\"p-2 border\">Six</div>\n <div class=\"p-2 border\">Seven</div>\n <div class=\"p-2 border\">Eight</div>\n <div class=\"p-2 border\">Nine</div>\n</div>" }, { "code": null, "e": 1863, "s": 1804, "text": "The following is an example to avoid wrapping flex items βˆ’" }, { "code": null, "e": 1873, "s": 1863, "text": "Live Demo" }, { "code": null, "e": 3380, "s": 1873, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container mt-3\">\n <h3>FLEX WRAP AND NOWRAP</h3>\n <p>Flex items will wrap</p>\n <div class=\"d-flex flex-wrap bg-primary\">\n <div class=\"p-2 border\">One</div>\n <div class=\"p-2 border\">Two</div>\n <div class=\"p-2 border\">Three</div>\n <div class=\"p-2 border\">Four</div>\n <div class=\"p-2 border\">Five</div>\n <div class=\"p-2 border\">Six</div>\n <div class=\"p-2 border\">Seven</div>\n <div class=\"p-2 border\">Eight</div>\n <div class=\"p-2 border\">Nine</div>\n </div><br>\n <p>Flex items won't wrap</p>\n <div class=\"d-flex flex-nowrap bg-primary\">\n <div class=\"p-2 border\">One</div>\n <div class=\"p-2 border\">Two</div>\n <div class=\"p-2 border\">Three</div>\n <div class=\"p-2 border\">Four</div>\n <div class=\"p-2 border\">Five</div>\n <div class=\"p-2 border\">Six</div>\n <div class=\"p-2 border\">Seven</div>\n <div class=\"p-2 border\">Eight</div>\n <div class=\"p-2 border\">Nine</div>\n </div><br>\n </div>\n</body>\n</html>" } ]
Remove duplicates from sorted array
04 Jul, 2022 Given a sorted array, the task is to remove the duplicate elements from the array.Examples: Input : arr[] = {2, 2, 2, 2, 2} Output : arr[] = {2} new size = 1 Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output : arr[] = {1, 2, 3, 4, 5} new size = 5 Method 1: (Using extra space) Create an auxiliary array temp[] to store unique elements.Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of unique elements. Let this count be j.Copy j elements from temp[] to arr[] and return j Create an auxiliary array temp[] to store unique elements. Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of unique elements. Let this count be j. Copy j elements from temp[] to arr[] and return j C++ C Java Python3 C# Javascript // Simple C++ program to remove duplicates#include <iostream>using namespace std; // Function to remove duplicate elements This function// returns new size of modified array.int removeDuplicates(int arr[], int n){ // Return, if array is empty or contains a single // element if (n == 0 || n == 1) return n; int temp[n]; // Start traversing elements int j = 0; // If current element is not equal to next element // then store that current element for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) temp[j++] = arr[i]; // Store the last element as whether it is unique or // repeated, it hasn't stored previously temp[j++] = arr[n - 1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // removeDuplicates() returns new size of array. n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Simple C program to remove duplicates#include <stdio.h> // Function to remove duplicate elements This function// returns new size of modified array.int removeDuplicates(int arr[], int n){ // Return, if array is empty or contains a single // element if (n == 0 || n == 1) return n; int temp[n]; // Start traversing elements int j = 0; // If current element is not equal to next element // then store that current element for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) temp[j++] = arr[i]; // Store the last element as whether it is unique or // repeated, it hasn't stored previously temp[j++] = arr[n - 1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // removeDuplicates() returns new size of array. n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // simple java program to remove duplicates class Main { // Function to remove duplicate elements This function // returns new size of modified array. static int removeDuplicates(int arr[], int n) { // Return, if array is empty or contains a single // element if (n == 0 || n == 1) return n; int[] temp = new int[n]; // Start traversing elements int j = 0; for (int i = 0; i < n - 1; i++) // If current element is not equal to next // element then store that current element if (arr[i] != arr[i + 1]) temp[j++] = arr[i]; // Store the last element as whether it is unique or // repeated, it hasn't stored previously temp[j++] = arr[n - 1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j; } public static void main(String[] args) { int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }; int n = arr.length; n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 program to# remove duplicates# Function to remove# duplicate elements # This function returns# new size of modified# array.def removeDuplicates(arr, n): # Return, if array is # empty or contains # a single element if n == 0 or n == 1: return n temp = list(range(n)) # Start traversing elements j = 0; for i in range(0, n-1): # If current element is # not equal to next # element then store that # current element if arr[i] != arr[i+1]: temp[j] = arr[i] j += 1 # Store the last element # as whether it is unique # or repeated, it hasn't # stored previously temp[j] = arr[n-1] j += 1 # Modify original array for i in range(0, j): arr[i] = temp[i] return j # Driver codearr = [1, 2, 2, 3, 4, 4, 4, 5, 5]n = len(arr) # removeDuplicates() returns# new size of array.n = removeDuplicates(arr, n) # Print updated arrayfor i in range(n): print ("%d"%(arr[i]), end = " ") // Simple C# program to remove// duplicatesusing System; class GFG { // Function to remove duplicate // elements This function returns // new size of modified array. static int removeDuplicates(int []arr, int n) { // Return, if array is empty // or contains a single element if (n == 0 || n == 1) return n; int []temp = new int[n]; // Start traversing elements int j = 0; for (int i = 0; i < n - 1; i++) // If current element is not equal // to next element then store that // current element if (arr[i] != arr[i+1]) temp[j++] = arr[i]; // Store the last element as // whether it is unique or // repeated, it hasn't // stored previously temp[j++] = arr[n-1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j; } public static void Main () { int []arr = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = arr.Length; n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by nitin mittal. <script> // Simple JavaScript program to remove// duplicates // Function to remove duplicate elements// This function returns new size of modified// array.function removeDuplicates(arr, n){ // Return, if array is empty // or contains a single element if (n==0 || n==1) return n; var temp = new Array(n); // Start traversing elements var j = 0; for (var i=0; i<n-1; i++) // If current element is not equal // to next element then store that // current element if (arr[i] != arr[i+1]) temp[j++] = arr[i]; // Store the last element as whether // it is unique or repeated, it hasn't // stored previously temp[j++] = arr[n-1]; // Modify original array for (var i=0; i<j; i++) arr[i] = temp[i]; return j;} var arr = [1, 2, 2, 3, 4, 4, 4, 5, 5]; var n = arr.length; // removeDuplicates() returns new size of // array. n = removeDuplicates(arr, n); // Print updated array for (var i=0; i<n; i++) document.write( arr[i]+" "); // This code is contributed by SoumikMondal </script> Output: 1 2 3 4 5 Time Complexity : O(n) Auxiliary Space : O(n)Method 2: (Constant extra space) Just maintain a separate index for same array as maintained for different array in Method 1. C++ Java C# Javascript // C++ program to remove duplicates in-place#include<iostream>using namespace std; // Function to remove duplicate elements// This function returns new size of modified// array.int removeDuplicates(int arr[], int n){ if (n==0 || n==1) return n; // To store index of next unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (int i=0; i < n-1; i++) if (arr[i] != arr[i+1]) arr[j++] = arr[i]; arr[j++] = arr[n-1]; return j;} // Driver codeint main(){ int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = sizeof(arr) / sizeof(arr[0]); // removeDuplicates() returns new size of // array. n = removeDuplicates(arr, n); // Print updated array for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;} // simple java program to remove// duplicates class Main{ // Function to remove duplicate elements // This function returns new size of modified // array. static int removeDuplicates(int arr[], int n) { if (n == 0 || n == 1) return n; // To store index of next unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (int i = 0; i < n-1; i++) if (arr[i] != arr[i+1]) arr[j++] = arr[i]; arr[j++] = arr[n-1]; return j; } public static void main (String[] args) { int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = arr.length; n = removeDuplicates(arr, n); // Print updated array for (int i=0; i<n; i++) System.out.print(arr[i]+" "); }} /* This code is contributed by Harsh Agarwal */ Python3 # Python3 program to remove # duplicate elements # This function returns new # size of modified array def removeDuplicates(arr, n): if n == 0 or n == 1: return n # To store index of next # unique element j = 0 # Doing same as done # in Method 1 Just # maintaining another # updated index i.e. j for i in range(0, n-1): if arr[i] != arr[i+1]: arr[j] = arr[i] j += 1 arr[j] = arr[n-1] j += 1 return j # Driver code arr = [1, 2, 2, 3, 4, 4, 4, 5, 5] n = len(arr) # removeDuplicates() returns # new size of array. n = removeDuplicates(arr, n) # Print updated array for i in range(0, n): print (" %d "%(arr[i]), end = " ") // simple C# program to remove// duplicatesusing System; class GfG { // Function to remove duplicate // elements This function returns // new size of modified array. static int removeDuplicates(int []arr, int n) { if (n == 0 || n == 1) return n; // To store index of next // unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated // index i.e. j for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) arr[j++] = arr[i]; arr[j++] = arr[n - 1]; return j; } public static void Main () { int []arr = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = arr.Length; n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by parashar. <script>// simple javascript program to remove// duplicates // Function to remove duplicate elements // This function returns new size of modified // array. function removeDuplicates(arr , n) { if (n == 0 || n == 1) return n; // To store index of next unique element var j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) arr[j++] = arr[i]; arr[j++] = arr[n - 1]; return j; } var arr = [ 1, 2, 2, 3, 4, 4, 4, 5, 5 ]; var n = arr.length; n = removeDuplicates(arr, n); // Print updated array for (i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by umadevi9616 </script> Output: 1 2 3 4 5 Time Complexity : O(n) Auxiliary Space : O(1)This article is contributed by Sahil Chhabra. 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. parashar nitin mittal SoumikMondal umadevi9616 arorakashish0911 adityakumar129 Morgan Stanley Wipro Xome Zoho Arrays Zoho Morgan Stanley Wipro Xome 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 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 146, "s": 52, "text": "Given a sorted array, the task is to remove the duplicate elements from the array.Examples: " }, { "code": null, "e": 323, "s": 146, "text": "Input : arr[] = {2, 2, 2, 2, 2}\nOutput : arr[] = {2}\n new size = 1\n\nInput : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}\nOutput : arr[] = {1, 2, 3, 4, 5}\n new size = 5" }, { "code": null, "e": 357, "s": 325, "text": "Method 1: (Using extra space) " }, { "code": null, "e": 607, "s": 357, "text": "Create an auxiliary array temp[] to store unique elements.Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of unique elements. Let this count be j.Copy j elements from temp[] to arr[] and return j" }, { "code": null, "e": 666, "s": 607, "text": "Create an auxiliary array temp[] to store unique elements." }, { "code": null, "e": 809, "s": 666, "text": "Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of unique elements. Let this count be j." }, { "code": null, "e": 859, "s": 809, "text": "Copy j elements from temp[] to arr[] and return j" }, { "code": null, "e": 865, "s": 861, "text": "C++" }, { "code": null, "e": 867, "s": 865, "text": "C" }, { "code": null, "e": 872, "s": 867, "text": "Java" }, { "code": null, "e": 880, "s": 872, "text": "Python3" }, { "code": null, "e": 883, "s": 880, "text": "C#" }, { "code": null, "e": 894, "s": 883, "text": "Javascript" }, { "code": "// Simple C++ program to remove duplicates#include <iostream>using namespace std; // Function to remove duplicate elements This function// returns new size of modified array.int removeDuplicates(int arr[], int n){ // Return, if array is empty or contains a single // element if (n == 0 || n == 1) return n; int temp[n]; // Start traversing elements int j = 0; // If current element is not equal to next element // then store that current element for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) temp[j++] = arr[i]; // Store the last element as whether it is unique or // repeated, it hasn't stored previously temp[j++] = arr[n - 1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // removeDuplicates() returns new size of array. n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2074, "s": 894, "text": null }, { "code": "// Simple C program to remove duplicates#include <stdio.h> // Function to remove duplicate elements This function// returns new size of modified array.int removeDuplicates(int arr[], int n){ // Return, if array is empty or contains a single // element if (n == 0 || n == 1) return n; int temp[n]; // Start traversing elements int j = 0; // If current element is not equal to next element // then store that current element for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) temp[j++] = arr[i]; // Store the last element as whether it is unique or // repeated, it hasn't stored previously temp[j++] = arr[n - 1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // removeDuplicates() returns new size of array. n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3229, "s": 2074, "text": null }, { "code": "// simple java program to remove duplicates class Main { // Function to remove duplicate elements This function // returns new size of modified array. static int removeDuplicates(int arr[], int n) { // Return, if array is empty or contains a single // element if (n == 0 || n == 1) return n; int[] temp = new int[n]; // Start traversing elements int j = 0; for (int i = 0; i < n - 1; i++) // If current element is not equal to next // element then store that current element if (arr[i] != arr[i + 1]) temp[j++] = arr[i]; // Store the last element as whether it is unique or // repeated, it hasn't stored previously temp[j++] = arr[n - 1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j; } public static void main(String[] args) { int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }; int n = arr.length; n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4481, "s": 3229, "text": null }, { "code": "# Python3 program to# remove duplicates# Function to remove# duplicate elements # This function returns# new size of modified# array.def removeDuplicates(arr, n): # Return, if array is # empty or contains # a single element if n == 0 or n == 1: return n temp = list(range(n)) # Start traversing elements j = 0; for i in range(0, n-1): # If current element is # not equal to next # element then store that # current element if arr[i] != arr[i+1]: temp[j] = arr[i] j += 1 # Store the last element # as whether it is unique # or repeated, it hasn't # stored previously temp[j] = arr[n-1] j += 1 # Modify original array for i in range(0, j): arr[i] = temp[i] return j # Driver codearr = [1, 2, 2, 3, 4, 4, 4, 5, 5]n = len(arr) # removeDuplicates() returns# new size of array.n = removeDuplicates(arr, n) # Print updated arrayfor i in range(n): print (\"%d\"%(arr[i]), end = \" \")", "e": 5502, "s": 4481, "text": null }, { "code": "// Simple C# program to remove// duplicatesusing System; class GFG { // Function to remove duplicate // elements This function returns // new size of modified array. static int removeDuplicates(int []arr, int n) { // Return, if array is empty // or contains a single element if (n == 0 || n == 1) return n; int []temp = new int[n]; // Start traversing elements int j = 0; for (int i = 0; i < n - 1; i++) // If current element is not equal // to next element then store that // current element if (arr[i] != arr[i+1]) temp[j++] = arr[i]; // Store the last element as // whether it is unique or // repeated, it hasn't // stored previously temp[j++] = arr[n-1]; // Modify original array for (int i = 0; i < j; i++) arr[i] = temp[i]; return j; } public static void Main () { int []arr = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = arr.Length; n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by nitin mittal.", "e": 6852, "s": 5502, "text": null }, { "code": "<script> // Simple JavaScript program to remove// duplicates // Function to remove duplicate elements// This function returns new size of modified// array.function removeDuplicates(arr, n){ // Return, if array is empty // or contains a single element if (n==0 || n==1) return n; var temp = new Array(n); // Start traversing elements var j = 0; for (var i=0; i<n-1; i++) // If current element is not equal // to next element then store that // current element if (arr[i] != arr[i+1]) temp[j++] = arr[i]; // Store the last element as whether // it is unique or repeated, it hasn't // stored previously temp[j++] = arr[n-1]; // Modify original array for (var i=0; i<j; i++) arr[i] = temp[i]; return j;} var arr = [1, 2, 2, 3, 4, 4, 4, 5, 5]; var n = arr.length; // removeDuplicates() returns new size of // array. n = removeDuplicates(arr, n); // Print updated array for (var i=0; i<n; i++) document.write( arr[i]+\" \"); // This code is contributed by SoumikMondal </script>", "e": 7963, "s": 6852, "text": null }, { "code": null, "e": 7973, "s": 7963, "text": "Output: " }, { "code": null, "e": 7983, "s": 7973, "text": "1 2 3 4 5" }, { "code": null, "e": 8155, "s": 7983, "text": "Time Complexity : O(n) Auxiliary Space : O(n)Method 2: (Constant extra space) Just maintain a separate index for same array as maintained for different array in Method 1. " }, { "code": null, "e": 8159, "s": 8155, "text": "C++" }, { "code": null, "e": 8164, "s": 8159, "text": "Java" }, { "code": null, "e": 8167, "s": 8164, "text": "C#" }, { "code": null, "e": 8178, "s": 8167, "text": "Javascript" }, { "code": "// C++ program to remove duplicates in-place#include<iostream>using namespace std; // Function to remove duplicate elements// This function returns new size of modified// array.int removeDuplicates(int arr[], int n){ if (n==0 || n==1) return n; // To store index of next unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (int i=0; i < n-1; i++) if (arr[i] != arr[i+1]) arr[j++] = arr[i]; arr[j++] = arr[n-1]; return j;} // Driver codeint main(){ int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = sizeof(arr) / sizeof(arr[0]); // removeDuplicates() returns new size of // array. n = removeDuplicates(arr, n); // Print updated array for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}", "e": 9025, "s": 8178, "text": null }, { "code": "// simple java program to remove// duplicates class Main{ // Function to remove duplicate elements // This function returns new size of modified // array. static int removeDuplicates(int arr[], int n) { if (n == 0 || n == 1) return n; // To store index of next unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (int i = 0; i < n-1; i++) if (arr[i] != arr[i+1]) arr[j++] = arr[i]; arr[j++] = arr[n-1]; return j; } public static void main (String[] args) { int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = arr.length; n = removeDuplicates(arr, n); // Print updated array for (int i=0; i<n; i++) System.out.print(arr[i]+\" \"); }} /* This code is contributed by Harsh Agarwal */", "e": 9977, "s": 9025, "text": null }, { "code": null, "e": 9986, "s": 9977, "text": "Python3 " }, { "code": null, "e": 10707, "s": 9986, "text": "\n# Python3 program to remove\n# duplicate elements\n\n# This function returns new \n# size of modified array\ndef removeDuplicates(arr, n):\n if n == 0 or n == 1:\n return n\n\n # To store index of next\n # unique element\n j = 0\n\n # Doing same as done\n # in Method 1 Just\n # maintaining another \n # updated index i.e. j\n for i in range(0, n-1):\n if arr[i] != arr[i+1]:\n arr[j] = arr[i]\n j += 1\n\n arr[j] = arr[n-1]\n j += 1\n return j\n\n# Driver code\narr = [1, 2, 2, 3, 4, 4, 4, 5, 5]\nn = len(arr)\n\n# removeDuplicates() returns\n# new size of array.\nn = removeDuplicates(arr, n)\n\n# Print updated array\nfor i in range(0, n):\n print (\" %d \"%(arr[i]), end = \" \")\n" }, { "code": "// simple C# program to remove// duplicatesusing System; class GfG { // Function to remove duplicate // elements This function returns // new size of modified array. static int removeDuplicates(int []arr, int n) { if (n == 0 || n == 1) return n; // To store index of next // unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated // index i.e. j for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) arr[j++] = arr[i]; arr[j++] = arr[n - 1]; return j; } public static void Main () { int []arr = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n = arr.Length; n = removeDuplicates(arr, n); // Print updated array for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by parashar.", "e": 11724, "s": 10707, "text": null }, { "code": "<script>// simple javascript program to remove// duplicates // Function to remove duplicate elements // This function returns new size of modified // array. function removeDuplicates(arr , n) { if (n == 0 || n == 1) return n; // To store index of next unique element var j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (i = 0; i < n - 1; i++) if (arr[i] != arr[i + 1]) arr[j++] = arr[i]; arr[j++] = arr[n - 1]; return j; } var arr = [ 1, 2, 2, 3, 4, 4, 4, 5, 5 ]; var n = arr.length; n = removeDuplicates(arr, n); // Print updated array for (i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by umadevi9616 </script>", "e": 12591, "s": 11724, "text": null }, { "code": null, "e": 12601, "s": 12591, "text": "Output: " }, { "code": null, "e": 12611, "s": 12601, "text": "1 2 3 4 5" }, { "code": null, "e": 13078, "s": 12611, "text": "Time Complexity : O(n) Auxiliary Space : O(1)This article is contributed by Sahil Chhabra. 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": 13087, "s": 13078, "text": "parashar" }, { "code": null, "e": 13100, "s": 13087, "text": "nitin mittal" }, { "code": null, "e": 13113, "s": 13100, "text": "SoumikMondal" }, { "code": null, "e": 13125, "s": 13113, "text": "umadevi9616" }, { "code": null, "e": 13142, "s": 13125, "text": "arorakashish0911" }, { "code": null, "e": 13157, "s": 13142, "text": "adityakumar129" }, { "code": null, "e": 13172, "s": 13157, "text": "Morgan Stanley" }, { "code": null, "e": 13178, "s": 13172, "text": "Wipro" }, { "code": null, "e": 13183, "s": 13178, "text": "Xome" }, { "code": null, "e": 13188, "s": 13183, "text": "Zoho" }, { "code": null, "e": 13195, "s": 13188, "text": "Arrays" }, { "code": null, "e": 13200, "s": 13195, "text": "Zoho" }, { "code": null, "e": 13215, "s": 13200, "text": "Morgan Stanley" }, { "code": null, "e": 13221, "s": 13215, "text": "Wipro" }, { "code": null, "e": 13226, "s": 13221, "text": "Xome" }, { "code": null, "e": 13233, "s": 13226, "text": "Arrays" }, { "code": null, "e": 13331, "s": 13233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13399, "s": 13331, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 13443, "s": 13399, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 13475, "s": 13443, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 13523, "s": 13475, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 13537, "s": 13523, "text": "Linear Search" }, { "code": null, "e": 13622, "s": 13537, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 13645, "s": 13622, "text": "Introduction to Arrays" }, { "code": null, "e": 13701, "s": 13645, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 13728, "s": 13701, "text": "Subset Sum Problem | DP-25" } ]
How to display confirmation dialog when clicking an <a> link using JavaScript / jQuery ?
03 Aug, 2021 Given <a> element and the task is to display the confirmation message when clicking the <a> link, with the help of JavaScript and jQuery. Display confirmation dialog when clicking an <a> link using JavaScript onclick Event: This event occurs when the user clicks on an element.Syntax:In HTML:<element onclick="myScript">In JavaScript:object.addEventListener("click", myScript);In JavaScript, using the addEventListener() method:object.onclick = function() {myScript}; Syntax: In HTML:<element onclick="myScript"> <element onclick="myScript"> In JavaScript:object.addEventListener("click", myScript); object.addEventListener("click", myScript); In JavaScript, using the addEventListener() method:object.onclick = function() {myScript}; object.onclick = function() {myScript}; addEventListener() Method: This method adds an event handler to the document.Syntax:document.addEventListener(event, function, useCapture)Parameters:event: This parameter is required. It specifies the string, the name of the event.function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the β€œclick” event belongs to the MouseEvent object.useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase. Syntax: document.addEventListener(event, function, useCapture) Parameters: event: This parameter is required. It specifies the string, the name of the event. function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the β€œclick” event belongs to the MouseEvent object. useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase. true: The event handler is executed in the capturing phase. false: The event handler is executed in the bubbling phase. Example 1: This example adds a confirm() method to the link with onclick event. This will verify whether you want to proceed or not. <!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <a href="#" onclick="return confirm('Are you sure?')"> Link </a> <br><br> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "Click on the LINK for further confirmation."; </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds a class confirm to all link. After this, it adds the EventListener to the elements of that class, on onclick event. Then it calls a method to separately handle the confirm dialog. <!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <a href="#" class="confirm">Link</a> <br><br> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "Click on the LINK for further confirmation."; var el = document.getElementsByClassName('confirm'); var confirmThis = function (e) { if (!confirm('Are you sure?')) e.preventDefault(); }; for (var i = 0, l = el.length; i < l; i++) { el[i].addEventListener('click', confirmThis, false); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Display confirmation dialog when clicking an <a> link using jQuery jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. Syntax: $(selector).on(event, childSelector, data, function, map) Parameters: event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid. childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements. data: This parameter is optional. It specifies additional data to pass to the function. function: This parameter is required. It specifies the function to run when the event occurs. map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. Example 1: This example adds a class confirm to the all link. After this, It adds the EventListener to the elements of that class, on onclick event. Then it calls the confirm dialog. <!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <a href="#" class="confirm">Link</a> <br><br> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $("#GFG_UP"). text("Click on the LINK for further confirmation."); $('.confirm').on('click', function () { return confirm('Are you sure?'); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds a confirm() method to the link with onclick event. This will verify whether you want to proceed or not. <!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <a href="#" onclick="return confirm('Are you sure?')"> Link </a> <br><br> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $("#GFG_UP"). text("Click on the LINK for further confirmation."); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of β€œWrite less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. JavaScript JQuery Web Technologies Web technologies Questions 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 166, "s": 28, "text": "Given <a> element and the task is to display the confirmation message when clicking the <a> link, with the help of JavaScript and jQuery." }, { "code": null, "e": 237, "s": 166, "text": "Display confirmation dialog when clicking an <a> link using JavaScript" }, { "code": null, "e": 496, "s": 237, "text": "onclick Event: This event occurs when the user clicks on an element.Syntax:In HTML:<element onclick=\"myScript\">In JavaScript:object.addEventListener(\"click\", myScript);In JavaScript, using the addEventListener() method:object.onclick = function() {myScript};" }, { "code": null, "e": 504, "s": 496, "text": "Syntax:" }, { "code": null, "e": 541, "s": 504, "text": "In HTML:<element onclick=\"myScript\">" }, { "code": null, "e": 570, "s": 541, "text": "<element onclick=\"myScript\">" }, { "code": null, "e": 628, "s": 570, "text": "In JavaScript:object.addEventListener(\"click\", myScript);" }, { "code": null, "e": 672, "s": 628, "text": "object.addEventListener(\"click\", myScript);" }, { "code": null, "e": 763, "s": 672, "text": "In JavaScript, using the addEventListener() method:object.onclick = function() {myScript};" }, { "code": null, "e": 803, "s": 763, "text": "object.onclick = function() {myScript};" }, { "code": null, "e": 1601, "s": 803, "text": "addEventListener() Method: This method adds an event handler to the document.Syntax:document.addEventListener(event, function, useCapture)Parameters:event: This parameter is required. It specifies the string, the name of the event.function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the β€œclick” event belongs to the MouseEvent object.useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase." }, { "code": null, "e": 1609, "s": 1601, "text": "Syntax:" }, { "code": null, "e": 1664, "s": 1609, "text": "document.addEventListener(event, function, useCapture)" }, { "code": null, "e": 1676, "s": 1664, "text": "Parameters:" }, { "code": null, "e": 1759, "s": 1676, "text": "event: This parameter is required. It specifies the string, the name of the event." }, { "code": null, "e": 2048, "s": 1759, "text": "function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the β€œclick” event belongs to the MouseEvent object." }, { "code": null, "e": 2327, "s": 2048, "text": "useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase." }, { "code": null, "e": 2387, "s": 2327, "text": "true: The event handler is executed in the capturing phase." }, { "code": null, "e": 2447, "s": 2387, "text": "false: The event handler is executed in the bubbling phase." }, { "code": null, "e": 2580, "s": 2447, "text": "Example 1: This example adds a confirm() method to the link with onclick event. This will verify whether you want to proceed or not." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <a href=\"#\" onclick=\"return confirm('Are you sure?')\"> Link </a> <br><br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"Click on the LINK for further confirmation.\"; </script> </body> </html> ", "e": 3469, "s": 2580, "text": null }, { "code": null, "e": 3477, "s": 3469, "text": "Output:" }, { "code": null, "e": 3508, "s": 3477, "text": "Before clicking on the button:" }, { "code": null, "e": 3538, "s": 3508, "text": "After clicking on the button:" }, { "code": null, "e": 3747, "s": 3538, "text": "Example 2: This example adds a class confirm to all link. After this, it adds the EventListener to the elements of that class, on onclick event. Then it calls a method to separately handle the confirm dialog." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <a href=\"#\" class=\"confirm\">Link</a> <br><br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"Click on the LINK for further confirmation.\"; var el = document.getElementsByClassName('confirm'); var confirmThis = function (e) { if (!confirm('Are you sure?')) e.preventDefault(); }; for (var i = 0, l = el.length; i < l; i++) { el[i].addEventListener('click', confirmThis, false); } </script> </body> </html> ", "e": 4963, "s": 3747, "text": null }, { "code": null, "e": 4971, "s": 4963, "text": "Output:" }, { "code": null, "e": 5002, "s": 4971, "text": "Before clicking on the button:" }, { "code": null, "e": 5032, "s": 5002, "text": "After clicking on the button:" }, { "code": null, "e": 5099, "s": 5032, "text": "Display confirmation dialog when clicking an <a> link using jQuery" }, { "code": null, "e": 5972, "s": 5099, "text": "jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 5980, "s": 5972, "text": "Syntax:" }, { "code": null, "e": 6038, "s": 5980, "text": "$(selector).on(event, childSelector, data, function, map)" }, { "code": null, "e": 6050, "s": 6038, "text": "Parameters:" }, { "code": null, "e": 6256, "s": 6050, "text": "event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid." }, { "code": null, "e": 6390, "s": 6256, "text": "childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements." }, { "code": null, "e": 6478, "s": 6390, "text": "data: This parameter is optional. It specifies additional data to pass to the function." }, { "code": null, "e": 6572, "s": 6478, "text": "function: This parameter is required. It specifies the function to run when the event occurs." }, { "code": null, "e": 6743, "s": 6572, "text": "map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 6926, "s": 6743, "text": "Example 1: This example adds a class confirm to the all link. After this, It adds the EventListener to the elements of that class, on onclick event. Then it calls the confirm dialog." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> <script src =\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <a href=\"#\" class=\"confirm\">Link</a> <br><br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $(\"#GFG_UP\"). text(\"Click on the LINK for further confirmation.\"); $('.confirm').on('click', function () { return confirm('Are you sure?'); }); </script> </body> </html> ", "e": 7942, "s": 6926, "text": null }, { "code": null, "e": 7950, "s": 7942, "text": "Output:" }, { "code": null, "e": 7981, "s": 7950, "text": "Before clicking on the button:" }, { "code": null, "e": 8011, "s": 7981, "text": "After clicking on the button:" }, { "code": null, "e": 8144, "s": 8011, "text": "Example 2: This example adds a confirm() method to the link with onclick event. This will verify whether you want to proceed or not." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Display a confirmation dialog when clicking an a tag link </title> <script src =\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <a href=\"#\" onclick=\"return confirm('Are you sure?')\"> Link </a> <br><br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $(\"#GFG_UP\"). text(\"Click on the LINK for further confirmation.\"); </script> </body> </html> ", "e": 9075, "s": 8144, "text": null }, { "code": null, "e": 9083, "s": 9075, "text": "Output:" }, { "code": null, "e": 9114, "s": 9083, "text": "Before clicking on the button:" }, { "code": null, "e": 9144, "s": 9114, "text": "After clicking on the button:" }, { "code": null, "e": 9412, "s": 9144, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of β€œWrite less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 9423, "s": 9412, "text": "JavaScript" }, { "code": null, "e": 9430, "s": 9423, "text": "JQuery" }, { "code": null, "e": 9447, "s": 9430, "text": "Web Technologies" }, { "code": null, "e": 9474, "s": 9447, "text": "Web technologies Questions" }, { "code": null, "e": 9572, "s": 9474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9633, "s": 9572, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 9705, "s": 9633, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 9745, "s": 9705, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 9786, "s": 9745, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 9828, "s": 9786, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 9874, "s": 9828, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 9903, "s": 9874, "text": "Form validation using jQuery" }, { "code": null, "e": 9966, "s": 9903, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 10019, "s": 9966, "text": "How to add options to a select element using jQuery?" } ]
How to get the count of a specific value in a column with MySQL?
Let us first create a table βˆ’ mysql> create table DemoTable ( Id int, Name varchar(100) ); Query OK, 0 rows affected (1.40 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable values(100,'John'); Query OK, 1 row affected (0.44 sec) mysql> insert into DemoTable values(101,'Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(102,'Chris'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(103,'Chris'); Query OK, 1 row affected (1.05 sec) mysql> insert into DemoTable values(104,'David'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(105,'Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(106,'Carol'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(107,'Bob'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable; This will produce the following output βˆ’ +------+-------+ | Id | Name | +------+-------+ | 100 | John | | 101 | Chris | | 102 | Chris | | 103 | Chris | | 104 | David | | 105 | Chris | | 106 | Carol | | 107 | Bob | +------+-------+ 8 rows in set (0.00 sec) Following is the query to get the count of a specific value in a column i.e. β€˜Chris’ here βˆ’ mysql> select count(*) from DemoTable where Name='Chris'; This will produce the following output βˆ’ +----------+ | count(*) | +----------+ | 4 | +----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1217, "s": 1187, "text": "Let us first create a table βˆ’" }, { "code": null, "e": 1333, "s": 1217, "text": "mysql> create table DemoTable\n (\n Id int,\n Name varchar(100)\n );\nQuery OK, 0 rows affected (1.40 sec)" }, { "code": null, "e": 1389, "s": 1333, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 2074, "s": 1389, "text": "mysql> insert into DemoTable values(100,'John');\nQuery OK, 1 row affected (0.44 sec)\nmysql> insert into DemoTable values(101,'Chris');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(102,'Chris');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(103,'Chris');\nQuery OK, 1 row affected (1.05 sec)\nmysql> insert into DemoTable values(104,'David');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(105,'Chris');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(106,'Carol');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable values(107,'Bob');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2134, "s": 2074, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 2165, "s": 2134, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2206, "s": 2165, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2435, "s": 2206, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 100 | John |\n| 101 | Chris |\n| 102 | Chris |\n| 103 | Chris |\n| 104 | David |\n| 105 | Chris |\n| 106 | Carol |\n| 107 | Bob |\n+------+-------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2527, "s": 2435, "text": "Following is the query to get the count of a specific value in a column i.e. β€˜Chris’ here βˆ’" }, { "code": null, "e": 2585, "s": 2527, "text": "mysql> select count(*) from DemoTable where Name='Chris';" }, { "code": null, "e": 2626, "s": 2585, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2715, "s": 2626, "text": "+----------+\n| count(*) |\n+----------+\n| 4 |\n+----------+\n1 row in set (0.00 sec)" } ]
How to Play Audio from URL in Android?
20 Jan, 2021 Many apps require the feature to add the audio feature in their application and there so many audio files that we have to play inside our application. If we will store so many audio files inside our application, then it will increase the size of the app and this may reduce the user base due to the huge app size. So the better way to tackle this problem is to store the audio files in your database and access them from their unique web URL. In this article, we will take a look at playing an audio file from URL in Android. We will be building a simple application in which we will display two buttons for play and pause of our audio. We will be loading that audio from the URL. Below is the video in which we will get to see what we are going to build in this article. Now let’s move towards the implementation. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Button for playing audio--> <Button android:id="@+id/idBtnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Play Audio file" android:textAllCaps="false" /> <!--Button for pausing the audio--> <Button android:id="@+id/idBtnPause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idBtnPlay" android:layout_centerInParent="true" android:text="Pause Audio" android:textAllCaps="false" /> </RelativeLayout> Step 3: Adding permissions to the AndroidManifest.xml file As we are playing audio from URL in android. So we will have to add Internet permissions to load URL. Add below permissions to the AndroidManifest.xml file. XML <!-- Permissions of internet --><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; public class MainActivity extends AppCompatActivity { // creating a variable for // button and media player Button playBtn, pauseBtn; MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our buttons playBtn = findViewById(R.id.idBtnPlay); pauseBtn = findViewById(R.id.idBtnPause); // setting on click listener for our play and pause buttons. playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to play audio. playAudio(); } }); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking the media player // if the audio is playing or not. if (mediaPlayer.isPlaying()) { // pausing the media player if media player // is playing we are calling below line to // stop our media player. mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); // below line is to display a message // when media player is paused. Toast.makeText(MainActivity.this, "Audio has been paused", Toast.LENGTH_SHORT).show(); } else { // this method is called when media // player is not playing. Toast.makeText(MainActivity.this, "Audio has not played", Toast.LENGTH_SHORT).show(); } } }); } private void playAudio() { String audioUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"; // initializing media player mediaPlayer = new MediaPlayer(); // below line is use to set the audio // stream type for our media player. mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // below line is use to set our // url to our media player. try { mediaPlayer.setDataSource(audioUrl); // below line is use to prepare // and start our media player. mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } // below line is use to display a toast message. Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show(); }} After adding the code now run your app and see the output of the app. Note: After clicking on the play button wait for some time as we are loading our audio file from the URL. So it will take a little bit of time to load our audio file. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jan, 2021" }, { "code": null, "e": 555, "s": 28, "text": "Many apps require the feature to add the audio feature in their application and there so many audio files that we have to play inside our application. If we will store so many audio files inside our application, then it will increase the size of the app and this may reduce the user base due to the huge app size. So the better way to tackle this problem is to store the audio files in your database and access them from their unique web URL. In this article, we will take a look at playing an audio file from URL in Android. " }, { "code": null, "e": 919, "s": 555, "text": "We will be building a simple application in which we will display two buttons for play and pause of our audio. We will be loading that audio from the URL. Below is the video in which we will get to see what we are going to build in this article. Now let’s move towards the implementation. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 948, "s": 919, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1110, "s": 948, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1158, "s": 1110, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1274, "s": 1158, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 1278, "s": 1274, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Button for playing audio--> <Button android:id=\"@+id/idBtnPlay\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Play Audio file\" android:textAllCaps=\"false\" /> <!--Button for pausing the audio--> <Button android:id=\"@+id/idBtnPause\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idBtnPlay\" android:layout_centerInParent=\"true\" android:text=\"Pause Audio\" android:textAllCaps=\"false\" /> </RelativeLayout>", "e": 2240, "s": 1278, "text": null }, { "code": null, "e": 2299, "s": 2240, "text": "Step 3: Adding permissions to the AndroidManifest.xml file" }, { "code": null, "e": 2456, "s": 2299, "text": "As we are playing audio from URL in android. So we will have to add Internet permissions to load URL. Add below permissions to the AndroidManifest.xml file." }, { "code": null, "e": 2460, "s": 2456, "text": "XML" }, { "code": "<!-- Permissions of internet --><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 2629, "s": 2460, "text": null }, { "code": null, "e": 2677, "s": 2629, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 2867, "s": 2677, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2872, "s": 2867, "text": "Java" }, { "code": "import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; public class MainActivity extends AppCompatActivity { // creating a variable for // button and media player Button playBtn, pauseBtn; MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our buttons playBtn = findViewById(R.id.idBtnPlay); pauseBtn = findViewById(R.id.idBtnPause); // setting on click listener for our play and pause buttons. playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to play audio. playAudio(); } }); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking the media player // if the audio is playing or not. if (mediaPlayer.isPlaying()) { // pausing the media player if media player // is playing we are calling below line to // stop our media player. mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); // below line is to display a message // when media player is paused. Toast.makeText(MainActivity.this, \"Audio has been paused\", Toast.LENGTH_SHORT).show(); } else { // this method is called when media // player is not playing. Toast.makeText(MainActivity.this, \"Audio has not played\", Toast.LENGTH_SHORT).show(); } } }); } private void playAudio() { String audioUrl = \"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\"; // initializing media player mediaPlayer = new MediaPlayer(); // below line is use to set the audio // stream type for our media player. mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // below line is use to set our // url to our media player. try { mediaPlayer.setDataSource(audioUrl); // below line is use to prepare // and start our media player. mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } // below line is use to display a toast message. Toast.makeText(this, \"Audio started playing..\", Toast.LENGTH_SHORT).show(); }}", "e": 5866, "s": 2872, "text": null }, { "code": null, "e": 5937, "s": 5866, "text": "After adding the code now run your app and see the output of the app. " }, { "code": null, "e": 6105, "s": 5937, "text": "Note: After clicking on the play button wait for some time as we are loading our audio file from the URL. So it will take a little bit of time to load our audio file. " }, { "code": null, "e": 6113, "s": 6105, "text": "android" }, { "code": null, "e": 6137, "s": 6113, "text": "Technical Scripter 2020" }, { "code": null, "e": 6145, "s": 6137, "text": "Android" }, { "code": null, "e": 6150, "s": 6145, "text": "Java" }, { "code": null, "e": 6169, "s": 6150, "text": "Technical Scripter" }, { "code": null, "e": 6174, "s": 6169, "text": "Java" }, { "code": null, "e": 6182, "s": 6174, "text": "Android" }, { "code": null, "e": 6280, "s": 6182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6349, "s": 6280, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6381, "s": 6349, "text": "Android SDK and it's Components" }, { "code": null, "e": 6430, "s": 6381, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 6469, "s": 6430, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6511, "s": 6469, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6526, "s": 6511, "text": "Arrays in Java" }, { "code": null, "e": 6570, "s": 6526, "text": "Split() String method in Java with examples" }, { "code": null, "e": 6606, "s": 6570, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6657, "s": 6606, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Count of subsets with sum equal to X using Recursion
21 Dec, 2021 Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X using recursion.Examples: Input: arr[] = {2, 3, 5, 6, 8, 10}, X = 10 Output: 3 Explanation: All possible subsets with sum 10 are {2, 3, 5}, {2, 8}, {10}Input: arr[] = {1, 2, 3, 4, 5}, X = 7 Output: 3 Explanation: All possible subsets with sum 7 are {2, 5}, {3, 4}, {1, 2, 4} Approach: The idea is to recursively check all the subsets. If any subset has the sum equal to N, then increment the count by 1. Else, continue. In order to form a subset, there are two cases for every element: Include the element in the set. Exclude the element in the set. Therefore, the following steps can be followed to compute the answer: Get the array for which the subsets with the sum equal to K is to be found.Recursively count the subsets with the sum equal to K in the following way:Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition. Get the array for which the subsets with the sum equal to K is to be found. Recursively count the subsets with the sum equal to K in the following way:Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition. Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition. if (n == 0) { if (sum == s) count++; return count; } Recursive Call: If the base case is not satisfied, then call the function twice. Once by including the element at index β€˜i’ and once by not including the element. Find the count for both these cases and then return the final count. count = subsetSum(arr, n, sum , s , count); count = subsetSum(arr, n, sum, s + arr[n-1 count); Return Statement: At every step, the count of subsets by either including a particular element or not including a particular element is returned. Finally, when the entire recursion stack is executed, the total count is returned. From the above approach, it can be clearly analyzed that if there are N elements in the array, then a total of 2N cases arise. Every element in the array is checked for the above cases using recursion. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the count of// subsets with sum equal to the given value X #include <iostream>using namespace std; // Recursive function to return the count// of subsets with sum equal to the given valueint subsetSum(int arr[], int n, int i, int sum, int count){ // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0) { count++; } return count; } // Recursively calling the function for two cases // Either the element can be counted in the subset // If the element is counted, then the remaining sum // to be checked is sum - the selected element // If the element is not included, then the remaining sum // to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count); count = subsetSum(arr, n, i + 1, sum, count); return count;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int sum = 10; int n = sizeof(arr) / sizeof(arr[0]); cout << subsetSum(arr, n, 0, sum, 0);} // Java program to print the count of// subsets with sum equal to the given value Ximport java.util.*; class GFG { // Recursive function to return the count // of subsets with sum equal to the given value static int subsetSum(int arr[], int n, int sum, int s, int count) { // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (n == 0) { // Incrementing the count if sum is // equal to the subset and returning the count if (sum == s) { count++; } return count; } count = subsetSum(arr, n - 1, sum, s, count); count = subsetSum(arr, n - 1, sum, s + arr[n - 1], count); return count; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int sum = 10; int s = 0; // Initially assigning the sum of subset // to be zero int n = arr.length; System.out.print(subsetSum(arr, n, sum, s, 0)); }} // This code is contributed by Sparsh Choudhary// (sparsht123t) # Python3 program to print the count of# subsets with sum equal to the given value X # Recursive function to return the count# of subsets with sum equal to the given valuedef subsetSum(arr, n, i,sum, count): # The recursion is stopped at N-th level # where all the subsets of the given array # have been checked if (i == n): # Incrementing the count if sum is # equal to 0 and returning the count if (sum == 0): count += 1 return count # Recursively calling the function for two cases # Either the element can be counted in the subset # If the element is counted, then the remaining sum # to be checked is sum - the selected element # If the element is not included, then the remaining sum # to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count) count = subsetSum(arr, n, i + 1, sum, count) return count # Driver codearr = [1, 2, 3, 4, 5]sum = 10n = len(arr) print(subsetSum(arr, n, 0, sum, 0)) # This code is contributed by mohit kumar 29 // C# program to print the count of// subsets with sum equal to the given value Xusing System; class GFG{ // Recursive function to return the count// of subsets with sum equal to the given valuestatic int subsetSum(int []arr, int n, int i, int sum, int count){ // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0) { count++; } return count; } // Recursively calling the function for two cases // Either the element can be counted in the subset // If the element is counted, then the remaining sum // to be checked is sum - the selected element // If the element is not included, then the remaining sum // to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count); count = subsetSum(arr, n, i + 1, sum, count); return count;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5 }; int sum = 10; int n = arr.Length; Console.Write(subsetSum(arr, n, 0, sum, 0));}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to print the count of// subsets with sum equal to the given value X // Recursive function to return the count// of subsets with sum equal to the given valuefunction subsetSum(arr, n, i, sum, count){ // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0) { count++; } return count; } // Recursively calling the function for two cases // Either the element can be counted in the subset // If the element is counted, then the remaining sum // to be checked is sum - the selected element // If the element is not included, then the remaining sum // to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count); count = subsetSum(arr, n, i + 1, sum, count); return count;} // Driver codevar arr = [1, 2, 3, 4, 5];var sum = 10;var n = arr.length;document.write( subsetSum(arr, n, 0, sum, 0)); </script> 3 Time Complexity: O(n2) Auxiliary Space: O(n2) Efficient Approach: An efficient method to solve the problem using Dynamic Programming has been discussed in this article. mohit kumar 29 29AjayKumar princiraj1992 Satzy Code_Mech itsok sparsht123t vansikasharma1329 subset Arrays Mathematical Recursion Arrays Mathematical Recursion subset 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 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Dec, 2021" }, { "code": null, "e": 197, "s": 54, "text": "Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X using recursion.Examples: " }, { "code": null, "e": 448, "s": 197, "text": "Input: arr[] = {2, 3, 5, 6, 8, 10}, X = 10 Output: 3 Explanation: All possible subsets with sum 10 are {2, 3, 5}, {2, 8}, {10}Input: arr[] = {1, 2, 3, 4, 5}, X = 7 Output: 3 Explanation: All possible subsets with sum 7 are {2, 5}, {3, 4}, {1, 2, 4} " }, { "code": null, "e": 663, "s": 450, "text": "Approach: The idea is to recursively check all the subsets. If any subset has the sum equal to N, then increment the count by 1. Else, continue. In order to form a subset, there are two cases for every element: " }, { "code": null, "e": 695, "s": 663, "text": "Include the element in the set." }, { "code": null, "e": 727, "s": 695, "text": "Exclude the element in the set." }, { "code": null, "e": 799, "s": 727, "text": "Therefore, the following steps can be followed to compute the answer: " }, { "code": null, "e": 1157, "s": 799, "text": "Get the array for which the subsets with the sum equal to K is to be found.Recursively count the subsets with the sum equal to K in the following way:Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition." }, { "code": null, "e": 1233, "s": 1157, "text": "Get the array for which the subsets with the sum equal to K is to be found." }, { "code": null, "e": 1516, "s": 1233, "text": "Recursively count the subsets with the sum equal to K in the following way:Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition." }, { "code": null, "e": 1724, "s": 1516, "text": "Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition." }, { "code": null, "e": 1793, "s": 1724, "text": "if (n == 0) {\n if (sum == s)\n count++;\n return count;\n}" }, { "code": null, "e": 2025, "s": 1793, "text": "Recursive Call: If the base case is not satisfied, then call the function twice. Once by including the element at index β€˜i’ and once by not including the element. Find the count for both these cases and then return the final count." }, { "code": null, "e": 2120, "s": 2025, "text": "count = subsetSum(arr, n, sum , s , count);\ncount = subsetSum(arr, n, sum, s + arr[n-1 count);" }, { "code": null, "e": 2349, "s": 2120, "text": "Return Statement: At every step, the count of subsets by either including a particular element or not including a particular element is returned. Finally, when the entire recursion stack is executed, the total count is returned." }, { "code": null, "e": 2603, "s": 2349, "text": "From the above approach, it can be clearly analyzed that if there are N elements in the array, then a total of 2N cases arise. Every element in the array is checked for the above cases using recursion. Below is the implementation of the above approach: " }, { "code": null, "e": 2607, "s": 2603, "text": "C++" }, { "code": null, "e": 2612, "s": 2607, "text": "Java" }, { "code": null, "e": 2620, "s": 2612, "text": "Python3" }, { "code": null, "e": 2623, "s": 2620, "text": "C#" }, { "code": null, "e": 2634, "s": 2623, "text": "Javascript" }, { "code": "// C++ program to print the count of// subsets with sum equal to the given value X #include <iostream>using namespace std; // Recursive function to return the count// of subsets with sum equal to the given valueint subsetSum(int arr[], int n, int i, int sum, int count){ // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0) { count++; } return count; } // Recursively calling the function for two cases // Either the element can be counted in the subset // If the element is counted, then the remaining sum // to be checked is sum - the selected element // If the element is not included, then the remaining sum // to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count); count = subsetSum(arr, n, i + 1, sum, count); return count;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int sum = 10; int n = sizeof(arr) / sizeof(arr[0]); cout << subsetSum(arr, n, 0, sum, 0);}", "e": 3816, "s": 2634, "text": null }, { "code": "// Java program to print the count of// subsets with sum equal to the given value Ximport java.util.*; class GFG { // Recursive function to return the count // of subsets with sum equal to the given value static int subsetSum(int arr[], int n, int sum, int s, int count) { // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (n == 0) { // Incrementing the count if sum is // equal to the subset and returning the count if (sum == s) { count++; } return count; } count = subsetSum(arr, n - 1, sum, s, count); count = subsetSum(arr, n - 1, sum, s + arr[n - 1], count); return count; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int sum = 10; int s = 0; // Initially assigning the sum of subset // to be zero int n = arr.length; System.out.print(subsetSum(arr, n, sum, s, 0)); }} // This code is contributed by Sparsh Choudhary// (sparsht123t)", "e": 5026, "s": 3816, "text": null }, { "code": "# Python3 program to print the count of# subsets with sum equal to the given value X # Recursive function to return the count# of subsets with sum equal to the given valuedef subsetSum(arr, n, i,sum, count): # The recursion is stopped at N-th level # where all the subsets of the given array # have been checked if (i == n): # Incrementing the count if sum is # equal to 0 and returning the count if (sum == 0): count += 1 return count # Recursively calling the function for two cases # Either the element can be counted in the subset # If the element is counted, then the remaining sum # to be checked is sum - the selected element # If the element is not included, then the remaining sum # to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count) count = subsetSum(arr, n, i + 1, sum, count) return count # Driver codearr = [1, 2, 3, 4, 5]sum = 10n = len(arr) print(subsetSum(arr, n, 0, sum, 0)) # This code is contributed by mohit kumar 29", "e": 6082, "s": 5026, "text": null }, { "code": "// C# program to print the count of// subsets with sum equal to the given value Xusing System; class GFG{ // Recursive function to return the count// of subsets with sum equal to the given valuestatic int subsetSum(int []arr, int n, int i, int sum, int count){ // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0) { count++; } return count; } // Recursively calling the function for two cases // Either the element can be counted in the subset // If the element is counted, then the remaining sum // to be checked is sum - the selected element // If the element is not included, then the remaining sum // to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count); count = subsetSum(arr, n, i + 1, sum, count); return count;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5 }; int sum = 10; int n = arr.Length; Console.Write(subsetSum(arr, n, 0, sum, 0));}} // This code is contributed by PrinciRaj1992", "e": 7333, "s": 6082, "text": null }, { "code": "<script> // Javascript program to print the count of// subsets with sum equal to the given value X // Recursive function to return the count// of subsets with sum equal to the given valuefunction subsetSum(arr, n, i, sum, count){ // The recursion is stopped at N-th level // where all the subsets of the given array // have been checked if (i == n) { // Incrementing the count if sum is // equal to 0 and returning the count if (sum == 0) { count++; } return count; } // Recursively calling the function for two cases // Either the element can be counted in the subset // If the element is counted, then the remaining sum // to be checked is sum - the selected element // If the element is not included, then the remaining sum // to be checked is the total sum count = subsetSum(arr, n, i + 1, sum - arr[i], count); count = subsetSum(arr, n, i + 1, sum, count); return count;} // Driver codevar arr = [1, 2, 3, 4, 5];var sum = 10;var n = arr.length;document.write( subsetSum(arr, n, 0, sum, 0)); </script>", "e": 8429, "s": 7333, "text": null }, { "code": null, "e": 8431, "s": 8429, "text": "3" }, { "code": null, "e": 8456, "s": 8433, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 8479, "s": 8456, "text": "Auxiliary Space: O(n2)" }, { "code": null, "e": 8603, "s": 8479, "text": "Efficient Approach: An efficient method to solve the problem using Dynamic Programming has been discussed in this article. " }, { "code": null, "e": 8618, "s": 8603, "text": "mohit kumar 29" }, { "code": null, "e": 8630, "s": 8618, "text": "29AjayKumar" }, { "code": null, "e": 8644, "s": 8630, "text": "princiraj1992" }, { "code": null, "e": 8650, "s": 8644, "text": "Satzy" }, { "code": null, "e": 8660, "s": 8650, "text": "Code_Mech" }, { "code": null, "e": 8666, "s": 8660, "text": "itsok" }, { "code": null, "e": 8678, "s": 8666, "text": "sparsht123t" }, { "code": null, "e": 8696, "s": 8678, "text": "vansikasharma1329" }, { "code": null, "e": 8703, "s": 8696, "text": "subset" }, { "code": null, "e": 8710, "s": 8703, "text": "Arrays" }, { "code": null, "e": 8723, "s": 8710, "text": "Mathematical" }, { "code": null, "e": 8733, "s": 8723, "text": "Recursion" }, { "code": null, "e": 8740, "s": 8733, "text": "Arrays" }, { "code": null, "e": 8753, "s": 8740, "text": "Mathematical" }, { "code": null, "e": 8763, "s": 8753, "text": "Recursion" }, { "code": null, "e": 8770, "s": 8763, "text": "subset" }, { "code": null, "e": 8868, "s": 8770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8936, "s": 8868, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 8980, "s": 8936, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9012, "s": 8980, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9060, "s": 9012, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 9074, "s": 9060, "text": "Linear Search" }, { "code": null, "e": 9104, "s": 9074, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9147, "s": 9104, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9162, "s": 9147, "text": "C++ Data Types" }, { "code": null, "e": 9186, "s": 9162, "text": "Merge two sorted arrays" } ]
Python Power Tip: Enumerated Types | by Don Cross | Towards Data Science
Often, programmers wish to represent something in their code whose value must belong to a predetermined, finite collection of values. Examples include: Days of the week: Monday, Tuesday, ..., Sunday. Types of image file format: JPEG, PNG, GIF, .... The suits in a card game: club, diamond, heart, spade. The states of some finite state machine. To address cases like these, many programming languages support enumerated types. Python did not support enumerated types until March 2014, when version 3.4 was released. Before then, Python programmers had to resort to some less-than-ideal tactics. A common workaround was to define some global variables with unique integer values, like this: Then the rest of the code could use CLUB, DIAMOND, HEART, or SPADE to represent the suit of a card as needed. There are problems with this approach: These global variables are mutable. One has to make sure no code ever assigns a different value to them. There is no type checking. It is easy to mix up some other integer value with a card suit, causing bugs. This deficiency of Python led to the creation of various third-party packages. There was a rejected proposal in 2005 to add enumerated types to the Python standard library. Then, in January 2013, an email conversation among language developers reignited consideration of standard support. The result was PEP 435, a proposal to add a new enum module to the standard library. Guido van Rossum, the creator of Python, approved PEP 435 on May 10, 2013. The enum module first appeared in Python 3.4 the following year. For simple cases where you just want some alternative values, you can follow this pattern: This creates an enumerated type Suit that defines symbols for the four card suits, called members. The optional decorator @unique adds a sanity check ensuring that all members have unique values. If you accidentally add more than one symbol with the same value, a ValueError exception will occur when the class declaration executes. For example, the following code will fail: Running this code produces the following behavior: Traceback (most recent call last): File "cards2.py", line 2, in <module> class Suit(Enum): File "/usr/lib/python3.5/enum.py", line 573, in unique (enumeration, alias_details))ValueError: duplicate values found in <enum 'Suit'>: Diamond -> Club At this point, you can quickly spot the problem that Diamond and Club both have the same value: 1. The members of an enumerated type like Suit are constants. Here are examples of things you can try with the Python interpreter, after repairing the uniqueness problem in Suit. First, if you evaluate one of the members, you see its representation: >>> s = Suit.Spade>>> s<Suit.Spade: 4> Each enumeration member also has a name property that results in the name as a string: >>> s.name'Spade' Each member also has a value property that returns whatever value you gave it: >>> s.value4 The name and value properties are read-only. This solves the mutability problem we mentioned above: >>> s.value = 7Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.5/types.py", line 141, in __set__ raise AttributeError("can't set attribute")AttributeError: can't set attribute>>> s.name = 'Joker'Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.5/types.py", line 141, in __set__ raise AttributeError("can't set attribute")AttributeError: can't set attribute>>> Suit.Heart.value = 9Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.5/types.py", line 141, in __set__ raise AttributeError("can't set attribute")AttributeError: can't set attribute The enumeration members are directly comparable with each other for equality or inequality: >>> s == Suit.SpadeTrue>>> s == Suit.HeartFalse>>> s != Suit.HeartTrue This allows you to write code that handles alternative cases, like this: Enumeration members work as dictionary keys: >>> color = { Suit.Heart: 'red', Suit.Diamond: 'red',... Suit.Spade: 'black', Suit.Club: 'black' }>>> color[Suit.Club]'black' If you have the name of an enumeration member in a string, you can use the type name with brackets to fetch the corresponding enumeration member. >>> text = 'Heart'>>> Suit[text]<Suit.Heart: 3> The type name also acts as a function that, when given one of the initializer values as an argument, returns the corresponding member. >>> Suit(3)<Suit.Heart: 3> Just by their name, it makes sense that enumerated types should provide the ability to enumerate the members they contain. And indeed that is the case. The type name serves as an enumerator of its members: >>> for x in Suit:... print(x)... Suit.ClubSuit.DiamondSuit.HeartSuit.Spade>>> list(Suit)[<Suit.Club: 1>, <Suit.Diamond: 2>, <Suit.Heart: 3>, <Suit.Spade: 4>] One of the problems I mentioned above is that it is possible to mix up different kinds of enumeration values. Let’s add another enumeration type and see what happens when we try to compare them. Even though Suit.Club and Animal.Dog have the same associated value, 1, they do not compare as equal: >>> Suit.Club == Animal.DogFalse This makes sense, because Suit and Animal are different types, and different types compare as unequal in general: >>> Suit.Club == 1False>>> Suit.Club == 'one'False This helps you avoid writing code that confuses an animal with a card suit! The Enum base class as demonstrated above is typically the most useful way to create an enumerated type. However, there are times where you want enumeration members that act like integer constants. In cases like this, you might not want to make an abstract type so much as a collection of symbols that represent specific integer constants. Perhaps you have an external API that reports the format of an image file as 1=PNG, 2=JPEG, or 3=GIF. In cases like these, the Python enum module provides another base class called IntEnum. Here is how you could define a less picky enumerated type where the members act like integer constants: Now the member ImageFormat.JPEG still has its own identity as an enumeration member: >>> ImageFormat.JPEG<ImageFormat.JPEG: 2> Yet when compared with the integer 2, it matches: >>> ImageFormat.JPEG == 2True You can even do math with it, unlike a member of an Enum: >>> ImageFormat.JPEG + 13>>> Suit.Club + 1Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for +: 'Suit' and 'int' Other helpful Enum functionality still works, such as enumeration and fetching members using names or values: >>> list(ImageFormat)[<ImageFormat.PNG: 1>, <ImageFormat.JPEG: 2>, <ImageFormat.GIF: 3>]>>> ImageFormat(3)<ImageFormat.GIF: 3>>>> ImageFormat['PNG']<ImageFormat.PNG: 1> We have covered the basics of Python enumerated types here, and it’s enough to get you started. Now you can put enumerated types to good use in your code. However, there are a lot more details and nuances remaining. I encourage you to read the official proposal and documentation pages linked below. Both pages are great reading for a deep understanding of this important language feature. PEP 435: Adding an Enum type to the Python standard library : this is the proposal that led to adding the enum module to the Python 3.4+ standard library.Python official documentation for the enum module. PEP 435: Adding an Enum type to the Python standard library : this is the proposal that led to adding the enum module to the Python 3.4+ standard library. Python official documentation for the enum module.
[ { "code": null, "e": 323, "s": 171, "text": "Often, programmers wish to represent something in their code whose value must belong to a predetermined, finite collection of values. Examples include:" }, { "code": null, "e": 371, "s": 323, "text": "Days of the week: Monday, Tuesday, ..., Sunday." }, { "code": null, "e": 420, "s": 371, "text": "Types of image file format: JPEG, PNG, GIF, ...." }, { "code": null, "e": 475, "s": 420, "text": "The suits in a card game: club, diamond, heart, spade." }, { "code": null, "e": 516, "s": 475, "text": "The states of some finite state machine." }, { "code": null, "e": 766, "s": 516, "text": "To address cases like these, many programming languages support enumerated types. Python did not support enumerated types until March 2014, when version 3.4 was released. Before then, Python programmers had to resort to some less-than-ideal tactics." }, { "code": null, "e": 861, "s": 766, "text": "A common workaround was to define some global variables with unique integer values, like this:" }, { "code": null, "e": 971, "s": 861, "text": "Then the rest of the code could use CLUB, DIAMOND, HEART, or SPADE to represent the suit of a card as needed." }, { "code": null, "e": 1010, "s": 971, "text": "There are problems with this approach:" }, { "code": null, "e": 1115, "s": 1010, "text": "These global variables are mutable. One has to make sure no code ever assigns a different value to them." }, { "code": null, "e": 1220, "s": 1115, "text": "There is no type checking. It is easy to mix up some other integer value with a card suit, causing bugs." }, { "code": null, "e": 1734, "s": 1220, "text": "This deficiency of Python led to the creation of various third-party packages. There was a rejected proposal in 2005 to add enumerated types to the Python standard library. Then, in January 2013, an email conversation among language developers reignited consideration of standard support. The result was PEP 435, a proposal to add a new enum module to the standard library. Guido van Rossum, the creator of Python, approved PEP 435 on May 10, 2013. The enum module first appeared in Python 3.4 the following year." }, { "code": null, "e": 1825, "s": 1734, "text": "For simple cases where you just want some alternative values, you can follow this pattern:" }, { "code": null, "e": 2201, "s": 1825, "text": "This creates an enumerated type Suit that defines symbols for the four card suits, called members. The optional decorator @unique adds a sanity check ensuring that all members have unique values. If you accidentally add more than one symbol with the same value, a ValueError exception will occur when the class declaration executes. For example, the following code will fail:" }, { "code": null, "e": 2252, "s": 2201, "text": "Running this code produces the following behavior:" }, { "code": null, "e": 2504, "s": 2252, "text": "Traceback (most recent call last): File \"cards2.py\", line 2, in <module> class Suit(Enum): File \"/usr/lib/python3.5/enum.py\", line 573, in unique (enumeration, alias_details))ValueError: duplicate values found in <enum 'Suit'>: Diamond -> Club" }, { "code": null, "e": 2603, "s": 2504, "text": "At this point, you can quickly spot the problem that Diamond and Club both have the same value: 1." }, { "code": null, "e": 2850, "s": 2603, "text": "The members of an enumerated type like Suit are constants. Here are examples of things you can try with the Python interpreter, after repairing the uniqueness problem in Suit. First, if you evaluate one of the members, you see its representation:" }, { "code": null, "e": 2889, "s": 2850, "text": ">>> s = Suit.Spade>>> s<Suit.Spade: 4>" }, { "code": null, "e": 2976, "s": 2889, "text": "Each enumeration member also has a name property that results in the name as a string:" }, { "code": null, "e": 2994, "s": 2976, "text": ">>> s.name'Spade'" }, { "code": null, "e": 3073, "s": 2994, "text": "Each member also has a value property that returns whatever value you gave it:" }, { "code": null, "e": 3086, "s": 3073, "text": ">>> s.value4" }, { "code": null, "e": 3186, "s": 3086, "text": "The name and value properties are read-only. This solves the mutability problem we mentioned above:" }, { "code": null, "e": 3879, "s": 3186, "text": ">>> s.value = 7Traceback (most recent call last): File \"<stdin>\", line 1, in <module> File \"/usr/lib/python3.5/types.py\", line 141, in __set__ raise AttributeError(\"can't set attribute\")AttributeError: can't set attribute>>> s.name = 'Joker'Traceback (most recent call last): File \"<stdin>\", line 1, in <module> File \"/usr/lib/python3.5/types.py\", line 141, in __set__ raise AttributeError(\"can't set attribute\")AttributeError: can't set attribute>>> Suit.Heart.value = 9Traceback (most recent call last): File \"<stdin>\", line 1, in <module> File \"/usr/lib/python3.5/types.py\", line 141, in __set__ raise AttributeError(\"can't set attribute\")AttributeError: can't set attribute" }, { "code": null, "e": 3971, "s": 3879, "text": "The enumeration members are directly comparable with each other for equality or inequality:" }, { "code": null, "e": 4042, "s": 3971, "text": ">>> s == Suit.SpadeTrue>>> s == Suit.HeartFalse>>> s != Suit.HeartTrue" }, { "code": null, "e": 4115, "s": 4042, "text": "This allows you to write code that handles alternative cases, like this:" }, { "code": null, "e": 4160, "s": 4115, "text": "Enumeration members work as dictionary keys:" }, { "code": null, "e": 4286, "s": 4160, "text": ">>> color = { Suit.Heart: 'red', Suit.Diamond: 'red',... Suit.Spade: 'black', Suit.Club: 'black' }>>> color[Suit.Club]'black'" }, { "code": null, "e": 4432, "s": 4286, "text": "If you have the name of an enumeration member in a string, you can use the type name with brackets to fetch the corresponding enumeration member." }, { "code": null, "e": 4480, "s": 4432, "text": ">>> text = 'Heart'>>> Suit[text]<Suit.Heart: 3>" }, { "code": null, "e": 4615, "s": 4480, "text": "The type name also acts as a function that, when given one of the initializer values as an argument, returns the corresponding member." }, { "code": null, "e": 4642, "s": 4615, "text": ">>> Suit(3)<Suit.Heart: 3>" }, { "code": null, "e": 4848, "s": 4642, "text": "Just by their name, it makes sense that enumerated types should provide the ability to enumerate the members they contain. And indeed that is the case. The type name serves as an enumerator of its members:" }, { "code": null, "e": 5011, "s": 4848, "text": ">>> for x in Suit:... print(x)... Suit.ClubSuit.DiamondSuit.HeartSuit.Spade>>> list(Suit)[<Suit.Club: 1>, <Suit.Diamond: 2>, <Suit.Heart: 3>, <Suit.Spade: 4>]" }, { "code": null, "e": 5206, "s": 5011, "text": "One of the problems I mentioned above is that it is possible to mix up different kinds of enumeration values. Let’s add another enumeration type and see what happens when we try to compare them." }, { "code": null, "e": 5308, "s": 5206, "text": "Even though Suit.Club and Animal.Dog have the same associated value, 1, they do not compare as equal:" }, { "code": null, "e": 5341, "s": 5308, "text": ">>> Suit.Club == Animal.DogFalse" }, { "code": null, "e": 5455, "s": 5341, "text": "This makes sense, because Suit and Animal are different types, and different types compare as unequal in general:" }, { "code": null, "e": 5506, "s": 5455, "text": ">>> Suit.Club == 1False>>> Suit.Club == 'one'False" }, { "code": null, "e": 5582, "s": 5506, "text": "This helps you avoid writing code that confuses an animal with a card suit!" }, { "code": null, "e": 6024, "s": 5582, "text": "The Enum base class as demonstrated above is typically the most useful way to create an enumerated type. However, there are times where you want enumeration members that act like integer constants. In cases like this, you might not want to make an abstract type so much as a collection of symbols that represent specific integer constants. Perhaps you have an external API that reports the format of an image file as 1=PNG, 2=JPEG, or 3=GIF." }, { "code": null, "e": 6216, "s": 6024, "text": "In cases like these, the Python enum module provides another base class called IntEnum. Here is how you could define a less picky enumerated type where the members act like integer constants:" }, { "code": null, "e": 6301, "s": 6216, "text": "Now the member ImageFormat.JPEG still has its own identity as an enumeration member:" }, { "code": null, "e": 6343, "s": 6301, "text": ">>> ImageFormat.JPEG<ImageFormat.JPEG: 2>" }, { "code": null, "e": 6393, "s": 6343, "text": "Yet when compared with the integer 2, it matches:" }, { "code": null, "e": 6423, "s": 6393, "text": ">>> ImageFormat.JPEG == 2True" }, { "code": null, "e": 6481, "s": 6423, "text": "You can even do math with it, unlike a member of an Enum:" }, { "code": null, "e": 6657, "s": 6481, "text": ">>> ImageFormat.JPEG + 13>>> Suit.Club + 1Traceback (most recent call last): File \"<stdin>\", line 1, in <module>TypeError: unsupported operand type(s) for +: 'Suit' and 'int'" }, { "code": null, "e": 6767, "s": 6657, "text": "Other helpful Enum functionality still works, such as enumeration and fetching members using names or values:" }, { "code": null, "e": 6936, "s": 6767, "text": ">>> list(ImageFormat)[<ImageFormat.PNG: 1>, <ImageFormat.JPEG: 2>, <ImageFormat.GIF: 3>]>>> ImageFormat(3)<ImageFormat.GIF: 3>>>> ImageFormat['PNG']<ImageFormat.PNG: 1>" }, { "code": null, "e": 7091, "s": 6936, "text": "We have covered the basics of Python enumerated types here, and it’s enough to get you started. Now you can put enumerated types to good use in your code." }, { "code": null, "e": 7326, "s": 7091, "text": "However, there are a lot more details and nuances remaining. I encourage you to read the official proposal and documentation pages linked below. Both pages are great reading for a deep understanding of this important language feature." }, { "code": null, "e": 7531, "s": 7326, "text": "PEP 435: Adding an Enum type to the Python standard library : this is the proposal that led to adding the enum module to the Python 3.4+ standard library.Python official documentation for the enum module." }, { "code": null, "e": 7686, "s": 7531, "text": "PEP 435: Adding an Enum type to the Python standard library : this is the proposal that led to adding the enum module to the Python 3.4+ standard library." } ]
GATE | GATE CS 2013 | Question 31 - GeeksforGeeks
31 May, 2021 Consider the following function: int unknown(int n) { int i, j, k = 0; for (i = n/2; i <= n; i++) for (j = 2; j <= n; j = j * 2) k = k + n/2; return k; } (A) (B) (C) (D) (A) A(B) B(C) C(D) DAnswer: (B)Explanation: Here we have to tell the value of k returned not the time complexity. for (i = n/2; i <= n; i++) for (j = 2; j <= n; j = j * 2) k = k + n/2; return k; The outer loop runs n/2 times The inner loop runs logn times.(2^k = n => k = logn). Now looking at the value of k in inner loop, n is added to k, logn times as the inner loop is running logn times. Therefore total time complexity is inner multiplied with outer loop complexity which (n for outer and nlogn for inner) n*logn. Therefore the value of k after running the inner loop one time is n^2logn.See http://geeksquiz.com/algorithms-analysis-of-algorithms-question-5/This solution is contributed by Parul Sharma. Quiz of this Question AbhinavPanse GATE-CS-2013 GATE-GATE CS 2013 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE CS 1997 | Question 25 GATE | GATE CS 2019 | Question 37
[ { "code": null, "e": 24354, "s": 24326, "text": "\n31 May, 2021" }, { "code": null, "e": 24387, "s": 24354, "text": "Consider the following function:" }, { "code": "int unknown(int n) { int i, j, k = 0; for (i = n/2; i <= n; i++) for (j = 2; j <= n; j = j * 2) k = k + n/2; return k; }", "e": 24536, "s": 24387, "text": null }, { "code": null, "e": 24540, "s": 24536, "text": "(A)" }, { "code": null, "e": 24544, "s": 24540, "text": "(B)" }, { "code": null, "e": 24548, "s": 24544, "text": "(C)" }, { "code": null, "e": 24552, "s": 24548, "text": "(D)" }, { "code": null, "e": 24668, "s": 24552, "text": "(A) A(B) B(C) C(D) DAnswer: (B)Explanation: Here we have to tell the value of k returned not the time complexity. " }, { "code": null, "e": 24774, "s": 24668, "text": "for (i = n/2; i <= n; i++)\n for (j = 2; j <= n; j = j * 2)\n k = k + n/2;\n return k;" }, { "code": null, "e": 25100, "s": 24774, "text": "The outer loop runs n/2 times The inner loop runs logn times.(2^k = n => k = logn). Now looking at the value of k in inner loop, n is added to k, logn times as the inner loop is running logn times. Therefore total time complexity is inner multiplied with outer loop complexity which (n for outer and nlogn for inner) n*logn. " }, { "code": null, "e": 25291, "s": 25100, "text": "Therefore the value of k after running the inner loop one time is n^2logn.See http://geeksquiz.com/algorithms-analysis-of-algorithms-question-5/This solution is contributed by Parul Sharma." }, { "code": null, "e": 25313, "s": 25291, "text": "Quiz of this Question" }, { "code": null, "e": 25326, "s": 25313, "text": "AbhinavPanse" }, { "code": null, "e": 25339, "s": 25326, "text": "GATE-CS-2013" }, { "code": null, "e": 25357, "s": 25339, "text": "GATE-GATE CS 2013" }, { "code": null, "e": 25362, "s": 25357, "text": "GATE" }, { "code": null, "e": 25460, "s": 25362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25469, "s": 25460, "text": "Comments" }, { "code": null, "e": 25482, "s": 25469, "text": "Old Comments" }, { "code": null, "e": 25516, "s": 25482, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25558, "s": 25516, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25592, "s": 25558, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25634, "s": 25592, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25676, "s": 25634, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25718, "s": 25676, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25752, "s": 25718, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 25794, "s": 25752, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25828, "s": 25794, "text": "GATE | GATE CS 1997 | Question 25" } ]
How to remove first character from column name in R data frame?
To remove first character from column name in R data frame, we can use str_sub function of stringr package. For Example, if we have a data frame called df that contains two columns say XID and XDV then we can remove X from both the column names by using the below mentioned command βˆ’ names(df)=str_sub(names(df),2) Following snippet creates a sample data frame βˆ’ XColor<-sample(c("Green","Red","Blue"),20,replace=TRUE) YScore<-sample(1:100,20) df1<-data.frame(XColor,YScore) df1 The following dataframe is created XColor YScore 1 Green 46 2 Red 80 3 Red 22 4 Green 21 5 Blue 54 6 Red 81 7 Blue 41 8 Red 4 9 Blue 63 10 Green 67 11 Green 71 12 Red 65 13 Red 79 14 Blue 58 15 Blue 76 16 Green 10 17 Red 60 18 Red 16 19 Green 27 20 Red 74 To load stringr package and remove first character from column names in df1 on the above created data frame, add the following code to the above snippet βˆ’ XColor<-sample(c("Green","Red","Blue"),20,replace=TRUE) YScore<-sample(1:100,20) df1<-data.frame(XColor,YScore) library(stringr) names(df1)=str_sub(names(df1),2) df1 If you execute all the above given snippets as a single program, it generates the following Output βˆ’ Color Score 1 Green 46 2 Red 80 3 Red 22 4 Green 21 5 Blue 54 6 Red 81 7 Blue 41 8 Red 4 9 Blue 63 10 Green 67 11 Green 71 12 Red 65 13 Red 79 14 Blue 58 15 Blue 76 16 Green 10 17 Red 60 18 Red 16 19 Green 27 20 Red 74 Following snippet creates a sample data frame βˆ’ SStudents_ID<-c(200001:200020) LLevel<-sample(c("First","Second","Third"),20,replace=TRUE) df2<-data.frame(SStudents,LLevel) df2 The following dataframe is created SStudents LLevel 1 200001 First 2 200002 Third 3 200003 Third 4 200004 Second 5 200005 Second 6 200006 Second 7 200007 Second 8 200008 First 9 200009 Second 10 200010 Second 11 200011 First 12 200012 Third 13 200013 Second 14 200014 Second 15 200015 Second 16 200016 First 17 200017 First 18 200018 Third 19 200019 Third 20 200020 Second To remove first character from column names in df2 on the above created data frame, add the following code to the above snippet βˆ’ SStudents_ID<-c(200001:200020) LLevel<-sample(c("First","Second","Third"),20,replace=TRUE) df2<-data.frame(SStudents,LLevel) names(df2)=str_sub(names(df2),2) df2 If you execute all the above given snippets as a single program, it generates the following Output βˆ’ Students Level 1 200001 First 2 200002 Third 3 200003 Third 4 200004 Second 5 200005 Second 6 200006 Second 7 200007 Second 8 200008 First 9 200009 Second 10 200010 Second 11 200011 First 12 200012 Third 13 200013 Second 14 200014 Second 15 200015 Second 16 200016 First 17 200017 First 18 200018 Third 19 200019 Third 20 200020 Second
[ { "code": null, "e": 1170, "s": 1062, "text": "To remove first character from column name in R data frame, we can use str_sub function of stringr package." }, { "code": null, "e": 1346, "s": 1170, "text": "For Example, if we have a data frame called df that contains two columns say XID and XDV then we can remove X from both the column names by using the below mentioned command βˆ’" }, { "code": null, "e": 1377, "s": 1346, "text": "names(df)=str_sub(names(df),2)" }, { "code": null, "e": 1425, "s": 1377, "text": "Following snippet creates a sample data frame βˆ’" }, { "code": null, "e": 1541, "s": 1425, "text": "XColor<-sample(c(\"Green\",\"Red\",\"Blue\"),20,replace=TRUE)\nYScore<-sample(1:100,20)\ndf1<-data.frame(XColor,YScore)\ndf1" }, { "code": null, "e": 1576, "s": 1541, "text": "The following dataframe is created" }, { "code": null, "e": 1873, "s": 1576, "text": " XColor YScore\n1 Green 46\n2 Red 80\n3 Red 22\n4 Green 21\n5 Blue 54\n6 Red 81\n7 Blue 41\n8 Red 4\n9 Blue 63\n10 Green 67\n11 Green 71\n12 Red 65\n13 Red 79\n14 Blue 58\n15 Blue 76\n16 Green 10\n17 Red 60 \n18 Red 16\n19 Green 27\n20 Red 74" }, { "code": null, "e": 2028, "s": 1873, "text": "To load stringr package and remove first character from column names in df1 on the above created data frame, add the following code to the above snippet βˆ’" }, { "code": null, "e": 2194, "s": 2028, "text": "XColor<-sample(c(\"Green\",\"Red\",\"Blue\"),20,replace=TRUE)\nYScore<-sample(1:100,20)\ndf1<-data.frame(XColor,YScore)\nlibrary(stringr)\nnames(df1)=str_sub(names(df1),2)\ndf1" }, { "code": null, "e": 2295, "s": 2194, "text": "If you execute all the above given snippets as a single program, it generates the following Output βˆ’" }, { "code": null, "e": 2590, "s": 2295, "text": " Color Score\n1 Green 46\n2 Red 80\n3 Red 22\n4 Green 21\n5 Blue 54\n6 Red 81\n7 Blue 41\n8 Red 4\n9 Blue 63\n10 Green 67\n11 Green 71\n12 Red 65\n13 Red 79\n14 Blue 58\n15 Blue 76\n16 Green 10\n17 Red 60\n18 Red 16\n19 Green 27\n20 Red 74" }, { "code": null, "e": 2638, "s": 2590, "text": "Following snippet creates a sample data frame βˆ’" }, { "code": null, "e": 2767, "s": 2638, "text": "SStudents_ID<-c(200001:200020)\nLLevel<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\ndf2<-data.frame(SStudents,LLevel)\ndf2" }, { "code": null, "e": 2802, "s": 2767, "text": "The following dataframe is created" }, { "code": null, "e": 3149, "s": 2802, "text": "SStudents LLevel\n1 200001 First\n2 200002 Third\n3 200003 Third\n4 200004 Second\n5 200005 Second\n6 200006 Second\n7 200007 Second\n8 200008 First\n9 200009 Second\n10 200010 Second\n11 200011 First\n12 200012 Third\n13 200013 Second\n14 200014 Second\n15 200015 Second\n16 200016 First\n17 200017 First\n18 200018 Third\n19 200019 Third\n20 200020 Second" }, { "code": null, "e": 3279, "s": 3149, "text": "To remove first character from column names in df2 on the above created data frame, add the following code to the above snippet βˆ’" }, { "code": null, "e": 3441, "s": 3279, "text": "SStudents_ID<-c(200001:200020)\nLLevel<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\ndf2<-data.frame(SStudents,LLevel)\nnames(df2)=str_sub(names(df2),2)\ndf2" }, { "code": null, "e": 3542, "s": 3441, "text": "If you execute all the above given snippets as a single program, it generates the following Output βˆ’" }, { "code": null, "e": 3889, "s": 3542, "text": " Students Level\n1 200001 First\n2 200002 Third\n3 200003 Third\n4 200004 Second\n5 200005 Second\n6 200006 Second\n7 200007 Second\n8 200008 First\n9 200009 Second\n10 200010 Second\n11 200011 First\n12 200012 Third\n13 200013 Second\n14 200014 Second\n15 200015 Second\n16 200016 First\n17 200017 First\n18 200018 Third\n19 200019 Third\n20 200020 Second" } ]
Docker Made Easy for Data Scientists | by Gagandeep Singh | Towards Data Science
β€œGoogle runs all software in containers and they run around 2 billion containers every week.” Before proceeding any further the first question that should come to your mind is why I need docker and even more important what is it? So, what is Docker? A Docker is a set of platform service products that use OS-level virtualization to deliver software in packages called containers. The great advantage of Docker is that it makes your deployment easy and when the time comes you can even deploy it on multiple machines with almost no extra effort. You can also use Docker with Kubernetes that can automatically handle the workload by distributing the work among different Docker Containers. On top of that, it also takes care if any Docker Container goes offline and automatically restarts it and many more things. Here, we are going to build various flask apps using Docker. Simple Hello World app using FlaskPassing arguments in Docker ContainerSimple ML app in Docker ContainerPassing Image as an argument in Docker Container Simple Hello World app using Flask Passing arguments in Docker Container Simple ML app in Docker Container Passing Image as an argument in Docker Container $ sudo apt update$ sudo apt install docker.io This will install docker. Now, to check if docker is running or not type $ sudo service docker status If you don’t see docker in active mode then type $ sudo service docker start Docker Image β€” In very simple terms docker image is just like an ISO image file used to install any OS. You can view all docker images(publicly available on DockerHub)Docker Container β€” When a Docker Image runs it becomes a Docker Container. You can run the same image again and a different docker container will be created.Dockerfile β€” A Dockerfile contains all the code to set up a docker container from downloading the docker image to setting the environment. Docker Image β€” In very simple terms docker image is just like an ISO image file used to install any OS. You can view all docker images(publicly available on DockerHub) Docker Container β€” When a Docker Image runs it becomes a Docker Container. You can run the same image again and a different docker container will be created. Dockerfile β€” A Dockerfile contains all the code to set up a docker container from downloading the docker image to setting the environment. I’ve put the GitHub link on the bottom where all the code is available. Docker is very easy to learn after you have understood its flow. This is a very simple app that prints β€˜hello world’ on the browser’s screen. Let’s build the flask app Also, create requirements.txt file by $ pip3 list > requirements.txt A few things to remember while making the flask app is that the host should be set to β€˜0.0.0.0’ because we are running it inside Docker. Let’s build the docker file With the below command we are pulling ubuntu image. It also contains a tag with which we can specify the version. Here we are pulling the β€˜latest’ image. With the below command we are pulling ubuntu image. It also contains a tag with which we can specify the version. Here we are pulling the β€˜latest’ image. FROM ubuntu:latest 2. Now, imagine you freshly install Linux os, the first thing you’ll do is update the local database that contains software package info. RUN A β€˜-y’ flag is also added to make sure it doesn’t expect any user input. RUN sudo apt update -y 3. The next task is to install python. There isn’t any need to set up a virtual environment since we are using only one application. RUN apt install -y python3-pip 4. The next task is to copy all files from the directory to the docker image. COPY . /app where β€˜.’ is the current directory and β€˜/app’ is where we wish to copy the files. You can choose any folder of your choice. 5. Set the working directory to /app. WORKDIR /app 6. We have pulled ubuntu image, installed python, copied all data. The next will be to set up a python environment by installing all the required packages. We’ve already created requirements.txt file. Now, we just have to install it. RUN pip3 install -r requirements.txt 7. Now, set ENTRYPOINT as β€˜python3’. ENTRYPOINT ['python3'] 8. Lastly, run the app.py file CMD ['app.py'] The final file will look like this. This file will be saved as Dockerfile with no extension. The final directory structure will look like this Finally, build the docker file by $ docker build -t simpleflask . All this may sound confusing and please bear with me. We are gonna see more examples to learn better. Let’s recap what we learned so far. You need to create a Dockerfile that will contain information about the Docker Container will setup. It includes an image, python, python environment and then running the app itself.Then you’ll need to build Dockerfile. You need to create a Dockerfile that will contain information about the Docker Container will setup. It includes an image, python, python environment and then running the app itself. Then you’ll need to build Dockerfile. Now, please pay attention here You can view all docker container by $ docker ps -a You will not see any docker container because you have just build it. Now, we’ll run that image. Type $ docker images You can view all your docker images with this command. The next task will be to run that docker image that you just build. $ docker run -d -p 5000:5000 <docker_image_id> 5000:5000 means you have attached port 5000 of your system to docker. The latter port is of Flask. By default, flask runs on port 5000. -d flag means you want to run it in daemon mode (background). After running it successfully, you’ll see an output. To check if your container is running or not. Type $ docker ps -a If it is running successfully, then in your web browser type localhost:5000. You’ll see β€œHello World”. This isn’t a machine learning prediction model rather we are going to learn how to take input from flask via POST method and print it. Let’s Create the flask app first We have used the POST method by explicitly declaring it. To receive the input use request.get_json method. Then simply print the value Let’s create requirements.txt file $ pip3 list > requirements.txt The Dockerfile is going to be exactly same as previous To build the docker file use $ docker build -t passingarguments . We’ll follow all the steps we followed above. $ docker images$ docker run -d -p 5000:5000 <docker_image_id> Now, pay attention here There are various ways to call the API we just created. Using requests in python. Using requests in python. 2. Using POSTMAN 3. Using Curl curl -X POST http://127.0.0.1:5000/predict -d 5 The result will be the square of the number passed. In this example, we are going to see how to pass multiple examples at the same time. We are going to pass arguments in the form of a JSON. For now, you need not worry about model training. The code to train model is in the Docker file and the model will be trained as part of the Docker building process. Ideally the model should be trained on local system and then should be copied to Docker Container. Let’s look at the Flask application This time in flask application we are fetching the parameters from JSON received. JSON has a similar data format as of the python dictionary. In practice we should also include error handling here. Errors can include if the parameters are not numbers or if parameters are empty. Also, create a requirements.txt file $ pip3 list > requirements.txt Now, let's look at the Docker file Notice we are training the model inside Docker Container. You could also train the model on your local system and copy it to Container. In that case you’ll just have to remove the line that is training the model. Now, there are multiple ways to get a prediction. Using requests in python Using requests in python 2. Using curl curl -X POST http://127.0.0.1:5000/predict -d '{"f1":4, "f2":5, "f3":10}' Notice how we are passing the data in JSON format. While using requests in python you’ll have to use json.dumps to data to convert it into JSON form. For simplicity, I’m using MNIST dataset for the classification task. Let’s look at the Flask app We are importing all necessary packages We are loading the model on run time to make inference faster We are converting the image to greyscale by using convert(β€˜L’). The image is resized to 28x28 pixel. For prediction, Keras needs the image in format (batch_size, width, height, colour_channel). So, we are converting it to (1, 28, 28, 1). Next, we are using its prediction method with no.argmax to find the class which has the highest probability. Let’s create requirements.txt file $ pip3 list > requirements.txt Let’s look at its docker file Note- Here I’ve already trained the model. You could also add the functionality of training while docker file is build. We’ll follow the steps we did above $ docker build -t imageclassification .$ docker run -d -p 5000:5000 <docker_image_id> Before building the Docker Image make sure to train the model using train.py file included in folder Now, there are multiple ways to get a prediction. Using curl Using curl curl -F "file=@pic_name.extension" http://localhost:5000/predict 2. Using requests That’s enough for now. If you have understood to some basic extent then congratulations on making up to this far. You’ll learn more when you will try new things and not hesitate to experiment. A master now once was a beginner. GitHub repo where all the code is present.
[ { "code": null, "e": 265, "s": 171, "text": "β€œGoogle runs all software in containers and they run around 2 billion containers every week.”" }, { "code": null, "e": 401, "s": 265, "text": "Before proceeding any further the first question that should come to your mind is why I need docker and even more important what is it?" }, { "code": null, "e": 717, "s": 401, "text": "So, what is Docker? A Docker is a set of platform service products that use OS-level virtualization to deliver software in packages called containers. The great advantage of Docker is that it makes your deployment easy and when the time comes you can even deploy it on multiple machines with almost no extra effort." }, { "code": null, "e": 984, "s": 717, "text": "You can also use Docker with Kubernetes that can automatically handle the workload by distributing the work among different Docker Containers. On top of that, it also takes care if any Docker Container goes offline and automatically restarts it and many more things." }, { "code": null, "e": 1045, "s": 984, "text": "Here, we are going to build various flask apps using Docker." }, { "code": null, "e": 1198, "s": 1045, "text": "Simple Hello World app using FlaskPassing arguments in Docker ContainerSimple ML app in Docker ContainerPassing Image as an argument in Docker Container" }, { "code": null, "e": 1233, "s": 1198, "text": "Simple Hello World app using Flask" }, { "code": null, "e": 1271, "s": 1233, "text": "Passing arguments in Docker Container" }, { "code": null, "e": 1305, "s": 1271, "text": "Simple ML app in Docker Container" }, { "code": null, "e": 1354, "s": 1305, "text": "Passing Image as an argument in Docker Container" }, { "code": null, "e": 1400, "s": 1354, "text": "$ sudo apt update$ sudo apt install docker.io" }, { "code": null, "e": 1473, "s": 1400, "text": "This will install docker. Now, to check if docker is running or not type" }, { "code": null, "e": 1502, "s": 1473, "text": "$ sudo service docker status" }, { "code": null, "e": 1551, "s": 1502, "text": "If you don’t see docker in active mode then type" }, { "code": null, "e": 1579, "s": 1551, "text": "$ sudo service docker start" }, { "code": null, "e": 2042, "s": 1579, "text": "Docker Image β€” In very simple terms docker image is just like an ISO image file used to install any OS. You can view all docker images(publicly available on DockerHub)Docker Container β€” When a Docker Image runs it becomes a Docker Container. You can run the same image again and a different docker container will be created.Dockerfile β€” A Dockerfile contains all the code to set up a docker container from downloading the docker image to setting the environment." }, { "code": null, "e": 2210, "s": 2042, "text": "Docker Image β€” In very simple terms docker image is just like an ISO image file used to install any OS. You can view all docker images(publicly available on DockerHub)" }, { "code": null, "e": 2368, "s": 2210, "text": "Docker Container β€” When a Docker Image runs it becomes a Docker Container. You can run the same image again and a different docker container will be created." }, { "code": null, "e": 2507, "s": 2368, "text": "Dockerfile β€” A Dockerfile contains all the code to set up a docker container from downloading the docker image to setting the environment." }, { "code": null, "e": 2644, "s": 2507, "text": "I’ve put the GitHub link on the bottom where all the code is available. Docker is very easy to learn after you have understood its flow." }, { "code": null, "e": 2721, "s": 2644, "text": "This is a very simple app that prints β€˜hello world’ on the browser’s screen." }, { "code": null, "e": 2747, "s": 2721, "text": "Let’s build the flask app" }, { "code": null, "e": 2785, "s": 2747, "text": "Also, create requirements.txt file by" }, { "code": null, "e": 2816, "s": 2785, "text": "$ pip3 list > requirements.txt" }, { "code": null, "e": 2953, "s": 2816, "text": "A few things to remember while making the flask app is that the host should be set to β€˜0.0.0.0’ because we are running it inside Docker." }, { "code": null, "e": 2981, "s": 2953, "text": "Let’s build the docker file" }, { "code": null, "e": 3135, "s": 2981, "text": "With the below command we are pulling ubuntu image. It also contains a tag with which we can specify the version. Here we are pulling the β€˜latest’ image." }, { "code": null, "e": 3289, "s": 3135, "text": "With the below command we are pulling ubuntu image. It also contains a tag with which we can specify the version. Here we are pulling the β€˜latest’ image." }, { "code": null, "e": 3308, "s": 3289, "text": "FROM ubuntu:latest" }, { "code": null, "e": 3523, "s": 3308, "text": "2. Now, imagine you freshly install Linux os, the first thing you’ll do is update the local database that contains software package info. RUN A β€˜-y’ flag is also added to make sure it doesn’t expect any user input." }, { "code": null, "e": 3547, "s": 3523, "text": "RUN sudo apt update -y " }, { "code": null, "e": 3680, "s": 3547, "text": "3. The next task is to install python. There isn’t any need to set up a virtual environment since we are using only one application." }, { "code": null, "e": 3711, "s": 3680, "text": "RUN apt install -y python3-pip" }, { "code": null, "e": 3789, "s": 3711, "text": "4. The next task is to copy all files from the directory to the docker image." }, { "code": null, "e": 3801, "s": 3789, "text": "COPY . /app" }, { "code": null, "e": 3925, "s": 3801, "text": "where β€˜.’ is the current directory and β€˜/app’ is where we wish to copy the files. You can choose any folder of your choice." }, { "code": null, "e": 3963, "s": 3925, "text": "5. Set the working directory to /app." }, { "code": null, "e": 3976, "s": 3963, "text": "WORKDIR /app" }, { "code": null, "e": 4210, "s": 3976, "text": "6. We have pulled ubuntu image, installed python, copied all data. The next will be to set up a python environment by installing all the required packages. We’ve already created requirements.txt file. Now, we just have to install it." }, { "code": null, "e": 4247, "s": 4210, "text": "RUN pip3 install -r requirements.txt" }, { "code": null, "e": 4284, "s": 4247, "text": "7. Now, set ENTRYPOINT as β€˜python3’." }, { "code": null, "e": 4307, "s": 4284, "text": "ENTRYPOINT ['python3']" }, { "code": null, "e": 4338, "s": 4307, "text": "8. Lastly, run the app.py file" }, { "code": null, "e": 4353, "s": 4338, "text": "CMD ['app.py']" }, { "code": null, "e": 4389, "s": 4353, "text": "The final file will look like this." }, { "code": null, "e": 4446, "s": 4389, "text": "This file will be saved as Dockerfile with no extension." }, { "code": null, "e": 4496, "s": 4446, "text": "The final directory structure will look like this" }, { "code": null, "e": 4530, "s": 4496, "text": "Finally, build the docker file by" }, { "code": null, "e": 4562, "s": 4530, "text": "$ docker build -t simpleflask ." }, { "code": null, "e": 4700, "s": 4562, "text": "All this may sound confusing and please bear with me. We are gonna see more examples to learn better. Let’s recap what we learned so far." }, { "code": null, "e": 4920, "s": 4700, "text": "You need to create a Dockerfile that will contain information about the Docker Container will setup. It includes an image, python, python environment and then running the app itself.Then you’ll need to build Dockerfile." }, { "code": null, "e": 5103, "s": 4920, "text": "You need to create a Dockerfile that will contain information about the Docker Container will setup. It includes an image, python, python environment and then running the app itself." }, { "code": null, "e": 5141, "s": 5103, "text": "Then you’ll need to build Dockerfile." }, { "code": null, "e": 5172, "s": 5141, "text": "Now, please pay attention here" }, { "code": null, "e": 5209, "s": 5172, "text": "You can view all docker container by" }, { "code": null, "e": 5224, "s": 5209, "text": "$ docker ps -a" }, { "code": null, "e": 5321, "s": 5224, "text": "You will not see any docker container because you have just build it. Now, we’ll run that image." }, { "code": null, "e": 5326, "s": 5321, "text": "Type" }, { "code": null, "e": 5342, "s": 5326, "text": "$ docker images" }, { "code": null, "e": 5465, "s": 5342, "text": "You can view all your docker images with this command. The next task will be to run that docker image that you just build." }, { "code": null, "e": 5512, "s": 5465, "text": "$ docker run -d -p 5000:5000 <docker_image_id>" }, { "code": null, "e": 5648, "s": 5512, "text": "5000:5000 means you have attached port 5000 of your system to docker. The latter port is of Flask. By default, flask runs on port 5000." }, { "code": null, "e": 5710, "s": 5648, "text": "-d flag means you want to run it in daemon mode (background)." }, { "code": null, "e": 5814, "s": 5710, "text": "After running it successfully, you’ll see an output. To check if your container is running or not. Type" }, { "code": null, "e": 5829, "s": 5814, "text": "$ docker ps -a" }, { "code": null, "e": 5932, "s": 5829, "text": "If it is running successfully, then in your web browser type localhost:5000. You’ll see β€œHello World”." }, { "code": null, "e": 6067, "s": 5932, "text": "This isn’t a machine learning prediction model rather we are going to learn how to take input from flask via POST method and print it." }, { "code": null, "e": 6100, "s": 6067, "text": "Let’s Create the flask app first" }, { "code": null, "e": 6157, "s": 6100, "text": "We have used the POST method by explicitly declaring it." }, { "code": null, "e": 6207, "s": 6157, "text": "To receive the input use request.get_json method." }, { "code": null, "e": 6235, "s": 6207, "text": "Then simply print the value" }, { "code": null, "e": 6270, "s": 6235, "text": "Let’s create requirements.txt file" }, { "code": null, "e": 6301, "s": 6270, "text": "$ pip3 list > requirements.txt" }, { "code": null, "e": 6356, "s": 6301, "text": "The Dockerfile is going to be exactly same as previous" }, { "code": null, "e": 6385, "s": 6356, "text": "To build the docker file use" }, { "code": null, "e": 6422, "s": 6385, "text": "$ docker build -t passingarguments ." }, { "code": null, "e": 6468, "s": 6422, "text": "We’ll follow all the steps we followed above." }, { "code": null, "e": 6530, "s": 6468, "text": "$ docker images$ docker run -d -p 5000:5000 <docker_image_id>" }, { "code": null, "e": 6554, "s": 6530, "text": "Now, pay attention here" }, { "code": null, "e": 6610, "s": 6554, "text": "There are various ways to call the API we just created." }, { "code": null, "e": 6636, "s": 6610, "text": "Using requests in python." }, { "code": null, "e": 6662, "s": 6636, "text": "Using requests in python." }, { "code": null, "e": 6679, "s": 6662, "text": "2. Using POSTMAN" }, { "code": null, "e": 6693, "s": 6679, "text": "3. Using Curl" }, { "code": null, "e": 6741, "s": 6693, "text": "curl -X POST http://127.0.0.1:5000/predict -d 5" }, { "code": null, "e": 6793, "s": 6741, "text": "The result will be the square of the number passed." }, { "code": null, "e": 6932, "s": 6793, "text": "In this example, we are going to see how to pass multiple examples at the same time. We are going to pass arguments in the form of a JSON." }, { "code": null, "e": 7098, "s": 6932, "text": "For now, you need not worry about model training. The code to train model is in the Docker file and the model will be trained as part of the Docker building process." }, { "code": null, "e": 7197, "s": 7098, "text": "Ideally the model should be trained on local system and then should be copied to Docker Container." }, { "code": null, "e": 7233, "s": 7197, "text": "Let’s look at the Flask application" }, { "code": null, "e": 7375, "s": 7233, "text": "This time in flask application we are fetching the parameters from JSON received. JSON has a similar data format as of the python dictionary." }, { "code": null, "e": 7512, "s": 7375, "text": "In practice we should also include error handling here. Errors can include if the parameters are not numbers or if parameters are empty." }, { "code": null, "e": 7549, "s": 7512, "text": "Also, create a requirements.txt file" }, { "code": null, "e": 7580, "s": 7549, "text": "$ pip3 list > requirements.txt" }, { "code": null, "e": 7615, "s": 7580, "text": "Now, let's look at the Docker file" }, { "code": null, "e": 7828, "s": 7615, "text": "Notice we are training the model inside Docker Container. You could also train the model on your local system and copy it to Container. In that case you’ll just have to remove the line that is training the model." }, { "code": null, "e": 7878, "s": 7828, "text": "Now, there are multiple ways to get a prediction." }, { "code": null, "e": 7903, "s": 7878, "text": "Using requests in python" }, { "code": null, "e": 7928, "s": 7903, "text": "Using requests in python" }, { "code": null, "e": 7942, "s": 7928, "text": "2. Using curl" }, { "code": null, "e": 8016, "s": 7942, "text": "curl -X POST http://127.0.0.1:5000/predict -d '{\"f1\":4, \"f2\":5, \"f3\":10}'" }, { "code": null, "e": 8166, "s": 8016, "text": "Notice how we are passing the data in JSON format. While using requests in python you’ll have to use json.dumps to data to convert it into JSON form." }, { "code": null, "e": 8235, "s": 8166, "text": "For simplicity, I’m using MNIST dataset for the classification task." }, { "code": null, "e": 8263, "s": 8235, "text": "Let’s look at the Flask app" }, { "code": null, "e": 8303, "s": 8263, "text": "We are importing all necessary packages" }, { "code": null, "e": 8365, "s": 8303, "text": "We are loading the model on run time to make inference faster" }, { "code": null, "e": 8429, "s": 8365, "text": "We are converting the image to greyscale by using convert(β€˜L’)." }, { "code": null, "e": 8466, "s": 8429, "text": "The image is resized to 28x28 pixel." }, { "code": null, "e": 8603, "s": 8466, "text": "For prediction, Keras needs the image in format (batch_size, width, height, colour_channel). So, we are converting it to (1, 28, 28, 1)." }, { "code": null, "e": 8712, "s": 8603, "text": "Next, we are using its prediction method with no.argmax to find the class which has the highest probability." }, { "code": null, "e": 8747, "s": 8712, "text": "Let’s create requirements.txt file" }, { "code": null, "e": 8778, "s": 8747, "text": "$ pip3 list > requirements.txt" }, { "code": null, "e": 8808, "s": 8778, "text": "Let’s look at its docker file" }, { "code": null, "e": 8928, "s": 8808, "text": "Note- Here I’ve already trained the model. You could also add the functionality of training while docker file is build." }, { "code": null, "e": 8964, "s": 8928, "text": "We’ll follow the steps we did above" }, { "code": null, "e": 9050, "s": 8964, "text": "$ docker build -t imageclassification .$ docker run -d -p 5000:5000 <docker_image_id>" }, { "code": null, "e": 9151, "s": 9050, "text": "Before building the Docker Image make sure to train the model using train.py file included in folder" }, { "code": null, "e": 9201, "s": 9151, "text": "Now, there are multiple ways to get a prediction." }, { "code": null, "e": 9212, "s": 9201, "text": "Using curl" }, { "code": null, "e": 9223, "s": 9212, "text": "Using curl" }, { "code": null, "e": 9288, "s": 9223, "text": "curl -F \"file=@pic_name.extension\" http://localhost:5000/predict" }, { "code": null, "e": 9306, "s": 9288, "text": "2. Using requests" }, { "code": null, "e": 9329, "s": 9306, "text": "That’s enough for now." }, { "code": null, "e": 9533, "s": 9329, "text": "If you have understood to some basic extent then congratulations on making up to this far. You’ll learn more when you will try new things and not hesitate to experiment. A master now once was a beginner." } ]
How to create an HTML document which uses aside element ? - GeeksforGeeks
15 Oct, 2020 The <aside> tag is used to describe the main object of the web page in a shorter way like a highlighter. It basically identifies the content that is related to the primary content of the web page but does not constitute the main intent of the primary page. The <aside> tag contains mainly author information, links, related content and so on. The <aside> tag makes easy to design the page and it enhances clarity of HTML document. It let us easily recognize the main text and subordinate text. In both the time <div> and <aside> need CSS to specific design. The <aside> tag supports Global attributes and Event attributes in HTML. Syntax: <aside> <h3>Contents...</h3> <p>Contents...</p> </aside> Example 1: HTML <!DOCTYPE html><html> <head> <style> h1 { font-size: 40px; color: #090; font-weight: bold; } p { font-size: 20px; margin: 20px 0; } </style></head> <body> <aside> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> </aside></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <style> .gfg { font-size: 40px; color: #090; font-weight: bold; text-align: center; margin-bottom: 20px; } article { width: 50%; float: left; padding: 10px; float: left; } aside { float: right; width: 40%; float: right; background-color: green; color: white; padding: 5px; margin: 10px; height: 100px; } </style></head> <body> <div class="gfg"> GeeksforGeeks </div> <article> <h1>Article Title</h1> <p> Aside tag is use to display important information about the primary page. </p> </article> <aside> <h1>Aside Tag Example</h1> <p>Aside tag content. . .</p> </aside></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between CSS and CSS3 Borders in bootstrap with examples How to create fade-in effect on page load using CSS ? Simple Tic-Tac-Toe Game using JavaScript How to style a checkbox using CSS? Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTML | <img> align Attribute
[ { "code": null, "e": 26621, "s": 26593, "text": "\n15 Oct, 2020" }, { "code": null, "e": 26964, "s": 26621, "text": "The <aside> tag is used to describe the main object of the web page in a shorter way like a highlighter. It basically identifies the content that is related to the primary content of the web page but does not constitute the main intent of the primary page. The <aside> tag contains mainly author information, links, related content and so on." }, { "code": null, "e": 27252, "s": 26964, "text": "The <aside> tag makes easy to design the page and it enhances clarity of HTML document. It let us easily recognize the main text and subordinate text. In both the time <div> and <aside> need CSS to specific design. The <aside> tag supports Global attributes and Event attributes in HTML." }, { "code": null, "e": 27260, "s": 27252, "text": "Syntax:" }, { "code": null, "e": 27326, "s": 27260, "text": "<aside>\n <h3>Contents...</h3>\n <p>Contents...</p>\n</aside>\n" }, { "code": null, "e": 27337, "s": 27326, "text": "Example 1:" }, { "code": null, "e": 27342, "s": 27337, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { font-size: 40px; color: #090; font-weight: bold; } p { font-size: 20px; margin: 20px 0; } </style></head> <body> <aside> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> </aside></body> </html>", "e": 27713, "s": 27342, "text": null }, { "code": null, "e": 27721, "s": 27713, "text": "Output:" }, { "code": null, "e": 27732, "s": 27721, "text": "Example 2:" }, { "code": null, "e": 27737, "s": 27732, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg { font-size: 40px; color: #090; font-weight: bold; text-align: center; margin-bottom: 20px; } article { width: 50%; float: left; padding: 10px; float: left; } aside { float: right; width: 40%; float: right; background-color: green; color: white; padding: 5px; margin: 10px; height: 100px; } </style></head> <body> <div class=\"gfg\"> GeeksforGeeks </div> <article> <h1>Article Title</h1> <p> Aside tag is use to display important information about the primary page. </p> </article> <aside> <h1>Aside Tag Example</h1> <p>Aside tag content. . .</p> </aside></body> </html>", "e": 28695, "s": 27737, "text": null }, { "code": null, "e": 28703, "s": 28695, "text": "Output:" }, { "code": null, "e": 28840, "s": 28703, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28849, "s": 28840, "text": "CSS-Misc" }, { "code": null, "e": 28859, "s": 28849, "text": "HTML-Misc" }, { "code": null, "e": 28863, "s": 28859, "text": "CSS" }, { "code": null, "e": 28868, "s": 28863, "text": "HTML" }, { "code": null, "e": 28885, "s": 28868, "text": "Web Technologies" }, { "code": null, "e": 28912, "s": 28885, "text": "Web technologies Questions" }, { "code": null, "e": 28917, "s": 28912, "text": "HTML" }, { "code": null, "e": 29015, "s": 28917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29047, "s": 29015, "text": "Difference between CSS and CSS3" }, { "code": null, "e": 29082, "s": 29047, "text": "Borders in bootstrap with examples" }, { "code": null, "e": 29136, "s": 29082, "text": "How to create fade-in effect on page load using CSS ?" }, { "code": null, "e": 29177, "s": 29136, "text": "Simple Tic-Tac-Toe Game using JavaScript" }, { "code": null, "e": 29212, "s": 29177, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29265, "s": 29212, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29325, "s": 29265, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29386, "s": 29325, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Automata Theory | Set 10 - GeeksforGeeks
28 Feb, 2019 These questions for practice purpose of GATE CS Exam. Ques-1: Consider the following statements: X: For any language either a language L or its compliment L’ must be finite. Y: DFA for language which contains epsilon must have initial state as final state. Z: Non-deterministic finite automata is more powerful than deterministic finite automata. Which of the following statement(s) is/are correct? (A) only X(B) only Y(C) only Z(D) all of the above. Explanation:X: It is incorrect. since, a language L and its compliment can be infinite.Y: It is correct.since, if the language contains epsilon then its initial state must be final also, otherwise the DFA wont be able to accept epsilon.Z: It is incorrect. since, every language accepted by NFA is also accepted by some DFA. Hence, NFA and DFA both are equivalent in power. Option (B) is true. Ques-2: Which one of the following regular expression describes the language over {a, b} which consists of no pair of consecutive b’s? (A) (a*baa*)(b + epsilon)(B) (a + ba)*(b + epsilon)(C) (a*baa*)*(b + epsilon) + a*(D) (a*ba*)*(b + epsilon) + a*(b + epsilon) Explanation: (A) It is incorrect. since, it does not contains (a or epsilon). (B) It is correct. since, it contains (epsilon, a, b, ba, ab, .....), i.e., no pair of consecutive b’s. (C) It is incorrect. since, it does not contains β€˜ab’ or β€˜aab’. (D) It is incorrect. since, it contains β€˜bb’, which is not allowed. Option (B) is true. Ques-3: What is the length of the shortest string not in the language over alphabet {0, 1} for regular expression given below: 1*(0 + 1)*1* (A) three(B) five(C) six(D) four Explanation:Check each string generated over the alphabet {0, 1} until you reach the shortest string which is not generated by the given regular expression.In this case, smallest string which is not generated by the given regular expression is 0110, whose length is four. so, option (D) is true. Ques-4: Let β€˜X’ be set of all languages accepted by deterministic push down automata (DPDA) by final state and β€˜Y’ be set of all languages accepted by DPDA by empty stack then, which of the following is true? (A) X is proper subset of Y(B) X = Y(C) X is proper super set of Y(D) none of the above Explanation:The set of languages accepted by DPDA by final state is proper super set of languages accepted by empty stack DPDA. So X is proper super set of Y. Option (C) is true. Ques-5: Consider X and Y are two languages over alphabet {0, 1} represented by regular expression 0*(10*)* and (0* + 1*)* respectively. which of the following is true? (A) X is proper subset of Y(B) Y is proper subset of X(C) X = Y(D) none Explanation:Here, L(X) = 0*(10*)* = {epsilon, 0, 1, 10, 01, 00, 11, ......} And. L(Y) = (0* + 1*)* = {epsilon, 0, 1, 10, 01, 00, 11, ....} So, both languages are equivalent to each other. Option (C) is true. GATE GATE CS Theory of Computation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 25799, "s": 25771, "text": "\n28 Feb, 2019" }, { "code": null, "e": 25853, "s": 25799, "text": "These questions for practice purpose of GATE CS Exam." }, { "code": null, "e": 25896, "s": 25853, "text": "Ques-1: Consider the following statements:" }, { "code": null, "e": 25973, "s": 25896, "text": "X: For any language either a language L or its compliment L’ must be finite." }, { "code": null, "e": 26056, "s": 25973, "text": "Y: DFA for language which contains epsilon must have initial state as final state." }, { "code": null, "e": 26146, "s": 26056, "text": "Z: Non-deterministic finite automata is more powerful than deterministic finite automata." }, { "code": null, "e": 26198, "s": 26146, "text": "Which of the following statement(s) is/are correct?" }, { "code": null, "e": 26250, "s": 26198, "text": "(A) only X(B) only Y(C) only Z(D) all of the above." }, { "code": null, "e": 26623, "s": 26250, "text": "Explanation:X: It is incorrect. since, a language L and its compliment can be infinite.Y: It is correct.since, if the language contains epsilon then its initial state must be final also, otherwise the DFA wont be able to accept epsilon.Z: It is incorrect. since, every language accepted by NFA is also accepted by some DFA. Hence, NFA and DFA both are equivalent in power." }, { "code": null, "e": 26643, "s": 26623, "text": "Option (B) is true." }, { "code": null, "e": 26778, "s": 26643, "text": "Ques-2: Which one of the following regular expression describes the language over {a, b} which consists of no pair of consecutive b’s?" }, { "code": null, "e": 26904, "s": 26778, "text": "(A) (a*baa*)(b + epsilon)(B) (a + ba)*(b + epsilon)(C) (a*baa*)*(b + epsilon) + a*(D) (a*ba*)*(b + epsilon) + a*(b + epsilon)" }, { "code": null, "e": 26917, "s": 26904, "text": "Explanation:" }, { "code": null, "e": 26982, "s": 26917, "text": "(A) It is incorrect. since, it does not contains (a or epsilon)." }, { "code": null, "e": 27086, "s": 26982, "text": "(B) It is correct. since, it contains (epsilon, a, b, ba, ab, .....), i.e., no pair of consecutive b’s." }, { "code": null, "e": 27150, "s": 27086, "text": "(C) It is incorrect. since, it does not contains β€˜ab’ or β€˜aab’." }, { "code": null, "e": 27218, "s": 27150, "text": "(D) It is incorrect. since, it contains β€˜bb’, which is not allowed." }, { "code": null, "e": 27238, "s": 27218, "text": "Option (B) is true." }, { "code": null, "e": 27365, "s": 27238, "text": "Ques-3: What is the length of the shortest string not in the language over alphabet {0, 1} for regular expression given below:" }, { "code": null, "e": 27379, "s": 27365, "text": "1*(0 + 1)*1* " }, { "code": null, "e": 27412, "s": 27379, "text": "(A) three(B) five(C) six(D) four" }, { "code": null, "e": 27684, "s": 27412, "text": "Explanation:Check each string generated over the alphabet {0, 1} until you reach the shortest string which is not generated by the given regular expression.In this case, smallest string which is not generated by the given regular expression is 0110, whose length is four." }, { "code": null, "e": 27708, "s": 27684, "text": "so, option (D) is true." }, { "code": null, "e": 27917, "s": 27708, "text": "Ques-4: Let β€˜X’ be set of all languages accepted by deterministic push down automata (DPDA) by final state and β€˜Y’ be set of all languages accepted by DPDA by empty stack then, which of the following is true?" }, { "code": null, "e": 28005, "s": 27917, "text": "(A) X is proper subset of Y(B) X = Y(C) X is proper super set of Y(D) none of the above" }, { "code": null, "e": 28164, "s": 28005, "text": "Explanation:The set of languages accepted by DPDA by final state is proper super set of languages accepted by empty stack DPDA. So X is proper super set of Y." }, { "code": null, "e": 28184, "s": 28164, "text": "Option (C) is true." }, { "code": null, "e": 28352, "s": 28184, "text": "Ques-5: Consider X and Y are two languages over alphabet {0, 1} represented by regular expression 0*(10*)* and (0* + 1*)* respectively. which of the following is true?" }, { "code": null, "e": 28424, "s": 28352, "text": "(A) X is proper subset of Y(B) Y is proper subset of X(C) X = Y(D) none" }, { "code": null, "e": 28442, "s": 28424, "text": "Explanation:Here," }, { "code": null, "e": 28503, "s": 28442, "text": "L(X) \n= 0*(10*)* \n= {epsilon, 0, 1, 10, 01, 00, 11, ......} " }, { "code": null, "e": 28508, "s": 28503, "text": "And." }, { "code": null, "e": 28569, "s": 28508, "text": "L(Y) \n= (0* + 1*)* \n= {epsilon, 0, 1, 10, 01, 00, 11, ....} " }, { "code": null, "e": 28618, "s": 28569, "text": "So, both languages are equivalent to each other." }, { "code": null, "e": 28638, "s": 28618, "text": "Option (C) is true." }, { "code": null, "e": 28643, "s": 28638, "text": "GATE" }, { "code": null, "e": 28651, "s": 28643, "text": "GATE CS" }, { "code": null, "e": 28673, "s": 28651, "text": "Theory of Computation" }, { "code": null, "e": 28771, "s": 28673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28805, "s": 28771, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 28839, "s": 28805, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28873, "s": 28839, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 28906, "s": 28873, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28942, "s": 28906, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28962, "s": 28942, "text": "Layers of OSI Model" }, { "code": null, "e": 28986, "s": 28962, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28999, "s": 28986, "text": "TCP/IP Model" }, { "code": null, "e": 29026, "s": 28999, "text": "Types of Operating Systems" } ]
How to Extract Frames From a Video in MATLAB? - GeeksforGeeks
20 Aug, 2020 Let us see how to extract frames from a video in MATLAB. Approach : Import the video which is to be converted into frames into the current matlab environment.Extract the total number of frames in the video.Make an empty directory named frames before the execution.Run a for loop and start extracting the frames into the directory. Import the video which is to be converted into frames into the current matlab environment. Extract the total number of frames in the video. Make an empty directory named frames before the execution. Run a for loop and start extracting the frames into the directory. In our demonstration, we shall consider the following video : % import the video fileobj = VideoReader('org.mp4');vid = read(obj); % read the total number of framesframes = obj.NumberOfFrames; % file format of the frames to be saved inST ='.jpg'; % reading and writing the frames for x = 1 : frames % converting integer to string Sx = num2str(x); % concatenating 2 strings Strc = strcat(Sx, ST); Vid = vid(:, :, :, x); cd frames % exporting the frames imwrite(Vid, Strc); cd .. end Output :The frames directory will look something like this : Images saved in the frames folder MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example System Design Tutorial Copying Files to and from Docker Containers Python | Decision tree implementation ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction
[ { "code": null, "e": 25891, "s": 25863, "text": "\n20 Aug, 2020" }, { "code": null, "e": 25948, "s": 25891, "text": "Let us see how to extract frames from a video in MATLAB." }, { "code": null, "e": 25959, "s": 25948, "text": "Approach :" }, { "code": null, "e": 26222, "s": 25959, "text": "Import the video which is to be converted into frames into the current matlab environment.Extract the total number of frames in the video.Make an empty directory named frames before the execution.Run a for loop and start extracting the frames into the directory." }, { "code": null, "e": 26313, "s": 26222, "text": "Import the video which is to be converted into frames into the current matlab environment." }, { "code": null, "e": 26362, "s": 26313, "text": "Extract the total number of frames in the video." }, { "code": null, "e": 26421, "s": 26362, "text": "Make an empty directory named frames before the execution." }, { "code": null, "e": 26488, "s": 26421, "text": "Run a for loop and start extracting the frames into the directory." }, { "code": null, "e": 26550, "s": 26488, "text": "In our demonstration, we shall consider the following video :" }, { "code": "% import the video fileobj = VideoReader('org.mp4');vid = read(obj); % read the total number of framesframes = obj.NumberOfFrames; % file format of the frames to be saved inST ='.jpg'; % reading and writing the frames for x = 1 : frames % converting integer to string Sx = num2str(x); % concatenating 2 strings Strc = strcat(Sx, ST); Vid = vid(:, :, :, x); cd frames % exporting the frames imwrite(Vid, Strc); cd .. end", "e": 27008, "s": 26550, "text": null }, { "code": null, "e": 27069, "s": 27008, "text": "Output :The frames directory will look something like this :" }, { "code": null, "e": 27103, "s": 27069, "text": "Images saved in the frames folder" }, { "code": null, "e": 27110, "s": 27103, "text": "MATLAB" }, { "code": null, "e": 27136, "s": 27110, "text": "Advanced Computer Subject" }, { "code": null, "e": 27234, "s": 27136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27257, "s": 27234, "text": "ML | Linear Regression" }, { "code": null, "e": 27280, "s": 27257, "text": "Reinforcement learning" }, { "code": null, "e": 27294, "s": 27280, "text": "Decision Tree" }, { "code": null, "e": 27334, "s": 27294, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27357, "s": 27334, "text": "System Design Tutorial" }, { "code": null, "e": 27401, "s": 27357, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27439, "s": 27401, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27473, "s": 27439, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 27504, "s": 27473, "text": "Clustering in Machine Learning" } ]
Duration from(TemporalUnit) method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The from(TemporalUnit) method of Duration Class in java.time package is used to get a duration from the amount passed as the first parameter in the TemporalUnit. The TemporalUnit can be DAYS, HOURS, etc. Syntax: public static Duration from(TemporalUnit amount) Parameters: This method accepts a parameter amount which is amount from which the Duration is to be found, passed as the TemporalUnit. Return Value: This method returns a Duration representing the time of specified amount. Exception: This method throws following unit: ArithmeticException: if numeric overflow occurs. DateTimeException: if unable to convert to a Duration Below examples illustrate the Duration.from() method: Example 1: // Java code to illustrate from() method import java.time.Duration; public class GFG { public static void main(String[] args) { // Get the amount Duration duration = Duration.ofDays(5); // Duration using from() method Duration duration1 = Duration.from(duration); System.out.println(duration1.getSeconds()); }} 432000 Example 2: // Java code to illustrate from() method import java.time.Duration; public class GFG { public static void main(String[] args) { // Get the amount Duration duration = Duration.ofHours(5); // Duration using from() method Duration duration1 = Duration.from(duration); System.out.println(duration1.getSeconds()); }} 18000 Reference: Oracle Doc Java-Duration Java-Functions Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26199, "s": 26171, "text": "\n26 Nov, 2018" }, { "code": null, "e": 26403, "s": 26199, "text": "The from(TemporalUnit) method of Duration Class in java.time package is used to get a duration from the amount passed as the first parameter in the TemporalUnit. The TemporalUnit can be DAYS, HOURS, etc." }, { "code": null, "e": 26411, "s": 26403, "text": "Syntax:" }, { "code": null, "e": 26461, "s": 26411, "text": "public static Duration from(TemporalUnit amount)\n" }, { "code": null, "e": 26596, "s": 26461, "text": "Parameters: This method accepts a parameter amount which is amount from which the Duration is to be found, passed as the TemporalUnit." }, { "code": null, "e": 26684, "s": 26596, "text": "Return Value: This method returns a Duration representing the time of specified amount." }, { "code": null, "e": 26730, "s": 26684, "text": "Exception: This method throws following unit:" }, { "code": null, "e": 26779, "s": 26730, "text": "ArithmeticException: if numeric overflow occurs." }, { "code": null, "e": 26833, "s": 26779, "text": "DateTimeException: if unable to convert to a Duration" }, { "code": null, "e": 26887, "s": 26833, "text": "Below examples illustrate the Duration.from() method:" }, { "code": null, "e": 26898, "s": 26887, "text": "Example 1:" }, { "code": "// Java code to illustrate from() method import java.time.Duration; public class GFG { public static void main(String[] args) { // Get the amount Duration duration = Duration.ofDays(5); // Duration using from() method Duration duration1 = Duration.from(duration); System.out.println(duration1.getSeconds()); }}", "e": 27261, "s": 26898, "text": null }, { "code": null, "e": 27269, "s": 27261, "text": "432000\n" }, { "code": null, "e": 27280, "s": 27269, "text": "Example 2:" }, { "code": "// Java code to illustrate from() method import java.time.Duration; public class GFG { public static void main(String[] args) { // Get the amount Duration duration = Duration.ofHours(5); // Duration using from() method Duration duration1 = Duration.from(duration); System.out.println(duration1.getSeconds()); }}", "e": 27644, "s": 27280, "text": null }, { "code": null, "e": 27651, "s": 27644, "text": "18000\n" }, { "code": null, "e": 27673, "s": 27651, "text": "Reference: Oracle Doc" }, { "code": null, "e": 27687, "s": 27673, "text": "Java-Duration" }, { "code": null, "e": 27702, "s": 27687, "text": "Java-Functions" }, { "code": null, "e": 27720, "s": 27702, "text": "Java-time package" }, { "code": null, "e": 27725, "s": 27720, "text": "Java" }, { "code": null, "e": 27730, "s": 27725, "text": "Java" }, { "code": null, "e": 27828, "s": 27730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27879, "s": 27828, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27909, "s": 27879, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27924, "s": 27909, "text": "Stream In Java" }, { "code": null, "e": 27943, "s": 27924, "text": "Interfaces in Java" }, { "code": null, "e": 27974, "s": 27943, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27992, "s": 27974, "text": "ArrayList in Java" }, { "code": null, "e": 28024, "s": 27992, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28044, "s": 28024, "text": "Stack Class in Java" }, { "code": null, "e": 28076, "s": 28044, "text": "Multidimensional Arrays in Java" } ]
Python - String Repetition and spacing in List - GeeksforGeeks
25 Oct, 2021 Sometimes while working with Python, we can have a problem in which we need to perform the repetition of each string in list and also attach a deliminator to each occurrence. This kind of problem can occur in day-day programming. Lets discuss certain ways in which this task can be performed.Method #1 : Using loop This task can be performed in brute force way using loop. In this, we iterate the list and perform string addition and multiplication while iteration using suitable operators. Python3 # Python3 code to demonstrate working of# String Repetition and spacing in List# Using loop # initializing listtest_list = ['gfg', 'is', 'best'] # printing original listprint("The original list is : " + str(test_list)) # initializing delimdelim = '-' # initializing KK = 3 # String Repetition and spacing in List# Using loopres = []for sub in test_list: res.append((sub + delim) * K) # printing resultprint("List after performing operations : " + str(res)) The original list is : ['gfg', 'is', 'best'] List after performing operations : ['gfg-gfg-gfg-', 'is-is-is-', 'best-best-best-'] Method #2 : Using join() + list comprehension The combination of above functionalities can also be used to perform this task. In this, we perform the task of attaching delim using join() and list comprehension performs the task of repetition. Avoids trailing delim. Python3 # Python3 code to demonstrate working of# String Repetition and spacing in List# Using join() + list comprehension # initializing listtest_list = ['gfg', 'is', 'best'] # printing original listprint("The original list is : " + str(test_list)) # initializing delimdelim = '-' # initializing KK = 3 # String Repetition and spacing in List# Using join() + list comprehensionres = []for sub in test_list: res.append(delim.join([sub for _ in range(K)])) # printing resultprint("List after performing operations : " + str(res)) The original list is : ['gfg', 'is', 'best'] List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best'] ruhelaa48 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n25 Oct, 2021" }, { "code": null, "e": 26029, "s": 25537, "text": "Sometimes while working with Python, we can have a problem in which we need to perform the repetition of each string in list and also attach a deliminator to each occurrence. This kind of problem can occur in day-day programming. Lets discuss certain ways in which this task can be performed.Method #1 : Using loop This task can be performed in brute force way using loop. In this, we iterate the list and perform string addition and multiplication while iteration using suitable operators. " }, { "code": null, "e": 26037, "s": 26029, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# String Repetition and spacing in List# Using loop # initializing listtest_list = ['gfg', 'is', 'best'] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing delimdelim = '-' # initializing KK = 3 # String Repetition and spacing in List# Using loopres = []for sub in test_list: res.append((sub + delim) * K) # printing resultprint(\"List after performing operations : \" + str(res))", "e": 26501, "s": 26037, "text": null }, { "code": null, "e": 26630, "s": 26501, "text": "The original list is : ['gfg', 'is', 'best']\nList after performing operations : ['gfg-gfg-gfg-', 'is-is-is-', 'best-best-best-']" }, { "code": null, "e": 26900, "s": 26632, "text": " Method #2 : Using join() + list comprehension The combination of above functionalities can also be used to perform this task. In this, we perform the task of attaching delim using join() and list comprehension performs the task of repetition. Avoids trailing delim. " }, { "code": null, "e": 26908, "s": 26900, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# String Repetition and spacing in List# Using join() + list comprehension # initializing listtest_list = ['gfg', 'is', 'best'] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing delimdelim = '-' # initializing KK = 3 # String Repetition and spacing in List# Using join() + list comprehensionres = []for sub in test_list: res.append(delim.join([sub for _ in range(K)])) # printing resultprint(\"List after performing operations : \" + str(res))", "e": 27436, "s": 26908, "text": null }, { "code": null, "e": 27562, "s": 27436, "text": "The original list is : ['gfg', 'is', 'best']\nList after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']" }, { "code": null, "e": 27574, "s": 27564, "text": "ruhelaa48" }, { "code": null, "e": 27595, "s": 27574, "text": "Python list-programs" }, { "code": null, "e": 27602, "s": 27595, "text": "Python" }, { "code": null, "e": 27618, "s": 27602, "text": "Python Programs" }, { "code": null, "e": 27716, "s": 27618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27748, "s": 27716, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27790, "s": 27748, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27832, "s": 27790, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27888, "s": 27832, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27915, "s": 27888, "text": "Python Classes and Objects" }, { "code": null, "e": 27937, "s": 27915, "text": "Defaultdict in Python" }, { "code": null, "e": 27976, "s": 27937, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28022, "s": 27976, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28060, "s": 28022, "text": "Python | Convert a list to dictionary" } ]
How to make smooth bounce animation using CSS ? - GeeksforGeeks
28 Nov, 2019 The smooth bounce animation can be done with the help of HTML and CSS. It will generate fun and desired outputs. For this project, a simple div with class ball is needed in HTML page: <div class="ball"></div> We will switch to CSS for animation programming. Now, Flexbox is used to have the ball at the middle of the page and make the ball 70px by 70px in size. It can be taken in any size of the user’s choice as it determines the size of the ball. body { display: flex; justify-content: center; }.ball { width: 100px; height: 100px; border-radius: 50%; background-color: #FF5722; } Here,justify-content: center is used to center the ball horizontally.border-radius : 50% turns the square into a circle.background-color: #FF5722 turns the circle to orange colour. There are various code notations for colors to be remembered. Keyframe creating: Keyframes in CSS animations gives complete control over the animation. Simple use of the keyword @keyframes followed by the name of the animation, i.e, smooth bounce ball: @keyframes smoothbounceball{ statements} Within the keyframe, use keywords from and to to make a start and end point for the animation. @keyframes smoothbounceball{ from {/*starting*/} to {/*ending*/}} To our understanding, we can add starting and ending values to the animation. To create a bouncing effect, we need to transform the location of the ball. transform allows to modify co-ordinates of a given element. Hence the final keyframe: @keyframes smoothbounceball{ from { transform: translate3d(0, 0, 0);} to { transform: translate3d(0, 200px, 0);}} Here, translate3d functions takes three inputs, the change in 3-dimensional axis (x, y, z). It will translate the ball in 3-Dimensional axes. If the ball wants to move up and down, the ball needs to translate along the y-axis. Running the keyframe: Since the @keyframe has been created, now it needs to run. In the above mentioned code of .ball{ }, a following a line has to be added: .ball{ Given statements... animation: bounce 0.5s; animation-direction: alternate; animation-iteration-count: infinite;} The understanding of the animation: The animation tells ball element to use the given keyframe rule bounce and sets the length of the animation of 0.5 seconds. Then at finishing, the animation direction alternates. Then runs the animation an infinite number of times. But it does not like the ball bounces but moves back and forth, up and down.Hence, it looks like: That is because the timing of the animation is off. Animations are set to ease, by default. So, to look like the ball is bouncing, the animation needs to be slow at the start and speeding up in the middle and then finishing slowly. Hence bezier curve is used to customize animation timings. Therefore the code: .ball{ Given statements.. animation: bounce 0.5s cubic-bezier(0.5, 0.05, 1, 0.5);} After this, the ball shows the bouncing effect. Here is the final code: <!DOCTYPE html><html> <head> <style> body { display: flex; justify-content: center; } .ball { width: 100px; height: 100px; border-radius: 50%; background-color: #FF5722; animation: bounce 0.5s; animation-direction: alternate; animation-timing-function: cubic-bezier(.5, 0.05, 1, .5); animation-iteration-count: infinite; } @keyframes bounce { from { transform: translate3d(0, 0, 0); } to { transform: translate3d(0, 200px, 0); } } /* Prefix Support */ ball { -webkit-animation-name: bounce; -webkit-animation-duration: 0.5s; -webkit-animation-direction: alternate; -webkit-animation-timing-function: cubic-bezier( .5, 0.05, 1, .5); -webkit-animation-iteration-count: infinite; } @-webkit-keyframes bounce { from { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } to { -webkit-transform: translate3d(0, 200px, 0); transform: translate3d(0, 200px, 0); } } </style></head> <body> <div class="ball"></div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to position a div at the bottom of its container using CSS? Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? Design a web page using HTML and CSS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26417, "s": 26389, "text": "\n28 Nov, 2019" }, { "code": null, "e": 26530, "s": 26417, "text": "The smooth bounce animation can be done with the help of HTML and CSS. It will generate fun and desired outputs." }, { "code": null, "e": 26601, "s": 26530, "text": "For this project, a simple div with class ball is needed in HTML page:" }, { "code": "<div class=\"ball\"></div>", "e": 26626, "s": 26601, "text": null }, { "code": null, "e": 26867, "s": 26626, "text": "We will switch to CSS for animation programming. Now, Flexbox is used to have the ball at the middle of the page and make the ball 70px by 70px in size. It can be taken in any size of the user’s choice as it determines the size of the ball." }, { "code": "body { display: flex; justify-content: center; }.ball { width: 100px; height: 100px; border-radius: 50%; background-color: #FF5722; }", "e": 27033, "s": 26867, "text": null }, { "code": null, "e": 27276, "s": 27033, "text": "Here,justify-content: center is used to center the ball horizontally.border-radius : 50% turns the square into a circle.background-color: #FF5722 turns the circle to orange colour. There are various code notations for colors to be remembered." }, { "code": null, "e": 27467, "s": 27276, "text": "Keyframe creating: Keyframes in CSS animations gives complete control over the animation. Simple use of the keyword @keyframes followed by the name of the animation, i.e, smooth bounce ball:" }, { "code": "@keyframes smoothbounceball{ statements}", "e": 27511, "s": 27467, "text": null }, { "code": null, "e": 27606, "s": 27511, "text": "Within the keyframe, use keywords from and to to make a start and end point for the animation." }, { "code": "@keyframes smoothbounceball{ from {/*starting*/} to {/*ending*/}}", "e": 27678, "s": 27606, "text": null }, { "code": null, "e": 27918, "s": 27678, "text": "To our understanding, we can add starting and ending values to the animation. To create a bouncing effect, we need to transform the location of the ball. transform allows to modify co-ordinates of a given element. Hence the final keyframe:" }, { "code": "@keyframes smoothbounceball{ from { transform: translate3d(0, 0, 0);} to { transform: translate3d(0, 200px, 0);}}", "e": 28038, "s": 27918, "text": null }, { "code": null, "e": 28265, "s": 28038, "text": "Here, translate3d functions takes three inputs, the change in 3-dimensional axis (x, y, z). It will translate the ball in 3-Dimensional axes. If the ball wants to move up and down, the ball needs to translate along the y-axis." }, { "code": null, "e": 28423, "s": 28265, "text": "Running the keyframe: Since the @keyframe has been created, now it needs to run. In the above mentioned code of .ball{ }, a following a line has to be added:" }, { "code": ".ball{ Given statements... animation: bounce 0.5s; animation-direction: alternate; animation-iteration-count: infinite;}", "e": 28558, "s": 28423, "text": null }, { "code": null, "e": 28826, "s": 28558, "text": "The understanding of the animation: The animation tells ball element to use the given keyframe rule bounce and sets the length of the animation of 0.5 seconds. Then at finishing, the animation direction alternates. Then runs the animation an infinite number of times." }, { "code": null, "e": 28924, "s": 28826, "text": "But it does not like the ball bounces but moves back and forth, up and down.Hence, it looks like:" }, { "code": null, "e": 29156, "s": 28924, "text": "That is because the timing of the animation is off. Animations are set to ease, by default. So, to look like the ball is bouncing, the animation needs to be slow at the start and speeding up in the middle and then finishing slowly." }, { "code": null, "e": 29235, "s": 29156, "text": "Hence bezier curve is used to customize animation timings. Therefore the code:" }, { "code": ".ball{ Given statements.. animation: bounce 0.5s cubic-bezier(0.5, 0.05, 1, 0.5);}", "e": 29326, "s": 29235, "text": null }, { "code": null, "e": 29398, "s": 29326, "text": "After this, the ball shows the bouncing effect. Here is the final code:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { display: flex; justify-content: center; } .ball { width: 100px; height: 100px; border-radius: 50%; background-color: #FF5722; animation: bounce 0.5s; animation-direction: alternate; animation-timing-function: cubic-bezier(.5, 0.05, 1, .5); animation-iteration-count: infinite; } @keyframes bounce { from { transform: translate3d(0, 0, 0); } to { transform: translate3d(0, 200px, 0); } } /* Prefix Support */ ball { -webkit-animation-name: bounce; -webkit-animation-duration: 0.5s; -webkit-animation-direction: alternate; -webkit-animation-timing-function: cubic-bezier( .5, 0.05, 1, .5); -webkit-animation-iteration-count: infinite; } @-webkit-keyframes bounce { from { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } to { -webkit-transform: translate3d(0, 200px, 0); transform: translate3d(0, 200px, 0); } } </style></head> <body> <div class=\"ball\"></div></body> </html>", "e": 30825, "s": 29398, "text": null }, { "code": null, "e": 30833, "s": 30825, "text": "Output:" }, { "code": null, "e": 30970, "s": 30833, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 30979, "s": 30970, "text": "CSS-Misc" }, { "code": null, "e": 30989, "s": 30979, "text": "HTML-Misc" }, { "code": null, "e": 30996, "s": 30989, "text": "Picked" }, { "code": null, "e": 31000, "s": 30996, "text": "CSS" }, { "code": null, "e": 31005, "s": 31000, "text": "HTML" }, { "code": null, "e": 31022, "s": 31005, "text": "Web Technologies" }, { "code": null, "e": 31027, "s": 31022, "text": "HTML" }, { "code": null, "e": 31125, "s": 31027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31180, "s": 31125, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 31244, "s": 31180, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 31281, "s": 31244, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31320, "s": 31281, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31357, "s": 31320, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31417, "s": 31357, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31470, "s": 31417, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31531, "s": 31470, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31555, "s": 31531, "text": "REST API (Introduction)" } ]
Perl | Finding Files and Directories - GeeksforGeeks
19 Jul, 2019 For traversing a directory tree in Perl, there are several ways/methods. Traversing can be performed through function calls opendir and readdir which are a part of Perl programming language. Traversing files and directories in Perl can also be done through File::Find module which comes with the Perl language. File::Find contains 2 modules: Find: find() function performs a depth-first search on the mentioned/defined @directories. It calls and invokes the "&wanted" function for each file or sub-directory found in that directory. find() works from top to down. Finddepth: finddepth() performs a post-order traversal instead of performing pre-order, working from down to top. Working of finddepth() function is almost similar to the find() function except for the fact that it invokes &wanted for directory’s content first than invokes it for the directory. The only difference among both the modules is the order in which the files and directories are parsed. Find modules in Perl has all the functions similar to the Unix Find command.Find function takes two arguments: 1st argument is a subroutine called for each file which we found through find function. 2nd argument is the list of the directories where find function is going to search the files. Following are some example scripts of Perl to find the Files and Directories:Example 1: To print all the available directories in the searched folder. #!usr/bin/perlprint "content-type: text/html\n\n"; use strict;use warnings;use File::Find; find({ wanted => \&findfiles,},'GeeksforGeeks'); sub findfiles{ #To search only the directory print "$File::Find::dir\n"; }exit; Output: Example 2: To print out the files available in a directory #!usr/bin/perlprint "content-type: text/html\n\n"; use strict;use warnings;use File::Find; find({ wanted => \&findfiles,},'GeeksforGeeks'); sub findfiles{ #To search the files inside the directories print "$File::Find::name\n"; }exit; Output: Example 3: Printing only once all the directories available/present in the folder/directory we are accessing. #!usr/bin/perlprint "content-type: text/html\n\n"; use strict;use warnings;use File::Find; find({ wanted => \&findfiles,},'GeeksforGeeks'); sub findfiles{ # To search all the available directories # in the given directory without accessing them print "$File::Find::name\n" if -d; }exit; Output: Example 4: To access the files present inside a directory without accessing the other directories available in that same directory. #!usr/bin/perlprint "content-type: text/html\n\n"; use strict;use warnings;use File::Find; find({ wanted => \&findfiles,},'GeeksforGeeks'); sub findfiles{ # Not accessing Geeks_New and Image directory # present inside the dir GeeksforGeeks $File::Find::prune = 1 if /Geeks_New/; $File::Find::prune = 1 if /Images/; # To print the files present in dir GeekforGeeks print "$File::Find::name\n"; }exit; Output: Example 5: Use of finddepth() function to find the files and sub-directories in a directory. #!usr/bin/perlprint "content-type: text/html\n\n"; use strict;use warnings;use File::Find; finddepth({ wanted => \&findfiles,},'GeeksforGeeks'); sub findfiles{ print "$File::Find::name\n";}exit; Example 6: To find all types of text files. #!usr/bin/perlprint "content-type: text/html\n\n"; use strict;use warnings;use File::Find; find({ wanted => \&findfiles,},'GeeksforGeeks'); sub findfiles{ print "$File::Find::name\n" if -T;}exit; Output: Perl-files Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | length() Function Perl | join() Function Perl | Basic Syntax of a Perl Program Perl | Boolean Values Perl | sleep() Function Perl | Subroutines or Functions
[ { "code": null, "e": 25285, "s": 25257, "text": "\n19 Jul, 2019" }, { "code": null, "e": 25596, "s": 25285, "text": "For traversing a directory tree in Perl, there are several ways/methods. Traversing can be performed through function calls opendir and readdir which are a part of Perl programming language. Traversing files and directories in Perl can also be done through File::Find module which comes with the Perl language." }, { "code": null, "e": 25627, "s": 25596, "text": "File::Find contains 2 modules:" }, { "code": null, "e": 25849, "s": 25627, "text": "Find: find() function performs a depth-first search on the mentioned/defined @directories. It calls and invokes the \"&wanted\" function for each file or sub-directory found in that directory. find() works from top to down." }, { "code": null, "e": 26145, "s": 25849, "text": "Finddepth: finddepth() performs a post-order traversal instead of performing pre-order, working from down to top. Working of finddepth() function is almost similar to the find() function except for the fact that it invokes &wanted for directory’s content first than invokes it for the directory." }, { "code": null, "e": 26359, "s": 26145, "text": "The only difference among both the modules is the order in which the files and directories are parsed. Find modules in Perl has all the functions similar to the Unix Find command.Find function takes two arguments:" }, { "code": null, "e": 26447, "s": 26359, "text": "1st argument is a subroutine called for each file which we found through find function." }, { "code": null, "e": 26541, "s": 26447, "text": "2nd argument is the list of the directories where find function is going to search the files." }, { "code": null, "e": 26692, "s": 26541, "text": "Following are some example scripts of Perl to find the Files and Directories:Example 1: To print all the available directories in the searched folder." }, { "code": "#!usr/bin/perlprint \"content-type: text/html\\n\\n\"; use strict;use warnings;use File::Find; find({ wanted => \\&findfiles,},'GeeksforGeeks'); sub findfiles{ #To search only the directory print \"$File::Find::dir\\n\"; }exit;", "e": 26928, "s": 26692, "text": null }, { "code": null, "e": 26995, "s": 26928, "text": "Output: Example 2: To print out the files available in a directory" }, { "code": "#!usr/bin/perlprint \"content-type: text/html\\n\\n\"; use strict;use warnings;use File::Find; find({ wanted => \\&findfiles,},'GeeksforGeeks'); sub findfiles{ #To search the files inside the directories print \"$File::Find::name\\n\"; }exit;", "e": 27250, "s": 26995, "text": null }, { "code": null, "e": 27368, "s": 27250, "text": "Output: Example 3: Printing only once all the directories available/present in the folder/directory we are accessing." }, { "code": "#!usr/bin/perlprint \"content-type: text/html\\n\\n\"; use strict;use warnings;use File::Find; find({ wanted => \\&findfiles,},'GeeksforGeeks'); sub findfiles{ # To search all the available directories # in the given directory without accessing them print \"$File::Find::name\\n\" if -d; }exit;", "e": 27681, "s": 27368, "text": null }, { "code": null, "e": 27821, "s": 27681, "text": "Output: Example 4: To access the files present inside a directory without accessing the other directories available in that same directory." }, { "code": "#!usr/bin/perlprint \"content-type: text/html\\n\\n\"; use strict;use warnings;use File::Find; find({ wanted => \\&findfiles,},'GeeksforGeeks'); sub findfiles{ # Not accessing Geeks_New and Image directory # present inside the dir GeeksforGeeks $File::Find::prune = 1 if /Geeks_New/; $File::Find::prune = 1 if /Images/; # To print the files present in dir GeekforGeeks print \"$File::Find::name\\n\"; }exit;", "e": 28255, "s": 27821, "text": null }, { "code": null, "e": 28356, "s": 28255, "text": "Output: Example 5: Use of finddepth() function to find the files and sub-directories in a directory." }, { "code": "#!usr/bin/perlprint \"content-type: text/html\\n\\n\"; use strict;use warnings;use File::Find; finddepth({ wanted => \\&findfiles,},'GeeksforGeeks'); sub findfiles{ print \"$File::Find::name\\n\";}exit;", "e": 28563, "s": 28356, "text": null }, { "code": null, "e": 28608, "s": 28563, "text": " Example 6: To find all types of text files." }, { "code": "#!usr/bin/perlprint \"content-type: text/html\\n\\n\"; use strict;use warnings;use File::Find; find({ wanted => \\&findfiles,},'GeeksforGeeks'); sub findfiles{ print \"$File::Find::name\\n\" if -T;}exit;", "e": 28819, "s": 28608, "text": null }, { "code": null, "e": 28827, "s": 28819, "text": "Output:" }, { "code": null, "e": 28838, "s": 28827, "text": "Perl-files" }, { "code": null, "e": 28843, "s": 28838, "text": "Perl" }, { "code": null, "e": 28848, "s": 28843, "text": "Perl" }, { "code": null, "e": 28946, "s": 28848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28988, "s": 28946, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 29002, "s": 28988, "text": "Perl | Arrays" }, { "code": null, "e": 29043, "s": 29002, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29076, "s": 29043, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 29101, "s": 29076, "text": "Perl | length() Function" }, { "code": null, "e": 29124, "s": 29101, "text": "Perl | join() Function" }, { "code": null, "e": 29162, "s": 29124, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 29184, "s": 29162, "text": "Perl | Boolean Values" }, { "code": null, "e": 29208, "s": 29184, "text": "Perl | sleep() Function" } ]
Python | Numpy.broadcast_arrays() method - GeeksforGeeks
17 Sep, 2019 With the help of Numpy.broadcast_arrays() method, we can get the one broadcasted array with the help of two or more arrays by using Numpy.broadcast_arrays() method. Syntax : Numpy.broadcast_arrays() Return : Return the broadcasted array using numpy. Example #1 :In this example we can see that by using Numpy.broadcast_arrays() method, we are able to get the broadcasted array using two or more numpy arrays. # import numpyimport numpy as np # using Numpy.broadcast_arrays() methodgfg1 = np.array([[1, 2]])gfg2 = np.array([[3], [4]]) print(np.broadcast_arrays(gfg1, gfg2)) Output : [array([[1, 2],[1, 2]]), array([[3, 3],[4, 4]])] Example #2 : # import numpyimport numpy as np # using Numpy.broadcast_arrays() methodgfg1 = np.array([[1, 2], [6, 7]])gfg2 = np.array([[3, 5], [4, 8]]) print(np.broadcast_arrays(gfg1, gfg2)) Output : [array([[1, 2],[6, 7]]), array([[3, 5],[4, 8]])] Python numpy-Basics 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": 25537, "s": 25509, "text": "\n17 Sep, 2019" }, { "code": null, "e": 25702, "s": 25537, "text": "With the help of Numpy.broadcast_arrays() method, we can get the one broadcasted array with the help of two or more arrays by using Numpy.broadcast_arrays() method." }, { "code": null, "e": 25736, "s": 25702, "text": "Syntax : Numpy.broadcast_arrays()" }, { "code": null, "e": 25787, "s": 25736, "text": "Return : Return the broadcasted array using numpy." }, { "code": null, "e": 25946, "s": 25787, "text": "Example #1 :In this example we can see that by using Numpy.broadcast_arrays() method, we are able to get the broadcasted array using two or more numpy arrays." }, { "code": "# import numpyimport numpy as np # using Numpy.broadcast_arrays() methodgfg1 = np.array([[1, 2]])gfg2 = np.array([[3], [4]]) print(np.broadcast_arrays(gfg1, gfg2))", "e": 26112, "s": 25946, "text": null }, { "code": null, "e": 26121, "s": 26112, "text": "Output :" }, { "code": null, "e": 26170, "s": 26121, "text": "[array([[1, 2],[1, 2]]), array([[3, 3],[4, 4]])]" }, { "code": null, "e": 26183, "s": 26170, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using Numpy.broadcast_arrays() methodgfg1 = np.array([[1, 2], [6, 7]])gfg2 = np.array([[3, 5], [4, 8]]) print(np.broadcast_arrays(gfg1, gfg2))", "e": 26363, "s": 26183, "text": null }, { "code": null, "e": 26372, "s": 26363, "text": "Output :" }, { "code": null, "e": 26421, "s": 26372, "text": "[array([[1, 2],[6, 7]]), array([[3, 5],[4, 8]])]" }, { "code": null, "e": 26441, "s": 26421, "text": "Python numpy-Basics" }, { "code": null, "e": 26448, "s": 26441, "text": "Python" }, { "code": null, "e": 26546, "s": 26448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26578, "s": 26546, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26620, "s": 26578, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26662, "s": 26620, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26689, "s": 26662, "text": "Python Classes and Objects" }, { "code": null, "e": 26745, "s": 26689, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26784, "s": 26745, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26806, "s": 26784, "text": "Defaultdict in Python" }, { "code": null, "e": 26837, "s": 26806, "text": "Python | os.path.join() method" }, { "code": null, "e": 26866, "s": 26837, "text": "Create a directory in Python" } ]
TypeScript | Array join() Method - GeeksforGeeks
18 Jun, 2020 The Array.join() is an inbuilt TypeScript function which is used to joins all the elements of an array into a string. Syntax: array.join(separator) Parameter: This method accept a single parameter as mentioned above and described below: separator : This parameter is the a string to separate each element of the array. Return Value: This method returns the string after joining all the array elements. Below examples illustrate the Array join() method in TypeScript. Example 1: JavaScript <script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of join() method var str = arr.join(", ") // printing element console.log("String : " + str);</script> Output: String : 11, 89, 23, 7, 98 Example 2: JavaScript <script> // Driver code var arr = [ 'a','b','c','a','e' ]; // use of join() method var val = arr.join(" ") var val1 = arr.join(" + ") // printing element console.log(val); console.log(val1);</script> Output: a b c a e a + b + c + a + e TypeScript 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25779, "s": 25751, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25905, "s": 25779, "text": "The Array.join() is an inbuilt TypeScript function which is used to joins all the elements of an array into a string. Syntax:" }, { "code": null, "e": 25928, "s": 25905, "text": "array.join(separator)\n" }, { "code": null, "e": 26017, "s": 25928, "text": "Parameter: This method accept a single parameter as mentioned above and described below:" }, { "code": null, "e": 26099, "s": 26017, "text": "separator : This parameter is the a string to separate each element of the array." }, { "code": null, "e": 26247, "s": 26099, "text": "Return Value: This method returns the string after joining all the array elements. Below examples illustrate the Array join() method in TypeScript." }, { "code": null, "e": 26259, "s": 26247, "text": "Example 1: " }, { "code": null, "e": 26270, "s": 26259, "text": "JavaScript" }, { "code": "<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of join() method var str = arr.join(\", \") // printing element console.log(\"String : \" + str);</script>", "e": 26466, "s": 26270, "text": null }, { "code": null, "e": 26475, "s": 26466, "text": "Output: " }, { "code": null, "e": 26504, "s": 26475, "text": "String : 11, 89, 23, 7, 98\n\n" }, { "code": null, "e": 26516, "s": 26504, "text": "Example 2: " }, { "code": null, "e": 26527, "s": 26516, "text": "JavaScript" }, { "code": "<script> // Driver code var arr = [ 'a','b','c','a','e' ]; // use of join() method var val = arr.join(\" \") var val1 = arr.join(\" + \") // printing element console.log(val); console.log(val1);</script>", "e": 26762, "s": 26527, "text": null }, { "code": null, "e": 26771, "s": 26762, "text": "Output: " }, { "code": null, "e": 26801, "s": 26771, "text": "a b c a e\na + b + c + a + e\n\n" }, { "code": null, "e": 26812, "s": 26801, "text": "TypeScript" }, { "code": null, "e": 26823, "s": 26812, "text": "JavaScript" }, { "code": null, "e": 26840, "s": 26823, "text": "Web Technologies" }, { "code": null, "e": 26938, "s": 26840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26978, "s": 26938, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27023, "s": 26978, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27084, "s": 27023, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27156, "s": 27084, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27208, "s": 27156, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27248, "s": 27208, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27281, "s": 27248, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27326, "s": 27281, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27369, "s": 27326, "text": "How to fetch data from an API in ReactJS ?" } ]
ML | Determine the optimal value of K in K-Means Clustering - GeeksforGeeks
12 Oct, 2021 Prerequisite: K-Means Clustering | IntroductionThere is a popular method known as elbow method which is used to determine the optimal value of K to perform the K-Means Clustering Algorithm. The basic idea behind this method is that it plots the various values of cost with changing k. As the value of K increases, there will be fewer elements in the cluster. So average distortion will decrease. The lesser number of elements means closer to the centroid. So, the point where this distortion declines the most is the elbow point. 3 clusters are forming In the above figure, its clearly observed that the distribution of points are forming 3 clusters. Now, let’s see the plot for the squared error(Cost) for different values of K. Elbow is forming at K=3 Clearly the elbow is forming at K=3. So the optimal value will be 3 for performing K-Means.Another Example with 4 clusters. 4-clusters Corresponding Cost graph- Elbow is forming at K=4 In this case the optimal value for k would be 4. (Observable from the scattered points).Below is the Python implementation: Python3 import matplotlib.pyplot as pltfrom matplotlib import stylefrom sklearn.cluster import KMeansfrom sklearn.datasets.samples_generator import make_blobs style.use("fivethirtyeight") # make_blobs() is used to generate sample points# around c centers (randomly chosen)X, y = make_blobs(n_samples = 100, centers = 4, cluster_std = 1, n_features = 2) plt.scatter(X[:, 0], X[:, 1], s = 30, color ='b') # label the axesplt.xlabel('X')plt.ylabel('Y') plt.show()plt.clf() # clear the figure Output: Python3 cost =[]for i in range(1, 11): KM = KMeans(n_clusters = i, max_iter = 500) KM.fit(X) # calculates squared error # for the clustered points cost.append(KM.inertia_) # plot the cost against K valuesplt.plot(range(1, 11), cost, color ='g', linewidth ='3')plt.xlabel("Value of K")plt.ylabel("Squared Error (Cost)")plt.show() # clear the plot # the point of the elbow is the# most optimal value for choosing k Output: surinderdawra388 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network Support Vector Machine Algorithm 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": 25667, "s": 25639, "text": "\n12 Oct, 2021" }, { "code": null, "e": 26198, "s": 25667, "text": "Prerequisite: K-Means Clustering | IntroductionThere is a popular method known as elbow method which is used to determine the optimal value of K to perform the K-Means Clustering Algorithm. The basic idea behind this method is that it plots the various values of cost with changing k. As the value of K increases, there will be fewer elements in the cluster. So average distortion will decrease. The lesser number of elements means closer to the centroid. So, the point where this distortion declines the most is the elbow point. " }, { "code": null, "e": 26221, "s": 26198, "text": "3 clusters are forming" }, { "code": null, "e": 26400, "s": 26221, "text": "In the above figure, its clearly observed that the distribution of points are forming 3 clusters. Now, let’s see the plot for the squared error(Cost) for different values of K. " }, { "code": null, "e": 26424, "s": 26400, "text": "Elbow is forming at K=3" }, { "code": null, "e": 26550, "s": 26424, "text": "Clearly the elbow is forming at K=3. So the optimal value will be 3 for performing K-Means.Another Example with 4 clusters. " }, { "code": null, "e": 26561, "s": 26550, "text": "4-clusters" }, { "code": null, "e": 26589, "s": 26561, "text": "Corresponding Cost graph- " }, { "code": null, "e": 26613, "s": 26589, "text": "Elbow is forming at K=4" }, { "code": null, "e": 26739, "s": 26613, "text": "In this case the optimal value for k would be 4. (Observable from the scattered points).Below is the Python implementation: " }, { "code": null, "e": 26747, "s": 26739, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltfrom matplotlib import stylefrom sklearn.cluster import KMeansfrom sklearn.datasets.samples_generator import make_blobs style.use(\"fivethirtyeight\") # make_blobs() is used to generate sample points# around c centers (randomly chosen)X, y = make_blobs(n_samples = 100, centers = 4, cluster_std = 1, n_features = 2) plt.scatter(X[:, 0], X[:, 1], s = 30, color ='b') # label the axesplt.xlabel('X')plt.ylabel('Y') plt.show()plt.clf() # clear the figure", "e": 27259, "s": 26747, "text": null }, { "code": null, "e": 27269, "s": 27259, "text": "Output: " }, { "code": null, "e": 27279, "s": 27271, "text": "Python3" }, { "code": "cost =[]for i in range(1, 11): KM = KMeans(n_clusters = i, max_iter = 500) KM.fit(X) # calculates squared error # for the clustered points cost.append(KM.inertia_) # plot the cost against K valuesplt.plot(range(1, 11), cost, color ='g', linewidth ='3')plt.xlabel(\"Value of K\")plt.ylabel(\"Squared Error (Cost)\")plt.show() # clear the plot # the point of the elbow is the# most optimal value for choosing k", "e": 27708, "s": 27279, "text": null }, { "code": null, "e": 27718, "s": 27708, "text": "Output: " }, { "code": null, "e": 27737, "s": 27720, "text": "surinderdawra388" }, { "code": null, "e": 27754, "s": 27737, "text": "Machine Learning" }, { "code": null, "e": 27761, "s": 27754, "text": "Python" }, { "code": null, "e": 27778, "s": 27761, "text": "Machine Learning" }, { "code": null, "e": 27876, "s": 27778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27890, "s": 27876, "text": "Decision Tree" }, { "code": null, "e": 27930, "s": 27890, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 27970, "s": 27930, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 28011, "s": 27970, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28044, "s": 28011, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28072, "s": 28044, "text": "Read JSON file using Python" }, { "code": null, "e": 28122, "s": 28072, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28144, "s": 28122, "text": "Python map() function" } ]
Longest Common Prefix using Divide and Conquer Algorithm - GeeksforGeeks
12 Jun, 2021 Given a set of strings, find the longest common prefix. Examples: Input : {β€œgeeksforgeeks”, β€œgeeks”, β€œgeek”, β€œgeezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" We have discussed word by word matching and character by character matching algorithms.In this algorithm, a divide and conquer approach is discussed. We first divide the arrays of string into two parts. Then we do the same for left part and after that for the right part. We will do it until and unless all the strings become of length 1. Now after that, we will start conquering by returning the common prefix of the left and the right strings. The algorithm will be clear using the below illustration. We consider our strings as – β€œgeeksforgeeks”, β€œgeeks”, β€œgeek”, β€œgeezer”. Below is the implementation. C++ Java Python3 C# Javascript // A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Utility Function to find the common prefix between// strings- str1 and str2string commonPrefixUtil(string str1, string str2){ string result; int n1 = str1.length(), n2 = str2.length(); for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++) { if (str1[i] != str2[j]) break; result.push_back(str1[i]); } return (result);} // A Divide and Conquer based function to find the// longest common prefix. This is similar to the// merge sort techniquestring commonPrefix(string arr[], int low, int high){ if (low == high) return (arr[low]); if (high > low) { // Same as (low + high)/2, but avoids overflow for // large low and high int mid = low + (high - low) / 2; string str1 = commonPrefix(arr, low, mid); string str2 = commonPrefix(arr, mid+1, high); return (commonPrefixUtil(str1, str2)); }} // Driver program to test above functionint main(){ string arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix(arr, 0, n-1); if (ans.length()) cout << "The longest common prefix is " << ans; else cout << "There is no common prefix"; return (0);} // Java Program to find the longest common prefix class GFG { // A Utility Function to find the common prefix between// strings- str1 and str2 static String commonPrefixUtil(String str1, String str2) { String result = ""; int n1 = str1.length(), n2 = str2.length(); for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { if (str1.charAt(i) != str2.charAt(j)) { break; } result += str1.charAt(i); } return (result); } // A Divide and Conquer based function to find the// longest common prefix. This is similar to the// merge sort technique static String commonPrefix(String arr[], int low, int high) { if (low == high) { return (arr[low]); } if (high > low) { // Same as (low + high)/2, but avoids overflow for // large low and high int mid = low + (high - low) / 2; String str1 = commonPrefix(arr, low, mid); String str2 = commonPrefix(arr, mid + 1, high); return (commonPrefixUtil(str1, str2)); } return null; } // Driver program to test above function public static void main(String[] args) { String arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.length; String ans = commonPrefix(arr, 0, n - 1); if (ans.length() != 0) { System.out.println("The longest common prefix is " + ans); } else { System.out.println("There is no common prefix"); } }}/* This JAVA code is contributed by 29AjayKumar*/ # A Python3 Program to find the longest common prefix # A Utility Function to find the common# prefix between strings- str1 and str2def commonPrefixUtil(str1, str2): result = "" n1, n2 = len(str1), len(str2) i, j = 0, 0 while i <= n1 - 1 and j <= n2 - 1: if str1[i] != str2[j]: break result += str1[i] i, j = i + 1, j + 1 return result # A Divide and Conquer based function to# find the longest common prefix. This is# similar to the merge sort techniquedef commonPrefix(arr, low, high): if low == high: return arr[low] if high > low: # Same as (low + high)/2, but avoids # overflow for large low and high mid = low + (high - low) // 2 str1 = commonPrefix(arr, low, mid) str2 = commonPrefix(arr, mid + 1, high) return commonPrefixUtil(str1, str2) # Driver Codeif __name__ == "__main__": arr = ["geeksforgeeks", "geeks", "geek", "geezer"] n = len(arr) ans = commonPrefix(arr, 0, n - 1) if len(ans): print("The longest common prefix is", ans) else: print("There is no common prefix") # This code is contributed by Rituraj Jain // C# Program to find the longest// common prefixusing System; class GFG{// A Utility Function to find// the common prefix between// strings- str1 and str2static string commonPrefixUtil(string str1, string str2){ string result = ""; int n1 = str1.Length, n2 = str2.Length; for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { if (str1[i] != str2[j]) break; result += str1[i]; } return (result);} // A Divide and Conquer based// function to find the longest// common prefix. This is similar// to the merge sort techniquestatic string commonPrefix(string []arr, int low, int high){ if (low == high) return (arr[low]); if (high > low) { // Same as (low + high)/2, // but avoids overflow for // large low and high int mid = low + (high - low) / 2; string str1 = commonPrefix(arr, low, mid); string str2 = commonPrefix(arr, mid + 1, high); return (commonPrefixUtil(str1, str2)); } return null;} // Driver Codepublic static void Main(){ String []arr = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.Length; String ans = commonPrefix(arr, 0, n - 1); if (ans.Length!= 0) { Console.Write("The longest common " + "prefix is " + ans); } else { Console.Write("There is no common prefix"); }}} // This code is contributed by 29AjayKumar <script> // Javascript program to find the// longest common prefix // A Utility Function to find the// common prefix between strings-// str1 and str2function commonPrefixUtil(str1, str2){ let result = ""; let n1 = str1.length, n2 = str2.length; for(let i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { if (str1[i] != str2[j]) { break; } result += str1[i]; } return (result);} // A Divide and Conquer based function// to find the longest common prefix. This// is similar to the merge sort techniquefunction commonPrefix(arr, low, high){ if (low == high) { return (arr[low]); } if (high > low) { // Same as (low + high)/2, but avoids // overflow for large low and high let mid = low + Math.floor((high - low) / 2); let str1 = commonPrefix(arr, low, mid); let str2 = commonPrefix(arr, mid + 1, high); return (commonPrefixUtil(str1, str2)); } return null;} // Driver codelet arr = [ "geeksforgeeks", "geeks", "geek", "geezer" ];let n = arr.length;let ans = commonPrefix(arr, 0, n - 1); if (ans.length != 0){ document.write( "The longest common prefix is " + ans);}else{ document.write( "There is no common prefix");} // This code is contributed by rag2127 </script> Output : The longest common prefix is gee Time Complexity: Since we are iterating through all the characters of all the strings, so we can say that the time complexity is O(N M) where, N = Number of strings M = Length of the largest string string Auxiliary Space: To store the longest prefix string we are allocating space which is O(M Log N). This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [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. 29AjayKumar rituraj_jain rag2127 Longest Common Prefix Divide and Conquer Strings Strings Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Write a program to calculate pow(x,n) Count number of occurrences (or frequency) in a sorted array Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26025, "s": 25997, "text": "\n12 Jun, 2021" }, { "code": null, "e": 26082, "s": 26025, "text": "Given a set of strings, find the longest common prefix. " }, { "code": null, "e": 26093, "s": 26082, "text": "Examples: " }, { "code": null, "e": 26212, "s": 26093, "text": "Input : {β€œgeeksforgeeks”, β€œgeeks”, β€œgeek”, β€œgeezer”}\nOutput : \"gee\"\n\nInput : {\"apple\", \"ape\", \"april\"}\nOutput : \"ap\"" }, { "code": null, "e": 26789, "s": 26212, "text": "We have discussed word by word matching and character by character matching algorithms.In this algorithm, a divide and conquer approach is discussed. We first divide the arrays of string into two parts. Then we do the same for left part and after that for the right part. We will do it until and unless all the strings become of length 1. Now after that, we will start conquering by returning the common prefix of the left and the right strings. The algorithm will be clear using the below illustration. We consider our strings as – β€œgeeksforgeeks”, β€œgeeks”, β€œgeek”, β€œgeezer”." }, { "code": null, "e": 26819, "s": 26789, "text": "Below is the implementation. " }, { "code": null, "e": 26823, "s": 26819, "text": "C++" }, { "code": null, "e": 26828, "s": 26823, "text": "Java" }, { "code": null, "e": 26836, "s": 26828, "text": "Python3" }, { "code": null, "e": 26839, "s": 26836, "text": "C#" }, { "code": null, "e": 26850, "s": 26839, "text": "Javascript" }, { "code": "// A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Utility Function to find the common prefix between// strings- str1 and str2string commonPrefixUtil(string str1, string str2){ string result; int n1 = str1.length(), n2 = str2.length(); for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++) { if (str1[i] != str2[j]) break; result.push_back(str1[i]); } return (result);} // A Divide and Conquer based function to find the// longest common prefix. This is similar to the// merge sort techniquestring commonPrefix(string arr[], int low, int high){ if (low == high) return (arr[low]); if (high > low) { // Same as (low + high)/2, but avoids overflow for // large low and high int mid = low + (high - low) / 2; string str1 = commonPrefix(arr, low, mid); string str2 = commonPrefix(arr, mid+1, high); return (commonPrefixUtil(str1, str2)); }} // Driver program to test above functionint main(){ string arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix(arr, 0, n-1); if (ans.length()) cout << \"The longest common prefix is \" << ans; else cout << \"There is no common prefix\"; return (0);}", "e": 28215, "s": 26850, "text": null }, { "code": "// Java Program to find the longest common prefix class GFG { // A Utility Function to find the common prefix between// strings- str1 and str2 static String commonPrefixUtil(String str1, String str2) { String result = \"\"; int n1 = str1.length(), n2 = str2.length(); for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { if (str1.charAt(i) != str2.charAt(j)) { break; } result += str1.charAt(i); } return (result); } // A Divide and Conquer based function to find the// longest common prefix. This is similar to the// merge sort technique static String commonPrefix(String arr[], int low, int high) { if (low == high) { return (arr[low]); } if (high > low) { // Same as (low + high)/2, but avoids overflow for // large low and high int mid = low + (high - low) / 2; String str1 = commonPrefix(arr, low, mid); String str2 = commonPrefix(arr, mid + 1, high); return (commonPrefixUtil(str1, str2)); } return null; } // Driver program to test above function public static void main(String[] args) { String arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.length; String ans = commonPrefix(arr, 0, n - 1); if (ans.length() != 0) { System.out.println(\"The longest common prefix is \" + ans); } else { System.out.println(\"There is no common prefix\"); } }}/* This JAVA code is contributed by 29AjayKumar*/", "e": 29865, "s": 28215, "text": null }, { "code": "# A Python3 Program to find the longest common prefix # A Utility Function to find the common# prefix between strings- str1 and str2def commonPrefixUtil(str1, str2): result = \"\" n1, n2 = len(str1), len(str2) i, j = 0, 0 while i <= n1 - 1 and j <= n2 - 1: if str1[i] != str2[j]: break result += str1[i] i, j = i + 1, j + 1 return result # A Divide and Conquer based function to# find the longest common prefix. This is# similar to the merge sort techniquedef commonPrefix(arr, low, high): if low == high: return arr[low] if high > low: # Same as (low + high)/2, but avoids # overflow for large low and high mid = low + (high - low) // 2 str1 = commonPrefix(arr, low, mid) str2 = commonPrefix(arr, mid + 1, high) return commonPrefixUtil(str1, str2) # Driver Codeif __name__ == \"__main__\": arr = [\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"] n = len(arr) ans = commonPrefix(arr, 0, n - 1) if len(ans): print(\"The longest common prefix is\", ans) else: print(\"There is no common prefix\") # This code is contributed by Rituraj Jain", "e": 31062, "s": 29865, "text": null }, { "code": "// C# Program to find the longest// common prefixusing System; class GFG{// A Utility Function to find// the common prefix between// strings- str1 and str2static string commonPrefixUtil(string str1, string str2){ string result = \"\"; int n1 = str1.Length, n2 = str2.Length; for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { if (str1[i] != str2[j]) break; result += str1[i]; } return (result);} // A Divide and Conquer based// function to find the longest// common prefix. This is similar// to the merge sort techniquestatic string commonPrefix(string []arr, int low, int high){ if (low == high) return (arr[low]); if (high > low) { // Same as (low + high)/2, // but avoids overflow for // large low and high int mid = low + (high - low) / 2; string str1 = commonPrefix(arr, low, mid); string str2 = commonPrefix(arr, mid + 1, high); return (commonPrefixUtil(str1, str2)); } return null;} // Driver Codepublic static void Main(){ String []arr = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.Length; String ans = commonPrefix(arr, 0, n - 1); if (ans.Length!= 0) { Console.Write(\"The longest common \" + \"prefix is \" + ans); } else { Console.Write(\"There is no common prefix\"); }}} // This code is contributed by 29AjayKumar", "e": 32598, "s": 31062, "text": null }, { "code": "<script> // Javascript program to find the// longest common prefix // A Utility Function to find the// common prefix between strings-// str1 and str2function commonPrefixUtil(str1, str2){ let result = \"\"; let n1 = str1.length, n2 = str2.length; for(let i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { if (str1[i] != str2[j]) { break; } result += str1[i]; } return (result);} // A Divide and Conquer based function// to find the longest common prefix. This// is similar to the merge sort techniquefunction commonPrefix(arr, low, high){ if (low == high) { return (arr[low]); } if (high > low) { // Same as (low + high)/2, but avoids // overflow for large low and high let mid = low + Math.floor((high - low) / 2); let str1 = commonPrefix(arr, low, mid); let str2 = commonPrefix(arr, mid + 1, high); return (commonPrefixUtil(str1, str2)); } return null;} // Driver codelet arr = [ \"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\" ];let n = arr.length;let ans = commonPrefix(arr, 0, n - 1); if (ans.length != 0){ document.write( \"The longest common prefix is \" + ans);}else{ document.write( \"There is no common prefix\");} // This code is contributed by rag2127 </script>", "e": 33947, "s": 32598, "text": null }, { "code": null, "e": 33957, "s": 33947, "text": "Output : " }, { "code": null, "e": 33990, "s": 33957, "text": "The longest common prefix is gee" }, { "code": null, "e": 34134, "s": 33990, "text": "Time Complexity: Since we are iterating through all the characters of all the strings, so we can say that the time complexity is O(N M) where, " }, { "code": null, "e": 34196, "s": 34134, "text": "N = Number of strings\nM = Length of the largest string string" }, { "code": null, "e": 34293, "s": 34196, "text": "Auxiliary Space: To store the longest prefix string we are allocating space which is O(M Log N)." }, { "code": null, "e": 34689, "s": 34293, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [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": 34701, "s": 34689, "text": "29AjayKumar" }, { "code": null, "e": 34714, "s": 34701, "text": "rituraj_jain" }, { "code": null, "e": 34722, "s": 34714, "text": "rag2127" }, { "code": null, "e": 34744, "s": 34722, "text": "Longest Common Prefix" }, { "code": null, "e": 34763, "s": 34744, "text": "Divide and Conquer" }, { "code": null, "e": 34771, "s": 34763, "text": "Strings" }, { "code": null, "e": 34779, "s": 34771, "text": "Strings" }, { "code": null, "e": 34798, "s": 34779, "text": "Divide and Conquer" }, { "code": null, "e": 34896, "s": 34798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34923, "s": 34896, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 34967, "s": 34923, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 35014, "s": 34967, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 35052, "s": 35014, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 35113, "s": 35052, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 35159, "s": 35113, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35184, "s": 35159, "text": "Reverse a string in Java" }, { "code": null, "e": 35244, "s": 35184, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35259, "s": 35244, "text": "C++ Data Types" } ]
C# | Check if an array is synchronized (thread safe) or not - GeeksforGeeks
01 Feb, 2019 Array.IsSynchronized Property is used to get a value which indicates whether access to the Array is synchronized (thread-safe) or not. Syntax: public bool IsSynchronized { get; } Property Value: This property always returns false for all arrays. Below programs illustrate the use of above-discussed property: Example 1: // C# program to illustrate// IsSynchronized Property of// Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // The array with dimensions // specified 4 row and 2 column. int[, ] arr = new int[4, 2] {{1, 2 }, {3, 4}, {5, 6 }, {7, 8}}; // Here we check whether the // array is synchronized (thread safe) // or not Console.WriteLine("Result: " + arr.IsSynchronized); }}} Result: False Example 2: // C# program to illustrate// IsSynchronized Property of// Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating null to array topic = new string[] { null }; // Here we check whether the // array is synchronized (thread safe) // or not Console.WriteLine("Result: " + topic.IsSynchronized); }}} Result: False Note: Array implements the IsSynchronized property because it is needed by the System.Collections.ICollection interface. Classes which uses the arrays can also implement their own synchronization using the SyncRoot property. Enumerating through a collection is not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. Retrieving the value of this property is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.issynchronized?view=netframework-4.7.2 CSharp-Arrays 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# | Replace() Method Introduction to .NET Framework
[ { "code": null, "e": 25833, "s": 25805, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25968, "s": 25833, "text": "Array.IsSynchronized Property is used to get a value which indicates whether access to the Array is synchronized (thread-safe) or not." }, { "code": null, "e": 25976, "s": 25968, "text": "Syntax:" }, { "code": null, "e": 26012, "s": 25976, "text": "public bool IsSynchronized { get; }" }, { "code": null, "e": 26079, "s": 26012, "text": "Property Value: This property always returns false for all arrays." }, { "code": null, "e": 26142, "s": 26079, "text": "Below programs illustrate the use of above-discussed property:" }, { "code": null, "e": 26153, "s": 26142, "text": "Example 1:" }, { "code": "// C# program to illustrate// IsSynchronized Property of// Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // The array with dimensions // specified 4 row and 2 column. int[, ] arr = new int[4, 2] {{1, 2 }, {3, 4}, {5, 6 }, {7, 8}}; // Here we check whether the // array is synchronized (thread safe) // or not Console.WriteLine(\"Result: \" + arr.IsSynchronized); }}}", "e": 26693, "s": 26153, "text": null }, { "code": null, "e": 26708, "s": 26693, "text": "Result: False\n" }, { "code": null, "e": 26719, "s": 26708, "text": "Example 2:" }, { "code": "// C# program to illustrate// IsSynchronized Property of// Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating null to array topic = new string[] { null }; // Here we check whether the // array is synchronized (thread safe) // or not Console.WriteLine(\"Result: \" + topic.IsSynchronized); }}}", "e": 27206, "s": 26719, "text": null }, { "code": null, "e": 27221, "s": 27206, "text": "Result: False\n" }, { "code": null, "e": 27227, "s": 27221, "text": "Note:" }, { "code": null, "e": 27342, "s": 27227, "text": "Array implements the IsSynchronized property because it is needed by the System.Collections.ICollection interface." }, { "code": null, "e": 27446, "s": 27342, "text": "Classes which uses the arrays can also implement their own synchronization using the SyncRoot property." }, { "code": null, "e": 27831, "s": 27446, "text": "Enumerating through a collection is not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads." }, { "code": null, "e": 27891, "s": 27831, "text": "Retrieving the value of this property is an O(1) operation." }, { "code": null, "e": 27902, "s": 27891, "text": "Reference:" }, { "code": null, "e": 27998, "s": 27902, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.issynchronized?view=netframework-4.7.2" }, { "code": null, "e": 28012, "s": 27998, "text": "CSharp-Arrays" }, { "code": null, "e": 28015, "s": 28012, "text": "C#" }, { "code": null, "e": 28113, "s": 28015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28141, "s": 28113, "text": "C# Dictionary with examples" }, { "code": null, "e": 28156, "s": 28141, "text": "C# | Delegates" }, { "code": null, "e": 28179, "s": 28156, "text": "C# | Method Overriding" }, { "code": null, "e": 28201, "s": 28179, "text": "C# | Abstract Classes" }, { "code": null, "e": 28247, "s": 28201, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28270, "s": 28247, "text": "Extension Method in C#" }, { "code": null, "e": 28292, "s": 28270, "text": "C# | Class and Object" }, { "code": null, "e": 28310, "s": 28292, "text": "C# | Constructors" }, { "code": null, "e": 28332, "s": 28310, "text": "C# | Replace() Method" } ]
Python | Iterate over multiple lists simultaneously - GeeksforGeeks
18 Aug, 2021 Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding of iteration of multiple lists, we are iterating over 3 lists at a time. We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.Below is an implementation of the zip function and itertools.izip which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using zip function import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and executes # 2 times as len(value)= 2 which is the# minimum among all the three for (a, b, c) in zip(num, color, value): print (a, b, c)Output:1 red 255 2 while 256 itertools.zip_longest() : zip_longest stops when all lists are exhausted. When the shorter iterator(s) are exhausted, zip_longest yields a tuple with None value.Below is an implementation of the itertools.zip_longest which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and till all are exhaustedfor (a, b, c) in itertools.zip_longest(num, color, value): print (a, b, c)Output:1 red 255 2 while 256 3 black None Output:1 red 255 2 while 256 3 black None zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.Below is an implementation of the zip function and itertools.izip which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using zip function import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and executes # 2 times as len(value)= 2 which is the# minimum among all the three for (a, b, c) in zip(num, color, value): print (a, b, c)Output:1 red 255 2 while 256 Below is an implementation of the zip function and itertools.izip which iterates over 3 lists: Python3 # Python program to iterate# over 3 lists using zip function import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and executes # 2 times as len(value)= 2 which is the# minimum among all the three for (a, b, c) in zip(num, color, value): print (a, b, c) 1 red 255 2 while 256 itertools.zip_longest() : zip_longest stops when all lists are exhausted. When the shorter iterator(s) are exhausted, zip_longest yields a tuple with None value.Below is an implementation of the itertools.zip_longest which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and till all are exhaustedfor (a, b, c) in itertools.zip_longest(num, color, value): print (a, b, c)Output:1 red 255 2 while 256 3 black None Output:1 red 255 2 while 256 3 black None Below is an implementation of the itertools.zip_longest which iterates over 3 lists: Python3 # Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and till all are exhaustedfor (a, b, c) in itertools.zip_longest(num, color, value): print (a, b, c) 1 red 255 2 while 256 3 black None Output: 1 red 255 2 while 256 3 black None We can also specify a default value instead of None in zip_longest() Python3 # Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # Specifying default value as -1for (a, b, c) in itertools.zip_longest(num, color, value, fillvalue=-1): print (a, b, c) 1 red 255 2 while 256 3 black -1 Note : Python 2.x had two extra functions izip() and izip_longest(). In Python 2.x, zip() and zip_longest() used to return list, and izip() and izip_longest() used to return iterator. In Python 3.x, there izip() and izip_longest() are not there as zip() and zip_longest() return iterator. Sheetansh kumar abhishek0719kadiyan python-list Python python-list 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 ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25687, "s": 25659, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25974, "s": 25687, "text": "Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step." }, { "code": null, "e": 26012, "s": 25974, "text": "Iterate over multiple lists at a time" }, { "code": null, "e": 26110, "s": 26012, "text": "For better understanding of iteration of multiple lists, we are iterating over 3 lists at a time." }, { "code": null, "e": 26160, "s": 26110, "text": "We can iterate over lists simultaneously in ways:" }, { "code": null, "e": 27425, "s": 26160, "text": "zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.Below is an implementation of the zip function and itertools.izip which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using zip function import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and executes # 2 times as len(value)= 2 which is the# minimum among all the three for (a, b, c) in zip(num, color, value): print (a, b, c)Output:1 red 255\n2 while 256\nitertools.zip_longest() : zip_longest stops when all lists are exhausted. When the shorter iterator(s) are exhausted, zip_longest yields a tuple with None value.Below is an implementation of the itertools.zip_longest which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and till all are exhaustedfor (a, b, c) in itertools.zip_longest(num, color, value): print (a, b, c)Output:1 red 255\n2 while 256\n3 black None\nOutput:1 red 255\n2 while 256\n3 black None\n" }, { "code": null, "e": 28062, "s": 27425, "text": "zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.Below is an implementation of the zip function and itertools.izip which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using zip function import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and executes # 2 times as len(value)= 2 which is the# minimum among all the three for (a, b, c) in zip(num, color, value): print (a, b, c)Output:1 red 255\n2 while 256\n" }, { "code": null, "e": 28157, "s": 28062, "text": "Below is an implementation of the zip function and itertools.izip which iterates over 3 lists:" }, { "code": null, "e": 28165, "s": 28157, "text": "Python3" }, { "code": "# Python program to iterate# over 3 lists using zip function import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and executes # 2 times as len(value)= 2 which is the# minimum among all the three for (a, b, c) in zip(num, color, value): print (a, b, c)", "e": 28481, "s": 28165, "text": null }, { "code": null, "e": 28504, "s": 28481, "text": "1 red 255\n2 while 256\n" }, { "code": null, "e": 29133, "s": 28504, "text": "itertools.zip_longest() : zip_longest stops when all lists are exhausted. When the shorter iterator(s) are exhausted, zip_longest yields a tuple with None value.Below is an implementation of the itertools.zip_longest which iterates over 3 lists:Python3Python3# Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and till all are exhaustedfor (a, b, c) in itertools.zip_longest(num, color, value): print (a, b, c)Output:1 red 255\n2 while 256\n3 black None\nOutput:1 red 255\n2 while 256\n3 black None\n" }, { "code": null, "e": 29218, "s": 29133, "text": "Below is an implementation of the itertools.zip_longest which iterates over 3 lists:" }, { "code": null, "e": 29226, "s": 29218, "text": "Python3" }, { "code": "# Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # iterates over 3 lists and till all are exhaustedfor (a, b, c) in itertools.zip_longest(num, color, value): print (a, b, c)", "e": 29512, "s": 29226, "text": null }, { "code": null, "e": 29548, "s": 29512, "text": "1 red 255\n2 while 256\n3 black None\n" }, { "code": null, "e": 29556, "s": 29548, "text": "Output:" }, { "code": null, "e": 29592, "s": 29556, "text": "1 red 255\n2 while 256\n3 black None\n" }, { "code": null, "e": 29661, "s": 29592, "text": "We can also specify a default value instead of None in zip_longest()" }, { "code": null, "e": 29669, "s": 29661, "text": "Python3" }, { "code": "# Python program to iterate# over 3 lists using itertools.zip_longest import itertools num = [1, 2, 3]color = ['red', 'while', 'black']value = [255, 256] # Specifying default value as -1for (a, b, c) in itertools.zip_longest(num, color, value, fillvalue=-1): print (a, b, c)", "e": 29951, "s": 29669, "text": null }, { "code": null, "e": 29985, "s": 29951, "text": "1 red 255\n2 while 256\n3 black -1\n" }, { "code": null, "e": 30274, "s": 29985, "text": "Note : Python 2.x had two extra functions izip() and izip_longest(). In Python 2.x, zip() and zip_longest() used to return list, and izip() and izip_longest() used to return iterator. In Python 3.x, there izip() and izip_longest() are not there as zip() and zip_longest() return iterator." }, { "code": null, "e": 30290, "s": 30274, "text": "Sheetansh kumar" }, { "code": null, "e": 30310, "s": 30290, "text": "abhishek0719kadiyan" }, { "code": null, "e": 30322, "s": 30310, "text": "python-list" }, { "code": null, "e": 30329, "s": 30322, "text": "Python" }, { "code": null, "e": 30341, "s": 30329, "text": "python-list" }, { "code": null, "e": 30439, "s": 30341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30457, "s": 30439, "text": "Python Dictionary" }, { "code": null, "e": 30492, "s": 30457, "text": "Read a file line by line in Python" }, { "code": null, "e": 30524, "s": 30492, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30566, "s": 30524, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30592, "s": 30566, "text": "Python String | replace()" }, { "code": null, "e": 30621, "s": 30592, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30665, "s": 30621, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30702, "s": 30665, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30738, "s": 30702, "text": "Convert integer to string in Python" } ]
Deque interface in Java
java.util.Deque interface is a subtype of java.util.Queue interface which supports insertion and removal of elements at both ends. public interface Deque<E> extends Queue<E> The java.util.ArrayDeque class provides resizable-array and implements the Deque interface. Following are the important points about Array Deques βˆ’ Array deques have no capacity restrictions so they grow as necessary to support usage. Array deques have no capacity restrictions so they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization. They are not thread-safe; in the absence of external synchronization. They do not support concurrent access by multiple threads. They do not support concurrent access by multiple threads. Null elements are prohibited in the array deques. Null elements are prohibited in the array deques. They are faster than Stack and LinkedList. They are faster than Stack and LinkedList. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. Following is the declaration for java.util.ArrayDeque class βˆ’ public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable Here <E> represents an Element, which could be any class. For example, if you're building an array list of Integers then you'd initialize it as βˆ’ ArrayList<Integer> list = new ArrayList<Integer>(); import java.util.ArrayDeque; import java.util.Deque; public class Tester { public static void main(String[] args) { // create an empty array deque with an initial capacity Deque<Integer> deque = new ArrayDeque<Integer>(5); // use add() method to add elements in the deque deque.add(20); deque.add(30); deque.add(20); deque.add(30); deque.add(15); deque.add(22); deque.add(11); // let us print all the elements available in deque for (Integer number : deque) { System.out.println("Number = " + number); } // getFirst() will retrieve element at first position int first = deque.getFirst(); System.out.println("Retrieved Element is = " + first); // getLast() will retrieve element at last position int last = deque.getLast(); System.out.println("Retrieved Element is = " + last); } } Number = 20 Number = 30 Number = 20 Number = 30 Number = 15 Number = 22 Number = 11 Retrieved Element is = 20 Retrieved Element is = 11
[ { "code": null, "e": 1193, "s": 1062, "text": "java.util.Deque interface is a subtype of java.util.Queue interface which supports insertion and removal of elements at both ends." }, { "code": null, "e": 1236, "s": 1193, "text": "public interface Deque<E>\nextends Queue<E>" }, { "code": null, "e": 1384, "s": 1236, "text": "The java.util.ArrayDeque class provides resizable-array and implements the Deque interface. Following are the important points about Array Deques βˆ’" }, { "code": null, "e": 1471, "s": 1384, "text": "Array deques have no capacity restrictions so they grow as necessary to support usage." }, { "code": null, "e": 1558, "s": 1471, "text": "Array deques have no capacity restrictions so they grow as necessary to support usage." }, { "code": null, "e": 1628, "s": 1558, "text": "They are not thread-safe; in the absence of external synchronization." }, { "code": null, "e": 1698, "s": 1628, "text": "They are not thread-safe; in the absence of external synchronization." }, { "code": null, "e": 1757, "s": 1698, "text": "They do not support concurrent access by multiple threads." }, { "code": null, "e": 1816, "s": 1757, "text": "They do not support concurrent access by multiple threads." }, { "code": null, "e": 1866, "s": 1816, "text": "Null elements are prohibited in the array deques." }, { "code": null, "e": 1916, "s": 1866, "text": "Null elements are prohibited in the array deques." }, { "code": null, "e": 1959, "s": 1916, "text": "They are faster than Stack and LinkedList." }, { "code": null, "e": 2002, "s": 1959, "text": "They are faster than Stack and LinkedList." }, { "code": null, "e": 2111, "s": 2002, "text": "This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces." }, { "code": null, "e": 2173, "s": 2111, "text": "Following is the declaration for java.util.ArrayDeque class βˆ’" }, { "code": null, "e": 2275, "s": 2173, "text": "public class ArrayDeque<E>\nextends AbstractCollection<E>\nimplements Deque<E>, Cloneable, Serializable" }, { "code": null, "e": 2421, "s": 2275, "text": "Here <E> represents an Element, which could be any class. For example, if you're building an array list of Integers then you'd initialize it as βˆ’" }, { "code": null, "e": 2473, "s": 2421, "text": "ArrayList<Integer> list = new ArrayList<Integer>();" }, { "code": null, "e": 3389, "s": 2473, "text": "import java.util.ArrayDeque;\nimport java.util.Deque;\n\npublic class Tester {\n public static void main(String[] args) {\n\n // create an empty array deque with an initial capacity\n Deque<Integer> deque = new ArrayDeque<Integer>(5);\n\n // use add() method to add elements in the deque\n deque.add(20);\n deque.add(30);\n deque.add(20);\n deque.add(30);\n deque.add(15);\n deque.add(22);\n deque.add(11);\n\n // let us print all the elements available in deque\n for (Integer number : deque) {\n System.out.println(\"Number = \" + number);\n }\n\n // getFirst() will retrieve element at first position\n int first = deque.getFirst();\n System.out.println(\"Retrieved Element is = \" + first);\n\n // getLast() will retrieve element at last position\n int last = deque.getLast();\n System.out.println(\"Retrieved Element is = \" + last);\n }\n}" }, { "code": null, "e": 3525, "s": 3389, "text": "Number = 20\nNumber = 30\nNumber = 20\nNumber = 30\nNumber = 15\nNumber = 22\nNumber = 11\nRetrieved Element is = 20\nRetrieved Element is = 11" } ]
Cyclically rotate an array by one | Practice | GeeksforGeeks
Given an array, rotate the array by one position in clock-wise direction. Example 1: Input: N = 5 A[] = {1, 2, 3, 4, 5} Output: 5 1 2 3 4 Example 2: Input: N = 8 A[] = {9, 8, 7, 6, 4, 2, 1, 3} Output: 3 9 8 7 6 4 2 1 Your Task: You don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1<=N<=105 0<=a[i]<=105 0 amreshpathak1 hour ago Simple Solution:- public void rotate(int arr[], int n) { int temp = arr[arr.length - 1]; for(int i = arr.length-1;i>0;i--){ arr[i] = arr[i-1]; } arr[0] = temp; } 0 aryanraveshia126 hours ago void rotate(int arr[], int n){ int temp = arr[n-1]; for(int i=1;i<=n;i++){ arr[n-i] = arr[n-i-1]; } arr[0] = temp;} 0 georgepriji8 hours ago //c,c++, java int k = arr[n-1]; for(int i = n-2; i>=0; i--){ k = arr[i+1]; arr[i+1]=arr[i]; arr[i] = k; } arr[0] = k; +1 shubhsahane12341 day ago void rotate(int arr[], int n){ for(int i=0;i<n;i++){ int temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; }} +1 rahulvishwas26021 day ago int temp=arr[n-1];for(int i=n-1;i>0;i--){ arr[i]=arr[i-1];}arr[0]=temp; 0 ateebashway1712 days ago void rotate(int arr[], int n){ for(int i=n-1; i>=1; i--){ int temp = arr[i]; arr[i] = arr[i-1]; arr[i-1] = temp; }} 0 himanshusethin2 days ago if(n>1){ int temp = arr[n-1]; for(int i =n-1;i>0;i--) arr[i] = arr[i-1]; arr[0] = temp; } 0 pramodchary242 days ago public void rotate(int arr[], int n) { int temp1=arr[n-1]; int temp2=0; for(int i=0; i<n; i++){ temp2=arr[i]; arr[i]=temp1; temp1=temp2; } } +1 harshscode5 days ago int t=a[n-1]; for(int i=n-1;i>0;i--) a[i]=a[i-1]; a[0]=t; -1 harshscode5 days ago for(int i=0;i<n;i++) { int t=a[i]; a[i]=a[n-1]; a[n-1]=t; } 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": 314, "s": 238, "text": "Given an array, rotate the array by one position in clock-wise direction.\n " }, { "code": null, "e": 325, "s": 314, "text": "Example 1:" }, { "code": null, "e": 378, "s": 325, "text": "Input:\nN = 5\nA[] = {1, 2, 3, 4, 5}\nOutput:\n5 1 2 3 4" }, { "code": null, "e": 391, "s": 380, "text": "Example 2:" }, { "code": null, "e": 459, "s": 391, "text": "Input:\nN = 8\nA[] = {9, 8, 7, 6, 4, 2, 1, 3}\nOutput:\n3 9 8 7 6 4 2 1" }, { "code": null, "e": 642, "s": 461, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array." }, { "code": null, "e": 706, "s": 644, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 744, "s": 708, "text": "Constraints:\n1<=N<=105\n0<=a[i]<=105" }, { "code": null, "e": 746, "s": 744, "text": "0" }, { "code": null, "e": 769, "s": 746, "text": "amreshpathak1 hour ago" }, { "code": null, "e": 788, "s": 769, "text": "Simple Solution:- " }, { "code": null, "e": 972, "s": 790, "text": "public void rotate(int arr[], int n) { int temp = arr[arr.length - 1]; for(int i = arr.length-1;i>0;i--){ arr[i] = arr[i-1]; } arr[0] = temp; }" }, { "code": null, "e": 974, "s": 972, "text": "0" }, { "code": null, "e": 1001, "s": 974, "text": "aryanraveshia126 hours ago" }, { "code": null, "e": 1131, "s": 1001, "text": "void rotate(int arr[], int n){ int temp = arr[n-1]; for(int i=1;i<=n;i++){ arr[n-i] = arr[n-i-1]; } arr[0] = temp;}" }, { "code": null, "e": 1133, "s": 1131, "text": "0" }, { "code": null, "e": 1156, "s": 1133, "text": "georgepriji8 hours ago" }, { "code": null, "e": 1170, "s": 1156, "text": "//c,c++, java" }, { "code": null, "e": 1298, "s": 1170, "text": "int k = arr[n-1]; for(int i = n-2; i>=0; i--){ k = arr[i+1]; arr[i+1]=arr[i]; arr[i] = k; } arr[0] = k;" }, { "code": null, "e": 1301, "s": 1298, "text": "+1" }, { "code": null, "e": 1326, "s": 1301, "text": "shubhsahane12341 day ago" }, { "code": null, "e": 1447, "s": 1326, "text": "void rotate(int arr[], int n){ for(int i=0;i<n;i++){ int temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; }}" }, { "code": null, "e": 1450, "s": 1447, "text": "+1" }, { "code": null, "e": 1476, "s": 1450, "text": "rahulvishwas26021 day ago" }, { "code": null, "e": 1550, "s": 1476, "text": "int temp=arr[n-1];for(int i=n-1;i>0;i--){ arr[i]=arr[i-1];}arr[0]=temp;" }, { "code": null, "e": 1552, "s": 1550, "text": "0" }, { "code": null, "e": 1577, "s": 1552, "text": "ateebashway1712 days ago" }, { "code": null, "e": 1715, "s": 1577, "text": "void rotate(int arr[], int n){ for(int i=n-1; i>=1; i--){ int temp = arr[i]; arr[i] = arr[i-1]; arr[i-1] = temp; }}" }, { "code": null, "e": 1717, "s": 1715, "text": "0" }, { "code": null, "e": 1742, "s": 1717, "text": "himanshusethin2 days ago" }, { "code": null, "e": 1862, "s": 1742, "text": "if(n>1){ int temp = arr[n-1]; for(int i =n-1;i>0;i--) arr[i] = arr[i-1]; arr[0] = temp; }" }, { "code": null, "e": 1864, "s": 1862, "text": "0" }, { "code": null, "e": 1888, "s": 1864, "text": "pramodchary242 days ago" }, { "code": null, "e": 2087, "s": 1888, "text": "public void rotate(int arr[], int n) { int temp1=arr[n-1]; int temp2=0; for(int i=0; i<n; i++){ temp2=arr[i]; arr[i]=temp1; temp1=temp2; } }" }, { "code": null, "e": 2090, "s": 2087, "text": "+1" }, { "code": null, "e": 2111, "s": 2090, "text": "harshscode5 days ago" }, { "code": null, "e": 2174, "s": 2111, "text": " int t=a[n-1]; for(int i=n-1;i>0;i--) a[i]=a[i-1]; a[0]=t;" }, { "code": null, "e": 2177, "s": 2174, "text": "-1" }, { "code": null, "e": 2198, "s": 2177, "text": "harshscode5 days ago" }, { "code": null, "e": 2276, "s": 2198, "text": " for(int i=0;i<n;i++) { int t=a[i]; a[i]=a[n-1]; a[n-1]=t; }" }, { "code": null, "e": 2422, "s": 2276, "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": 2458, "s": 2422, "text": " Login to access your submissions. " }, { "code": null, "e": 2468, "s": 2458, "text": "\nProblem\n" }, { "code": null, "e": 2478, "s": 2468, "text": "\nContest\n" }, { "code": null, "e": 2541, "s": 2478, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2689, "s": 2541, "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": 2897, "s": 2689, "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": 3003, "s": 2897, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Mastering TensorFlow β€œVariables” in 5 Easy Steps | by Orhan G. YalcΜ§Δ±n | Medium | Towards Data Science
WARNING: Do not confuse this article with β€œMastering TensorFlow Tensors in 5 Easy Steps”! If you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. YalcΜ§Δ±n β€” Linkedin In this tutorial, we will focus on TensorFlow Variables. After the tutorial, you will be able to create, update, and manage TensorFlow Variables effectively. As usual, our tutorial will deliver code examples with detailed explanations as well as conceptual explanations. We will master TensorFlow Variables in 5 easy steps: Step 1: Definition of Variables β†’A Brief Introduction, Comparison with Tensors Step 2: Creation of Variables β†’ Instantiating tf.Variable Objects Step 3: Qualifications of Variables β†’ Characteristics and Features Step 4: Operations with Variables β†’ Basic Tensor Operations, Indexing, Shape Manipulation, and Broadcasting Step 5: Hardware Selection for Variables β†’ GPUs, CPUs, TPUs Fasten your belts, and let’s start! In this step, we will briefly cover what Variables are and understand the difference between plain Tensor objects and Variable objects. A TensorFlow Variable is the preferred object type representing a shared and persistent state that you can manipulate with any operation, including TensorFlow models. Manipulation refers to any value or parameter update. This characteristic is the most distinguishing feature of Variables compared to tf.Tensor objects. TensorFlow Variables are recorded as tf.Variable objects. Let’s make a brief comparison between tf.Tensor and tf.Variable objects to understand their similarities and differences. So, the most important difference between Variables and Tensors is mutability. The values in a Variable object can be updated (e.g., with the assign() function) as opposed to Tensors. β€œThe values of tensor objects cannot be updated, and you can only create a new Tensor object with the new values.” Variable objects are mainly used to store model parameters, and since these values are constantly updated during training, using Variables, instead of Tensors, is a necessity rather than a choice. The shape of a Variable object can be updated with the reshape() instance function just like the shape of a Tensor object. Since Variable objects are built on top of Tensor objects, they have common attributes such as .shape and .dtype. But, Variables also have unique attributes such as .trainable,.device, and .name attributes that the Tensors do not have. Let’s see how we can create tf.Variable objects! We can instantiate (i.e., create) tf.Variableobjects with the tf.Variable() function. The tf.Variable() function accepts different data types as parameter such as integers, floats, strings, lists, and tf.Constant objects. Before showing different Variable object examples with these different data types, I want you to start a new Google Colab notebook and import TensorFlow library with the following code: Now, we can start creating tf.Variable objects. 1 β€” We can pass a tf.constant() object as the initial_value: 2 β€” We can pass a single integer as the initial_value: 3 β€” We can pass a list of integers or floats as the initial_value: 4β€” We can pass a single string as the initial_value: 5β€” We can pass a list of strings as the initial_value: As you can see, there are several data types that th etf.Variable() function accepts as the initial_value argument. Now let’s take a look at the characteristics and features of variables. Every Variable must have some properties such as value, name, uniform data type, shape, rank, size, and more. In this section, we will see what these properties are and how we can view these properties in a Colab notebook. Every Variable must specify an initial_value. Otherwise, TensorFlow raises an error and says that Value Error: initial_value must be specified. Therefore, make sure that you pass on an initial_valueargument when creating Variable objects. To be able to view a Variable’s values, we can use the .value() function as well as the .numpy() function. See the example below: Output:The values stored in the variables:tf.Tensor( [[1. 2.] [1. 2.]], shape=(2, 2), dtype=float32)The values stored in the variables:[[1. 2.][1. 2.]] Name is a Variable attribute which helps developers to track the updates on a particular variable. You can pass a name argument while creating the Variable object. If you don’t specify a name, TensorFlow assigns a default name, as shown below: Output:The name of the variable: Variable:0 Each Variable must have a uniform data type that it stores. Since there is a single type of data stored for every Variable, you can also view this type with the .dtype attribute. See the example below: Output:The selected datatype for the variable: <dtype: 'float32'> The shape property shows the size of each dimension in the form of a list. We can view the shape of the Variable object with the .shape attribute. Then, we can view the number of dimensions that a Variable object has with the tf.size() function. Finally, Size corresponds to the total number of elements a Variable has. We need to use the tf.size() function to count the number of elements in a Variable. See the code below for all three properties: Output:The shape of the variable: (2, 2)The number of dimensions in the variable: 2The number of dimensions in the variable: 4 There are several basic operations you can easily conduct with math operators and TensorFlow functions. On top of what we covered in Part 2 of this tutorial series, you may also use the following math operators for Variable operations. Addition and Subtraction: We can conduct addition and subtraction with + and β€” signs. Addition by 2:tf.Tensor( [[3. 4.] [3. 4.]], shape=(2, 2), dtype=float32)Substraction by 2:tf.Tensor( [[-1. 0.] [-1. 0.]], shape=(2, 2), dtype=float32) Multiplication and Division: We can conduct multiplication and division with * and / signs. Multiplication by 2:tf.Tensor( [[2. 4.] [2. 4.]], shape=(2, 2), dtype=float32)Division by 2:tf.Tensor( [[0.5 1. ] [0.5 1. ]], shape=(2, 2), dtype=float32) Matmul and Modulo Operations: Finally, you can also do matmul and modulo operations with @ and % signs: Matmul operation with itself:tf.Tensor( [[3. 6.] [3. 6.]], shape=(2, 2), dtype=float32)Modulo operation by 2:tf.Tensor( [[1. 0.] [1. 0.]], shape=(2, 2), dtype=float32) These are elementary examples, but they can be extended into complex calculations, which creates the algorithms that we use for deep learning applications. Note: These operators also work on regular Tensor objects. With the tf.assign() function, you may assign new values to a Variable object without creating a new object. Being able to assign new values is one of the advantages of Variables, where value reassignment is required. Here is an example of reassignment of values: Output:...array([[ 2., 100.], [ 1., 10.]],... Just as in Tensors, you may easily access particular elements using index values, as shown below: Output:The 1st element of the first level is: [1. 2.]The 2nd element of the first level is: [1. 2.]The 1st element of the second level is: 1.0The 3rd element of the second level is: 2.0 Just as with Tensor objects, when we try to do combined operations using multiple Variable objects, the smaller Variables can stretch out automatically to fit larger Variables, just as NumPy arrays can. For example, when you attempt to multiply a scalar Variable with a 2-dimensional Variable, the scalar is stretched to multiply every 2-dimensional Variable element. See the example below: tf.Tensor([[ 5 10] [15 20]], shape=(2, 2), dtype=int32) Just as in Tensor objects, you can reshape Variable objects as well. For the reshape operation, we can use the tf.reshape() function. Let's use the tf.reshape() function in code: tf.Tensor( [[1.] [2.] [1.] [2.]], shape=(4, 1), dtype=float32) As you will see in the upcoming Parts, we will accelerate our model training with GPUs and TPUs. To be able to see what type of device (i.e., processor) our variable is processed with, we can use .device attribute: The device which process the variable: /job:localhost/replica:0/task:0/device:GPU:0 We can also set which device should process a particular calculation with the tf.device() function by passing the device name as an argument. See the example below: Output:The device which processes the variable a: /job:localhost/replica:0/task:0/device:CPU:0The device which processes the variable b: /job:localhost/replica:0/task:0/device:CPU:0The device which processes the calculation: /job:localhost/replica:0/task:0/device:GPU:0 Even though you will not have to set this manually while training a model, there might be circumstances where you have to choose a device for a particular calculation or data processing work. So, beware of this option. We have successfully covered the basics of TensorFlow’s Variable objects. Give yourself a pat on the back! This should give you a lot of confidence since you are now much more informed about the main mutable Variable object type used for all kinds of operations in TensorFlow. If this is your first post, consider starting from Part 1 of this tutorial series: towardsdatascience.com or check out Part 2: towardsdatascience.com If you would like to have access to full code on Google Colab and the rest of my latest content, consider subscribing to the mailing list: Subscribe Now Finally, if you are interested in more advanced applied deep learning tutorials, check out some of my other articles:
[ { "code": null, "e": 262, "s": 172, "text": "WARNING: Do not confuse this article with β€œMastering TensorFlow Tensors in 5 Easy Steps”!" }, { "code": null, "e": 485, "s": 262, "text": "If you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. YalcΜ§Δ±n β€” Linkedin" }, { "code": null, "e": 809, "s": 485, "text": "In this tutorial, we will focus on TensorFlow Variables. After the tutorial, you will be able to create, update, and manage TensorFlow Variables effectively. As usual, our tutorial will deliver code examples with detailed explanations as well as conceptual explanations. We will master TensorFlow Variables in 5 easy steps:" }, { "code": null, "e": 888, "s": 809, "text": "Step 1: Definition of Variables β†’A Brief Introduction, Comparison with Tensors" }, { "code": null, "e": 954, "s": 888, "text": "Step 2: Creation of Variables β†’ Instantiating tf.Variable Objects" }, { "code": null, "e": 1021, "s": 954, "text": "Step 3: Qualifications of Variables β†’ Characteristics and Features" }, { "code": null, "e": 1129, "s": 1021, "text": "Step 4: Operations with Variables β†’ Basic Tensor Operations, Indexing, Shape Manipulation, and Broadcasting" }, { "code": null, "e": 1189, "s": 1129, "text": "Step 5: Hardware Selection for Variables β†’ GPUs, CPUs, TPUs" }, { "code": null, "e": 1225, "s": 1189, "text": "Fasten your belts, and let’s start!" }, { "code": null, "e": 1361, "s": 1225, "text": "In this step, we will briefly cover what Variables are and understand the difference between plain Tensor objects and Variable objects." }, { "code": null, "e": 1861, "s": 1361, "text": "A TensorFlow Variable is the preferred object type representing a shared and persistent state that you can manipulate with any operation, including TensorFlow models. Manipulation refers to any value or parameter update. This characteristic is the most distinguishing feature of Variables compared to tf.Tensor objects. TensorFlow Variables are recorded as tf.Variable objects. Let’s make a brief comparison between tf.Tensor and tf.Variable objects to understand their similarities and differences." }, { "code": null, "e": 2045, "s": 1861, "text": "So, the most important difference between Variables and Tensors is mutability. The values in a Variable object can be updated (e.g., with the assign() function) as opposed to Tensors." }, { "code": null, "e": 2160, "s": 2045, "text": "β€œThe values of tensor objects cannot be updated, and you can only create a new Tensor object with the new values.”" }, { "code": null, "e": 2357, "s": 2160, "text": "Variable objects are mainly used to store model parameters, and since these values are constantly updated during training, using Variables, instead of Tensors, is a necessity rather than a choice." }, { "code": null, "e": 2716, "s": 2357, "text": "The shape of a Variable object can be updated with the reshape() instance function just like the shape of a Tensor object. Since Variable objects are built on top of Tensor objects, they have common attributes such as .shape and .dtype. But, Variables also have unique attributes such as .trainable,.device, and .name attributes that the Tensors do not have." }, { "code": null, "e": 2765, "s": 2716, "text": "Let’s see how we can create tf.Variable objects!" }, { "code": null, "e": 2987, "s": 2765, "text": "We can instantiate (i.e., create) tf.Variableobjects with the tf.Variable() function. The tf.Variable() function accepts different data types as parameter such as integers, floats, strings, lists, and tf.Constant objects." }, { "code": null, "e": 3173, "s": 2987, "text": "Before showing different Variable object examples with these different data types, I want you to start a new Google Colab notebook and import TensorFlow library with the following code:" }, { "code": null, "e": 3221, "s": 3173, "text": "Now, we can start creating tf.Variable objects." }, { "code": null, "e": 3282, "s": 3221, "text": "1 β€” We can pass a tf.constant() object as the initial_value:" }, { "code": null, "e": 3337, "s": 3282, "text": "2 β€” We can pass a single integer as the initial_value:" }, { "code": null, "e": 3404, "s": 3337, "text": "3 β€” We can pass a list of integers or floats as the initial_value:" }, { "code": null, "e": 3457, "s": 3404, "text": "4β€” We can pass a single string as the initial_value:" }, { "code": null, "e": 3512, "s": 3457, "text": "5β€” We can pass a list of strings as the initial_value:" }, { "code": null, "e": 3700, "s": 3512, "text": "As you can see, there are several data types that th etf.Variable() function accepts as the initial_value argument. Now let’s take a look at the characteristics and features of variables." }, { "code": null, "e": 3923, "s": 3700, "text": "Every Variable must have some properties such as value, name, uniform data type, shape, rank, size, and more. In this section, we will see what these properties are and how we can view these properties in a Colab notebook." }, { "code": null, "e": 4292, "s": 3923, "text": "Every Variable must specify an initial_value. Otherwise, TensorFlow raises an error and says that Value Error: initial_value must be specified. Therefore, make sure that you pass on an initial_valueargument when creating Variable objects. To be able to view a Variable’s values, we can use the .value() function as well as the .numpy() function. See the example below:" }, { "code": null, "e": 4457, "s": 4292, "text": "Output:The values stored in the variables:tf.Tensor( [[1. 2.] [1. 2.]], shape=(2, 2), dtype=float32)The values stored in the variables:[[1. 2.][1. 2.]]" }, { "code": null, "e": 4701, "s": 4457, "text": "Name is a Variable attribute which helps developers to track the updates on a particular variable. You can pass a name argument while creating the Variable object. If you don’t specify a name, TensorFlow assigns a default name, as shown below:" }, { "code": null, "e": 4746, "s": 4701, "text": "Output:The name of the variable: Variable:0" }, { "code": null, "e": 4948, "s": 4746, "text": "Each Variable must have a uniform data type that it stores. Since there is a single type of data stored for every Variable, you can also view this type with the .dtype attribute. See the example below:" }, { "code": null, "e": 5015, "s": 4948, "text": "Output:The selected datatype for the variable: <dtype: 'float32'>" }, { "code": null, "e": 5465, "s": 5015, "text": "The shape property shows the size of each dimension in the form of a list. We can view the shape of the Variable object with the .shape attribute. Then, we can view the number of dimensions that a Variable object has with the tf.size() function. Finally, Size corresponds to the total number of elements a Variable has. We need to use the tf.size() function to count the number of elements in a Variable. See the code below for all three properties:" }, { "code": null, "e": 5593, "s": 5465, "text": "Output:The shape of the variable: (2, 2)The number of dimensions in the variable: 2The number of dimensions in the variable: 4" }, { "code": null, "e": 5829, "s": 5593, "text": "There are several basic operations you can easily conduct with math operators and TensorFlow functions. On top of what we covered in Part 2 of this tutorial series, you may also use the following math operators for Variable operations." }, { "code": null, "e": 5915, "s": 5829, "text": "Addition and Subtraction: We can conduct addition and subtraction with + and β€” signs." }, { "code": null, "e": 6070, "s": 5915, "text": "Addition by 2:tf.Tensor( [[3. 4.] [3. 4.]], shape=(2, 2), dtype=float32)Substraction by 2:tf.Tensor( [[-1. 0.] [-1. 0.]], shape=(2, 2), dtype=float32)" }, { "code": null, "e": 6162, "s": 6070, "text": "Multiplication and Division: We can conduct multiplication and division with * and / signs." }, { "code": null, "e": 6319, "s": 6162, "text": "Multiplication by 2:tf.Tensor( [[2. 4.] [2. 4.]], shape=(2, 2), dtype=float32)Division by 2:tf.Tensor( [[0.5 1. ] [0.5 1. ]], shape=(2, 2), dtype=float32)" }, { "code": null, "e": 6423, "s": 6319, "text": "Matmul and Modulo Operations: Finally, you can also do matmul and modulo operations with @ and % signs:" }, { "code": null, "e": 6593, "s": 6423, "text": "Matmul operation with itself:tf.Tensor( [[3. 6.] [3. 6.]], shape=(2, 2), dtype=float32)Modulo operation by 2:tf.Tensor( [[1. 0.] [1. 0.]], shape=(2, 2), dtype=float32)" }, { "code": null, "e": 6749, "s": 6593, "text": "These are elementary examples, but they can be extended into complex calculations, which creates the algorithms that we use for deep learning applications." }, { "code": null, "e": 6808, "s": 6749, "text": "Note: These operators also work on regular Tensor objects." }, { "code": null, "e": 7072, "s": 6808, "text": "With the tf.assign() function, you may assign new values to a Variable object without creating a new object. Being able to assign new values is one of the advantages of Variables, where value reassignment is required. Here is an example of reassignment of values:" }, { "code": null, "e": 7130, "s": 7072, "text": "Output:...array([[ 2., 100.], [ 1., 10.]],..." }, { "code": null, "e": 7228, "s": 7130, "text": "Just as in Tensors, you may easily access particular elements using index values, as shown below:" }, { "code": null, "e": 7414, "s": 7228, "text": "Output:The 1st element of the first level is: [1. 2.]The 2nd element of the first level is: [1. 2.]The 1st element of the second level is: 1.0The 3rd element of the second level is: 2.0" }, { "code": null, "e": 7805, "s": 7414, "text": "Just as with Tensor objects, when we try to do combined operations using multiple Variable objects, the smaller Variables can stretch out automatically to fit larger Variables, just as NumPy arrays can. For example, when you attempt to multiply a scalar Variable with a 2-dimensional Variable, the scalar is stretched to multiply every 2-dimensional Variable element. See the example below:" }, { "code": null, "e": 7871, "s": 7805, "text": "tf.Tensor([[ 5 10] [15 20]], shape=(2, 2), dtype=int32)" }, { "code": null, "e": 8050, "s": 7871, "text": "Just as in Tensor objects, you can reshape Variable objects as well. For the reshape operation, we can use the tf.reshape() function. Let's use the tf.reshape() function in code:" }, { "code": null, "e": 8146, "s": 8050, "text": "tf.Tensor( [[1.] [2.] [1.] [2.]], shape=(4, 1), dtype=float32)" }, { "code": null, "e": 8361, "s": 8146, "text": "As you will see in the upcoming Parts, we will accelerate our model training with GPUs and TPUs. To be able to see what type of device (i.e., processor) our variable is processed with, we can use .device attribute:" }, { "code": null, "e": 8447, "s": 8361, "text": "The device which process the variable: /job:localhost/replica:0/task:0/device:GPU:0" }, { "code": null, "e": 8612, "s": 8447, "text": "We can also set which device should process a particular calculation with the tf.device() function by passing the device name as an argument. See the example below:" }, { "code": null, "e": 8882, "s": 8612, "text": "Output:The device which processes the variable a: /job:localhost/replica:0/task:0/device:CPU:0The device which processes the variable b: /job:localhost/replica:0/task:0/device:CPU:0The device which processes the calculation: /job:localhost/replica:0/task:0/device:GPU:0" }, { "code": null, "e": 9101, "s": 8882, "text": "Even though you will not have to set this manually while training a model, there might be circumstances where you have to choose a device for a particular calculation or data processing work. So, beware of this option." }, { "code": null, "e": 9175, "s": 9101, "text": "We have successfully covered the basics of TensorFlow’s Variable objects." }, { "code": null, "e": 9208, "s": 9175, "text": "Give yourself a pat on the back!" }, { "code": null, "e": 9378, "s": 9208, "text": "This should give you a lot of confidence since you are now much more informed about the main mutable Variable object type used for all kinds of operations in TensorFlow." }, { "code": null, "e": 9461, "s": 9378, "text": "If this is your first post, consider starting from Part 1 of this tutorial series:" }, { "code": null, "e": 9484, "s": 9461, "text": "towardsdatascience.com" }, { "code": null, "e": 9505, "s": 9484, "text": "or check out Part 2:" }, { "code": null, "e": 9528, "s": 9505, "text": "towardsdatascience.com" }, { "code": null, "e": 9667, "s": 9528, "text": "If you would like to have access to full code on Google Colab and the rest of my latest content, consider subscribing to the mailing list:" }, { "code": null, "e": 9681, "s": 9667, "text": "Subscribe Now" } ]
Tryit Editor v3.7
Tryit: Display a none-breaking-space
[]
How to create a frame inside a frame tkinter? - GeeksforGeeks
21 Jun, 2021 Prerequisite: Tkinter It is very easy to create a basic frame using Tkinter, this article focuses on how another frame can be created within it. To create a basic frame the name of the parent window is given as the first parameter to the frame() function. Therefore, to add another frame within this frame, just the name of the first frame needs to given to the second frame as the parent window. Optional values such as frame padding are give relative to the parent window. We can add multiple frames in this fashion using the same approach, by making the previous frame the parent of the current frame. Approach: Create Normal Tkinter Window Create first frame normally Create second frame Take the first window as its parent window Execute code frame() is an inbuilt Tkinter method which helps realize our required functionality. Syntax: frame(master) Parameter: master: parent window highlightcolor: To set the color of the focus highlight when widget has to be focused. bd: to set the border width in pixels. bg: to set the normal background color. cursor: to set the cursor used. width: to set the width of the widget. height: to set the height of the widget. Program: Python3 # Import Modulefrom tkinter import * # Create Tkinter Objectroot = Tk() # Set Geometryroot.geometry("400x400") # Frame 1frame1 = Frame(root,bg="black",width=500,height=300)frame1.pack() # Frame 2frame2 = Frame(frame1,bg="white",width=100,height=100)frame2.pack(pady=20,padx=20) # Execute Tkinterroot.mainloop() Output: anikakapoor Picked Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n21 Jun, 2021" }, { "code": null, "e": 24314, "s": 24292, "text": "Prerequisite: Tkinter" }, { "code": null, "e": 24689, "s": 24314, "text": "It is very easy to create a basic frame using Tkinter, this article focuses on how another frame can be created within it. To create a basic frame the name of the parent window is given as the first parameter to the frame() function. Therefore, to add another frame within this frame, just the name of the first frame needs to given to the second frame as the parent window." }, { "code": null, "e": 24897, "s": 24689, "text": "Optional values such as frame padding are give relative to the parent window. We can add multiple frames in this fashion using the same approach, by making the previous frame the parent of the current frame." }, { "code": null, "e": 24907, "s": 24897, "text": "Approach:" }, { "code": null, "e": 24936, "s": 24907, "text": "Create Normal Tkinter Window" }, { "code": null, "e": 24964, "s": 24936, "text": "Create first frame normally" }, { "code": null, "e": 24984, "s": 24964, "text": "Create second frame" }, { "code": null, "e": 25027, "s": 24984, "text": "Take the first window as its parent window" }, { "code": null, "e": 25040, "s": 25027, "text": "Execute code" }, { "code": null, "e": 25125, "s": 25040, "text": "frame() is an inbuilt Tkinter method which helps realize our required functionality." }, { "code": null, "e": 25147, "s": 25125, "text": "Syntax: frame(master)" }, { "code": null, "e": 25158, "s": 25147, "text": "Parameter:" }, { "code": null, "e": 25180, "s": 25158, "text": "master: parent window" }, { "code": null, "e": 25267, "s": 25180, "text": "highlightcolor: To set the color of the focus highlight when widget has to be focused." }, { "code": null, "e": 25306, "s": 25267, "text": "bd: to set the border width in pixels." }, { "code": null, "e": 25346, "s": 25306, "text": "bg: to set the normal background color." }, { "code": null, "e": 25378, "s": 25346, "text": "cursor: to set the cursor used." }, { "code": null, "e": 25417, "s": 25378, "text": "width: to set the width of the widget." }, { "code": null, "e": 25458, "s": 25417, "text": "height: to set the height of the widget." }, { "code": null, "e": 25467, "s": 25458, "text": "Program:" }, { "code": null, "e": 25475, "s": 25467, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # Create Tkinter Objectroot = Tk() # Set Geometryroot.geometry(\"400x400\") # Frame 1frame1 = Frame(root,bg=\"black\",width=500,height=300)frame1.pack() # Frame 2frame2 = Frame(frame1,bg=\"white\",width=100,height=100)frame2.pack(pady=20,padx=20) # Execute Tkinterroot.mainloop()", "e": 25786, "s": 25475, "text": null }, { "code": null, "e": 25798, "s": 25790, "text": "Output:" }, { "code": null, "e": 25814, "s": 25802, "text": "anikakapoor" }, { "code": null, "e": 25821, "s": 25814, "text": "Picked" }, { "code": null, "e": 25836, "s": 25821, "text": "Python-tkinter" }, { "code": null, "e": 25843, "s": 25836, "text": "Python" }, { "code": null, "e": 25941, "s": 25843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25973, "s": 25941, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26015, "s": 25973, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26071, "s": 26015, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26113, "s": 26071, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26168, "s": 26113, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26199, "s": 26168, "text": "Python | os.path.join() method" }, { "code": null, "e": 26221, "s": 26199, "text": "Defaultdict in Python" }, { "code": null, "e": 26260, "s": 26221, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26289, "s": 26260, "text": "Create a directory in Python" } ]
jQuery - scrollTop( ) Method
The scrollTop( ) method gets the scroll top offset of the first matched element. This method works for both visible and hidden elements. Here is the simple syntax to use this method βˆ’ selector.scrollTop( ) Here is the description of all the parameters used by this method βˆ’ NA NA Following is a simple example a simple showing the usage of this method βˆ’ <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function(){ $("div.demo").scrollTop( 200 ); $("div.demo").mousemove(function () { var top = $("div.demo").scrollTop(); $("#result").html("top offset: <span>" + top + "</span>."); }); }); </script> <style> div.demo {background:#CCCCCC none repeat scroll 0 0; border:3px solid #666666; margin:5px; padding:5px; position:relative; width:200px; height:100px; overflow:auto;} div.result{margin:10px; width:100px; height:100px; margin:5px; float:left; background-color:blue;} p { margin:10px; padding:5px; border:2px solid #666; width:1000px; height:1000px;} </style> </head> <body> <div class = "demo"><p>Hello</p></div> <span>Scroll vertical button to see the result:</span> <div class = "result"><span id = "result"></span></div> </body> </html> This will produce following result βˆ’ Hello 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2403, "s": 2322, "text": "The scrollTop( ) method gets the scroll top offset of the first matched element." }, { "code": null, "e": 2459, "s": 2403, "text": "This method works for both visible and hidden elements." }, { "code": null, "e": 2506, "s": 2459, "text": "Here is the simple syntax to use this method βˆ’" }, { "code": null, "e": 2529, "s": 2506, "text": "selector.scrollTop( )\n" }, { "code": null, "e": 2597, "s": 2529, "text": "Here is the description of all the parameters used by this method βˆ’" }, { "code": null, "e": 2600, "s": 2597, "text": "NA" }, { "code": null, "e": 2603, "s": 2600, "text": "NA" }, { "code": null, "e": 2677, "s": 2603, "text": "Following is a simple example a simple showing the usage of this method βˆ’" }, { "code": null, "e": 3933, "s": 2677, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function(){\n $(\"div.demo\").scrollTop( 200 );\n\t\t\t\t\n $(\"div.demo\").mousemove(function () {\n var top = $(\"div.demo\").scrollTop();\n $(\"#result\").html(\"top offset: <span>\" + top + \"</span>.\");\n });\n\t\t\t\t\n });\n </script>\n\t\t\n <style>\n div.demo {background:#CCCCCC none repeat scroll 0 0; border:3px \n solid #666666; margin:5px; padding:5px; position:relative;\n width:200px; height:100px; overflow:auto;}\n\t\t\t\t\n div.result{margin:10px; width:100px; height:100px; \n margin:5px; float:left; background-color:blue;}\n\t\t\t\t\n p { margin:10px; padding:5px; border:2px solid #666; \n width:1000px; height:1000px;}\n </style>\n </head>\n\t\n <body>\n <div class = \"demo\"><p>Hello</p></div>\n <span>Scroll vertical button to see the result:</span>\n <div class = \"result\"><span id = \"result\"></span></div>\n </body>\n</html>" }, { "code": null, "e": 3970, "s": 3933, "text": "This will produce following result βˆ’" }, { "code": null, "e": 3976, "s": 3970, "text": "Hello" }, { "code": null, "e": 4009, "s": 3976, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4023, "s": 4009, "text": " Mahesh Kumar" }, { "code": null, "e": 4058, "s": 4023, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4072, "s": 4058, "text": " Pratik Singh" }, { "code": null, "e": 4107, "s": 4072, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4124, "s": 4107, "text": " Frahaan Hussain" }, { "code": null, "e": 4157, "s": 4124, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4185, "s": 4157, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4218, "s": 4185, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4239, "s": 4218, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4271, "s": 4239, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4288, "s": 4271, "text": " Laurence Svekis" }, { "code": null, "e": 4295, "s": 4288, "text": " Print" }, { "code": null, "e": 4306, "s": 4295, "text": " Add Notes" } ]
How to work with document.forms in JavaScript?
Use the document.forms property in JavaScript to get the number of <form> tags in a document. You can try to run the following code to implement document.forms property in JavaScript. Live Demo <!DOCTYPE html> <html> <head> <title>JavaScript Example</title> </head> <body> <h1>Employee Information</h1> <form> Name: <input type="text" name="name" value="Amit"><br> Subject: <input type="text" name="sub" value="Java"> </form> <h1>Department Information</h1> <form> DepartmentID: <input type="text" name="dptid" value="D001"><br> Dept Name: <input type="text" name="dname" value="Marketing"> </form> <script> var num = document.forms.length; document.write("<br>How many forms? "+num); </script> </body> </html>
[ { "code": null, "e": 1156, "s": 1062, "text": "Use the document.forms property in JavaScript to get the number of <form> tags in a document." }, { "code": null, "e": 1246, "s": 1156, "text": "You can try to run the following code to implement document.forms property in JavaScript." }, { "code": null, "e": 1256, "s": 1246, "text": "Live Demo" }, { "code": null, "e": 1893, "s": 1256, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>JavaScript Example</title>\n </head>\n <body>\n <h1>Employee Information</h1>\n <form>\n Name: <input type=\"text\" name=\"name\" value=\"Amit\"><br>\n Subject: <input type=\"text\" name=\"sub\" value=\"Java\">\n </form>\n <h1>Department Information</h1>\n <form>\n DepartmentID: <input type=\"text\" name=\"dptid\" value=\"D001\"><br>\n Dept Name: <input type=\"text\" name=\"dname\" value=\"Marketing\">\n </form>\n <script>\n var num = document.forms.length;\n document.write(\"<br>How many forms? \"+num);\n </script>\n </body>\n</html>" } ]
How to animate the colorbar in Matplotlib?
To animate the colorbar in matplotlib, we can take the following steps βˆ’ Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a new figure or activate an existing figure. Create a new figure or activate an existing figure. Add an '~.axes.Axes' to the figure as part of a subplot arrangement. Add an '~.axes.Axes' to the figure as part of a subplot arrangement. Instantiate Divider based on the pre-existing axes, i.e., ax object and return a new axis locator for the specified cell. Instantiate Divider based on the pre-existing axes, i.e., ax object and return a new axis locator for the specified cell. Create an axes at the given *position* with the same height (or width) of the main axes. Create an axes at the given *position* with the same height (or width) of the main axes. Create random data using numpy. Create random data using numpy. Use imshow() method to plot random data. Use imshow() method to plot random data. Set the title of the plot. Set the title of the plot. Instantiate the list of colormaps. Instantiate the list of colormaps. To animate the colorbar, use animate() method. To animate the colorbar, use animate() method. To display the figure, use show() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.axes_grid1 import make_axes_locatable plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(111) div = make_axes_locatable(ax) cax = div.append_axes('right', '5%', '5%') data = np.random.rand(5, 5) im = ax.imshow(data) cb = fig.colorbar(im, cax=cax) tx = ax.set_title('Frame 0') cmap = ["copper", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma'] def animate(i): cax.cla() data = np.random.rand(5, 5) im = ax.imshow(data, cmap=cmap[i%len(cmap)]) fig.colorbar(im, cax=cax) tx.set_text('Frame {0}'.format(i)) ani = animation.FuncAnimation(fig, animate, frames=10) plt.show()
[ { "code": null, "e": 1135, "s": 1062, "text": "To animate the colorbar in matplotlib, we can take the following steps βˆ’" }, { "code": null, "e": 1211, "s": 1135, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1287, "s": 1211, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1339, "s": 1287, "text": "Create a new figure or activate an existing figure." }, { "code": null, "e": 1391, "s": 1339, "text": "Create a new figure or activate an existing figure." }, { "code": null, "e": 1460, "s": 1391, "text": "Add an '~.axes.Axes' to the figure as part of a subplot arrangement." }, { "code": null, "e": 1529, "s": 1460, "text": "Add an '~.axes.Axes' to the figure as part of a subplot arrangement." }, { "code": null, "e": 1651, "s": 1529, "text": "Instantiate Divider based on the pre-existing axes, i.e., ax object and return a new axis locator for the specified cell." }, { "code": null, "e": 1773, "s": 1651, "text": "Instantiate Divider based on the pre-existing axes, i.e., ax object and return a new axis locator for the specified cell." }, { "code": null, "e": 1862, "s": 1773, "text": "Create an axes at the given *position* with the same height (or width) of the main axes." }, { "code": null, "e": 1951, "s": 1862, "text": "Create an axes at the given *position* with the same height (or width) of the main axes." }, { "code": null, "e": 1983, "s": 1951, "text": "Create random data using numpy." }, { "code": null, "e": 2015, "s": 1983, "text": "Create random data using numpy." }, { "code": null, "e": 2056, "s": 2015, "text": "Use imshow() method to plot random data." }, { "code": null, "e": 2097, "s": 2056, "text": "Use imshow() method to plot random data." }, { "code": null, "e": 2124, "s": 2097, "text": "Set the title of the plot." }, { "code": null, "e": 2151, "s": 2124, "text": "Set the title of the plot." }, { "code": null, "e": 2186, "s": 2151, "text": "Instantiate the list of colormaps." }, { "code": null, "e": 2221, "s": 2186, "text": "Instantiate the list of colormaps." }, { "code": null, "e": 2268, "s": 2221, "text": "To animate the colorbar, use animate() method." }, { "code": null, "e": 2315, "s": 2268, "text": "To animate the colorbar, use animate() method." }, { "code": null, "e": 2357, "s": 2315, "text": "To display the figure, use show() method." }, { "code": null, "e": 2399, "s": 2357, "text": "To display the figure, use show() method." }, { "code": null, "e": 3174, "s": 2399, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig = plt.figure()\n\nax = fig.add_subplot(111)\ndiv = make_axes_locatable(ax)\ncax = div.append_axes('right', '5%', '5%')\ndata = np.random.rand(5, 5)\nim = ax.imshow(data)\ncb = fig.colorbar(im, cax=cax)\ntx = ax.set_title('Frame 0')\ncmap = [\"copper\", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']\n\ndef animate(i):\n cax.cla()\n data = np.random.rand(5, 5)\n im = ax.imshow(data, cmap=cmap[i%len(cmap)])\n fig.colorbar(im, cax=cax)\n tx.set_text('Frame {0}'.format(i))\nani = animation.FuncAnimation(fig, animate, frames=10)\n\nplt.show()" } ]
How to format a number with two decimals in JavaScript?
Use the toFixed() method in JavaScript to format a number with two decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal. It returns a string representation of the number that does not use exponential notation and has the exact number of digits after the decimal place. You can try to run the following code to format a number with two decimals. Add the parameter of the toFixed() method to 2, for getting number with two decimals βˆ’ Live Demo <html> <head> <title>JavaScript toFixed() Method</title> </head> <body> <script> var num1 = 4.6; var num2 = 177.1234; document.write("num1.toFixed() is : " + num1.toFixed(2)); document.write("<br />"); document.write("nu2m.toFixed() is : " + num2.toFixed(2)); document.write("<br />"); </script> </body> </html> num1.toFixed() is : 4.60 nu2m.toFixed() is : 177.12
[ { "code": null, "e": 1387, "s": 1062, "text": "Use the toFixed() method in JavaScript to format a number with two decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal. It returns a string representation of the number that does not use exponential notation and has the exact number of digits after the decimal place." }, { "code": null, "e": 1550, "s": 1387, "text": "You can try to run the following code to format a number with two decimals. Add the parameter of the toFixed() method to 2, for getting number with two decimals βˆ’" }, { "code": null, "e": 1560, "s": 1550, "text": "Live Demo" }, { "code": null, "e": 1958, "s": 1560, "text": "<html>\n <head>\n <title>JavaScript toFixed() Method</title>\n </head>\n <body>\n <script>\n var num1 = 4.6;\n var num2 = 177.1234;\n\n document.write(\"num1.toFixed() is : \" + num1.toFixed(2));\n document.write(\"<br />\");\n\n document.write(\"nu2m.toFixed() is : \" + num2.toFixed(2));\n document.write(\"<br />\");\n </script>\n </body>\n</html>" }, { "code": null, "e": 2010, "s": 1958, "text": "num1.toFixed() is : 4.60\nnu2m.toFixed() is : 177.12" } ]
Implementation of Hashing with Chaining in Python
06 Jul, 2022 Hashing is a data structure that is used to store a large amount of data, which can be accessed in O(1) time by operations such as search, insert and delete. Various Applications of Hashing are: Indexing in database Cryptography Symbol Tables in Compiler/Interpreter Dictionaries, caches, etc. Hashing is an important Data Structure which is designed to use a special function called the Hash function which is used to map a given value with a particular key for faster access of elements. The efficiency of mapping depends of the efficiency of the hash function used. Example: h(large_value) = large_value % m Here, h() is the required hash function and β€˜m’ is the size of the hash table. For large values, hash functions produce value in a given range. How Hash Function Works? It should always map large keys to small keys. It should always generate values between 0 to m-1 where m is the size of the hash table. It should uniformly distribute large keys into hash table slots. If we know the keys beforehand, then we have can have perfect hashing. In perfect hashing, we do not have any collisions. However, If we do not know the keys, then we can use the following methods to avoid collisions: Chaining Open Addressing (Linear Probing, Quadratic Probing, Double Hashing) While hashing, the hashing function may lead to a collision that is two or more keys are mapped to the same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value. Note: In Linear Probing, whenever a collision occurs, we probe to the next empty slot. While in Quadratic Probing, whenever a collision occurs, we probe for i^2th slot in the ith iteration and we keep probing until an empty slot in the hashtable is found. The performance of hashing is evaluated on the basis that each key is equally likely to be hashed for any slot of the hash table. m = Length of Hash Table n = Total keys to be inserted in the hash table Load factor lf = n/m Expected time to search = O(1 +lf ) Expected time to insert/delete = O(1 + lf) The time complexity of search insert and delete is O(1) if lf is O(1) Python Implementation of Hashing # Function to display hashtabledef display_hash(hashTable): for i in range(len(hashTable)): print(i, end = " ") for j in hashTable[i]: print("-->", end = " ") print(j, end = " ") print() # Creating Hashtable as # a nested list.HashTable = [[] for _ in range(10)] # Hashing Function to return # key for every value.def Hashing(keyvalue): return keyvalue % len(HashTable) # Insert Function to add# values to the hash tabledef insert(Hashtable, keyvalue, value): hash_key = Hashing(keyvalue) Hashtable[hash_key].append(value) # Driver Codeinsert(HashTable, 10, 'Allahabad')insert(HashTable, 25, 'Mumbai')insert(HashTable, 20, 'Mathura')insert(HashTable, 9, 'Delhi')insert(HashTable, 21, 'Punjab')insert(HashTable, 21, 'Noida') display_hash (HashTable) Output: 0 --> Allahabad --> Mathura 1 --> Punjab --> Noida 2 3 4 5 --> Mumbai 6 7 8 9 --> Delhi Hash Python-Data-Structures python-list Python python-list Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 247, "s": 52, "text": "Hashing is a data structure that is used to store a large amount of data, which can be accessed in O(1) time by operations such as search, insert and delete. Various Applications of Hashing are:" }, { "code": null, "e": 268, "s": 247, "text": "Indexing in database" }, { "code": null, "e": 281, "s": 268, "text": "Cryptography" }, { "code": null, "e": 319, "s": 281, "text": "Symbol Tables in Compiler/Interpreter" }, { "code": null, "e": 346, "s": 319, "text": "Dictionaries, caches, etc." }, { "code": null, "e": 621, "s": 346, "text": "Hashing is an important Data Structure which is designed to use a special function called the Hash function which is used to map a given value with a particular key for faster access of elements. The efficiency of mapping depends of the efficiency of the hash function used." }, { "code": null, "e": 630, "s": 621, "text": "Example:" }, { "code": null, "e": 663, "s": 630, "text": "h(large_value) = large_value % m" }, { "code": null, "e": 807, "s": 663, "text": "Here, h() is the required hash function and β€˜m’ is the size of the hash table. For large values, hash functions produce value in a given range." }, { "code": null, "e": 832, "s": 807, "text": "How Hash Function Works?" }, { "code": null, "e": 879, "s": 832, "text": "It should always map large keys to small keys." }, { "code": null, "e": 968, "s": 879, "text": "It should always generate values between 0 to m-1 where m is the size of the hash table." }, { "code": null, "e": 1033, "s": 968, "text": "It should uniformly distribute large keys into hash table slots." }, { "code": null, "e": 1251, "s": 1033, "text": "If we know the keys beforehand, then we have can have perfect hashing. In perfect hashing, we do not have any collisions. However, If we do not know the keys, then we can use the following methods to avoid collisions:" }, { "code": null, "e": 1260, "s": 1251, "text": "Chaining" }, { "code": null, "e": 1328, "s": 1260, "text": "Open Addressing (Linear Probing, Quadratic Probing, Double Hashing)" }, { "code": null, "e": 1589, "s": 1328, "text": "While hashing, the hashing function may lead to a collision that is two or more keys are mapped to the same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value." }, { "code": null, "e": 1845, "s": 1589, "text": "Note: In Linear Probing, whenever a collision occurs, we probe to the next empty slot. While in Quadratic Probing, whenever a collision occurs, we probe for i^2th slot in the ith iteration and we keep probing until an empty slot in the hashtable is found." }, { "code": null, "e": 1975, "s": 1845, "text": "The performance of hashing is evaluated on the basis that each key is equally likely to be hashed for any slot of the hash table." }, { "code": null, "e": 2225, "s": 1975, "text": "m = Length of Hash Table\nn = Total keys to be inserted in the hash table\n \nLoad factor lf = n/m \nExpected time to search = O(1 +lf )\nExpected time to insert/delete = O(1 + lf)\n\nThe time complexity of search insert and delete is \nO(1) if lf is O(1)\n" }, { "code": null, "e": 2258, "s": 2225, "text": "Python Implementation of Hashing" }, { "code": "# Function to display hashtabledef display_hash(hashTable): for i in range(len(hashTable)): print(i, end = \" \") for j in hashTable[i]: print(\"-->\", end = \" \") print(j, end = \" \") print() # Creating Hashtable as # a nested list.HashTable = [[] for _ in range(10)] # Hashing Function to return # key for every value.def Hashing(keyvalue): return keyvalue % len(HashTable) # Insert Function to add# values to the hash tabledef insert(Hashtable, keyvalue, value): hash_key = Hashing(keyvalue) Hashtable[hash_key].append(value) # Driver Codeinsert(HashTable, 10, 'Allahabad')insert(HashTable, 25, 'Mumbai')insert(HashTable, 20, 'Mathura')insert(HashTable, 9, 'Delhi')insert(HashTable, 21, 'Punjab')insert(HashTable, 21, 'Noida') display_hash (HashTable)", "e": 3105, "s": 2258, "text": null }, { "code": null, "e": 3113, "s": 3105, "text": "Output:" }, { "code": null, "e": 3211, "s": 3113, "text": "0 --> Allahabad --> Mathura \n1 --> Punjab --> Noida \n2 \n3 \n4 \n5 --> Mumbai \n6 \n7 \n8 \n9 --> Delhi " }, { "code": null, "e": 3216, "s": 3211, "text": "Hash" }, { "code": null, "e": 3239, "s": 3216, "text": "Python-Data-Structures" }, { "code": null, "e": 3251, "s": 3239, "text": "python-list" }, { "code": null, "e": 3258, "s": 3251, "text": "Python" }, { "code": null, "e": 3270, "s": 3258, "text": "python-list" }, { "code": null, "e": 3275, "s": 3270, "text": "Hash" }, { "code": null, "e": 3373, "s": 3275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3391, "s": 3373, "text": "Python Dictionary" }, { "code": null, "e": 3433, "s": 3391, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3455, "s": 3433, "text": "Enumerate() in Python" }, { "code": null, "e": 3481, "s": 3455, "text": "Python String | replace()" }, { "code": null, "e": 3513, "s": 3481, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3542, "s": 3513, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3572, "s": 3542, "text": "Iterate over a list in Python" }, { "code": null, "e": 3599, "s": 3572, "text": "Python Classes and Objects" }, { "code": null, "e": 3635, "s": 3599, "text": "Convert integer to string in Python" } ]
MoviePy – Applying Speed effect on Video Clip
01 Aug, 2020 In this article we will see how we can apply speed effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Speed up video or slow down also known as fast motion/slow-motion effects in video production, which makes the video clips play faster or slower than original speed. In order to do this we will use fx method with the VideoFileClip object Syntax : clip.fx( vfx.speedx, m) Argument : It takes vfx object and multiplier as argument Return : It returns VideoFileClip object Below is the implementation # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting only first 5 secondsclip = clip.subclip(0, 5) # applying speed effectfinal = clip.fx( vfx.speedx, 0.5) # showing final clipfinal.ipython_display() Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Another example # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip from itclip = clip.subclip(0, 9) # applying speed effectfinal = clip.fx( vfx.speedx, 2) # showing final clipfinal.ipython_display() Output : Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Aug, 2020" }, { "code": null, "e": 419, "s": 54, "text": "In this article we will see how we can apply speed effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Speed up video or slow down also known as fast motion/slow-motion effects in video production, which makes the video clips play faster or slower than original speed." }, { "code": null, "e": 491, "s": 419, "text": "In order to do this we will use fx method with the VideoFileClip object" }, { "code": null, "e": 524, "s": 491, "text": "Syntax : clip.fx( vfx.speedx, m)" }, { "code": null, "e": 582, "s": 524, "text": "Argument : It takes vfx object and multiplier as argument" }, { "code": null, "e": 623, "s": 582, "text": "Return : It returns VideoFileClip object" }, { "code": null, "e": 651, "s": 623, "text": "Below is the implementation" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip(\"dsa_geek.webm\") # getting only first 5 secondsclip = clip.subclip(0, 5) # applying speed effectfinal = clip.fx( vfx.speedx, 0.5) # showing final clipfinal.ipython_display()", "e": 963, "s": 651, "text": null }, { "code": null, "e": 972, "s": 963, "text": "Output :" }, { "code": null, "e": 1222, "s": 972, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 1238, "s": 1222, "text": "Another example" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclip from itclip = clip.subclip(0, 9) # applying speed effectfinal = clip.fx( vfx.speedx, 2) # showing final clipfinal.ipython_display()", "e": 1522, "s": 1238, "text": null }, { "code": null, "e": 1531, "s": 1522, "text": "Output :" }, { "code": null, "e": 1974, "s": 1531, "text": "Moviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n\n" }, { "code": null, "e": 1989, "s": 1974, "text": "Python-MoviePy" }, { "code": null, "e": 1996, "s": 1989, "text": "Python" }, { "code": null, "e": 2094, "s": 1996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2112, "s": 2094, "text": "Python Dictionary" }, { "code": null, "e": 2154, "s": 2112, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2176, "s": 2154, "text": "Enumerate() in Python" }, { "code": null, "e": 2211, "s": 2176, "text": "Read a file line by line in Python" }, { "code": null, "e": 2237, "s": 2211, "text": "Python String | replace()" }, { "code": null, "e": 2269, "s": 2237, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2298, "s": 2269, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2325, "s": 2298, "text": "Python Classes and Objects" }, { "code": null, "e": 2355, "s": 2325, "text": "Iterate over a list in Python" } ]
Python list remove()
21 Jun, 2022 Python List remove() is an inbuilt function in the Python programming language that removes a given object from the List. Syntax: list_name.remove(obj) Parameters: obj: object to be removed from the list Returns: The method does not return any value but removes the given object from the list. Exception: If the element doesn’t exist, it throws ValueError: list.remove(x): x not in list exception. Note: It removes the first occurrence of the object from the list. Python3 # Python3 program to demonstrate the use of# remove() method # the first occurrence of 1 is removed from the listlist1 = [ 1, 2, 1, 1, 4, 5 ]list1.remove(1)print(list1) # removes 'a' from list2list2 = [ 'a', 'b', 'c', 'd' ]list2.remove('a')print(list2) [2, 1, 1, 4, 5] ['b', 'c', 'd'] Python3 # Python3 program for the error in# remove() method # removes 'e' from list2list2 = [ 'a', 'b', 'c', 'd' ] list2.remove('e')print(list2) Output: Traceback (most recent call last): File "/home/e35b642d8d5c06d24e9b31c7e7b9a7fa.py", line 8, in list2.remove('e') ValueError: list.remove(x): x not in list Python3 # My Listlist2 = [ 'a', 'b', 'c', 'd', 'd', 'e', 'd' ] # removing 'd'list2.remove('d') print(list2) ['a', 'b', 'c', 'd', 'e', 'd'] Note: If a list contains duplicate elements, it removes the first occurrence of the object from the list. Python3 # Python3 program for practical application# of removing 1 until all 1 are removed from the list list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] # looping till all 1's are removedwhile (list1.count(1)): list1.remove(1) print(list1) [2, 3, 4, 4, 5] Python3 # Python3 program for practical application# of removing 2 until all 2 are removed from the list mylist = [1, 2, 3, 2, 2] # looping till all 2's are removedwhile 2 in mylist: mylist.remove(2) print(mylist) [1, 3] Complexity Class: Average case : O(N) Amortised Worst case : O(N) rajinkya26 sooda367 AmiyaRanjanRout devendrasalunke Python-Built-in-functions python-list python-list-functions Python python-list 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 Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 151, "s": 28, "text": "Python List remove() is an inbuilt function in the Python programming language that removes a given object from the List. " }, { "code": null, "e": 160, "s": 151, "text": "Syntax: " }, { "code": null, "e": 183, "s": 160, "text": "list_name.remove(obj) " }, { "code": null, "e": 197, "s": 183, "text": "Parameters: " }, { "code": null, "e": 238, "s": 197, "text": "obj: object to be removed from the list " }, { "code": null, "e": 249, "s": 238, "text": "Returns: " }, { "code": null, "e": 330, "s": 249, "text": "The method does not return any value but removes the given object from the list." }, { "code": null, "e": 341, "s": 330, "text": "Exception:" }, { "code": null, "e": 434, "s": 341, "text": "If the element doesn’t exist, it throws ValueError: list.remove(x): x not in list exception." }, { "code": null, "e": 441, "s": 434, "text": "Note: " }, { "code": null, "e": 503, "s": 441, "text": "It removes the first occurrence of the object from the list. " }, { "code": null, "e": 511, "s": 503, "text": "Python3" }, { "code": "# Python3 program to demonstrate the use of# remove() method # the first occurrence of 1 is removed from the listlist1 = [ 1, 2, 1, 1, 4, 5 ]list1.remove(1)print(list1) # removes 'a' from list2list2 = [ 'a', 'b', 'c', 'd' ]list2.remove('a')print(list2)", "e": 764, "s": 511, "text": null }, { "code": null, "e": 797, "s": 764, "text": "[2, 1, 1, 4, 5]\n['b', 'c', 'd']\n" }, { "code": null, "e": 805, "s": 797, "text": "Python3" }, { "code": "# Python3 program for the error in# remove() method # removes 'e' from list2list2 = [ 'a', 'b', 'c', 'd' ] list2.remove('e')print(list2)", "e": 943, "s": 805, "text": null }, { "code": null, "e": 952, "s": 943, "text": "Output: " }, { "code": null, "e": 1116, "s": 952, "text": "Traceback (most recent call last):\n File \"/home/e35b642d8d5c06d24e9b31c7e7b9a7fa.py\", line 8, in \n list2.remove('e') \nValueError: list.remove(x): x not in list" }, { "code": null, "e": 1124, "s": 1116, "text": "Python3" }, { "code": "# My Listlist2 = [ 'a', 'b', 'c', 'd', 'd', 'e', 'd' ] # removing 'd'list2.remove('d') print(list2)", "e": 1224, "s": 1124, "text": null }, { "code": null, "e": 1256, "s": 1224, "text": "['a', 'b', 'c', 'd', 'e', 'd']\n" }, { "code": null, "e": 1363, "s": 1256, "text": "Note: If a list contains duplicate elements, it removes the first occurrence of the object from the list. " }, { "code": null, "e": 1371, "s": 1363, "text": "Python3" }, { "code": "# Python3 program for practical application# of removing 1 until all 1 are removed from the list list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] # looping till all 1's are removedwhile (list1.count(1)): list1.remove(1) print(list1)", "e": 1599, "s": 1371, "text": null }, { "code": null, "e": 1616, "s": 1599, "text": "[2, 3, 4, 4, 5]\n" }, { "code": null, "e": 1624, "s": 1616, "text": "Python3" }, { "code": "# Python3 program for practical application# of removing 2 until all 2 are removed from the list mylist = [1, 2, 3, 2, 2] # looping till all 2's are removedwhile 2 in mylist: mylist.remove(2) print(mylist)", "e": 1833, "s": 1624, "text": null }, { "code": null, "e": 1841, "s": 1833, "text": "[1, 3]\n" }, { "code": null, "e": 1861, "s": 1841, "text": "Complexity Class: " }, { "code": null, "e": 1881, "s": 1861, "text": "Average case : O(N)" }, { "code": null, "e": 1909, "s": 1881, "text": "Amortised Worst case : O(N)" }, { "code": null, "e": 1920, "s": 1909, "text": "rajinkya26" }, { "code": null, "e": 1929, "s": 1920, "text": "sooda367" }, { "code": null, "e": 1945, "s": 1929, "text": "AmiyaRanjanRout" }, { "code": null, "e": 1961, "s": 1945, "text": "devendrasalunke" }, { "code": null, "e": 1987, "s": 1961, "text": "Python-Built-in-functions" }, { "code": null, "e": 1999, "s": 1987, "text": "python-list" }, { "code": null, "e": 2021, "s": 1999, "text": "python-list-functions" }, { "code": null, "e": 2028, "s": 2021, "text": "Python" }, { "code": null, "e": 2040, "s": 2028, "text": "python-list" }, { "code": null, "e": 2138, "s": 2040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2180, "s": 2138, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2202, "s": 2180, "text": "Enumerate() in Python" }, { "code": null, "e": 2228, "s": 2202, "text": "Python String | replace()" }, { "code": null, "e": 2260, "s": 2228, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2289, "s": 2260, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2316, "s": 2289, "text": "Python Classes and Objects" }, { "code": null, "e": 2337, "s": 2316, "text": "Python OOPs Concepts" }, { "code": null, "e": 2360, "s": 2337, "text": "Introduction To PYTHON" }, { "code": null, "e": 2396, "s": 2360, "text": "Convert integer to string in Python" } ]
Copy Constructor vs Assignment Operator in C++
10 May, 2022 Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Syntax: className(const className &obj) { // body } Syntax: className obj1, obj2; obj2 = obj1; Consider the following C++ program. CPP // CPP Program to demonstrate the use of copy constructor// and assignment operator#include <iostream>#include <stdio.h>using namespace std; class Test {public: Test() {} Test(const Test& t) { cout << "Copy constructor called " << endl; } Test& operator=(const Test& t) { cout << "Assignment operator called " << endl; return *this; }}; // Driver codeint main(){ Test t1, t2; t2 = t1; Test t3 = t1; getchar(); return 0;} Assignment operator called Copy constructor called Explanation: Here, t2 = t1; calls the assignment operator, same as t2.operator=(t1); and Test t3 = t1; calls the copy constructor, same as Test t3(t1); Must Read: When is a Copy Constructor Called in C++? Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 connorsfitzgerald C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Substring in C++ C++ Classes and Objects Sorting a vector in C++ 2D Vector In C++ With User Defined Size C++ Data Types Templates in C++ with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n10 May, 2022" }, { "code": null, "e": 228, "s": 54, "text": "Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them:" }, { "code": null, "e": 236, "s": 228, "text": "Syntax:" }, { "code": null, "e": 270, "s": 236, "text": "className(const className &obj) {" }, { "code": null, "e": 279, "s": 270, "text": "// body " }, { "code": null, "e": 281, "s": 279, "text": "}" }, { "code": null, "e": 290, "s": 281, "text": "Syntax: " }, { "code": null, "e": 312, "s": 290, "text": "className obj1, obj2;" }, { "code": null, "e": 325, "s": 312, "text": "obj2 = obj1;" }, { "code": null, "e": 362, "s": 325, "text": "Consider the following C++ program. " }, { "code": null, "e": 366, "s": 362, "text": "CPP" }, { "code": "// CPP Program to demonstrate the use of copy constructor// and assignment operator#include <iostream>#include <stdio.h>using namespace std; class Test {public: Test() {} Test(const Test& t) { cout << \"Copy constructor called \" << endl; } Test& operator=(const Test& t) { cout << \"Assignment operator called \" << endl; return *this; }}; // Driver codeint main(){ Test t1, t2; t2 = t1; Test t3 = t1; getchar(); return 0;}", "e": 845, "s": 366, "text": null }, { "code": null, "e": 898, "s": 845, "text": "Assignment operator called \nCopy constructor called " }, { "code": null, "e": 1053, "s": 898, "text": "Explanation: Here, t2 = t1; calls the assignment operator, same as t2.operator=(t1); and Test t3 = t1; calls the copy constructor, same as Test t3(t1);" }, { "code": null, "e": 1106, "s": 1053, "text": "Must Read: When is a Copy Constructor Called in C++?" }, { "code": null, "e": 1231, "s": 1106, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1245, "s": 1231, "text": "anshikajain26" }, { "code": null, "e": 1263, "s": 1245, "text": "connorsfitzgerald" }, { "code": null, "e": 1267, "s": 1263, "text": "C++" }, { "code": null, "e": 1271, "s": 1267, "text": "CPP" }, { "code": null, "e": 1369, "s": 1271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1412, "s": 1369, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1446, "s": 1412, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1471, "s": 1446, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1525, "s": 1471, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1542, "s": 1525, "text": "Substring in C++" }, { "code": null, "e": 1566, "s": 1542, "text": "C++ Classes and Objects" }, { "code": null, "e": 1590, "s": 1566, "text": "Sorting a vector in C++" }, { "code": null, "e": 1630, "s": 1590, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 1645, "s": 1630, "text": "C++ Data Types" } ]
Kali Linux – Crunch Utility
04 Aug, 2021 In order to hack a password, we have to try a lot of passwords to get the right one. When an attacker uses thousands or millions of words or character combinations to crack a password there is no surety that any one of those millions of combinations will work or not. This collection of a different combination of characters is called a wordlist. And in order to crack a password or a hash, we need to have a good wordlist which could break the password. So to do so we have a tool in kali Linux called crunch crunch is a wordlist generating tool that comes pre-installed with Kali Linux. It is used to generate custom keywords based on wordlists. It generates a wordlist with permutation and combination. We could use some specific patterns and symbols to generate a wordlist. To install crunch tool use the following commands as per your Linux distribution. In case of Debian/Ubuntu $sudo apt-get install crunch In case of CentOS/RedHat $sudo yum install crunch In case of Fedora OS $sudo dnf install crunch 1. To check the installation. crunch This command will display the initial page of crunch tool which verifies the tool installation. 2. To create a word list of specific numbers. cruch 1 2 0123456789 This command will generate a wordlist of 110 words having the one and 2 digit numbers with all combinations of digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. you could use alphabets 3. To save the wordlist into a file crunch 1 2 0123456789 >wordlist.txt This command will generate a wordlist of 110 words having the one and 2 digit numbers with all combinations of digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and will copy the same to a text file named as wordlist.txt. 4. To save the wordlist to a file with -o option crunch 1 2 0123456789 -o wordlist.txt This command will generate a wordlist of 110 words having the one and 2 digit numbers with all combinations of digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and will copy the same to a text file named as wordlist.txt. 5. To generate a file using rainbow charset file crunch 2 3 -f /usr/share/rainbowcrack/charset.txt This command will use the charset present in the /usr/share/rainbowcrack/charset.txt file in order to generate a wordlist. 6. To generate a wordlist with a specific pattern. crunch 10 10 -t manav^%%%% Here we have 4 characters to represent some group of characters which are as follows: , for all uppercase letters @ for all lowercase letters % for all numeric characters ^ for all special characters So the above command will output all the words starting with β€œmanav” and then after that a special character and then 4 digit number. 7. To generate a wordlist with a permutation of some strings or characters crunch 1 10 -p Hello Manav In the case of -p, the minimum size and the maximum size values are ignored by the crunch and it displays all the possible permutations. The above command will give 2 permutations of β€œhello manav”. anikakapoor Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Aug, 2021" }, { "code": null, "e": 539, "s": 28, "text": "In order to hack a password, we have to try a lot of passwords to get the right one. When an attacker uses thousands or millions of words or character combinations to crack a password there is no surety that any one of those millions of combinations will work or not. This collection of a different combination of characters is called a wordlist. And in order to crack a password or a hash, we need to have a good wordlist which could break the password. So to do so we have a tool in kali Linux called crunch " }, { "code": null, "e": 808, "s": 539, "text": "crunch is a wordlist generating tool that comes pre-installed with Kali Linux. It is used to generate custom keywords based on wordlists. It generates a wordlist with permutation and combination. We could use some specific patterns and symbols to generate a wordlist. " }, { "code": null, "e": 891, "s": 808, "text": "To install crunch tool use the following commands as per your Linux distribution. " }, { "code": null, "e": 918, "s": 891, "text": "In case of Debian/Ubuntu " }, { "code": null, "e": 947, "s": 918, "text": "$sudo apt-get install crunch" }, { "code": null, "e": 974, "s": 947, "text": "In case of CentOS/RedHat " }, { "code": null, "e": 999, "s": 974, "text": "$sudo yum install crunch" }, { "code": null, "e": 1022, "s": 999, "text": "In case of Fedora OS " }, { "code": null, "e": 1047, "s": 1022, "text": "$sudo dnf install crunch" }, { "code": null, "e": 1078, "s": 1047, "text": "1. To check the installation. " }, { "code": null, "e": 1085, "s": 1078, "text": "crunch" }, { "code": null, "e": 1182, "s": 1085, "text": "This command will display the initial page of crunch tool which verifies the tool installation. " }, { "code": null, "e": 1230, "s": 1182, "text": "2. To create a word list of specific numbers. " }, { "code": null, "e": 1252, "s": 1230, "text": "cruch 1 2 0123456789 " }, { "code": null, "e": 1425, "s": 1252, "text": "This command will generate a wordlist of 110 words having the one and 2 digit numbers with all combinations of digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. you could use alphabets " }, { "code": null, "e": 1463, "s": 1425, "text": "3. To save the wordlist into a file " }, { "code": null, "e": 1500, "s": 1463, "text": "crunch 1 2 0123456789 >wordlist.txt " }, { "code": null, "e": 1709, "s": 1500, "text": "This command will generate a wordlist of 110 words having the one and 2 digit numbers with all combinations of digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and will copy the same to a text file named as wordlist.txt. " }, { "code": null, "e": 1760, "s": 1709, "text": "4. To save the wordlist to a file with -o option " }, { "code": null, "e": 1799, "s": 1760, "text": "crunch 1 2 0123456789 -o wordlist.txt" }, { "code": null, "e": 2008, "s": 1799, "text": "This command will generate a wordlist of 110 words having the one and 2 digit numbers with all combinations of digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and will copy the same to a text file named as wordlist.txt. " }, { "code": null, "e": 2059, "s": 2008, "text": "5. To generate a file using rainbow charset file " }, { "code": null, "e": 2110, "s": 2059, "text": "crunch 2 3 -f /usr/share/rainbowcrack/charset.txt " }, { "code": null, "e": 2234, "s": 2110, "text": "This command will use the charset present in the /usr/share/rainbowcrack/charset.txt file in order to generate a wordlist. " }, { "code": null, "e": 2287, "s": 2234, "text": "6. To generate a wordlist with a specific pattern. " }, { "code": null, "e": 2315, "s": 2287, "text": "crunch 10 10 -t manav^%%%% " }, { "code": null, "e": 2403, "s": 2315, "text": "Here we have 4 characters to represent some group of characters which are as follows: " }, { "code": null, "e": 2431, "s": 2403, "text": ", for all uppercase letters" }, { "code": null, "e": 2459, "s": 2431, "text": "@ for all lowercase letters" }, { "code": null, "e": 2488, "s": 2459, "text": "% for all numeric characters" }, { "code": null, "e": 2517, "s": 2488, "text": "^ for all special characters" }, { "code": null, "e": 2652, "s": 2517, "text": "So the above command will output all the words starting with β€œmanav” and then after that a special character and then 4 digit number. " }, { "code": null, "e": 2729, "s": 2652, "text": "7. To generate a wordlist with a permutation of some strings or characters " }, { "code": null, "e": 2756, "s": 2729, "text": "crunch 1 10 -p Hello Manav" }, { "code": null, "e": 2895, "s": 2756, "text": "In the case of -p, the minimum size and the maximum size values are ignored by the crunch and it displays all the possible permutations. " }, { "code": null, "e": 2957, "s": 2895, "text": "The above command will give 2 permutations of β€œhello manav”. " }, { "code": null, "e": 2969, "s": 2957, "text": "anikakapoor" }, { "code": null, "e": 2980, "s": 2969, "text": "Kali-Linux" }, { "code": null, "e": 2991, "s": 2980, "text": "Linux-Unix" } ]
Probability Density Estimation & Maximum Likelihood Estimation
30 May, 2021 Prerequisite: Probability Distribution Probability Density: Assume a random variable x that has a probability distribution p(x). The relationship between the outcomes of a random variable and its probability is referred to as the probability density. The problem is that we don’t always know the full probability distribution for a random variable. This is because we only use a small subset of observations to derive the outcome. This problem is referred to as Probability Density Estimation as we use only a random sample of observations to find the general density of the whole sample space. Probability Density Function (PDF) A PDF is a function that tells the probability of the random variable from a sub-sample space falling within a particular range of values and not just one value. It tells the likelihood of the range of values in the random variable sub-space being the same as that of the whole sample. By definition, if X is any continuous random variable, then the function f(x) is called a probability density function if: where, a -> lower limit b -> upper limit X -> continuous random variable f(x) -> probability density function Steps Involved: Step 1 - Create a histogram for the random set of observations to understand the density of the random sample. Step 2 - Create the probability density function and fit it on the random sample. Observe how it fits the histogram plot. Step 3 - Now iterate steps 1 and 2 in the following manner: 3.1 - Calculate the distribution parameters. 3.2 - Calculate the PDF for the random sample distribution. 3.3 - Observe the resulting PDF against the data. 3.4 - Transform the data to until it best fits the distribution. Most of the histogram of the different random sample after fitting should match the histogram plot of the whole population. Density Estimation: It is the process of finding out the density of the whole population by examining a random sample of data from that population. One of the best ways to achieve a density estimate is by using a histogram plot. Parametric Density Estimation A normal distribution has two given parameters, mean and standard deviation. We calculate the sample mean and standard deviation of the random sample taken from this population to estimate the density of the random sample. The reason it is termed as β€˜parametric’ is due to the fact that the relation between the observations and its probability can be different based on the values of the two parameters. Now, it is important to understand that the mean and standard deviation of this random sample is not going to be the same as that of the whole population due to its small size. A sample plot for parametric density estimation is shown below. PDF fitted over histogram plot with one peak value Nonparametric Density Estimation In some cases, the PDF may not fit the random sample as it doesn’t follow a normal distribution (i.e instead of one peak there are multiple peaks in the graph). Here, instead of using distribution parameters like mean and standard deviation, a particular algorithm is used to estimate the probability distribution. Thus, it is known as a β€˜nonparametric density estimation’. One of the most common nonparametric approach is known as Kernel Density Estimation. In this, the objective is to calculate the unknown density fh(x) using the equation given below: where, K -> kernel (non-negative function) h -> bandwidth (smoothing parameter, h > 0) Kh -> scaled kernel fh(x) -> density (to calculate) n -> no. of samples in random sample. A sample plot for nonparametric density estimation is given below. PDF plot over sample histogram plot based on KDE Problems with Probability Distribution Estimation Probability Distribution Estimation relies on finding the best PDF and determining its parameters accurately. But the random data sample that we consider, is very small. Hence, it becomes very difficult to determine what parameters and what probability distribution function to use. To tackle this problem, Maximum Likelihood Estimation is used. Maximum Likelihood Estimation It is a method of determining the parameters (mean, standard deviation, etc) of normally distributed random sample data or a method of finding the best fitting PDF over the random sample data. This is done by maximizing the likelihood function so that the PDF fitted over the random sample. Another way to look at it is that MLE function gives the mean, the standard deviation of the random sample is most similar to that of the whole sample. NOTE: MLE assumes that all PDFs are a likely candidate to being the best fitting curve. Hence, it is computationally expensive method. Intuition: Fig 1 : MLE Intuition Fig 1 shows multiple attempts at fitting the PDF bell curve over the random sample data. Red bell curves indicate poorly fitted PDF and the green bell curve shows the best fitting PDF over the data. We obtained the optimum bell curve by checking the values in Maximum Likelihood Estimate plot corresponding to each PDF. As observed in Fig 1, the red plots poorly fit the normal distribution, hence their β€˜likelihood estimate’ is also lower. The green PDF curve has the maximum likelihood estimate as it fits the data perfectly. This is how the maximum likelihood estimate method works. Mathematics Involved In the intuition, we discussed the role that Likelihood value plays in determining the optimum PDF curve. Let us understand the math involved in MLE method. We calculate Likelihood based on conditional probabilities. See the equation given below. where, L -> Likelihood value F -> Probability distribution function P -> Probability X1, X2, ... Xn -> random sample of size n taken from the whole population. x1, x2, ... xn -> values that these random sample (Xi) takes when determining the PDF. Ξ  -> product from 1 to n. In the above-given equation, we are trying to determine the likelihood value by calculating the joint probability of each Xi taking a specific value xi involved in a particular PDF. Now, since we are looking for the maximum likelihood value, we differentiate the likelihood function w.r.t P and set it to 0 as given below. This way, we can obtain the PDF curve that has the maximum likelihood of fit over the random sample data. But, if you observe carefully, differentiating L w.r.t P is not an easy task as all the probabilities in the likelihood function is a product. Hence, the calculation becomes computationally expensive. To solve this, we take the log of the Likelihood function L. Log Likelihood Taking the log of likelihood function gives the same result as before due to the increasing nature of Log function. But now, it becomes less computational due to the property of logarithm: Thus, the equation becomes: Now, we can easily differentiate log L wrt P and obtain the desired result. For any doubt/query, comment below. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2021" }, { "code": null, "e": 67, "s": 28, "text": "Prerequisite: Probability Distribution" }, { "code": null, "e": 280, "s": 67, "text": "Probability Density: Assume a random variable x that has a probability distribution p(x). The relationship between the outcomes of a random variable and its probability is referred to as the probability density. " }, { "code": null, "e": 625, "s": 280, "text": "The problem is that we don’t always know the full probability distribution for a random variable. This is because we only use a small subset of observations to derive the outcome. This problem is referred to as Probability Density Estimation as we use only a random sample of observations to find the general density of the whole sample space. " }, { "code": null, "e": 660, "s": 625, "text": "Probability Density Function (PDF)" }, { "code": null, "e": 947, "s": 660, "text": "A PDF is a function that tells the probability of the random variable from a sub-sample space falling within a particular range of values and not just one value. It tells the likelihood of the range of values in the random variable sub-space being the same as that of the whole sample. " }, { "code": null, "e": 1073, "s": 947, "text": "By definition, if X is any continuous random variable, then the function f(x) is called a probability density function if: " }, { "code": null, "e": 1183, "s": 1073, "text": "where,\na -> lower limit\nb -> upper limit\nX -> continuous random variable\nf(x) -> probability density function" }, { "code": null, "e": 1200, "s": 1183, "text": "Steps Involved: " }, { "code": null, "e": 1773, "s": 1200, "text": "Step 1 - Create a histogram for the random set of observations to understand the \n density of the random sample.\n\nStep 2 - Create the probability density function and fit it on the random sample. \n Observe how it fits the histogram plot.\n\nStep 3 - Now iterate steps 1 and 2 in the following manner:\n 3.1 - Calculate the distribution parameters.\n 3.2 - Calculate the PDF for the random sample distribution.\n 3.3 - Observe the resulting PDF against the data.\n 3.4 - Transform the data to until it best fits the distribution. " }, { "code": null, "e": 1898, "s": 1773, "text": "Most of the histogram of the different random sample after fitting should match the histogram plot of the whole population. " }, { "code": null, "e": 2128, "s": 1898, "text": "Density Estimation: It is the process of finding out the density of the whole population by examining a random sample of data from that population. One of the best ways to achieve a density estimate is by using a histogram plot. " }, { "code": null, "e": 2158, "s": 2128, "text": "Parametric Density Estimation" }, { "code": null, "e": 2564, "s": 2158, "text": "A normal distribution has two given parameters, mean and standard deviation. We calculate the sample mean and standard deviation of the random sample taken from this population to estimate the density of the random sample. The reason it is termed as β€˜parametric’ is due to the fact that the relation between the observations and its probability can be different based on the values of the two parameters. " }, { "code": null, "e": 2805, "s": 2564, "text": "Now, it is important to understand that the mean and standard deviation of this random sample is not going to be the same as that of the whole population due to its small size. A sample plot for parametric density estimation is shown below." }, { "code": null, "e": 2856, "s": 2805, "text": "PDF fitted over histogram plot with one peak value" }, { "code": null, "e": 2889, "s": 2856, "text": "Nonparametric Density Estimation" }, { "code": null, "e": 3264, "s": 2889, "text": "In some cases, the PDF may not fit the random sample as it doesn’t follow a normal distribution (i.e instead of one peak there are multiple peaks in the graph). Here, instead of using distribution parameters like mean and standard deviation, a particular algorithm is used to estimate the probability distribution. Thus, it is known as a β€˜nonparametric density estimation’. " }, { "code": null, "e": 3446, "s": 3264, "text": "One of the most common nonparametric approach is known as Kernel Density Estimation. In this, the objective is to calculate the unknown density fh(x) using the equation given below:" }, { "code": null, "e": 3624, "s": 3446, "text": "where,\nK -> kernel (non-negative function)\nh -> bandwidth (smoothing parameter, h > 0)\nKh -> scaled kernel \nfh(x) -> density (to calculate)\nn -> no. of samples in random sample." }, { "code": null, "e": 3691, "s": 3624, "text": "A sample plot for nonparametric density estimation is given below." }, { "code": null, "e": 3740, "s": 3691, "text": "PDF plot over sample histogram plot based on KDE" }, { "code": null, "e": 3790, "s": 3740, "text": "Problems with Probability Distribution Estimation" }, { "code": null, "e": 4136, "s": 3790, "text": "Probability Distribution Estimation relies on finding the best PDF and determining its parameters accurately. But the random data sample that we consider, is very small. Hence, it becomes very difficult to determine what parameters and what probability distribution function to use. To tackle this problem, Maximum Likelihood Estimation is used." }, { "code": null, "e": 4166, "s": 4136, "text": "Maximum Likelihood Estimation" }, { "code": null, "e": 4610, "s": 4166, "text": "It is a method of determining the parameters (mean, standard deviation, etc) of normally distributed random sample data or a method of finding the best fitting PDF over the random sample data. This is done by maximizing the likelihood function so that the PDF fitted over the random sample. Another way to look at it is that MLE function gives the mean, the standard deviation of the random sample is most similar to that of the whole sample. " }, { "code": null, "e": 4746, "s": 4610, "text": "NOTE: MLE assumes that all PDFs are a likely candidate to being the best fitting curve. Hence, it is computationally expensive method. " }, { "code": null, "e": 4758, "s": 4746, "text": "Intuition: " }, { "code": null, "e": 4780, "s": 4758, "text": "Fig 1 : MLE Intuition" }, { "code": null, "e": 5101, "s": 4780, "text": "Fig 1 shows multiple attempts at fitting the PDF bell curve over the random sample data. Red bell curves indicate poorly fitted PDF and the green bell curve shows the best fitting PDF over the data. We obtained the optimum bell curve by checking the values in Maximum Likelihood Estimate plot corresponding to each PDF. " }, { "code": null, "e": 5368, "s": 5101, "text": "As observed in Fig 1, the red plots poorly fit the normal distribution, hence their β€˜likelihood estimate’ is also lower. The green PDF curve has the maximum likelihood estimate as it fits the data perfectly. This is how the maximum likelihood estimate method works. " }, { "code": null, "e": 5389, "s": 5368, "text": "Mathematics Involved" }, { "code": null, "e": 5547, "s": 5389, "text": "In the intuition, we discussed the role that Likelihood value plays in determining the optimum PDF curve. Let us understand the math involved in MLE method. " }, { "code": null, "e": 5637, "s": 5547, "text": "We calculate Likelihood based on conditional probabilities. See the equation given below." }, { "code": null, "e": 5913, "s": 5637, "text": "where, \nL -> Likelihood value\nF -> Probability distribution function\nP -> Probability \nX1, X2, ... Xn -> random sample of size n taken from the whole population. \nx1, x2, ... xn -> values that these random sample (Xi) takes when determining the PDF.\nΞ  -> product from 1 to n." }, { "code": null, "e": 6237, "s": 5913, "text": "In the above-given equation, we are trying to determine the likelihood value by calculating the joint probability of each Xi taking a specific value xi involved in a particular PDF. Now, since we are looking for the maximum likelihood value, we differentiate the likelihood function w.r.t P and set it to 0 as given below. " }, { "code": null, "e": 6344, "s": 6237, "text": "This way, we can obtain the PDF curve that has the maximum likelihood of fit over the random sample data. " }, { "code": null, "e": 6606, "s": 6344, "text": "But, if you observe carefully, differentiating L w.r.t P is not an easy task as all the probabilities in the likelihood function is a product. Hence, the calculation becomes computationally expensive. To solve this, we take the log of the Likelihood function L." }, { "code": null, "e": 6621, "s": 6606, "text": "Log Likelihood" }, { "code": null, "e": 6811, "s": 6621, "text": "Taking the log of likelihood function gives the same result as before due to the increasing nature of Log function. But now, it becomes less computational due to the property of logarithm: " }, { "code": null, "e": 6839, "s": 6811, "text": "Thus, the equation becomes:" }, { "code": null, "e": 6952, "s": 6839, "text": "Now, we can easily differentiate log L wrt P and obtain the desired result. For any doubt/query, comment below. " }, { "code": null, "e": 6969, "s": 6952, "text": "Machine Learning" }, { "code": null, "e": 6986, "s": 6969, "text": "Machine Learning" } ]
Plotting World Map Using Pygal in Python
28 Jul, 2020 Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. We might want to plot the World Map with country wise boundaries and might even want to represent or differentiate countries on a geographical basis or based on some data in our project. Python Library β€œPygal” will help us achieve our task. So let’s get started. pip install pygal_maps_world Syntax: worldmap = pygal.maps.world.World() Now you can plot the graph of the countries by using their country code. Here is the list of the country code. Example 1: Plotting Countries Based on Data. Python3 # import pygal libraryimport pygal # create a world mapworldmap = pygal.maps.world.World() # set the title of the mapworldmap.title = 'Countries' # adding the countriesworldmap.add('Random Data', { 'aq' : 10, 'cd' : 30, 'de' : 40, 'eg' : 50, 'ga' : 45, 'hk' : 23, 'in' : 70, 'jp' : 54, 'nz' : 41, 'kz' : 32, 'us' : 66}) # save into the fileworldmap.render_to_file('abc.svg') print("Success") Output: Example 2: Plotting Countries with labels. Python3 # import pygalimport pygal # import Style class from pygal.stylefrom pygal.style import Style # create a Style objectcustom_style = Style( colors = ('#FF0000' , '#0000FF' , '#00FF00' , '#000000', '#FFD700')) # create a world map,# Style class is used for using# the custom colours in the map,worldmap = pygal.maps.world.World(style = custom_style) # set the title of the mapworldmap.title = 'Some Countries Starting from Specific Letters' # hex code of colours are used# for every .add() calledworldmap.add('"E" Countries', ['ec', 'ee', 'eg', 'eh', 'er', 'es','et']) worldmap.add('"F" Countries', ['fr', 'fi']) worldmap.add('"P" Countries', ['pa', 'pe', 'pg', 'ph', 'pk', 'pl','pr', 'ps', 'pt', 'py']) worldmap.add('"Z" Countries', ['zm', 'zw']) worldmap.add ('"A" Countries' , ['ad','ae', 'af', 'al', 'am', 'ao', 'aq', 'ar', 'at', 'au', 'az'], color = 'black') # save into the fileworldmap.render_to_file('abc.svg') print("Success") Output Example 3: Plotting Continents. Python3 # import pygal libraryimport pygal # create a world mapworldmap = pygal.maps.world.SupranationalWorld() # set the title of mapworldmap.title = 'Continents' # adding the continentsworldmap.add('Africa', [('africa')])worldmap.add('North america', [('north_america')])worldmap.add('Oceania', [('oceania')])worldmap.add('South america', [('south_america')])worldmap.add('Asia', [('asia')])worldmap.add('Europe', [('europe')])worldmap.add('Antartica', [('antartica')]) # save into the fileworldmap.render_to_file('abc.svg') print("Success") Output: Data Visualization Python-pygal Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 307, "s": 28, "text": "Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. " }, { "code": null, "e": 570, "s": 307, "text": "We might want to plot the World Map with country wise boundaries and might even want to represent or differentiate countries on a geographical basis or based on some data in our project. Python Library β€œPygal” will help us achieve our task. So let’s get started." }, { "code": null, "e": 600, "s": 570, "text": "pip install pygal_maps_world\n" }, { "code": null, "e": 608, "s": 600, "text": "Syntax:" }, { "code": null, "e": 646, "s": 608, "text": "worldmap = pygal.maps.world.World()\n" }, { "code": null, "e": 758, "s": 646, "text": "Now you can plot the graph of the countries by using their country code. Here is the list of the country code. " }, { "code": null, "e": 803, "s": 758, "text": "Example 1: Plotting Countries Based on Data." }, { "code": null, "e": 811, "s": 803, "text": "Python3" }, { "code": "# import pygal libraryimport pygal # create a world mapworldmap = pygal.maps.world.World() # set the title of the mapworldmap.title = 'Countries' # adding the countriesworldmap.add('Random Data', { 'aq' : 10, 'cd' : 30, 'de' : 40, 'eg' : 50, 'ga' : 45, 'hk' : 23, 'in' : 70, 'jp' : 54, 'nz' : 41, 'kz' : 32, 'us' : 66}) # save into the fileworldmap.render_to_file('abc.svg') print(\"Success\")", "e": 1286, "s": 811, "text": null }, { "code": null, "e": 1296, "s": 1286, "text": "Output: " }, { "code": null, "e": 1339, "s": 1296, "text": "Example 2: Plotting Countries with labels." }, { "code": null, "e": 1347, "s": 1339, "text": "Python3" }, { "code": "# import pygalimport pygal # import Style class from pygal.stylefrom pygal.style import Style # create a Style objectcustom_style = Style( colors = ('#FF0000' , '#0000FF' , '#00FF00' , '#000000', '#FFD700')) # create a world map,# Style class is used for using# the custom colours in the map,worldmap = pygal.maps.world.World(style = custom_style) # set the title of the mapworldmap.title = 'Some Countries Starting from Specific Letters' # hex code of colours are used# for every .add() calledworldmap.add('\"E\" Countries', ['ec', 'ee', 'eg', 'eh', 'er', 'es','et']) worldmap.add('\"F\" Countries', ['fr', 'fi']) worldmap.add('\"P\" Countries', ['pa', 'pe', 'pg', 'ph', 'pk', 'pl','pr', 'ps', 'pt', 'py']) worldmap.add('\"Z\" Countries', ['zm', 'zw']) worldmap.add ('\"A\" Countries' , ['ad','ae', 'af', 'al', 'am', 'ao', 'aq', 'ar', 'at', 'au', 'az'], color = 'black') # save into the fileworldmap.render_to_file('abc.svg') print(\"Success\")", "e": 2511, "s": 1347, "text": null }, { "code": null, "e": 2520, "s": 2511, "text": "Output " }, { "code": null, "e": 2554, "s": 2522, "text": "Example 3: Plotting Continents." }, { "code": null, "e": 2562, "s": 2554, "text": "Python3" }, { "code": "# import pygal libraryimport pygal # create a world mapworldmap = pygal.maps.world.SupranationalWorld() # set the title of mapworldmap.title = 'Continents' # adding the continentsworldmap.add('Africa', [('africa')])worldmap.add('North america', [('north_america')])worldmap.add('Oceania', [('oceania')])worldmap.add('South america', [('south_america')])worldmap.add('Asia', [('asia')])worldmap.add('Europe', [('europe')])worldmap.add('Antartica', [('antartica')]) # save into the fileworldmap.render_to_file('abc.svg') print(\"Success\")", "e": 3104, "s": 2562, "text": null }, { "code": null, "e": 3114, "s": 3104, "text": "Output: " }, { "code": null, "e": 3133, "s": 3114, "text": "Data Visualization" }, { "code": null, "e": 3146, "s": 3133, "text": "Python-pygal" }, { "code": null, "e": 3153, "s": 3146, "text": "Python" } ]
Lodash _.sortBy() Method
10 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _.sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements. Syntax: _.sortBy(collection, iteratees) Parameters: This method accepts two parameters as mentioned above and described below: collection: This parameter holds the collection to iterate over. iteratees: This parameter holds the iteratees to sort by and are invoked with one argument(value). Return Value: This method is used to return the new sorted array. Example 1: Here, const _ = require(β€˜lodash’) is used to import the lodash library in the file. javascript // Requiring the lodash library const _ = require("lodash"); // Original array var object = [ { 'obj': 'moto', 'price': 19999 }, { 'obj': 'oppo', 'price': 18999 }, { 'obj': 'moto', 'price': 17999 }, { 'obj': 'oppo', 'price': 15999 } ]; // Use of _.sortBy() methodlet gfg = _.sortBy(object, [function(o) { return o.obj; }]); // Printing the output console.log(gfg); Output: [ { 'obj': 'moto', 'price': 19999 }, { 'obj': 'moto', 'price': 17999 }, { 'obj': 'oppo', 'price': 18999 }, { 'obj': 'oppo', 'price': 15999 } ] Example 2: javascript // Requiring the lodash library const _ = require("lodash"); // Original array var object = [ { 'obj': 'moto', 'price': 19999 }, { 'obj': 'oppo', 'price': 18999 }, { 'obj': 'moto', 'price': 17999 }, { 'obj': 'oppo', 'price': 15999 } ]; // Use of _.sortBy() methodlet gfg = _.sortBy(object, ['obj', 'price']); // Printing the output console.log(gfg); Output: [ { 'obj': 'moto', 'price': 17999 }, { 'obj': 'moto', 'price': 19999 }, { 'obj': 'oppo', 'price': 15999 }, { 'obj': 'oppo', 'price': 18999 } ] Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. JavaScript-Lodash JavaScript 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Sep, 2020" }, { "code": null, "e": 204, "s": 53, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc." }, { "code": null, "e": 480, "s": 204, "text": "The _.sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements." }, { "code": null, "e": 488, "s": 480, "text": "Syntax:" }, { "code": null, "e": 520, "s": 488, "text": "_.sortBy(collection, iteratees)" }, { "code": null, "e": 607, "s": 520, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 672, "s": 607, "text": "collection: This parameter holds the collection to iterate over." }, { "code": null, "e": 771, "s": 672, "text": "iteratees: This parameter holds the iteratees to sort by and are invoked with one argument(value)." }, { "code": null, "e": 837, "s": 771, "text": "Return Value: This method is used to return the new sorted array." }, { "code": null, "e": 932, "s": 837, "text": "Example 1: Here, const _ = require(β€˜lodash’) is used to import the lodash library in the file." }, { "code": null, "e": 943, "s": 932, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var object = [ { 'obj': 'moto', 'price': 19999 }, { 'obj': 'oppo', 'price': 18999 }, { 'obj': 'moto', 'price': 17999 }, { 'obj': 'oppo', 'price': 15999 } ]; // Use of _.sortBy() methodlet gfg = _.sortBy(object, [function(o) { return o.obj; }]); // Printing the output console.log(gfg);", "e": 1326, "s": 943, "text": null }, { "code": null, "e": 1334, "s": 1326, "text": "Output:" }, { "code": null, "e": 1486, "s": 1334, "text": "[\n { 'obj': 'moto', 'price': 19999 },\n { 'obj': 'moto', 'price': 17999 },\n { 'obj': 'oppo', 'price': 18999 },\n { 'obj': 'oppo', 'price': 15999 }\n]\n" }, { "code": null, "e": 1497, "s": 1486, "text": "Example 2:" }, { "code": null, "e": 1508, "s": 1497, "text": "javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var object = [ { 'obj': 'moto', 'price': 19999 }, { 'obj': 'oppo', 'price': 18999 }, { 'obj': 'moto', 'price': 17999 }, { 'obj': 'oppo', 'price': 15999 } ]; // Use of _.sortBy() methodlet gfg = _.sortBy(object, ['obj', 'price']); // Printing the output console.log(gfg);", "e": 1872, "s": 1508, "text": null }, { "code": null, "e": 1880, "s": 1872, "text": "Output:" }, { "code": null, "e": 2033, "s": 1880, "text": "[\n { 'obj': 'moto', 'price': 17999 },\n { 'obj': 'moto', 'price': 19999 },\n { 'obj': 'oppo', 'price': 15999 },\n { 'obj': 'oppo', 'price': 18999 } \n]\n" }, { "code": null, "e": 2140, "s": 2033, "text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 2158, "s": 2140, "text": "JavaScript-Lodash" }, { "code": null, "e": 2169, "s": 2158, "text": "JavaScript" }, { "code": null, "e": 2186, "s": 2169, "text": "Web Technologies" }, { "code": null, "e": 2284, "s": 2186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2345, "s": 2284, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2417, "s": 2345, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2457, "s": 2417, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2499, "s": 2457, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2540, "s": 2499, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2573, "s": 2540, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2635, "s": 2573, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2696, "s": 2635, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2746, "s": 2696, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
GATE | GATE-CS-2014-(Set-3) | Question 65
28 Jun, 2021 Consider the following rooted tree with the vertex P labeled as root The order in which the nodes are visited during in-order traversal is(A) SQPTRWUV(B) SQPTURWV(C) SQPTWUVR(D) SQPTRUWVAnswer: (A)Explanation: Algorithm Inorder(tree) - Use of Recursion Steps: 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree) Understanding this algorithm requires the basic understanding of Recursion Therefore, We begin in the above tree with root as the starting point, which is P. # Step 1( for node P) : Traverse the left subtree of node or root P. So we have node Q on left of P. -> Step 1( for node Q) Traverse the left subtree of node Q. So we have node S on left of Q. * Step 1 (for node S) Now again traverse the left subtree of node S which is NULL here. * Step 2(for node S) Visit the node S, i.e print node S as the 1st element of inorder traversal. * Step 3(for node S) Traverse the right subtree of node S. Which is NULL here. Now move up in the tree to Q which is parent of S.( Recursion, function of Q called for function of S). Hence we go back to Q. -> Step 2( for node Q): Visit the node Q, i.e print node Q as the 2nd element of inorder traversal. -> Step 3 (for node Q) Traverse the right subtree of node Q. Which is NULL here. Now move up in the tree to P which is parent of Q.( Recursion, function of P called for function of Q). Hence we go back to P. # Step 2(for node P) Visit the node P, i.e print node S as the 3rd element of inorder traversal. # Step 3 (for node P) Traverse the right subtree of node P. Node R is at the right of P. Till now we have printed SQP as the inorder of the tree. Similarly other elements can be obtained by traversing the right subtree of P. The final correct order of Inorder traversal would be SQPTRWUV. Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 40 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 97, "s": 28, "text": "Consider the following rooted tree with the vertex P labeled as root" }, { "code": null, "e": 238, "s": 97, "text": "The order in which the nodes are visited during in-order traversal is(A) SQPTRWUV(B) SQPTURWV(C) SQPTWUVR(D) SQPTRUWVAnswer: (A)Explanation:" }, { "code": null, "e": 1901, "s": 238, "text": "Algorithm Inorder(tree) - Use of Recursion\nSteps:\n1. Traverse the left subtree, \n i.e., call Inorder(left-subtree)\n2. Visit the root.\n3. Traverse the right subtree, \n i.e., call Inorder(right-subtree)\n\nUnderstanding this algorithm requires the basic \nunderstanding of Recursion\n\nTherefore, We begin in the above tree with root as\nthe starting point, which is P.\n\n# Step 1( for node P) :\nTraverse the left subtree of node or root P.\nSo we have node Q on left of P.\n\n-> Step 1( for node Q)\nTraverse the left subtree of node Q.\nSo we have node S on left of Q.\n\n* Step 1 (for node S)\nNow again traverse the left subtree of node S which is \nNULL here.\n\n* Step 2(for node S)\nVisit the node S, i.e print node S as the 1st element of \ninorder traversal.\n\n* Step 3(for node S)\nTraverse the right subtree of node S.\nWhich is NULL here.\n\nNow move up in the tree to Q which is parent\nof S.( Recursion, function of Q called for function of S).\nHence we go back to Q.\n\n-> Step 2( for node Q):\nVisit the node Q, i.e print node Q as the 2nd\nelement of inorder traversal.\n\n-> Step 3 (for node Q)\nTraverse the right subtree of node Q.\nWhich is NULL here.\n\nNow move up in the tree to P which is parent\nof Q.( Recursion, function of P called for function of Q).\nHence we go back to P.\n\n# Step 2(for node P)\nVisit the node P, i.e print node S as the 3rd\nelement of inorder traversal.\n\n# Step 3 (for node P)\nTraverse the right subtree of node P.\nNode R is at the right of P.\n\nTill now we have printed SQP as the inorder of the tree. \nSimilarly other elements can be obtained by traversing \nthe right subtree of P.\n\nThe final correct order of Inorder traversal would \nbe SQPTRWUV. " }, { "code": null, "e": 1923, "s": 1901, "text": "Quiz of this Question" }, { "code": null, "e": 1944, "s": 1923, "text": "GATE-CS-2014-(Set-3)" }, { "code": null, "e": 1970, "s": 1944, "text": "GATE-GATE-CS-2014-(Set-3)" }, { "code": null, "e": 1975, "s": 1970, "text": "GATE" }, { "code": null, "e": 2073, "s": 1975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2115, "s": 2073, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2177, "s": 2115, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2219, "s": 2177, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 2253, "s": 2219, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 2287, "s": 2253, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2329, "s": 2287, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2371, "s": 2329, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2405, "s": 2371, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 2439, "s": 2405, "text": "GATE | GATE CS 1996 | Question 38" } ]
PHP | imagecreatefromjpeg() Function
30 Jan, 2020 The imagecreatefromjpeg() function is an inbuilt function in PHP which is used to create a new image from JPEG file or URL. This image can be further worked upon in the program. Syntax: resource imagecreatefromjpeg( string $filename ) Parameters: This function accepts a single parameter, $filename which holds the name of imageReturn Value: This function returns an image resource identifier on success, FALSE on errors. Below examples illustrate the imagecreatefromjpeg() function in PHP: Example 1: <?php // Load an image from jpeg URL$im = imagecreatefromjpeg('https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg'); // View the loaded image in browserheader('Content-type: image/jpg'); imagejpeg($im);imagedestroy($im);?> Output: Example 2: <?php // Load an image from jpeg URL$im = imagecreatefromjpeg('https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg'); // Flip the imageimageflip($im, 1); // View the loaded image in browserheader('Content-type: image/jpg'); imagejpeg($im);imagedestroy($im);?> Output:Reference: https://www.php.net/manual/en/function.imagecreatefromjpeg.php PHP-function PHP-Imagick PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function How to create admin login page using PHP? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 206, "s": 28, "text": "The imagecreatefromjpeg() function is an inbuilt function in PHP which is used to create a new image from JPEG file or URL. This image can be further worked upon in the program." }, { "code": null, "e": 214, "s": 206, "text": "Syntax:" }, { "code": null, "e": 263, "s": 214, "text": "resource imagecreatefromjpeg( string $filename )" }, { "code": null, "e": 450, "s": 263, "text": "Parameters: This function accepts a single parameter, $filename which holds the name of imageReturn Value: This function returns an image resource identifier on success, FALSE on errors." }, { "code": null, "e": 519, "s": 450, "text": "Below examples illustrate the imagecreatefromjpeg() function in PHP:" }, { "code": null, "e": 530, "s": 519, "text": "Example 1:" }, { "code": "<?php // Load an image from jpeg URL$im = imagecreatefromjpeg('https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg'); // View the loaded image in browserheader('Content-type: image/jpg'); imagejpeg($im);imagedestroy($im);?>", "e": 793, "s": 530, "text": null }, { "code": null, "e": 801, "s": 793, "text": "Output:" }, { "code": null, "e": 812, "s": 801, "text": "Example 2:" }, { "code": "<?php // Load an image from jpeg URL$im = imagecreatefromjpeg('https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg'); // Flip the imageimageflip($im, 1); // View the loaded image in browserheader('Content-type: image/jpg'); imagejpeg($im);imagedestroy($im);?>", "e": 1112, "s": 812, "text": null }, { "code": null, "e": 1193, "s": 1112, "text": "Output:Reference: https://www.php.net/manual/en/function.imagecreatefromjpeg.php" }, { "code": null, "e": 1206, "s": 1193, "text": "PHP-function" }, { "code": null, "e": 1218, "s": 1206, "text": "PHP-Imagick" }, { "code": null, "e": 1222, "s": 1218, "text": "PHP" }, { "code": null, "e": 1239, "s": 1222, "text": "Web Technologies" }, { "code": null, "e": 1243, "s": 1239, "text": "PHP" }, { "code": null, "e": 1341, "s": 1243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1423, "s": 1341, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 1468, "s": 1423, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 1519, "s": 1468, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 1549, "s": 1519, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 1591, "s": 1549, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 1653, "s": 1591, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1686, "s": 1653, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1747, "s": 1686, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1797, "s": 1747, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
WPF - Contextmenu
ContextMenu is a pop-up menu that enables a control to expose functionality that is specific to the context of the control. It appears whenever the context menu is requested through a user interface from within this element. The hierarchical inheritance of ContextMenu class is as follows βˆ’ Background Gets or sets a brush that provides the background of the control. (Inherited from Control) BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) ContextMenu Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.) FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) FontSize Gets or sets the size of the text in this control. (Inherited from Control) FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) HasItems Gets a value that indicates whether the ItemsControl contains items. (Inherited from ItemsControl.) Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) IsFocused Gets a value that determines whether this element has logical focus. This is a dependency property. (Inherited from UIElement.) IsOpen Gets or sets a value that indicates whether the ContextMenu is visible. IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) ItemsSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) AddChild Adds the specified object as the child of the ItemsControl object. (Inherited from ItemsControl.) Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) Focus Attempts to set the focus on the control. (Inherited from Control) GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) IsItemItsOwnContainer Determines if the specified item is (or is eligible to be) its own container. (Inherited from ItemsControl.) OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) OnDragOver Called before the DragOver event occurs. (Inherited from Control) OnDrop Called before the Drop event occurs. (Inherited from Control) OnContextMenuOpening Invoked whenever an unhandled ContextMenuClosing routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.) OnItemsChanged Invoked when the Items property changes. (Inherited from ItemsControl.) OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Closed Occurs when a particular instance of a ContextMenu closes. ContextMenuClosing Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.) ContextMenuOpening Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.) DataContextChanged Occurs when the data context for this element changes. (Inherited from FrameworkElement.) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) Let’s create a new WPF project with the name WPFContextMenuControl. Let’s create a new WPF project with the name WPFContextMenuControl. Drag a textbox from a toolbox and set the following properties in the properties window. Drag a textbox from a toolbox and set the following properties in the properties window. Now switch to XAML window in which you will see the XAML tags for textbox and ContextMenu. Now switch to XAML window in which you will see the XAML tags for textbox and ContextMenu. Add some more properties, menu items, and checked and unchecked events, as shown in the following XAML code. Add some more properties, menu items, and checked and unchecked events, as shown in the following XAML code. The following example contains a textbox with ContextMenu which manipulates the text inside the textbox. The following XAML code creates a textbox with some properties and events context menu. <Window x:Class = "WPFContextMenuControl.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFContextMenuControl" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <TextBox x:Name = "textBox1" HorizontalAlignment = "Left" Height = "178" Margin = "92,61,0,0" TextWrapping = "Wrap" Text = "Hi, this is WPF tutorial" VerticalAlignment = "Top" Width = "306"> <TextBox.ContextMenu> <ContextMenu> <MenuItem Header = "_Bold" IsCheckable = "True" Checked = "Bold_Checked" Unchecked = "Bold_Unchecked" /> <MenuItem Header = "_Italic" IsCheckable = "True" Checked = "Italic_Checked" Unchecked = "Italic_Unchecked" /> <Separator /> <MenuItem Header = "Increase Font Size" Click = "IncreaseFont_Click" /> <MenuItem Header = "_Decrease Font Size" Click = "DecreaseFont_Click" /> </ContextMenu> </TextBox.ContextMenu> </TextBox> </Grid> </Window> Here is the implementation in C# for different events. using System.Windows; namespace WPFContextMenuControl { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Bold_Checked(object sender, RoutedEventArgs e) { textBox1.FontWeight = FontWeights.Bold; } private void Bold_Unchecked(object sender, RoutedEventArgs e) { textBox1.FontWeight = FontWeights.Normal; } private void Italic_Checked(object sender, RoutedEventArgs e) { textBox1.FontStyle = FontStyles.Italic; } private void Italic_Unchecked(object sender, RoutedEventArgs e) { textBox1.FontStyle = FontStyles.Normal; } private void IncreaseFont_Click(object sender, RoutedEventArgs e) { if (textBox1.FontSize < 18) { textBox1.FontSize += 2; } } private void DecreaseFont_Click(object sender, RoutedEventArgs e) { if (textBox1.FontSize > 10) { textBox1.FontSize -= 2; } } } } When you compile and execute the above code, it will produce the following window βˆ’ We recommend that you execute the above example code and try some other properties and events of ContextMenu.
[ { "code": null, "e": 2445, "s": 2154, "text": "ContextMenu is a pop-up menu that enables a control to expose functionality that is specific to the context of the control. It appears whenever the context menu is requested through a user interface from within this element. The hierarchical inheritance of ContextMenu class is as follows βˆ’" }, { "code": null, "e": 2456, "s": 2445, "text": "Background" }, { "code": null, "e": 2547, "s": 2456, "text": "Gets or sets a brush that provides the background of the control. (Inherited from Control)" }, { "code": null, "e": 2563, "s": 2547, "text": "BorderThickness" }, { "code": null, "e": 2636, "s": 2563, "text": "Gets or sets the border thickness of a control. (Inherited from Control)" }, { "code": null, "e": 2648, "s": 2636, "text": "ContextMenu" }, { "code": null, "e": 2833, "s": 2648, "text": "Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 2844, "s": 2833, "text": "FontFamily" }, { "code": null, "e": 2928, "s": 2844, "text": "Gets or sets the font used to display text in the control. (Inherited from Control)" }, { "code": null, "e": 2937, "s": 2928, "text": "FontSize" }, { "code": null, "e": 3013, "s": 2937, "text": "Gets or sets the size of the text in this control. (Inherited from Control)" }, { "code": null, "e": 3023, "s": 3013, "text": "FontStyle" }, { "code": null, "e": 3102, "s": 3023, "text": "Gets or sets the style in which the text is rendered. (Inherited from Control)" }, { "code": null, "e": 3113, "s": 3102, "text": "FontWeight" }, { "code": null, "e": 3188, "s": 3113, "text": "Gets or sets the thickness of the specified font. (Inherited from Control)" }, { "code": null, "e": 3199, "s": 3188, "text": "Foreground" }, { "code": null, "e": 3282, "s": 3199, "text": "Gets or sets a brush that describes the foreground color. (Inherited from Control)" }, { "code": null, "e": 3293, "s": 3282, "text": "GroupStyle" }, { "code": null, "e": 3415, "s": 3293, "text": "Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl)" }, { "code": null, "e": 3424, "s": 3415, "text": "HasItems" }, { "code": null, "e": 3524, "s": 3424, "text": "Gets a value that indicates whether the ItemsControl contains items. (Inherited from ItemsControl.)" }, { "code": null, "e": 3531, "s": 3524, "text": "Height" }, { "code": null, "e": 3622, "s": 3531, "text": "Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 3642, "s": 3622, "text": "HorizontalAlignment" }, { "code": null, "e": 3843, "s": 3642, "text": "Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 3853, "s": 3843, "text": "IsFocused" }, { "code": null, "e": 3981, "s": 3853, "text": "Gets a value that determines whether this element has logical focus. This is a dependency property. (Inherited from UIElement.)" }, { "code": null, "e": 3988, "s": 3981, "text": "IsOpen" }, { "code": null, "e": 4060, "s": 3988, "text": "Gets or sets a value that indicates whether the ContextMenu is visible." }, { "code": null, "e": 4070, "s": 4060, "text": "IsEnabled" }, { "code": null, "e": 4175, "s": 4070, "text": "Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)" }, { "code": null, "e": 4187, "s": 4175, "text": "ItemsSource" }, { "code": null, "e": 4297, "s": 4187, "text": "Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl)" }, { "code": null, "e": 4304, "s": 4297, "text": "Margin" }, { "code": null, "e": 4391, "s": 4304, "text": "Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 4396, "s": 4391, "text": "Name" }, { "code": null, "e": 4609, "s": 4396, "text": "Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement)" }, { "code": null, "e": 4617, "s": 4609, "text": "Opacity" }, { "code": null, "e": 4693, "s": 4617, "text": "Gets or sets the degree of the object's opacity. (Inherited from UIElement)" }, { "code": null, "e": 4699, "s": 4693, "text": "Style" }, { "code": null, "e": 4825, "s": 4699, "text": "Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement)" }, { "code": null, "e": 4843, "s": 4825, "text": "VerticalAlignment" }, { "code": null, "e": 5041, "s": 4843, "text": "Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)" }, { "code": null, "e": 5047, "s": 5041, "text": "Width" }, { "code": null, "e": 5127, "s": 5047, "text": "Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 5136, "s": 5127, "text": "AddChild" }, { "code": null, "e": 5234, "s": 5136, "text": "Adds the specified object as the child of the ItemsControl object. (Inherited from ItemsControl.)" }, { "code": null, "e": 5242, "s": 5234, "text": "Arrange" }, { "code": null, "e": 5503, "s": 5242, "text": "Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement)" }, { "code": null, "e": 5512, "s": 5503, "text": "FindName" }, { "code": null, "e": 5606, "s": 5512, "text": "Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)" }, { "code": null, "e": 5612, "s": 5606, "text": "Focus" }, { "code": null, "e": 5679, "s": 5612, "text": "Attempts to set the focus on the control. (Inherited from Control)" }, { "code": null, "e": 5688, "s": 5679, "text": "GetValue" }, { "code": null, "e": 5808, "s": 5688, "text": "Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 5830, "s": 5808, "text": "IsItemItsOwnContainer" }, { "code": null, "e": 5939, "s": 5830, "text": "Determines if the specified item is (or is eligible to be) its own container. (Inherited from ItemsControl.)" }, { "code": null, "e": 5951, "s": 5939, "text": "OnDragEnter" }, { "code": null, "e": 6018, "s": 5951, "text": "Called before the DragEnter event occurs. (Inherited from Control)" }, { "code": null, "e": 6030, "s": 6018, "text": "OnDragLeave" }, { "code": null, "e": 6097, "s": 6030, "text": "Called before the DragLeave event occurs. (Inherited from Control)" }, { "code": null, "e": 6108, "s": 6097, "text": "OnDragOver" }, { "code": null, "e": 6174, "s": 6108, "text": "Called before the DragOver event occurs. (Inherited from Control)" }, { "code": null, "e": 6181, "s": 6174, "text": "OnDrop" }, { "code": null, "e": 6243, "s": 6181, "text": "Called before the Drop event occurs. (Inherited from Control)" }, { "code": null, "e": 6264, "s": 6243, "text": "OnContextMenuOpening" }, { "code": null, "e": 6454, "s": 6264, "text": "Invoked whenever an unhandled ContextMenuClosing routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.)" }, { "code": null, "e": 6469, "s": 6454, "text": "OnItemsChanged" }, { "code": null, "e": 6541, "s": 6469, "text": "Invoked when the Items property changes. (Inherited from ItemsControl.)" }, { "code": null, "e": 6553, "s": 6541, "text": "OnLostFocus" }, { "code": null, "e": 6620, "s": 6553, "text": "Called before the LostFocus event occurs. (Inherited from Control)" }, { "code": null, "e": 6635, "s": 6620, "text": "ReadLocalValue" }, { "code": null, "e": 6744, "s": 6635, "text": "Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)" }, { "code": null, "e": 6755, "s": 6744, "text": "SetBinding" }, { "code": null, "e": 6866, "s": 6755, "text": "Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)" }, { "code": null, "e": 6875, "s": 6866, "text": "SetValue" }, { "code": null, "e": 6978, "s": 6875, "text": "Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)" }, { "code": null, "e": 6985, "s": 6978, "text": "Closed" }, { "code": null, "e": 7044, "s": 6985, "text": "Occurs when a particular instance of a ContextMenu closes." }, { "code": null, "e": 7063, "s": 7044, "text": "ContextMenuClosing" }, { "code": null, "e": 7160, "s": 7063, "text": "Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)" }, { "code": null, "e": 7179, "s": 7160, "text": "ContextMenuOpening" }, { "code": null, "e": 7269, "s": 7179, "text": "Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)" }, { "code": null, "e": 7288, "s": 7269, "text": "DataContextChanged" }, { "code": null, "e": 7378, "s": 7288, "text": "Occurs when the data context for this element changes. (Inherited from FrameworkElement.)" }, { "code": null, "e": 7388, "s": 7378, "text": "DragEnter" }, { "code": null, "e": 7510, "s": 7388, "text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)" }, { "code": null, "e": 7520, "s": 7510, "text": "DragLeave" }, { "code": null, "e": 7642, "s": 7520, "text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)" }, { "code": null, "e": 7651, "s": 7642, "text": "DragOver" }, { "code": null, "e": 7788, "s": 7651, "text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)" }, { "code": null, "e": 7793, "s": 7788, "text": "Drop" }, { "code": null, "e": 7920, "s": 7793, "text": "Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement)" }, { "code": null, "e": 7929, "s": 7920, "text": "GotFocus" }, { "code": null, "e": 7996, "s": 7929, "text": "Occurs when a UIElement receives focus. (Inherited from UIElement)" }, { "code": null, "e": 8013, "s": 7996, "text": "IsEnabledChanged" }, { "code": null, "e": 8082, "s": 8013, "text": "Occurs when the IsEnabled property changes. (Inherited from Control)" }, { "code": null, "e": 8090, "s": 8082, "text": "KeyDown" }, { "code": null, "e": 8186, "s": 8090, "text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 8192, "s": 8186, "text": "KeyUp" }, { "code": null, "e": 8289, "s": 8192, "text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 8299, "s": 8289, "text": "LostFocus" }, { "code": null, "e": 8363, "s": 8299, "text": "Occurs when a UIElement loses focus. (Inherited from UIElement)" }, { "code": null, "e": 8431, "s": 8363, "text": "Let’s create a new WPF project with the name WPFContextMenuControl." }, { "code": null, "e": 8499, "s": 8431, "text": "Let’s create a new WPF project with the name WPFContextMenuControl." }, { "code": null, "e": 8588, "s": 8499, "text": "Drag a textbox from a toolbox and set the following properties in the properties window." }, { "code": null, "e": 8677, "s": 8588, "text": "Drag a textbox from a toolbox and set the following properties in the properties window." }, { "code": null, "e": 8768, "s": 8677, "text": "Now switch to XAML window in which you will see the XAML tags for textbox and ContextMenu." }, { "code": null, "e": 8859, "s": 8768, "text": "Now switch to XAML window in which you will see the XAML tags for textbox and ContextMenu." }, { "code": null, "e": 8968, "s": 8859, "text": "Add some more properties, menu items, and checked and unchecked events, as shown in the following XAML code." }, { "code": null, "e": 9077, "s": 8968, "text": "Add some more properties, menu items, and checked and unchecked events, as shown in the following XAML code." }, { "code": null, "e": 9270, "s": 9077, "text": "The following example contains a textbox with ContextMenu which manipulates the text inside the textbox. The following XAML code creates a textbox with some properties and events context menu." }, { "code": null, "e": 10622, "s": 9270, "text": "<Window x:Class = \"WPFContextMenuControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFContextMenuControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid> \n <TextBox x:Name = \"textBox1\" HorizontalAlignment = \"Left\" Height = \"178\"\n Margin = \"92,61,0,0\" TextWrapping = \"Wrap\" Text = \"Hi, this is WPF tutorial\" \n VerticalAlignment = \"Top\" Width = \"306\"> \n\t\t\t\n <TextBox.ContextMenu> \n <ContextMenu> \n <MenuItem Header = \"_Bold\" IsCheckable = \"True\" \n Checked = \"Bold_Checked\" Unchecked = \"Bold_Unchecked\" /> \n <MenuItem Header = \"_Italic\" IsCheckable = \"True\" \n Checked = \"Italic_Checked\" Unchecked = \"Italic_Unchecked\" /> \n <Separator /> \n <MenuItem Header = \"Increase Font Size\" Click = \"IncreaseFont_Click\" /> \n <MenuItem Header = \"_Decrease Font Size\" Click = \"DecreaseFont_Click\" /> \n </ContextMenu> \n </TextBox.ContextMenu> \n\t\t\t\n </TextBox>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 10677, "s": 10622, "text": "Here is the implementation in C# for different events." }, { "code": null, "e": 11846, "s": 10677, "text": "using System.Windows;\n \nnamespace WPFContextMenuControl { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void Bold_Checked(object sender, RoutedEventArgs e) { \n textBox1.FontWeight = FontWeights.Bold; \n } \n\t\t\n private void Bold_Unchecked(object sender, RoutedEventArgs e) { \n textBox1.FontWeight = FontWeights.Normal; \n } \n\t\t\n private void Italic_Checked(object sender, RoutedEventArgs e) { \n textBox1.FontStyle = FontStyles.Italic; \n }\n\t\t\n private void Italic_Unchecked(object sender, RoutedEventArgs e) { \n textBox1.FontStyle = FontStyles.Normal; \n }\n\t\t\n private void IncreaseFont_Click(object sender, RoutedEventArgs e) { \n\t\t\n if (textBox1.FontSize < 18) { \n textBox1.FontSize += 2; \n } \n } \n\t\t\n private void DecreaseFont_Click(object sender, RoutedEventArgs e) { \n\t\t\n if (textBox1.FontSize > 10) { \n textBox1.FontSize -= 2; \n } \n } \n\t\t\n } \n}" }, { "code": null, "e": 11930, "s": 11846, "text": "When you compile and execute the above code, it will produce the following window βˆ’" } ]
How to avoid callback hell in Node.js ?
30 Sep, 2021 Callback hell in Node.js is the situation in which we have complex nested callbacks. In this, each callback takes arguments that have been obtained as a result of previous callbacks. This kind of callback structure leads to lesser code readability and maintainability. We can avoid the callback hell with the help of Promises. Promises in javascript are a way to handle asynchronous operations in Node.js. It allows us to return a value from an asynchronous function like synchronous functions. When we return something from an asynchronous method it returns a promise which can be used to consume the final value when it is available in the future with the help of then() method or await inside of async functions. The syntax to create a promise is mentioned below. const promise = new Promise(function(resolve, reject){ // code logic }); Example: In the code example mentioned below, we simulate an asynchronous add operation with the help of setTimeout(). First, we create an add() function that takes three arguments in which two are the numbers that we want to add and the third one is the callback function which is called with the result of add operations after 2 seconds. Then, we calculate the result of the addition of the first four natural numbers using a nested callback to simulate a callback hell. After that, we create an addPromise() function that returns a promise and this promise is resolved after two seconds of calling the function. Then we consume the promise using the then() method and async/await. Javascript // The callback function for function// is executed after two seconds with// the result of additionconst add = function (a, b, callback) { setTimeout(() => { callback(a + b); }, 2000);}; // Using nested callbacks to calculate// the sum of first four natural numbers.add(1, 2, (sum1) => { add(3, sum1, (sum2) => { add(4, sum2, (sum3) => { console.log(`Sum of first 4 natural numbers using callback is ${sum3}`); }); });}); // This function returns a promise// that will later be consumed to get// the result of additionconst addPromise = function (a, b) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(a + b); }, 2000); });}; // Consuming promises with the chaining of then()// method and calculating the resultaddPromise(1, 2) .then((sum1) => { return addPromise(3, sum1); }) .then((sum2) => { return addPromise(4, sum2); }) .then((sum3) => { console.log( `Sum of first 4 natural numbers using promise and then() is ${sum3}` ); }); // Calculation the result of addition by// consuming the promise using async/await(async () => { const sum1 = await addPromise(1, 2); const sum2 = await addPromise(3, sum1); const sum3 = await addPromise(4, sum2); console.log( `Sum of first 4 natural numbers using promise and async/await is ${sum3}` );})(); Output: NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Windows JWT Authentication with Node.js Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2021" }, { "code": null, "e": 297, "s": 28, "text": "Callback hell in Node.js is the situation in which we have complex nested callbacks. In this, each callback takes arguments that have been obtained as a result of previous callbacks. This kind of callback structure leads to lesser code readability and maintainability." }, { "code": null, "e": 795, "s": 297, "text": "We can avoid the callback hell with the help of Promises. Promises in javascript are a way to handle asynchronous operations in Node.js. It allows us to return a value from an asynchronous function like synchronous functions. When we return something from an asynchronous method it returns a promise which can be used to consume the final value when it is available in the future with the help of then() method or await inside of async functions. The syntax to create a promise is mentioned below." }, { "code": null, "e": 873, "s": 795, "text": "const promise = new Promise(function(resolve, reject){\n // code logic\n});" }, { "code": null, "e": 993, "s": 873, "text": "Example: In the code example mentioned below, we simulate an asynchronous add operation with the help of setTimeout(). " }, { "code": null, "e": 1347, "s": 993, "text": "First, we create an add() function that takes three arguments in which two are the numbers that we want to add and the third one is the callback function which is called with the result of add operations after 2 seconds. Then, we calculate the result of the addition of the first four natural numbers using a nested callback to simulate a callback hell." }, { "code": null, "e": 1558, "s": 1347, "text": "After that, we create an addPromise() function that returns a promise and this promise is resolved after two seconds of calling the function. Then we consume the promise using the then() method and async/await." }, { "code": null, "e": 1569, "s": 1558, "text": "Javascript" }, { "code": "// The callback function for function// is executed after two seconds with// the result of additionconst add = function (a, b, callback) { setTimeout(() => { callback(a + b); }, 2000);}; // Using nested callbacks to calculate// the sum of first four natural numbers.add(1, 2, (sum1) => { add(3, sum1, (sum2) => { add(4, sum2, (sum3) => { console.log(`Sum of first 4 natural numbers using callback is ${sum3}`); }); });}); // This function returns a promise// that will later be consumed to get// the result of additionconst addPromise = function (a, b) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(a + b); }, 2000); });}; // Consuming promises with the chaining of then()// method and calculating the resultaddPromise(1, 2) .then((sum1) => { return addPromise(3, sum1); }) .then((sum2) => { return addPromise(4, sum2); }) .then((sum3) => { console.log( `Sum of first 4 natural numbers using promise and then() is ${sum3}` ); }); // Calculation the result of addition by// consuming the promise using async/await(async () => { const sum1 = await addPromise(1, 2); const sum2 = await addPromise(3, sum1); const sum3 = await addPromise(4, sum2); console.log( `Sum of first 4 natural numbers using promise and async/await is ${sum3}` );})();", "e": 2919, "s": 1569, "text": null }, { "code": null, "e": 2927, "s": 2919, "text": "Output:" }, { "code": null, "e": 2944, "s": 2927, "text": "NodeJS-Questions" }, { "code": null, "e": 2951, "s": 2944, "text": "Picked" }, { "code": null, "e": 2959, "s": 2951, "text": "Node.js" }, { "code": null, "e": 2976, "s": 2959, "text": "Web Technologies" }, { "code": null, "e": 3074, "s": 2976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3109, "s": 3074, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3141, "s": 3109, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3211, "s": 3141, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 3238, "s": 3211, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3263, "s": 3238, "text": "Mongoose find() Function" }, { "code": null, "e": 3325, "s": 3263, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3386, "s": 3325, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3436, "s": 3386, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3479, "s": 3436, "text": "How to fetch data from an API in ReactJS ?" } ]
& Operator in Java with Examples
10 Oct, 2019 The & operator in Java has two definite functions: As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false.However, there is a slight difference between them, which highlights the functionality of & operator:&& operator: It only evaluates the next condition, if the condition before it is true. If anyone condition is false, it does not evaluate the statement any further.& operator: It evaluates all conditions even if they are false. Thus, any change in the data values due to the conditions will only be reflected in this case.Example:// Java program to demonstrate// & operator as relational operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5, y = 7, z = 9; System.out.println("Demonstrating && operator"); if ((x > y) && (x++ > z)) ; else System.out.println("Value of x: " + x); System.out.println("\nDemonstrating & operator"); if ((x > y) & (x++ > z)) ; else System.out.println("Value of x: " + x); }}Output:Demonstrating && operator Value of x: 5 Demonstrating & operator Value of x: 6 As a Bitwise AND: & operator is used for adding Bitwise numbers in Java. Bitwise numbers are binary numbers stored in the form of integers. Some people will ask what is the use of these Bitwise numbers anyway? Why not store every number in its decimal form and perform the normal operations using our traditional operators: +, -, /, %, *. Its because all our encoding and decoding of data is done in bits, as they allow packing a huge amount of information into a tiny space.Example:// Java program to demonstrate// & operator as bitwise operator import java.io.*; class GFG { public static void main(String[] args) { int a = 12; int b = 25; System.out.println("Demonstrating & operator\n"); int c = a & b; System.out.println(a + " & " + b + " = " + c); }}Output:Demonstrating & operator 12 & 25 = 8 As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false.However, there is a slight difference between them, which highlights the functionality of & operator:&& operator: It only evaluates the next condition, if the condition before it is true. If anyone condition is false, it does not evaluate the statement any further.& operator: It evaluates all conditions even if they are false. Thus, any change in the data values due to the conditions will only be reflected in this case.Example:// Java program to demonstrate// & operator as relational operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5, y = 7, z = 9; System.out.println("Demonstrating && operator"); if ((x > y) && (x++ > z)) ; else System.out.println("Value of x: " + x); System.out.println("\nDemonstrating & operator"); if ((x > y) & (x++ > z)) ; else System.out.println("Value of x: " + x); }}Output:Demonstrating && operator Value of x: 5 Demonstrating & operator Value of x: 6 However, there is a slight difference between them, which highlights the functionality of & operator: && operator: It only evaluates the next condition, if the condition before it is true. If anyone condition is false, it does not evaluate the statement any further. & operator: It evaluates all conditions even if they are false. Thus, any change in the data values due to the conditions will only be reflected in this case. Example: // Java program to demonstrate// & operator as relational operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5, y = 7, z = 9; System.out.println("Demonstrating && operator"); if ((x > y) && (x++ > z)) ; else System.out.println("Value of x: " + x); System.out.println("\nDemonstrating & operator"); if ((x > y) & (x++ > z)) ; else System.out.println("Value of x: " + x); }} Demonstrating && operator Value of x: 5 Demonstrating & operator Value of x: 6 As a Bitwise AND: & operator is used for adding Bitwise numbers in Java. Bitwise numbers are binary numbers stored in the form of integers. Some people will ask what is the use of these Bitwise numbers anyway? Why not store every number in its decimal form and perform the normal operations using our traditional operators: +, -, /, %, *. Its because all our encoding and decoding of data is done in bits, as they allow packing a huge amount of information into a tiny space.Example:// Java program to demonstrate// & operator as bitwise operator import java.io.*; class GFG { public static void main(String[] args) { int a = 12; int b = 25; System.out.println("Demonstrating & operator\n"); int c = a & b; System.out.println(a + " & " + b + " = " + c); }}Output:Demonstrating & operator 12 & 25 = 8 Example: // Java program to demonstrate// & operator as bitwise operator import java.io.*; class GFG { public static void main(String[] args) { int a = 12; int b = 25; System.out.println("Demonstrating & operator\n"); int c = a & b; System.out.println(a + " & " + b + " = " + c); }} Demonstrating & operator 12 & 25 = 8 Java-Operators Picked Java Java-Operators Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Queue Interface In Java Multidimensional Arrays in Java HashMap in Java with Examples Math pow() method in Java with Example PriorityQueue in Java Stack Class in Java List Interface in Java with Examples Initialize an ArrayList in Java ArrayList in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Oct, 2019" }, { "code": null, "e": 104, "s": 53, "text": "The & operator in Java has two definite functions:" }, { "code": null, "e": 2216, "s": 104, "text": "As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false.However, there is a slight difference between them, which highlights the functionality of & operator:&& operator: It only evaluates the next condition, if the condition before it is true. If anyone condition is false, it does not evaluate the statement any further.& operator: It evaluates all conditions even if they are false. Thus, any change in the data values due to the conditions will only be reflected in this case.Example:// Java program to demonstrate// & operator as relational operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5, y = 7, z = 9; System.out.println(\"Demonstrating && operator\"); if ((x > y) && (x++ > z)) ; else System.out.println(\"Value of x: \" + x); System.out.println(\"\\nDemonstrating & operator\"); if ((x > y) & (x++ > z)) ; else System.out.println(\"Value of x: \" + x); }}Output:Demonstrating && operator\nValue of x: 5\n\nDemonstrating & operator\nValue of x: 6\nAs a Bitwise AND: & operator is used for adding Bitwise numbers in Java. Bitwise numbers are binary numbers stored in the form of integers. Some people will ask what is the use of these Bitwise numbers anyway? Why not store every number in its decimal form and perform the normal operations using our traditional operators: +, -, /, %, *. Its because all our encoding and decoding of data is done in bits, as they allow packing a huge amount of information into a tiny space.Example:// Java program to demonstrate// & operator as bitwise operator import java.io.*; class GFG { public static void main(String[] args) { int a = 12; int b = 25; System.out.println(\"Demonstrating & operator\\n\"); int c = a & b; System.out.println(a + \" & \" + b + \" = \" + c); }}Output:Demonstrating & operator\n\n12 & 25 = 8\n" }, { "code": null, "e": 3477, "s": 2216, "text": "As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false.However, there is a slight difference between them, which highlights the functionality of & operator:&& operator: It only evaluates the next condition, if the condition before it is true. If anyone condition is false, it does not evaluate the statement any further.& operator: It evaluates all conditions even if they are false. Thus, any change in the data values due to the conditions will only be reflected in this case.Example:// Java program to demonstrate// & operator as relational operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5, y = 7, z = 9; System.out.println(\"Demonstrating && operator\"); if ((x > y) && (x++ > z)) ; else System.out.println(\"Value of x: \" + x); System.out.println(\"\\nDemonstrating & operator\"); if ((x > y) & (x++ > z)) ; else System.out.println(\"Value of x: \" + x); }}Output:Demonstrating && operator\nValue of x: 5\n\nDemonstrating & operator\nValue of x: 6\n" }, { "code": null, "e": 3579, "s": 3477, "text": "However, there is a slight difference between them, which highlights the functionality of & operator:" }, { "code": null, "e": 3744, "s": 3579, "text": "&& operator: It only evaluates the next condition, if the condition before it is true. If anyone condition is false, it does not evaluate the statement any further." }, { "code": null, "e": 3903, "s": 3744, "text": "& operator: It evaluates all conditions even if they are false. Thus, any change in the data values due to the conditions will only be reflected in this case." }, { "code": null, "e": 3912, "s": 3903, "text": "Example:" }, { "code": "// Java program to demonstrate// & operator as relational operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5, y = 7, z = 9; System.out.println(\"Demonstrating && operator\"); if ((x > y) && (x++ > z)) ; else System.out.println(\"Value of x: \" + x); System.out.println(\"\\nDemonstrating & operator\"); if ((x > y) & (x++ > z)) ; else System.out.println(\"Value of x: \" + x); }}", "e": 4432, "s": 3912, "text": null }, { "code": null, "e": 4513, "s": 4432, "text": "Demonstrating && operator\nValue of x: 5\n\nDemonstrating & operator\nValue of x: 6\n" }, { "code": null, "e": 5365, "s": 4513, "text": "As a Bitwise AND: & operator is used for adding Bitwise numbers in Java. Bitwise numbers are binary numbers stored in the form of integers. Some people will ask what is the use of these Bitwise numbers anyway? Why not store every number in its decimal form and perform the normal operations using our traditional operators: +, -, /, %, *. Its because all our encoding and decoding of data is done in bits, as they allow packing a huge amount of information into a tiny space.Example:// Java program to demonstrate// & operator as bitwise operator import java.io.*; class GFG { public static void main(String[] args) { int a = 12; int b = 25; System.out.println(\"Demonstrating & operator\\n\"); int c = a & b; System.out.println(a + \" & \" + b + \" = \" + c); }}Output:Demonstrating & operator\n\n12 & 25 = 8\n" }, { "code": null, "e": 5374, "s": 5365, "text": "Example:" }, { "code": "// Java program to demonstrate// & operator as bitwise operator import java.io.*; class GFG { public static void main(String[] args) { int a = 12; int b = 25; System.out.println(\"Demonstrating & operator\\n\"); int c = a & b; System.out.println(a + \" & \" + b + \" = \" + c); }}", "e": 5698, "s": 5374, "text": null }, { "code": null, "e": 5737, "s": 5698, "text": "Demonstrating & operator\n\n12 & 25 = 8\n" }, { "code": null, "e": 5752, "s": 5737, "text": "Java-Operators" }, { "code": null, "e": 5759, "s": 5752, "text": "Picked" }, { "code": null, "e": 5764, "s": 5759, "text": "Java" }, { "code": null, "e": 5779, "s": 5764, "text": "Java-Operators" }, { "code": null, "e": 5784, "s": 5779, "text": "Java" }, { "code": null, "e": 5882, "s": 5784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5901, "s": 5882, "text": "Interfaces in Java" }, { "code": null, "e": 5925, "s": 5901, "text": "Queue Interface In Java" }, { "code": null, "e": 5957, "s": 5925, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5987, "s": 5957, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6026, "s": 5987, "text": "Math pow() method in Java with Example" }, { "code": null, "e": 6048, "s": 6026, "text": "PriorityQueue in Java" }, { "code": null, "e": 6068, "s": 6048, "text": "Stack Class in Java" }, { "code": null, "e": 6105, "s": 6068, "text": "List Interface in Java with Examples" }, { "code": null, "e": 6137, "s": 6105, "text": "Initialize an ArrayList in Java" } ]
C# | How to change the visibility of the Cursor of Console
28 Jan, 2019 Given the normal Console in C#, the task is to change the visibility of the Cursor of the Console. Approach: This can be done using the CursorVisible property in the Console class of the System package in C#. It gets or sets a value indicating whether the cursor is visible. Program 1: Getting the value of CursorVisible // C# program to illustrate the// Console.CursorVisible Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the default CursorVisible Console.WriteLine("Current Cursor Visible: {0}", Console.CursorVisible); }}} Output: Program 2: Setting the value of CursorVisible // C# program to illustrate the// Console.CursorVisible Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the CursorVisible Console.WriteLine("Current Cursor Visible: {0}", Console.CursorVisible); // Set the CursorVisible Console.CursorVisible = false; // Get the CursorVisible Console.Write("Current Cursor Visible: {0}", Console.CursorVisible); }}} Output: CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object Extension Method in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 127, "s": 28, "text": "Given the normal Console in C#, the task is to change the visibility of the Cursor of the Console." }, { "code": null, "e": 303, "s": 127, "text": "Approach: This can be done using the CursorVisible property in the Console class of the System package in C#. It gets or sets a value indicating whether the cursor is visible." }, { "code": null, "e": 349, "s": 303, "text": "Program 1: Getting the value of CursorVisible" }, { "code": "// C# program to illustrate the// Console.CursorVisible Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the default CursorVisible Console.WriteLine(\"Current Cursor Visible: {0}\", Console.CursorVisible); }}}", "e": 762, "s": 349, "text": null }, { "code": null, "e": 770, "s": 762, "text": "Output:" }, { "code": null, "e": 816, "s": 770, "text": "Program 2: Setting the value of CursorVisible" }, { "code": "// C# program to illustrate the// Console.CursorVisible Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the CursorVisible Console.WriteLine(\"Current Cursor Visible: {0}\", Console.CursorVisible); // Set the CursorVisible Console.CursorVisible = false; // Get the CursorVisible Console.Write(\"Current Cursor Visible: {0}\", Console.CursorVisible); }}}", "e": 1431, "s": 816, "text": null }, { "code": null, "e": 1439, "s": 1431, "text": "Output:" }, { "code": null, "e": 1460, "s": 1439, "text": "CSharp-Console-Class" }, { "code": null, "e": 1463, "s": 1460, "text": "C#" }, { "code": null, "e": 1561, "s": 1463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1592, "s": 1561, "text": "Introduction to .NET Framework" }, { "code": null, "e": 1607, "s": 1592, "text": "C# | Delegates" }, { "code": null, "e": 1650, "s": 1607, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1699, "s": 1650, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1722, "s": 1699, "text": "C# | Method Overriding" }, { "code": null, "e": 1738, "s": 1722, "text": "C# | Data Types" }, { "code": null, "e": 1756, "s": 1738, "text": "C# | Constructors" }, { "code": null, "e": 1796, "s": 1756, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 1818, "s": 1796, "text": "C# | Class and Object" } ]
Passing array of objects as parameter in C++
20 Jun, 2022 Array of Objects:It is an array whose elements are of the class type. It can be declared as an array of any datatype. Syntax: classname array_name [size]; Below is the C++ program to illustrate the array of objects by calculating the highest marks among 3 students: C++ // C++ program to illustrate the// passing the array of objects// to function parameter#include <bits/stdc++.h>using namespace std; // Class Studentclass Student { int roll; char name[50]; int total; public: // Function to input Roll Number void getdata() { cout << "Enter your Roll: " << endl; cin >> roll; cout << "Enter your Name: " << endl; cin.ignore(); cin.get(name, 50); cout << "Enter your Total " << "Marks: " << endl; cin >> total; } // Function to pass the array of // objects int pos(Student obj[], int size) { int pos = 0; int max = obj[0].total; // Traverse the array of object for (int i = 0; i < size; i++) { if (obj[i].total > max) { max = obj[i].total; pos = i; } } return pos; } // Function to display the students // details void putdata() { cout << "Roll: " << roll << endl; cout << "Name: " << name << endl; cout << "Total Marks: " << total << endl; }}; // Function that have array of objectsvoid arrayOfObjects(){ Student s[3], s1; int pos; for (int i = 0; i < 3; i++) { s[i].getdata(); } pos = s1.pos(s, 3); cout << "Highest scoring Student" << " Details:" << endl; s[pos].putdata();} // Driver Codeint main(){ // Function Call arrayOfObjects(); return 0;} Output: Explanation: In the main() function, objects of the Student class are created:Here, the first array of objects is s[3] and the other one is s1(a simple object).In the for loop, 3 sets of user input have been taken, (i.e, it is where the user will be entering the name, roll, total marks, for 3 students sets).Then passing the s[3] (array of an object which contains the sets of student details) and its size, through the s1 object in the pos(Student obj [], int size) member function. Here, the first array of objects is s[3] and the other one is s1(a simple object). In the for loop, 3 sets of user input have been taken, (i.e, it is where the user will be entering the name, roll, total marks, for 3 students sets). Then passing the s[3] (array of an object which contains the sets of student details) and its size, through the s1 object in the pos(Student obj [], int size) member function. The pos(Student obj [], int size) function, is returning the position of the object of the highest total marks scoring student set, i.e, (0, 1or 2 index position of s[3] object array), which is stored in pos = s1.pos(s, 3). Display part: For calling the display function, S[pos].putdata() is used.The putdata() function is displaying the object details of the student class.Here, pos is sent (which stores the index position of the highest student set object) in s, to display the highest total marks scored student details. The putdata() function is displaying the object details of the student class. Here, pos is sent (which stores the index position of the highest student set object) in s, to display the highest total marks scored student details. Time Complexity: O(n)Auxiliary Space: O(n) jayanth_mkv C++-Class and Object cpp-parameter-passing Arrays C++ C++ Programs Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2022" }, { "code": null, "e": 171, "s": 53, "text": "Array of Objects:It is an array whose elements are of the class type. It can be declared as an array of any datatype." }, { "code": null, "e": 179, "s": 171, "text": "Syntax:" }, { "code": null, "e": 208, "s": 179, "text": "classname array_name [size];" }, { "code": null, "e": 319, "s": 208, "text": "Below is the C++ program to illustrate the array of objects by calculating the highest marks among 3 students:" }, { "code": null, "e": 323, "s": 319, "text": "C++" }, { "code": "// C++ program to illustrate the// passing the array of objects// to function parameter#include <bits/stdc++.h>using namespace std; // Class Studentclass Student { int roll; char name[50]; int total; public: // Function to input Roll Number void getdata() { cout << \"Enter your Roll: \" << endl; cin >> roll; cout << \"Enter your Name: \" << endl; cin.ignore(); cin.get(name, 50); cout << \"Enter your Total \" << \"Marks: \" << endl; cin >> total; } // Function to pass the array of // objects int pos(Student obj[], int size) { int pos = 0; int max = obj[0].total; // Traverse the array of object for (int i = 0; i < size; i++) { if (obj[i].total > max) { max = obj[i].total; pos = i; } } return pos; } // Function to display the students // details void putdata() { cout << \"Roll: \" << roll << endl; cout << \"Name: \" << name << endl; cout << \"Total Marks: \" << total << endl; }}; // Function that have array of objectsvoid arrayOfObjects(){ Student s[3], s1; int pos; for (int i = 0; i < 3; i++) { s[i].getdata(); } pos = s1.pos(s, 3); cout << \"Highest scoring Student\" << \" Details:\" << endl; s[pos].putdata();} // Driver Codeint main(){ // Function Call arrayOfObjects(); return 0;}", "e": 1840, "s": 323, "text": null }, { "code": null, "e": 1848, "s": 1840, "text": "Output:" }, { "code": null, "e": 1861, "s": 1848, "text": "Explanation:" }, { "code": null, "e": 2333, "s": 1861, "text": "In the main() function, objects of the Student class are created:Here, the first array of objects is s[3] and the other one is s1(a simple object).In the for loop, 3 sets of user input have been taken, (i.e, it is where the user will be entering the name, roll, total marks, for 3 students sets).Then passing the s[3] (array of an object which contains the sets of student details) and its size, through the s1 object in the pos(Student obj [], int size) member function." }, { "code": null, "e": 2416, "s": 2333, "text": "Here, the first array of objects is s[3] and the other one is s1(a simple object)." }, { "code": null, "e": 2566, "s": 2416, "text": "In the for loop, 3 sets of user input have been taken, (i.e, it is where the user will be entering the name, roll, total marks, for 3 students sets)." }, { "code": null, "e": 2742, "s": 2566, "text": "Then passing the s[3] (array of an object which contains the sets of student details) and its size, through the s1 object in the pos(Student obj [], int size) member function." }, { "code": null, "e": 2966, "s": 2742, "text": "The pos(Student obj [], int size) function, is returning the position of the object of the highest total marks scoring student set, i.e, (0, 1or 2 index position of s[3] object array), which is stored in pos = s1.pos(s, 3)." }, { "code": null, "e": 3267, "s": 2966, "text": "Display part: For calling the display function, S[pos].putdata() is used.The putdata() function is displaying the object details of the student class.Here, pos is sent (which stores the index position of the highest student set object) in s, to display the highest total marks scored student details." }, { "code": null, "e": 3345, "s": 3267, "text": "The putdata() function is displaying the object details of the student class." }, { "code": null, "e": 3496, "s": 3345, "text": "Here, pos is sent (which stores the index position of the highest student set object) in s, to display the highest total marks scored student details." }, { "code": null, "e": 3539, "s": 3496, "text": "Time Complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 3551, "s": 3539, "text": "jayanth_mkv" }, { "code": null, "e": 3572, "s": 3551, "text": "C++-Class and Object" }, { "code": null, "e": 3594, "s": 3572, "text": "cpp-parameter-passing" }, { "code": null, "e": 3601, "s": 3594, "text": "Arrays" }, { "code": null, "e": 3605, "s": 3601, "text": "C++" }, { "code": null, "e": 3618, "s": 3605, "text": "C++ Programs" }, { "code": null, "e": 3625, "s": 3618, "text": "Arrays" }, { "code": null, "e": 3629, "s": 3625, "text": "CPP" }, { "code": null, "e": 3727, "s": 3629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3759, "s": 3727, "text": "Introduction to Data Structures" }, { "code": null, "e": 3784, "s": 3759, "text": "Window Sliding Technique" }, { "code": null, "e": 3831, "s": 3784, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 3862, "s": 3831, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 3920, "s": 3862, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 3938, "s": 3920, "text": "Vector in C++ STL" }, { "code": null, "e": 3981, "s": 3938, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 4027, "s": 3981, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 4050, "s": 4027, "text": "std::sort() in C++ STL" } ]
Randomized Algorithms | Set 2 (Classification and Applications)
21 Nov, 2015 We strongly recommend to refer below post as a prerequisite of this. Randomized Algorithms | Set 1 (Introduction and Analysis) Randomized algorithms are classified in two categories. Las Vegas: These algorithms always produce correct or optimum result. Time complexity of these algorithms is based on a random value and time complexity is evaluated as expected value. For example, Randomized QuickSort always sorts an input array and expected worst case time complexity of QuickSort is O(nLogn). Monte Carlo: Produce correct or optimum result with some probability. These algorithms have deterministic running time and it is generally easier to find out worst case time complexity. For example this implementation of Karger’s Algorithm produces minimum cut with probability greater than or equal to 1/n2 (n is number of vertices) and has worst case time complexity as O(E). Another example is Fermet Method for Primality Testing. Example to Understand Classification: Consider a binary array where exactly half elements are 0 and half are 1. The task is to find index of any 1. A Las Vegas algorithm for this task is to keep picking a random element until we find a 1. A Monte Carlo algorithm for the same is to keep picking a random element until we either find 1 or we have tried maximum allowed times say k.The Las Vegas algorithm always finds an index of 1, but time complexity is determined as expect value. The expected number of trials before success is 2, therefore expected time complexity is O(1).The Monte Carlo Algorithm finds a 1 with probability [1 – (1/2)k]. Time complexity of Monte Carlo is O(k) which is deterministic Consider a tool that basically does sorting. Let the tool be used by many users and there are few users who always use tool for already sorted array. If the tool uses simple (not randomized) QuickSort, then those few users are always going to face worst case situation. On the other hand if the tool uses Randomized QuickSort, then there is no user that always gets worst case. Everybody gets expected O(n Log n) time. Randomized algorithms have huge applications in Cryptography. Load Balancing. Number-Theoretic Applications: Primality Testing Data Structures: Hashing, Sorting, Searching, Order Statistics and Computational Geometry. Algebraic identities: Polynomial and matrix identity verification. Interactive proof systems. Mathematical programming: Faster algorithms for linear programming, Rounding linear program solutions to integer program solutions Graph algorithms: Minimum spanning trees, shortest paths, minimum cuts. Counting and enumeration: Matrix permanent Counting combinatorial structures. Parallel and distributed computing: Deadlock avoidance distributed consensus. Probabilistic existence proofs: Show that a combinatorial object arises with non-zero probability among objects drawn from a suitable probability space. Derandomization: First devise a randomized algorithm then argue that it can be derandomized to yield a deterministic algorithm. Sources:http://theory.stanford.edu/people/pragh/amstalk.pdfhttps://en.wikipedia.org/wiki/Randomized_algorithm This article is contributed by Ashish Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Randomized Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) Shuffle a given array using Fisher–Yates shuffle Algorithm Shuffle or Randomize a list in Java Generating Random String Using PHP Estimating the value of Pi using Monte Carlo Operations on Sparse Matrices Reservoir Sampling Expected Number of Trials until Success Shuffle a deck of cards Randomized Binary Search Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Nov, 2015" }, { "code": null, "e": 123, "s": 54, "text": "We strongly recommend to refer below post as a prerequisite of this." }, { "code": null, "e": 181, "s": 123, "text": "Randomized Algorithms | Set 1 (Introduction and Analysis)" }, { "code": null, "e": 237, "s": 181, "text": "Randomized algorithms are classified in two categories." }, { "code": null, "e": 550, "s": 237, "text": "Las Vegas: These algorithms always produce correct or optimum result. Time complexity of these algorithms is based on a random value and time complexity is evaluated as expected value. For example, Randomized QuickSort always sorts an input array and expected worst case time complexity of QuickSort is O(nLogn)." }, { "code": null, "e": 984, "s": 550, "text": "Monte Carlo: Produce correct or optimum result with some probability. These algorithms have deterministic running time and it is generally easier to find out worst case time complexity. For example this implementation of Karger’s Algorithm produces minimum cut with probability greater than or equal to 1/n2 (n is number of vertices) and has worst case time complexity as O(E). Another example is Fermet Method for Primality Testing." }, { "code": null, "e": 1022, "s": 984, "text": "Example to Understand Classification:" }, { "code": null, "e": 1134, "s": 1022, "text": "Consider a binary array where exactly half elements are 0\nand half are 1. The task is to find index of any 1. " }, { "code": null, "e": 1692, "s": 1134, "text": "A Las Vegas algorithm for this task is to keep picking a random element until we find a 1. A Monte Carlo algorithm for the same is to keep picking a random element until we either find 1 or we have tried maximum allowed times say k.The Las Vegas algorithm always finds an index of 1, but time complexity is determined as expect value. The expected number of trials before success is 2, therefore expected time complexity is O(1).The Monte Carlo Algorithm finds a 1 with probability [1 – (1/2)k]. Time complexity of Monte Carlo is O(k) which is deterministic" }, { "code": null, "e": 2111, "s": 1692, "text": "Consider a tool that basically does sorting. Let the tool be used by many users and there are few users who always use tool for already sorted array. If the tool uses simple (not randomized) QuickSort, then those few users are always going to face worst case situation. On the other hand if the tool uses Randomized QuickSort, then there is no user that always gets worst case. Everybody gets expected O(n Log n) time." }, { "code": null, "e": 2173, "s": 2111, "text": "Randomized algorithms have huge applications in Cryptography." }, { "code": null, "e": 2189, "s": 2173, "text": "Load Balancing." }, { "code": null, "e": 2238, "s": 2189, "text": "Number-Theoretic Applications: Primality Testing" }, { "code": null, "e": 2329, "s": 2238, "text": "Data Structures: Hashing, Sorting, Searching, Order Statistics and Computational Geometry." }, { "code": null, "e": 2423, "s": 2329, "text": "Algebraic identities: Polynomial and matrix identity verification. Interactive proof systems." }, { "code": null, "e": 2554, "s": 2423, "text": "Mathematical programming: Faster algorithms for linear programming, Rounding linear program solutions to integer program solutions" }, { "code": null, "e": 2626, "s": 2554, "text": "Graph algorithms: Minimum spanning trees, shortest paths, minimum cuts." }, { "code": null, "e": 2704, "s": 2626, "text": "Counting and enumeration: Matrix permanent Counting combinatorial structures." }, { "code": null, "e": 2782, "s": 2704, "text": "Parallel and distributed computing: Deadlock avoidance distributed consensus." }, { "code": null, "e": 2935, "s": 2782, "text": "Probabilistic existence proofs: Show that a combinatorial object arises with non-zero probability among objects drawn from a suitable probability space." }, { "code": null, "e": 3063, "s": 2935, "text": "Derandomization: First devise a randomized algorithm then argue that it can be derandomized to yield a deterministic algorithm." }, { "code": null, "e": 3173, "s": 3063, "text": "Sources:http://theory.stanford.edu/people/pragh/amstalk.pdfhttps://en.wikipedia.org/wiki/Randomized_algorithm" }, { "code": null, "e": 3343, "s": 3173, "text": "This article is contributed by Ashish Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3354, "s": 3343, "text": "Randomized" }, { "code": null, "e": 3452, "s": 3354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3531, "s": 3452, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 3590, "s": 3531, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 3626, "s": 3590, "text": "Shuffle or Randomize a list in Java" }, { "code": null, "e": 3661, "s": 3626, "text": "Generating Random String Using PHP" }, { "code": null, "e": 3706, "s": 3661, "text": "Estimating the value of Pi using Monte Carlo" }, { "code": null, "e": 3736, "s": 3706, "text": "Operations on Sparse Matrices" }, { "code": null, "e": 3755, "s": 3736, "text": "Reservoir Sampling" }, { "code": null, "e": 3795, "s": 3755, "text": "Expected Number of Trials until Success" }, { "code": null, "e": 3819, "s": 3795, "text": "Shuffle a deck of cards" } ]
How to Enable Copy and Paste in Oracle VirtualBox?
19 Feb, 2020 In this article, we will see how to enable copy and paste from a Windows host to a VirtualBox and vice-versa. We’ve taken the VirtualBox guest additions which gives us various additional tooling, specifically giving us the ability to copy and paste. It also enables bi-directional copy and pastes. Step 1: Start the Virtual Box and go to Settings as shown in the below screenshot Step 2: Now click on Advanced as marked below Step 3: Now, click Share Clipboard --< Bidirectional Drag & Drop --< bidirectional. Technical Scripter 2019 Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2020" }, { "code": null, "e": 326, "s": 28, "text": "In this article, we will see how to enable copy and paste from a Windows host to a VirtualBox and vice-versa. We’ve taken the VirtualBox guest additions which gives us various additional tooling, specifically giving us the ability to copy and paste. It also enables bi-directional copy and pastes." }, { "code": null, "e": 408, "s": 326, "text": "Step 1: Start the Virtual Box and go to Settings as shown in the below screenshot" }, { "code": null, "e": 454, "s": 408, "text": "Step 2: Now click on Advanced as marked below" }, { "code": null, "e": 473, "s": 454, "text": "Step 3: Now, click" }, { "code": null, "e": 540, "s": 473, "text": "Share Clipboard --< Bidirectional \nDrag & Drop --< bidirectional.\n" }, { "code": null, "e": 564, "s": 540, "text": "Technical Scripter 2019" }, { "code": null, "e": 583, "s": 564, "text": "Technical Scripter" }, { "code": null, "e": 592, "s": 583, "text": "TechTips" } ]
Scala List distinct() method with example
26 Jul, 2019 The distinct() method is utilized to delete the duplicate elements from the stated list. Method Definition: def distinct: List[A] Return Type: It returns a new list of elements without any duplicates. Example #1: // Scala program of distinct()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 5, 2) // Applying distinct method val res = m1.distinct // Displays output println(res) }} List(1, 3, 5, 2) Example #2: // Scala program of distinct()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2) // Applying distinct method val res = m1.distinct // Displays output println(res) }} List(1, 3, 5, 4, 2) Scala Scala-list Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 117, "s": 28, "text": "The distinct() method is utilized to delete the duplicate elements from the stated list." }, { "code": null, "e": 158, "s": 117, "text": "Method Definition: def distinct: List[A]" }, { "code": null, "e": 229, "s": 158, "text": "Return Type: It returns a new list of elements without any duplicates." }, { "code": null, "e": 241, "s": 229, "text": "Example #1:" }, { "code": "// Scala program of distinct()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 5, 2) // Applying distinct method val res = m1.distinct // Displays output println(res) }}", "e": 583, "s": 241, "text": null }, { "code": null, "e": 601, "s": 583, "text": "List(1, 3, 5, 2)\n" }, { "code": null, "e": 613, "s": 601, "text": "Example #2:" }, { "code": "// Scala program of distinct()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 1, 3, 3, 3, 5, 4, 5, 2) // Applying distinct method val res = m1.distinct // Displays output println(res) }}", "e": 964, "s": 613, "text": null }, { "code": null, "e": 985, "s": 964, "text": "List(1, 3, 5, 4, 2)\n" }, { "code": null, "e": 991, "s": 985, "text": "Scala" }, { "code": null, "e": 1002, "s": 991, "text": "Scala-list" }, { "code": null, "e": 1015, "s": 1002, "text": "Scala-Method" }, { "code": null, "e": 1021, "s": 1015, "text": "Scala" } ]
CSS | 8 Digit Hex Color
21 Aug, 2019 The Eight Digit Hex color is as simple as Six Digit Hex color it contains 8 digits rather than six, it is used to define the color of your elements with the CSS. It has a prefixed hash(#) value before the digits like six-digit hex code.The difference between 6 and 8 digit hex codes is, that 2 extra characters define the alpha channel as the name suggests in the 8 digit hex color. The last two digits will define that the color will how much transparent or opaque. If the last two digit is 00 then that will be fully transparent and if that is FF then it will be fully opaque. Syntax: #RRGGBBAA Note: The first six character represent the RGB color as Six digit hex color code. Last two represent the alpha channel. Example 1: <!DOCTYPE html><html> <head> <title>CSS 8 Digit Hex Color</title> <style> body { background-color: #666600; } h1 { color: green; } article { background-color: #FFFFFF44; border: 5px solid green; margin: 15px; text-align: center; } </style></head> <body> <article> <h1>GeeksforGeeks</h1> </article></body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <title>CSS 8 Digit Hex Color</title> <style> body { background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png'); background-attachment: fixed; background-size: cover; } h2 { color: white; } article { background-color: #FFFFFF22; border: 2px solid green; background-position: center center; text-align: center; } </style></head> <body> <article> <h2>GeeksforGeeks</h2> </article></body> </html> Output: CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Aug, 2019" }, { "code": null, "e": 607, "s": 28, "text": "The Eight Digit Hex color is as simple as Six Digit Hex color it contains 8 digits rather than six, it is used to define the color of your elements with the CSS. It has a prefixed hash(#) value before the digits like six-digit hex code.The difference between 6 and 8 digit hex codes is, that 2 extra characters define the alpha channel as the name suggests in the 8 digit hex color. The last two digits will define that the color will how much transparent or opaque. If the last two digit is 00 then that will be fully transparent and if that is FF then it will be fully opaque." }, { "code": null, "e": 615, "s": 607, "text": "Syntax:" }, { "code": null, "e": 625, "s": 615, "text": "#RRGGBBAA" }, { "code": null, "e": 746, "s": 625, "text": "Note: The first six character represent the RGB color as Six digit hex color code. Last two represent the alpha channel." }, { "code": null, "e": 757, "s": 746, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS 8 Digit Hex Color</title> <style> body { background-color: #666600; } h1 { color: green; } article { background-color: #FFFFFF44; border: 5px solid green; margin: 15px; text-align: center; } </style></head> <body> <article> <h1>GeeksforGeeks</h1> </article></body> </html>", "e": 1223, "s": 757, "text": null }, { "code": null, "e": 1231, "s": 1223, "text": "Output:" }, { "code": null, "e": 1242, "s": 1231, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS 8 Digit Hex Color</title> <style> body { background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png'); background-attachment: fixed; background-size: cover; } h2 { color: white; } article { background-color: #FFFFFF22; border: 2px solid green; background-position: center center; text-align: center; } </style></head> <body> <article> <h2>GeeksforGeeks</h2> </article></body> </html>", "e": 1883, "s": 1242, "text": null }, { "code": null, "e": 1891, "s": 1883, "text": "Output:" }, { "code": null, "e": 1906, "s": 1891, "text": "CSS-Properties" }, { "code": null, "e": 1910, "s": 1906, "text": "CSS" }, { "code": null, "e": 1927, "s": 1910, "text": "Web Technologies" }, { "code": null, "e": 2025, "s": 1927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2062, "s": 2025, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2101, "s": 2062, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2140, "s": 2101, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2204, "s": 2140, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 2265, "s": 2204, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2298, "s": 2265, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2359, "s": 2298, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2402, "s": 2359, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2474, "s": 2402, "text": "Differences between Functional Components and Class Components in React" } ]
Count array elements that can be represented as sum of at least two consecutive array elements
08 Apr, 2021 Given an array A[] consisting of N integers from a range [1, N], the task is to calculate the count of array elements (non-distinct) that can be represented as the sum of two or more consecutive array elements. Examples: Input: a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}Output: 5Explanation:The array elements satisfying the condition are: 4 = 3 + 1 5 = 1 + 4 or 4 + 1 9 = 3 + 1 + 4 + 1 6 = 1 + 5 or 1 + 4 + 1 5 = 1 + 4 or 4 + 1 Input: a[] = {1, 1, 1, 1, 1}Output: 0Explanation:No such array element exists that can be represented as the sum of two or more consecutive elements. Naive Approach: Traverse the given array for each element, find the sum of all possible subarrays and check if sum of any of the subarrays becomes equal to that of the current element. Increase count if found to be true. Finally, print the count obtained. Time Complexity: O(n3) Auxiliary Space: O(1) Efficient Approach: Follow the steps below to optimize the above approach: Initialize an array cnt[] to store the number of occurrences of each array element. Iterate over all subarrays of at least length 2 maintaining the sum of the current subarray sum. If the current sum does not exceed N, then add cnt[sum] to the answer and set cnt[sum]=0 to prevent counting the same elements several times. Finally, print the sum obtained. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of// array elements that can be// represented as the sum of two// or more consecutive array elementsint countElements(int a[], int n){ // Stores the frequencies // of array elements int cnt[n + 1] = {0}; memset(cnt, 0, sizeof(cnt)); // Stores required count int ans = 0; // Update frequency of // each array element for(int i = 0; i < n; i++) { ++cnt[a[i]]; } // Find sum of all subarrays for(int l = 0; l < n; ++l) { int sum = 0; for(int r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans;} // Driver Codeint main(){ // Given array int a[] = { 1, 1, 1, 1, 1 }; int N = sizeof(a) / sizeof(a[0]); // Function call cout << countElements(a, N);} // This code is contributed by Amit Katiyar // Java Program for above approach import java.util.*;class GFG { // Function to find the number of array // elements that can be represented as the sum // of two or more consecutive array elements static int countElements(int[] a, int n) { // Stores the frequencies // of array elements int[] cnt = new int[n + 1]; // Stores required count int ans = 0; // Update frequency of // each array element for (int k : a) { ++cnt[k]; } // Find sum of all subarrays for (int l = 0; l < n; ++l) { int sum = 0; for (int r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans; } // Driver Code public static void main(String[] args) { // Given array int[] a = { 1, 1, 1, 1, 1 }; // Function call System.out.println( countElements(a, a.length)); }} # Python3 program for above approach # Function to find the number of array# elements that can be represented as the sum# of two or more consecutive array elementsdef countElements(a, n): # Stores the frequencies # of array elements cnt = [0] * (n + 1) # Stores required count ans = 0 # Update frequency of # each array element for k in a: cnt[k] += 1 # Find sum of all subarrays for l in range(n): sum = 0 for r in range(l, n): sum += a[r] if (l == r): continue if (sum <= n): # Increment ans by cnt[sum] ans += cnt[sum] # Reset cnt[sum] by 0 cnt[sum] = 0 # Return ans return ans # Driver Codeif __name__ == '__main__': # Given array a = [ 1, 1, 1, 1, 1 ] # Function call print(countElements(a, len(a))) # This code is contributed by mohit kumar 29 // C# program for above approachusing System; class GFG{ // Function to find the number of array// elements that can be represented as the sum// of two or more consecutive array elementsstatic int countElements(int[] a, int n){ // Stores the frequencies // of array elements int[] cnt = new int[n + 1]; // Stores required count int ans = 0; // Update frequency of // each array element foreach(int k in a) { ++cnt[k]; } // Find sum of all subarrays for(int l = 0; l < n; ++l) { int sum = 0; for(int r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans;} // Driver Codepublic static void Main(String[] args){ // Given array int[] a = { 1, 1, 1, 1, 1 }; // Function call Console.WriteLine(countElements(a, a.Length));}} // This code is contributed by Amit Katiyar <script> // Javascript program for above approach // Function to find the number of array// elements that can be represented as the sum// of two or more consecutive array elementsfunction countElements(a, n){ // Stores the frequencies // of array elements var cnt = Array(n + 1).fill(0); // Stores required count var ans = 0; // Update frequency of // each array element for(k = 0; k < n; k++) { cnt[a[k]]++; } // Find sum of all subarrays for(l = 0; l < n; ++l) { var sum = 0; for(r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans;} // Driver Code // Given arrayvar a = [ 1, 1, 1, 1, 1 ]; // Function calldocument.write(countElements(a, a.length)); // This code is contributed by todaysgaurav </script> 0 Time Complexity: O(N2)Auxiliary Space: O(N) mohit kumar 29 amit143katiyar todaysgaurav frequency-counting subarray subarray-sum Arrays Hash Mathematical Searching Arrays Searching Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Apr, 2021" }, { "code": null, "e": 263, "s": 52, "text": "Given an array A[] consisting of N integers from a range [1, N], the task is to calculate the count of array elements (non-distinct) that can be represented as the sum of two or more consecutive array elements." }, { "code": null, "e": 273, "s": 263, "text": "Examples:" }, { "code": null, "e": 472, "s": 273, "text": "Input: a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}Output: 5Explanation:The array elements satisfying the condition are: 4 = 3 + 1 5 = 1 + 4 or 4 + 1 9 = 3 + 1 + 4 + 1 6 = 1 + 5 or 1 + 4 + 1 5 = 1 + 4 or 4 + 1" }, { "code": null, "e": 622, "s": 472, "text": "Input: a[] = {1, 1, 1, 1, 1}Output: 0Explanation:No such array element exists that can be represented as the sum of two or more consecutive elements." }, { "code": null, "e": 923, "s": 622, "text": "Naive Approach: Traverse the given array for each element, find the sum of all possible subarrays and check if sum of any of the subarrays becomes equal to that of the current element. Increase count if found to be true. Finally, print the count obtained. Time Complexity: O(n3) Auxiliary Space: O(1)" }, { "code": null, "e": 998, "s": 923, "text": "Efficient Approach: Follow the steps below to optimize the above approach:" }, { "code": null, "e": 1082, "s": 998, "text": "Initialize an array cnt[] to store the number of occurrences of each array element." }, { "code": null, "e": 1179, "s": 1082, "text": "Iterate over all subarrays of at least length 2 maintaining the sum of the current subarray sum." }, { "code": null, "e": 1321, "s": 1179, "text": "If the current sum does not exceed N, then add cnt[sum] to the answer and set cnt[sum]=0 to prevent counting the same elements several times." }, { "code": null, "e": 1354, "s": 1321, "text": "Finally, print the sum obtained." }, { "code": null, "e": 1405, "s": 1354, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1409, "s": 1405, "text": "C++" }, { "code": null, "e": 1414, "s": 1409, "text": "Java" }, { "code": null, "e": 1422, "s": 1414, "text": "Python3" }, { "code": null, "e": 1425, "s": 1422, "text": "C#" }, { "code": null, "e": 1436, "s": 1425, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of// array elements that can be// represented as the sum of two// or more consecutive array elementsint countElements(int a[], int n){ // Stores the frequencies // of array elements int cnt[n + 1] = {0}; memset(cnt, 0, sizeof(cnt)); // Stores required count int ans = 0; // Update frequency of // each array element for(int i = 0; i < n; i++) { ++cnt[a[i]]; } // Find sum of all subarrays for(int l = 0; l < n; ++l) { int sum = 0; for(int r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans;} // Driver Codeint main(){ // Given array int a[] = { 1, 1, 1, 1, 1 }; int N = sizeof(a) / sizeof(a[0]); // Function call cout << countElements(a, N);} // This code is contributed by Amit Katiyar", "e": 2642, "s": 1436, "text": null }, { "code": "// Java Program for above approach import java.util.*;class GFG { // Function to find the number of array // elements that can be represented as the sum // of two or more consecutive array elements static int countElements(int[] a, int n) { // Stores the frequencies // of array elements int[] cnt = new int[n + 1]; // Stores required count int ans = 0; // Update frequency of // each array element for (int k : a) { ++cnt[k]; } // Find sum of all subarrays for (int l = 0; l < n; ++l) { int sum = 0; for (int r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans; } // Driver Code public static void main(String[] args) { // Given array int[] a = { 1, 1, 1, 1, 1 }; // Function call System.out.println( countElements(a, a.length)); }}", "e": 3889, "s": 2642, "text": null }, { "code": "# Python3 program for above approach # Function to find the number of array# elements that can be represented as the sum# of two or more consecutive array elementsdef countElements(a, n): # Stores the frequencies # of array elements cnt = [0] * (n + 1) # Stores required count ans = 0 # Update frequency of # each array element for k in a: cnt[k] += 1 # Find sum of all subarrays for l in range(n): sum = 0 for r in range(l, n): sum += a[r] if (l == r): continue if (sum <= n): # Increment ans by cnt[sum] ans += cnt[sum] # Reset cnt[sum] by 0 cnt[sum] = 0 # Return ans return ans # Driver Codeif __name__ == '__main__': # Given array a = [ 1, 1, 1, 1, 1 ] # Function call print(countElements(a, len(a))) # This code is contributed by mohit kumar 29", "e": 4831, "s": 3889, "text": null }, { "code": "// C# program for above approachusing System; class GFG{ // Function to find the number of array// elements that can be represented as the sum// of two or more consecutive array elementsstatic int countElements(int[] a, int n){ // Stores the frequencies // of array elements int[] cnt = new int[n + 1]; // Stores required count int ans = 0; // Update frequency of // each array element foreach(int k in a) { ++cnt[k]; } // Find sum of all subarrays for(int l = 0; l < n; ++l) { int sum = 0; for(int r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans;} // Driver Codepublic static void Main(String[] args){ // Given array int[] a = { 1, 1, 1, 1, 1 }; // Function call Console.WriteLine(countElements(a, a.Length));}} // This code is contributed by Amit Katiyar", "e": 5986, "s": 4831, "text": null }, { "code": "<script> // Javascript program for above approach // Function to find the number of array// elements that can be represented as the sum// of two or more consecutive array elementsfunction countElements(a, n){ // Stores the frequencies // of array elements var cnt = Array(n + 1).fill(0); // Stores required count var ans = 0; // Update frequency of // each array element for(k = 0; k < n; k++) { cnt[a[k]]++; } // Find sum of all subarrays for(l = 0; l < n; ++l) { var sum = 0; for(r = l; r < n; ++r) { sum += a[r]; if (l == r) continue; if (sum <= n) { // Increment ans by cnt[sum] ans += cnt[sum]; // Reset cnt[sum] by 0 cnt[sum] = 0; } } } // Return ans return ans;} // Driver Code // Given arrayvar a = [ 1, 1, 1, 1, 1 ]; // Function calldocument.write(countElements(a, a.length)); // This code is contributed by todaysgaurav </script>", "e": 7070, "s": 5986, "text": null }, { "code": null, "e": 7072, "s": 7070, "text": "0" }, { "code": null, "e": 7116, "s": 7072, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 7131, "s": 7116, "text": "mohit kumar 29" }, { "code": null, "e": 7146, "s": 7131, "text": "amit143katiyar" }, { "code": null, "e": 7159, "s": 7146, "text": "todaysgaurav" }, { "code": null, "e": 7178, "s": 7159, "text": "frequency-counting" }, { "code": null, "e": 7187, "s": 7178, "text": "subarray" }, { "code": null, "e": 7200, "s": 7187, "text": "subarray-sum" }, { "code": null, "e": 7207, "s": 7200, "text": "Arrays" }, { "code": null, "e": 7212, "s": 7207, "text": "Hash" }, { "code": null, "e": 7225, "s": 7212, "text": "Mathematical" }, { "code": null, "e": 7235, "s": 7225, "text": "Searching" }, { "code": null, "e": 7242, "s": 7235, "text": "Arrays" }, { "code": null, "e": 7252, "s": 7242, "text": "Searching" }, { "code": null, "e": 7257, "s": 7252, "text": "Hash" }, { "code": null, "e": 7270, "s": 7257, "text": "Mathematical" } ]
Hello World Program in Perl
11 Feb, 2019 Perl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX. Hello World! program in every programming language gives the beginner programmer a leap in proceeding further in the new language. The basic Hello world program just gives the output by printing ” Hello World!” on the screen. In Perl, a basic program consists of the following steps of execution, Step 1: Transfer the file to Perl Interpreter:Always in Perl, the first line starts with a pair of characters #!. It insists Perl interpreter how the file should be executed. Here, the file should be transferred to Perl interpreter that resides in /usr/bin/perl folder. So, the first line of the program will go this way, #!/usr/bin/perl Step 2: Pragma in Perl:A pragma is a specific module in Perl package which has the control over some functions of the compile time or Run time behavior of Perl, which is strict or warnings. So the next two lines go like this, use strict; use warnings; Step 3: Use of print() function:Lastly displaying the output, We use print() function to display a string in perl. print("Hello World\n"); Code: #!/usr/bin/perl # Modules useduse strict;use warnings; # Print function print("Hello World\n"); Output: Hello World Important Points: The file must be stored with an extension of .pl Directory of the Perl Package must be same as to where the Program file is saved. Using Online IDEs:You can use various online IDEs which can be used to run Perl programs without installing. Using Command-Line:You can also use command line options to run a Perl program. Below steps demonstrate how to run a Perl program on Command line in Windows/Unix Operating System: WindowsFirst, open a text editor like Notepad or Notepad++.Write the code in the text editor and save the file with .pl extensionMake sure you have downloaded and installed the latest version of Perl from https://www.perl.org/get.htmlOpen commandline and Run the command perl -v to check if your Perl’s latest version has been installed properly or not.To compile the code type perl HelloWorld.pl. If your code has no error then it will execute properly and output will be displayed.Unix/LinuxFollow the upgiven steps for writing code and saving the file with .pl extensionOpen Terminal of your Unix/Linux OS and follow the following steps to download and install Perl:Now, run the command perl -version to make sure if your Perl’s latest version has been installed properly or not.To compile the code type perl hello.pl. If your code has no error then it will execute properly and output will be displayed. First, open a text editor like Notepad or Notepad++. Write the code in the text editor and save the file with .pl extension Make sure you have downloaded and installed the latest version of Perl from https://www.perl.org/get.html Open commandline and Run the command perl -v to check if your Perl’s latest version has been installed properly or not. To compile the code type perl HelloWorld.pl. If your code has no error then it will execute properly and output will be displayed. Follow the upgiven steps for writing code and saving the file with .pl extension Open Terminal of your Unix/Linux OS and follow the following steps to download and install Perl: Now, run the command perl -version to make sure if your Perl’s latest version has been installed properly or not. To compile the code type perl hello.pl. If your code has no error then it will execute properly and output will be displayed. perl-basics Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Feb, 2019" }, { "code": null, "e": 272, "s": 28, "text": "Perl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX." }, { "code": null, "e": 569, "s": 272, "text": "Hello World! program in every programming language gives the beginner programmer a leap in proceeding further in the new language. The basic Hello world program just gives the output by printing ” Hello World!” on the screen. In Perl, a basic program consists of the following steps of execution," }, { "code": null, "e": 891, "s": 569, "text": "Step 1: Transfer the file to Perl Interpreter:Always in Perl, the first line starts with a pair of characters #!. It insists Perl interpreter how the file should be executed. Here, the file should be transferred to Perl interpreter that resides in /usr/bin/perl folder. So, the first line of the program will go this way," }, { "code": null, "e": 907, "s": 891, "text": "#!/usr/bin/perl" }, { "code": null, "e": 1133, "s": 907, "text": "Step 2: Pragma in Perl:A pragma is a specific module in Perl package which has the control over some functions of the compile time or Run time behavior of Perl, which is strict or warnings. So the next two lines go like this," }, { "code": null, "e": 1160, "s": 1133, "text": "use strict;\nuse warnings;\n" }, { "code": null, "e": 1275, "s": 1160, "text": "Step 3: Use of print() function:Lastly displaying the output, We use print() function to display a string in perl." }, { "code": null, "e": 1299, "s": 1275, "text": "print(\"Hello World\\n\");" }, { "code": null, "e": 1305, "s": 1299, "text": "Code:" }, { "code": "#!/usr/bin/perl # Modules useduse strict;use warnings; # Print function print(\"Hello World\\n\");", "e": 1403, "s": 1305, "text": null }, { "code": null, "e": 1411, "s": 1403, "text": "Output:" }, { "code": null, "e": 1423, "s": 1411, "text": "Hello World" }, { "code": null, "e": 1442, "s": 1423, "text": " Important Points:" }, { "code": null, "e": 1491, "s": 1442, "text": "The file must be stored with an extension of .pl" }, { "code": null, "e": 1573, "s": 1491, "text": "Directory of the Perl Package must be same as to where the Program file is saved." }, { "code": null, "e": 1682, "s": 1573, "text": "Using Online IDEs:You can use various online IDEs which can be used to run Perl programs without installing." }, { "code": null, "e": 2770, "s": 1682, "text": "Using Command-Line:You can also use command line options to run a Perl program. Below steps demonstrate how to run a Perl program on Command line in Windows/Unix Operating System: WindowsFirst, open a text editor like Notepad or Notepad++.Write the code in the text editor and save the file with .pl extensionMake sure you have downloaded and installed the latest version of Perl from https://www.perl.org/get.htmlOpen commandline and Run the command perl -v to check if your Perl’s latest version has been installed properly or not.To compile the code type perl HelloWorld.pl. If your code has no error then it will execute properly and output will be displayed.Unix/LinuxFollow the upgiven steps for writing code and saving the file with .pl extensionOpen Terminal of your Unix/Linux OS and follow the following steps to download and install Perl:Now, run the command perl -version to make sure if your Perl’s latest version has been installed properly or not.To compile the code type perl hello.pl. If your code has no error then it will execute properly and output will be displayed." }, { "code": null, "e": 2823, "s": 2770, "text": "First, open a text editor like Notepad or Notepad++." }, { "code": null, "e": 2894, "s": 2823, "text": "Write the code in the text editor and save the file with .pl extension" }, { "code": null, "e": 3000, "s": 2894, "text": "Make sure you have downloaded and installed the latest version of Perl from https://www.perl.org/get.html" }, { "code": null, "e": 3120, "s": 3000, "text": "Open commandline and Run the command perl -v to check if your Perl’s latest version has been installed properly or not." }, { "code": null, "e": 3251, "s": 3120, "text": "To compile the code type perl HelloWorld.pl. If your code has no error then it will execute properly and output will be displayed." }, { "code": null, "e": 3332, "s": 3251, "text": "Follow the upgiven steps for writing code and saving the file with .pl extension" }, { "code": null, "e": 3429, "s": 3332, "text": "Open Terminal of your Unix/Linux OS and follow the following steps to download and install Perl:" }, { "code": null, "e": 3543, "s": 3429, "text": "Now, run the command perl -version to make sure if your Perl’s latest version has been installed properly or not." }, { "code": null, "e": 3669, "s": 3543, "text": "To compile the code type perl hello.pl. If your code has no error then it will execute properly and output will be displayed." }, { "code": null, "e": 3681, "s": 3669, "text": "perl-basics" }, { "code": null, "e": 3688, "s": 3681, "text": "Picked" }, { "code": null, "e": 3693, "s": 3688, "text": "Perl" }, { "code": null, "e": 3698, "s": 3693, "text": "Perl" } ]
Search an element in a reverse sorted array
07 May, 2021 Given an array arr[] sorted in decreasing order, and an integer X, the task is to check if X is present in the given array or not. If X is present in the array, print its index ( 0-based indexing). Otherwise, print -1. Examples: Input: arr[] = {5, 4, 3, 2, 1}, X = 4Output: 1Explanation: Element X (= 4) is present at index 1.Therefore, the required output is 1. Input: arr[] = {10, 8, 2, -9}, X = 5Output: -1Explanation: Element X (= 5) is not present in the array.Therefore, the required output is -1. Naive Approach: The simplest approach to solve the problem is to traverse the array and for each element, check if it is equal to X or not. If any element is found to satisfy that condition, print the index of that element. Otherwise print -1. Time Complexity: O(N) Auxiliary Space: O(1) Efficient Approach: To solve the problem, the idea is to use Binary Search based on the approach discussed in the article search an element in a sorted array. Follow the steps below to solve the problem: Compare X with the middle element.If X matches with the middle element (arr[mid]), return the index mid.If X is found to be greater than the arr[mid], then X can only lie in the subarray [mid + 1, end]. So search for X in the subarray {arr[mid + 1], .., arr[end]} .Otherwise, search in the subarray {arr[start], ...., arr[mid]} Compare X with the middle element. If X matches with the middle element (arr[mid]), return the index mid. If X is found to be greater than the arr[mid], then X can only lie in the subarray [mid + 1, end]. So search for X in the subarray {arr[mid + 1], .., arr[end]} . Otherwise, search in the subarray {arr[start], ...., arr[mid]} Below is the implementation of the above approach: C C++ Java Python3 C# Javascript // C program for the above approach#include <stdio.h> // Function to search if element X// is present in reverse sorted arrayint binarySearch(int arr[], int N, int X){ // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver Codeint main(){ int arr[] = { 5, 4, 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int X = 4; int res = binarySearch(arr, N, X); printf(" %d " , res); return 0;}//This code is contributed by Pradeep Mondal P // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to search if element X// is present in reverse sorted arrayint binarySearch(int arr[], int N, int X){ // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver Codeint main(){ int arr[] = { 5, 4, 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int X = 5; cout << binarySearch(arr, N, X); return 0;} // Java Program to implement// the above approachclass GFG { // Function to search if element X // is present in reverse sorted array static int binarySearch(int arr[], int N, int X) { // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1; } public static void main(String[] args) { int arr[] = { 5, 4, 3, 2, 1 }; int N = arr.length; int X = 5; System.out.println( binarySearch(arr, N, X)); }} # Python3 program to implement# the above approach # Function to search if element X# is present in reverse sorted arraydef binarySearch(arr, N, X): # Store the first index of the # subarray in which X lies start = 0 # Store the last index of the # subarray in which X lies end = N while (start <= end): # Store the middle index # of the subarray mid = start + (end - start) // 2 # Check if value at middle index # of the subarray equal to X if (X == arr[mid]): # Element is found return mid # If X is smaller than the value # at middle index of the subarray elif (X < arr[mid]): # Search in right # half of subarray start = mid + 1 else: # Search in left # half of subarray end = mid - 1 # If X not found return -1 # Driver Codeif __name__ == '__main__': arr = [ 5, 4, 3, 2, 1 ] N = len(arr) X = 5 print(binarySearch(arr, N, X)) # This code is contributed by mohit kumar 29 // C# Program to implement// the above approachusing System;class GFG{ // Function to search if element X// is present in reverse sorted arraystatic int binarySearch(int []arr, int N, int X){ // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver codepublic static void Main(String[] args){ int []arr = {5, 4, 3, 2, 1}; int N = arr.Length; int X = 5; Console.WriteLine(binarySearch(arr, N, X));}} // This code is contributed by Princi Singh <script>// JavaScript program to implement// the above approach // Function to search if element X// is present in reverse sorted arrayfunction binarySearch(arr, N, X){ // Store the first index of the // subarray in which X lies let start = 0; // Store the last index of the // subarray in which X lies let end = N; while (start <= end) { // Store the middle index // of the subarray let mid = Math.floor(start + (end - start) / 2); // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver Code let arr = [ 5, 4, 3, 2, 1 ]; let N = arr.length; let X = 5; document.write(binarySearch(arr, N, X)); // This code is contributed by Surbhi Tyagi.</script> 1 Time Complexity: O(log2N)Auxiliary Space: O(1) mohit kumar 29 princi singh pradeepmondalp surbhityagi15 array-traversal-question Binary Search Arrays Searching Sorting Arrays Searching Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Search Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 52, "s": 24, "text": "\n07 May, 2021" }, { "code": null, "e": 271, "s": 52, "text": "Given an array arr[] sorted in decreasing order, and an integer X, the task is to check if X is present in the given array or not. If X is present in the array, print its index ( 0-based indexing). Otherwise, print -1." }, { "code": null, "e": 282, "s": 271, "text": "Examples: " }, { "code": null, "e": 416, "s": 282, "text": "Input: arr[] = {5, 4, 3, 2, 1}, X = 4Output: 1Explanation: Element X (= 4) is present at index 1.Therefore, the required output is 1." }, { "code": null, "e": 557, "s": 416, "text": "Input: arr[] = {10, 8, 2, -9}, X = 5Output: -1Explanation: Element X (= 5) is not present in the array.Therefore, the required output is -1." }, { "code": null, "e": 802, "s": 557, "text": "Naive Approach: The simplest approach to solve the problem is to traverse the array and for each element, check if it is equal to X or not. If any element is found to satisfy that condition, print the index of that element. Otherwise print -1. " }, { "code": null, "e": 846, "s": 802, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 1051, "s": 846, "text": "Efficient Approach: To solve the problem, the idea is to use Binary Search based on the approach discussed in the article search an element in a sorted array. Follow the steps below to solve the problem: " }, { "code": null, "e": 1379, "s": 1051, "text": "Compare X with the middle element.If X matches with the middle element (arr[mid]), return the index mid.If X is found to be greater than the arr[mid], then X can only lie in the subarray [mid + 1, end]. So search for X in the subarray {arr[mid + 1], .., arr[end]} .Otherwise, search in the subarray {arr[start], ...., arr[mid]}" }, { "code": null, "e": 1414, "s": 1379, "text": "Compare X with the middle element." }, { "code": null, "e": 1485, "s": 1414, "text": "If X matches with the middle element (arr[mid]), return the index mid." }, { "code": null, "e": 1647, "s": 1485, "text": "If X is found to be greater than the arr[mid], then X can only lie in the subarray [mid + 1, end]. So search for X in the subarray {arr[mid + 1], .., arr[end]} ." }, { "code": null, "e": 1710, "s": 1647, "text": "Otherwise, search in the subarray {arr[start], ...., arr[mid]}" }, { "code": null, "e": 1761, "s": 1710, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1763, "s": 1761, "text": "C" }, { "code": null, "e": 1767, "s": 1763, "text": "C++" }, { "code": null, "e": 1772, "s": 1767, "text": "Java" }, { "code": null, "e": 1780, "s": 1772, "text": "Python3" }, { "code": null, "e": 1783, "s": 1780, "text": "C#" }, { "code": null, "e": 1794, "s": 1783, "text": "Javascript" }, { "code": "// C program for the above approach#include <stdio.h> // Function to search if element X// is present in reverse sorted arrayint binarySearch(int arr[], int N, int X){ // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver Codeint main(){ int arr[] = { 5, 4, 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int X = 4; int res = binarySearch(arr, N, X); printf(\" %d \" , res); return 0;}//This code is contributed by Pradeep Mondal P", "e": 3059, "s": 1794, "text": null }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to search if element X// is present in reverse sorted arrayint binarySearch(int arr[], int N, int X){ // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver Codeint main(){ int arr[] = { 5, 4, 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int X = 5; cout << binarySearch(arr, N, X); return 0;}", "e": 4284, "s": 3059, "text": null }, { "code": "// Java Program to implement// the above approachclass GFG { // Function to search if element X // is present in reverse sorted array static int binarySearch(int arr[], int N, int X) { // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1; } public static void main(String[] args) { int arr[] = { 5, 4, 3, 2, 1 }; int N = arr.length; int X = 5; System.out.println( binarySearch(arr, N, X)); }}", "e": 5692, "s": 4284, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to search if element X# is present in reverse sorted arraydef binarySearch(arr, N, X): # Store the first index of the # subarray in which X lies start = 0 # Store the last index of the # subarray in which X lies end = N while (start <= end): # Store the middle index # of the subarray mid = start + (end - start) // 2 # Check if value at middle index # of the subarray equal to X if (X == arr[mid]): # Element is found return mid # If X is smaller than the value # at middle index of the subarray elif (X < arr[mid]): # Search in right # half of subarray start = mid + 1 else: # Search in left # half of subarray end = mid - 1 # If X not found return -1 # Driver Codeif __name__ == '__main__': arr = [ 5, 4, 3, 2, 1 ] N = len(arr) X = 5 print(binarySearch(arr, N, X)) # This code is contributed by mohit kumar 29", "e": 6788, "s": 5692, "text": null }, { "code": "// C# Program to implement// the above approachusing System;class GFG{ // Function to search if element X// is present in reverse sorted arraystatic int binarySearch(int []arr, int N, int X){ // Store the first index of the // subarray in which X lies int start = 0; // Store the last index of the // subarray in which X lies int end = N; while (start <= end) { // Store the middle index // of the subarray int mid = start + (end - start) / 2; // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver codepublic static void Main(String[] args){ int []arr = {5, 4, 3, 2, 1}; int N = arr.Length; int X = 5; Console.WriteLine(binarySearch(arr, N, X));}} // This code is contributed by Princi Singh", "e": 7944, "s": 6788, "text": null }, { "code": "<script>// JavaScript program to implement// the above approach // Function to search if element X// is present in reverse sorted arrayfunction binarySearch(arr, N, X){ // Store the first index of the // subarray in which X lies let start = 0; // Store the last index of the // subarray in which X lies let end = N; while (start <= end) { // Store the middle index // of the subarray let mid = Math.floor(start + (end - start) / 2); // Check if value at middle index // of the subarray equal to X if (X == arr[mid]) { // Element is found return mid; } // If X is smaller than the value // at middle index of the subarray else if (X < arr[mid]) { // Search in right // half of subarray start = mid + 1; } else { // Search in left // half of subarray end = mid - 1; } } // If X not found return -1;} // Driver Code let arr = [ 5, 4, 3, 2, 1 ]; let N = arr.length; let X = 5; document.write(binarySearch(arr, N, X)); // This code is contributed by Surbhi Tyagi.</script>", "e": 9165, "s": 7944, "text": null }, { "code": null, "e": 9167, "s": 9165, "text": "1" }, { "code": null, "e": 9216, "s": 9169, "text": "Time Complexity: O(log2N)Auxiliary Space: O(1)" }, { "code": null, "e": 9231, "s": 9216, "text": "mohit kumar 29" }, { "code": null, "e": 9244, "s": 9231, "text": "princi singh" }, { "code": null, "e": 9259, "s": 9244, "text": "pradeepmondalp" }, { "code": null, "e": 9273, "s": 9259, "text": "surbhityagi15" }, { "code": null, "e": 9298, "s": 9273, "text": "array-traversal-question" }, { "code": null, "e": 9312, "s": 9298, "text": "Binary Search" }, { "code": null, "e": 9319, "s": 9312, "text": "Arrays" }, { "code": null, "e": 9329, "s": 9319, "text": "Searching" }, { "code": null, "e": 9337, "s": 9329, "text": "Sorting" }, { "code": null, "e": 9344, "s": 9337, "text": "Arrays" }, { "code": null, "e": 9354, "s": 9344, "text": "Searching" }, { "code": null, "e": 9362, "s": 9354, "text": "Sorting" }, { "code": null, "e": 9376, "s": 9362, "text": "Binary Search" }, { "code": null, "e": 9474, "s": 9376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9506, "s": 9474, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9520, "s": 9506, "text": "Linear Search" }, { "code": null, "e": 9605, "s": 9520, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9628, "s": 9605, "text": "Introduction to Arrays" }, { "code": null, "e": 9684, "s": 9628, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 9698, "s": 9684, "text": "Binary Search" }, { "code": null, "e": 9712, "s": 9698, "text": "Linear Search" }, { "code": null, "e": 9768, "s": 9712, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 9816, "s": 9768, "text": "Search an element in a sorted and rotated array" } ]
Method Class | getAnnotation() method in Java
05 Dec, 2018 The java.lang.reflect.Method.getAnnotation(Class< T > annotationClass) method of Method class returns Method objects’s annotation for the specified type passed as parameter if such an annotation is present, else null. This is important method to get annotation for Method object. Syntax: public <T extends Annotation> T getAnnotation(Class<T> annotationClass) Parameter: This method takes a mandatory parameter annotationClass which is the Class object of the annotation type. Return Value: This method returns the method’s annotation for the specified annotation type if present on this element, else null. Exception: This method throws NullPointerException if the given annotation class is null Below program illustrates getAnnotation(Class annotationClass) method of Method class: Example 1: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class. In thi,s example a single class is used and class contains both methods which are main method and method with annotation. // Program Demonstrate getAnnotation(Class<T> annotationClass) method// of Method Class. import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // create a custom Annotation@Retention(RetentionPolicy.RUNTIME)@interface Annotation { // This annotation has two attributes. public String key(); public String value();} // create the Main Classpublic class GFG { // call Annotation for method and pass values for annotation @Annotation(key = "AvengersLeader", value = "CaptainAmerica") public static void getCustomAnnotation() { try { // create class object for class name GFG Class c = GFG.class; // get method name getCustomAnnotation as Method object Method[] methods = c.getMethods(); Method method = null; for (Method m : methods) { if (m.getName().equals("getCustomAnnotation")) method = m; } // get Annotation of Method object m by passing // Annotation class object as parameter Annotation anno = method.getAnnotation(Annotation.class); // print Annotation Details System.out.println("Annotation for Method Object" + " having name: " + method.getName()); System.out.println("Key Attribute of Annotation: " + anno.key()); System.out.println("Value Attribute of Annotation: " + anno.value()); } catch (Exception e) { e.printStackTrace(); } } // create main method public static void main(String args[]) { getCustomAnnotation(); }} Annotation for Method Object having name: getCustomAnnotation Key Attribute of Annotation: AvengersLeader Value Attribute of Annotation: CaptainAmerica Example 2: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class. In this example a two classes is used.One class contains main method which creates the method object and applying getAnnotation() method and other class contains method with some annotation. // Program Demonstrate getAnnotation(Class<T> annotationClass) method// of Method Class. import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; public class GFG { public static void main(String[] args) { // get array Method objects Method[] methods = GFGDemoClass.class.getMethods(); // get Annotation SelfCreatedAnnotation annotation = methods[0] .getAnnotation( SelfCreatedAnnotation .class); // Print annotation attribute System.out.println("key: " + annotation.key()); System.out.println("value: " + annotation.value()); }} // Another class on which we want to apply the annotationclass GFGDemoClass { private String field; // create annotation @SelfCreatedAnnotation(key = "getField", value = "getting field attribute") public String getField() { return field; }} // create custom annotation having two values@Retention(RetentionPolicy.RUNTIME)@interface SelfCreatedAnnotation { public String key(); public String value();} key: getField value: getting field attribute Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getAnnotation-java.lang.Class- 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2018" }, { "code": null, "e": 308, "s": 28, "text": "The java.lang.reflect.Method.getAnnotation(Class< T > annotationClass) method of Method class returns Method objects’s annotation for the specified type passed as parameter if such an annotation is present, else null. This is important method to get annotation for Method object." }, { "code": null, "e": 316, "s": 308, "text": "Syntax:" }, { "code": null, "e": 388, "s": 316, "text": "public <T extends Annotation> T getAnnotation(Class<T> annotationClass)" }, { "code": null, "e": 505, "s": 388, "text": "Parameter: This method takes a mandatory parameter annotationClass which is the Class object of the annotation type." }, { "code": null, "e": 636, "s": 505, "text": "Return Value: This method returns the method’s annotation for the specified annotation type if present on this element, else null." }, { "code": null, "e": 725, "s": 636, "text": "Exception: This method throws NullPointerException if the given annotation class is null" }, { "code": null, "e": 812, "s": 725, "text": "Below program illustrates getAnnotation(Class annotationClass) method of Method class:" }, { "code": null, "e": 1008, "s": 812, "text": "Example 1: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class." }, { "code": null, "e": 1130, "s": 1008, "text": "In thi,s example a single class is used and class contains both methods which are main method and method with annotation." }, { "code": "// Program Demonstrate getAnnotation(Class<T> annotationClass) method// of Method Class. import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // create a custom Annotation@Retention(RetentionPolicy.RUNTIME)@interface Annotation { // This annotation has two attributes. public String key(); public String value();} // create the Main Classpublic class GFG { // call Annotation for method and pass values for annotation @Annotation(key = \"AvengersLeader\", value = \"CaptainAmerica\") public static void getCustomAnnotation() { try { // create class object for class name GFG Class c = GFG.class; // get method name getCustomAnnotation as Method object Method[] methods = c.getMethods(); Method method = null; for (Method m : methods) { if (m.getName().equals(\"getCustomAnnotation\")) method = m; } // get Annotation of Method object m by passing // Annotation class object as parameter Annotation anno = method.getAnnotation(Annotation.class); // print Annotation Details System.out.println(\"Annotation for Method Object\" + \" having name: \" + method.getName()); System.out.println(\"Key Attribute of Annotation: \" + anno.key()); System.out.println(\"Value Attribute of Annotation: \" + anno.value()); } catch (Exception e) { e.printStackTrace(); } } // create main method public static void main(String args[]) { getCustomAnnotation(); }}", "e": 2904, "s": 1130, "text": null }, { "code": null, "e": 3057, "s": 2904, "text": "Annotation for Method Object having name: getCustomAnnotation\nKey Attribute of Annotation: AvengersLeader\nValue Attribute of Annotation: CaptainAmerica\n" }, { "code": null, "e": 3253, "s": 3057, "text": "Example 2: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class." }, { "code": null, "e": 3444, "s": 3253, "text": "In this example a two classes is used.One class contains main method which creates the method object and applying getAnnotation() method and other class contains method with some annotation." }, { "code": "// Program Demonstrate getAnnotation(Class<T> annotationClass) method// of Method Class. import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; public class GFG { public static void main(String[] args) { // get array Method objects Method[] methods = GFGDemoClass.class.getMethods(); // get Annotation SelfCreatedAnnotation annotation = methods[0] .getAnnotation( SelfCreatedAnnotation .class); // Print annotation attribute System.out.println(\"key: \" + annotation.key()); System.out.println(\"value: \" + annotation.value()); }} // Another class on which we want to apply the annotationclass GFGDemoClass { private String field; // create annotation @SelfCreatedAnnotation(key = \"getField\", value = \"getting field attribute\") public String getField() { return field; }} // create custom annotation having two values@Retention(RetentionPolicy.RUNTIME)@interface SelfCreatedAnnotation { public String key(); public String value();}", "e": 4713, "s": 3444, "text": null }, { "code": null, "e": 4759, "s": 4713, "text": "key: getField\nvalue: getting field attribute\n" }, { "code": null, "e": 4873, "s": 4759, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getAnnotation-java.lang.Class-" }, { "code": null, "e": 4888, "s": 4873, "text": "Java-Functions" }, { "code": null, "e": 4906, "s": 4888, "text": "Java-lang package" }, { "code": null, "e": 4932, "s": 4906, "text": "java-lang-reflect-package" }, { "code": null, "e": 4950, "s": 4932, "text": "Java-Method Class" }, { "code": null, "e": 4955, "s": 4950, "text": "Java" }, { "code": null, "e": 4960, "s": 4955, "text": "Java" } ]
Time Series - Moving Average
For a stationary time series, a moving average model sees the value of a variable at time β€˜t’ as a linear function of residual errors from β€˜q’ time steps preceding it. The residual error is calculated by comparing the value at the time β€˜t’ to moving average of the values preceding. Mathematically it can be written as βˆ’ yt=c+Ξ΅t+ΞΈ1Ξ΅tβˆ’1+ΞΈ2Ξ΅tβˆ’2+...+:ΞΈqΞ΅tβˆ’q Whereβ€˜q’ is the moving-average trend parameter Ξ΅t is white noise, and Ξ΅tβˆ’1,Ξ΅tβˆ’2...Ξ΅tβˆ’q are the error terms at previous time periods. Value of β€˜q’ can be calibrated using various methods. One way of finding the apt value of β€˜q’ is plotting the partial auto-correlation plot. A partial auto-correlation plot shows the relation of a variable with itself at prior time steps with indirect correlations removed, unlike auto-correlation plot which shows direct as well as indirect correlations, let’s see how it looks like for β€˜temperature’ variable of our data. Showing PACP In [143]: from statsmodels.graphics.tsaplots import plot_pacf plot_pacf(train, lags = 100) plt.show() A partial auto-correlation is read in the same way as a correlogram. Previous Page Print Page Next Page Advertisements Whereβ€˜q’ is the moving-average trend parameter Ξ΅t is white noise, and Ξ΅tβˆ’1,Ξ΅tβˆ’2...Ξ΅tβˆ’q are the error terms at previous time periods. Value of β€˜q’ can be calibrated using various methods. One way of finding the apt value of β€˜q’ is plotting the partial auto-correlation plot. A partial auto-correlation plot shows the relation of a variable with itself at prior time steps with indirect correlations removed, unlike auto-correlation plot which shows direct as well as indirect correlations, let’s see how it looks like for β€˜temperature’ variable of our data. In [143]: from statsmodels.graphics.tsaplots import plot_pacf plot_pacf(train, lags = 100) plt.show() A partial auto-correlation is read in the same way as a correlogram.
[ { "code": null, "e": 2558, "s": 2275, "text": "For a stationary time series, a moving average model sees the value of a variable at time β€˜t’ as a linear function of residual errors from β€˜q’ time steps preceding it. The residual error is calculated by comparing the value at the time β€˜t’ to moving average of the values preceding." }, { "code": null, "e": 2596, "s": 2558, "text": "Mathematically it can be written as βˆ’" }, { "code": null, "e": 3437, "s": 2596, "text": "yt=c+Ξ΅t+ΞΈ1Ξ΅tβˆ’1+ΞΈ2Ξ΅tβˆ’2+...+:ΞΈqΞ΅tβˆ’q\nWhereβ€˜q’ is the moving-average trend parameter\nΞ΅t is white noise, and\nΞ΅tβˆ’1,Ξ΅tβˆ’2...Ξ΅tβˆ’q are the error terms at previous time periods.\nValue of β€˜q’ can be calibrated using various methods. One way of finding the apt value of β€˜q’ is plotting the partial auto-correlation plot.\nA partial auto-correlation plot shows the relation of a variable with itself at prior time steps with indirect correlations removed, unlike auto-correlation plot which shows direct as well as indirect correlations, let’s see how it looks like for β€˜temperature’ variable of our data.\nShowing PACP\nIn [143]:\nfrom statsmodels.graphics.tsaplots import plot_pacf\n\nplot_pacf(train, lags = 100)\nplt.show()\n\n\nA partial auto-correlation is read in the same way as a correlogram.\n\n Previous Page\n Print Page\nNext Page \n\n\nAdvertisements\n\n\n\n\n\n" }, { "code": null, "e": 3484, "s": 3437, "text": "Whereβ€˜q’ is the moving-average trend parameter" }, { "code": null, "e": 3507, "s": 3484, "text": "Ξ΅t is white noise, and" }, { "code": null, "e": 3570, "s": 3507, "text": "Ξ΅tβˆ’1,Ξ΅tβˆ’2...Ξ΅tβˆ’q are the error terms at previous time periods." }, { "code": null, "e": 3711, "s": 3570, "text": "Value of β€˜q’ can be calibrated using various methods. One way of finding the apt value of β€˜q’ is plotting the partial auto-correlation plot." }, { "code": null, "e": 3994, "s": 3711, "text": "A partial auto-correlation plot shows the relation of a variable with itself at prior time steps with indirect correlations removed, unlike auto-correlation plot which shows direct as well as indirect correlations, let’s see how it looks like for β€˜temperature’ variable of our data." }, { "code": null, "e": 4004, "s": 3994, "text": "In [143]:" }, { "code": null, "e": 4098, "s": 4004, "text": "from statsmodels.graphics.tsaplots import plot_pacf\n\nplot_pacf(train, lags = 100)\nplt.show()\n" } ]
How to vertically center text with CSS ?
30 Jun, 2022 In this article, we will learn how to align the text vertically using CSS & Although CSS2 doesn’t support Vertical aligning. But, we can align the center blocks vertically, by combining a few properties. The trick is to specify the outer block to be formatted as a table cell because the contents of a table cell can be centered vertically. We will use the vertical-align property that specifies the vertical alignment of the table-box or inline element. Syntax: DIV.container { min-height: 10em; display: table-cell; vertical-align: middle } ... DIV { GeeksforGeeks } Example: This example describes the use of the vertical-align property along with the display property as table-cell. HTML <!DOCTYPE html><html> <head> <title>Horizontal and Vertical alignment</title> <style> div { height: 200px; width: 400px; border: 2px dashed #4b2869; } .container { min-height: 10em; display: table-cell; vertical-align: middle; } </style></head> <body> <div class="container">GeeksforGeeks</div></body> </html> Output: There is a more versatile approach to align text vertically.It will work for a single line as well as multiple lines of text, but it will still require a fixed height container. Syntax: div { height: 200px; line-height: 200px; text-align: center; border: 2px dashed #f69c55; } span { display: inline-block; vertical-align: middle; line-height: normal; } The CSS just sizes the div, vertically center aligns the span by setting the div’s line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block. Example: This example describes aligning the content vertically with a fixed height of the container. HTML <!DOCTYPE html><html> <head> <title> Horizontal and Vertical alignment </title> <style> div { height: 200px; line-height: 200px; text-align: center; border: 2px dashed #f69c55; } span { display: inline-block; vertical-align: middle; line-height: normal; } </style></head> <body> <div> <span>GeeksforGeeks</span> </div></body> </html> Output: CSS is the foundation of web pages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. bhaskargeeksforgeeks CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2022" }, { "code": null, "e": 483, "s": 28, "text": "In this article, we will learn how to align the text vertically using CSS & Although CSS2 doesn’t support Vertical aligning. But, we can align the center blocks vertically, by combining a few properties. The trick is to specify the outer block to be formatted as a table cell because the contents of a table cell can be centered vertically. We will use the vertical-align property that specifies the vertical alignment of the table-box or inline element." }, { "code": null, "e": 491, "s": 483, "text": "Syntax:" }, { "code": null, "e": 611, "s": 491, "text": "DIV.container {\n min-height: 10em;\n display: table-cell;\n vertical-align: middle }\n...\nDIV {\n GeeksforGeeks\n}" }, { "code": null, "e": 729, "s": 611, "text": "Example: This example describes the use of the vertical-align property along with the display property as table-cell." }, { "code": null, "e": 734, "s": 729, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Horizontal and Vertical alignment</title> <style> div { height: 200px; width: 400px; border: 2px dashed #4b2869; } .container { min-height: 10em; display: table-cell; vertical-align: middle; } </style></head> <body> <div class=\"container\">GeeksforGeeks</div></body> </html>", "e": 1119, "s": 734, "text": null }, { "code": null, "e": 1127, "s": 1119, "text": "Output:" }, { "code": null, "e": 1305, "s": 1127, "text": "There is a more versatile approach to align text vertically.It will work for a single line as well as multiple lines of text, but it will still require a fixed height container." }, { "code": null, "e": 1313, "s": 1305, "text": "Syntax:" }, { "code": null, "e": 1495, "s": 1313, "text": "div {\n height: 200px;\n line-height: 200px;\n text-align: center;\n border: 2px dashed #f69c55;\n}\nspan {\n display: inline-block;\n vertical-align: middle;\n line-height: normal;\n}" }, { "code": null, "e": 1787, "s": 1495, "text": "The CSS just sizes the div, vertically center aligns the span by setting the div’s line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block." }, { "code": null, "e": 1889, "s": 1787, "text": "Example: This example describes aligning the content vertically with a fixed height of the container." }, { "code": null, "e": 1894, "s": 1889, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Horizontal and Vertical alignment </title> <style> div { height: 200px; line-height: 200px; text-align: center; border: 2px dashed #f69c55; } span { display: inline-block; vertical-align: middle; line-height: normal; } </style></head> <body> <div> <span>GeeksforGeeks</span> </div></body> </html>", "e": 2321, "s": 1894, "text": null }, { "code": null, "e": 2329, "s": 2321, "text": "Output:" }, { "code": null, "e": 2517, "s": 2329, "text": "CSS is the foundation of web pages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 2538, "s": 2517, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2547, "s": 2538, "text": "CSS-Misc" }, { "code": null, "e": 2554, "s": 2547, "text": "Picked" }, { "code": null, "e": 2558, "s": 2554, "text": "CSS" }, { "code": null, "e": 2575, "s": 2558, "text": "Web Technologies" } ]
How to shuffle an array in Java?
Declare a string array and add elements in the form of letters βˆ’ String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" }; Convert the above array to list βˆ’ List<String>list = Arrays.asList(letters); Now, create a shuffled array using the Random class object and generate the random letters with nextInt() βˆ’ int len = list.size(); System.out.println("Shuffled array..."); for (int i = 0; i < letters.length; i++) { int index = new Random().nextInt(len); String shuffle = list.get(index); System.out.println(shuffle); } Live Demo import java.util.Arrays; import java.util.List; import java.util.Random; public class Demo { public static void main(String[] args) { String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" }; System.out.println("Initial array = "+Arrays.toString(letters)); List<String>list = Arrays.asList(letters); int len = list.size(); System.out.println("Shuffled array..."); for (int i = 0; i < letters.length; i++) { int index = new Random().nextInt(len); String shuffle = list.get(index); System.out.println(shuffle); } } } Initial array = [P, Q, R, S, T, U, V, W, X, Y, Z] Shuffled array... P X S X W S V R Y Q R
[ { "code": null, "e": 1252, "s": 1187, "text": "Declare a string array and add elements in the form of letters βˆ’" }, { "code": null, "e": 1329, "s": 1252, "text": "String[] letters = { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\",\"V\", \"W\", \"X\", \"Y\", \"Z\" };" }, { "code": null, "e": 1363, "s": 1329, "text": "Convert the above array to list βˆ’" }, { "code": null, "e": 1406, "s": 1363, "text": "List<String>list = Arrays.asList(letters);" }, { "code": null, "e": 1514, "s": 1406, "text": "Now, create a shuffled array using the Random class object and generate the random letters with nextInt() βˆ’" }, { "code": null, "e": 1734, "s": 1514, "text": "int len = list.size();\nSystem.out.println(\"Shuffled array...\");\nfor (int i = 0; i < letters.length; i++) {\n int index = new Random().nextInt(len);\n String shuffle = list.get(index);\n System.out.println(shuffle);\n}" }, { "code": null, "e": 1745, "s": 1734, "text": " Live Demo" }, { "code": null, "e": 2354, "s": 1745, "text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.Random;\npublic class Demo {\n public static void main(String[] args) {\n String[] letters = { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\",\"V\", \"W\", \"X\", \"Y\", \"Z\" };\n System.out.println(\"Initial array = \"+Arrays.toString(letters));\n List<String>list = Arrays.asList(letters);\n int len = list.size();\n System.out.println(\"Shuffled array...\");\n for (int i = 0; i < letters.length; i++) {\n int index = new Random().nextInt(len);\n String shuffle = list.get(index);\n System.out.println(shuffle);\n }\n }\n}" }, { "code": null, "e": 2444, "s": 2354, "text": "Initial array = [P, Q, R, S, T, U, V, W, X, Y, Z]\nShuffled array...\nP\nX\nS\nX\nW\nS\nV\nR\nY\nQ\nR" } ]
Remove Axis Labels and Ticks in ggplot2 Plot in R
24 Oct, 2021 In this article, we will discuss how to remove axis labels and ticks in ggplot2 in R Programming Language. The axes labels and ticks can be removed in ggplot using the theme() method. This method is basically used to modify the non-data components of the made plot. It gives the plot a good graphical customized look. The theme() method is used to work with the labels, ticks, and text of the plot made. The labels and ticks are aligned to the element_blank() method in order to remove them. Syntax : theme(axis.text.x = , axis.ticks.x = , axis.text.y = , axis.ticks.y = ) Arguments : axis.text.x , axis.text.y = tick labels along axes axis.ticks.x, axis.ticks.y = tick labels along axes R # creating data framecol1 = c(1: 10)col2 = c(11: 20) print("X coordinates")print(col1) print("Y coordinates")print(col2) # plotting the data framegraph < - ggplot(df, aes(x=col1, y=col2)) +geom_point() # removing axes labels and ticksgraph +theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) # printing the graphprint(graph) Output [1] "X coordinates" [1] 1 2 3 4 5 6 7 8 9 10 [1] "Y coordinates" [1] 11 12 13 14 15 16 17 18 19 20 Explanation: The x and y axes markings and tick marks have been removed from the graph by setting them to the element_blank() method. Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2021" }, { "code": null, "e": 135, "s": 28, "text": "In this article, we will discuss how to remove axis labels and ticks in ggplot2 in R Programming Language." }, { "code": null, "e": 520, "s": 135, "text": "The axes labels and ticks can be removed in ggplot using the theme() method. This method is basically used to modify the non-data components of the made plot. It gives the plot a good graphical customized look. The theme() method is used to work with the labels, ticks, and text of the plot made. The labels and ticks are aligned to the element_blank() method in order to remove them." }, { "code": null, "e": 530, "s": 520, "text": "Syntax : " }, { "code": null, "e": 602, "s": 530, "text": "theme(axis.text.x = , axis.ticks.x = , axis.text.y = , axis.ticks.y = )" }, { "code": null, "e": 615, "s": 602, "text": "Arguments : " }, { "code": null, "e": 667, "s": 615, "text": "axis.text.x , axis.text.y = tick labels along axes" }, { "code": null, "e": 720, "s": 667, "text": "axis.ticks.x, axis.ticks.y = tick labels along axes" }, { "code": null, "e": 722, "s": 720, "text": "R" }, { "code": "# creating data framecol1 = c(1: 10)col2 = c(11: 20) print(\"X coordinates\")print(col1) print(\"Y coordinates\")print(col2) # plotting the data framegraph < - ggplot(df, aes(x=col1, y=col2)) +geom_point() # removing axes labels and ticksgraph +theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) # printing the graphprint(graph)", "e": 1140, "s": 722, "text": null }, { "code": null, "e": 1147, "s": 1140, "text": "Output" }, { "code": null, "e": 1255, "s": 1147, "text": "[1] \"X coordinates\"\n[1] 1 2 3 4 5 6 7 8 9 10\n[1] \"Y coordinates\"\n[1] 11 12 13 14 15 16 17 18 19 20" }, { "code": null, "e": 1390, "s": 1255, "text": "Explanation: The x and y axes markings and tick marks have been removed from the graph by setting them to the element_blank() method. " }, { "code": null, "e": 1397, "s": 1390, "text": "Picked" }, { "code": null, "e": 1406, "s": 1397, "text": "R-ggplot" }, { "code": null, "e": 1417, "s": 1406, "text": "R Language" } ]
JavaScript | Replace() Method
02 Jun, 2022 The replace() method in JavaScript is used to replace the current page with another page. The Replace Method replaces the URL of the current window by the URL mention in the Replace method. Syntax: location.replace(URL) Parameter: This method accepts single parameter URL. The URL is the reference of other page which need to replace with older page. Return Value: This method returns or open the new page in window. Example: javascript <!DOCTYPE html><html> <head> <title>Redirect to Webpage</title> <style> body{ text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <h2>Replace Method</h2> <button onclick = "Replace()" >Replace with Gfg</button> <script> //Replace function that replace the current page. function Replace() { location.replace("https://www.geeksforgeeks.org/") } </script> </body></html> Output: Before clicking on the button: After clicking on the button: kumargaurav97520 javascript-functions Web technologies 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": "\n02 Jun, 2022" }, { "code": null, "e": 219, "s": 28, "text": "The replace() method in JavaScript is used to replace the current page with another page. The Replace Method replaces the URL of the current window by the URL mention in the Replace method. " }, { "code": null, "e": 227, "s": 219, "text": "Syntax:" }, { "code": null, "e": 249, "s": 227, "text": "location.replace(URL)" }, { "code": null, "e": 381, "s": 249, "text": "Parameter: This method accepts single parameter URL. The URL is the reference of other page which need to replace with older page. " }, { "code": null, "e": 448, "s": 381, "text": "Return Value: This method returns or open the new page in window. " }, { "code": null, "e": 458, "s": 448, "text": "Example: " }, { "code": null, "e": 469, "s": 458, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <head> <title>Redirect to Webpage</title> <style> body{ text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <h2>Replace Method</h2> <button onclick = \"Replace()\" >Replace with Gfg</button> <script> //Replace function that replace the current page. function Replace() { location.replace(\"https://www.geeksforgeeks.org/\") } </script> </body></html>", "e": 1166, "s": 469, "text": null }, { "code": null, "e": 1237, "s": 1166, "text": "Output: Before clicking on the button: After clicking on the button: " }, { "code": null, "e": 1256, "s": 1239, "text": "kumargaurav97520" }, { "code": null, "e": 1277, "s": 1256, "text": "javascript-functions" }, { "code": null, "e": 1294, "s": 1277, "text": "Web technologies" }, { "code": null, "e": 1305, "s": 1294, "text": "JavaScript" }, { "code": null, "e": 1322, "s": 1305, "text": "Web Technologies" } ]
Python VLC – Instance
29 Aug, 2020 In this article we will see how we can create a Instance class instance in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. In order to do this we will use vlc.Instance method Syntax : vlc.Instance() Argument : It takes no argument Return : It returns Instance object Below is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new("death_note.mkv") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Another exampleBelow is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new("1.mp4") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : Python vlc-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 500, "s": 28, "text": "In this article we will see how we can create a Instance class instance in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects." }, { "code": null, "e": 552, "s": 500, "text": "In order to do this we will use vlc.Instance method" }, { "code": null, "e": 576, "s": 552, "text": "Syntax : vlc.Instance()" }, { "code": null, "e": 608, "s": 576, "text": "Argument : It takes no argument" }, { "code": null, "e": 644, "s": 608, "text": "Return : It returns Instance object" }, { "code": null, "e": 672, "s": 644, "text": "Below is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new(\"death_note.mkv\") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)", "e": 1165, "s": 672, "text": null }, { "code": null, "e": 1174, "s": 1165, "text": "Output :" }, { "code": null, "e": 1217, "s": 1174, "text": "Another exampleBelow is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new mediamedia = player.media_new(\"1.mp4\") # creating a media player objectmedia_player = player.media_player_new() media_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)", "e": 1701, "s": 1217, "text": null }, { "code": null, "e": 1710, "s": 1701, "text": "Output :" }, { "code": null, "e": 1729, "s": 1710, "text": "Python vlc-library" }, { "code": null, "e": 1736, "s": 1729, "text": "Python" } ]
MoviePy – Setting Duration of the Clip
30 Aug, 2020 In this article we will see how we can set duration of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Duration is the time for which the clip get played increasing the duration make it repeat itself and decreasing duration will close the clip when duration is completed. In order to do this we will use set_duration method with the VideoFileClip object Syntax : clip.set_duration(n) Argument : It takes float value as argument Return : It returns VideoFileClip object Below is the implementation # Import everything needed to edit video clips from moviepy.editor import * # loading video dsa gfg intro video clip = VideoFileClip("dsa_geek.mp4") # getting only first 5 secondsclip = clip.subclip(0, 5) # new clip with new durationnew_clip = clip.set_duration(10) # new clip with new durationnew_clip.ipython_display(width = 360) Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting only first 2 secondsclip = clip.subclip(0, 2) # new clip with new durationnew_clip = clip.set_duration(6) # showing clip new_clip.ipython_display(width = 360) Output : Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2020" }, { "code": null, "e": 390, "s": 28, "text": "In this article we will see how we can set duration of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Duration is the time for which the clip get played increasing the duration make it repeat itself and decreasing duration will close the clip when duration is completed." }, { "code": null, "e": 472, "s": 390, "text": "In order to do this we will use set_duration method with the VideoFileClip object" }, { "code": null, "e": 502, "s": 472, "text": "Syntax : clip.set_duration(n)" }, { "code": null, "e": 546, "s": 502, "text": "Argument : It takes float value as argument" }, { "code": null, "e": 587, "s": 546, "text": "Return : It returns VideoFileClip object" }, { "code": null, "e": 615, "s": 587, "text": "Below is the implementation" }, { "code": "# Import everything needed to edit video clips from moviepy.editor import * # loading video dsa gfg intro video clip = VideoFileClip(\"dsa_geek.mp4\") # getting only first 5 secondsclip = clip.subclip(0, 5) # new clip with new durationnew_clip = clip.set_duration(10) # new clip with new durationnew_clip.ipython_display(width = 360)", "e": 959, "s": 615, "text": null }, { "code": null, "e": 968, "s": 959, "text": "Output :" }, { "code": null, "e": 1218, "s": 968, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting only first 2 secondsclip = clip.subclip(0, 2) # new clip with new durationnew_clip = clip.set_duration(6) # showing clip new_clip.ipython_display(width = 360) ", "e": 1521, "s": 1218, "text": null }, { "code": null, "e": 1530, "s": 1521, "text": "Output :" }, { "code": null, "e": 1972, "s": 1530, "text": "Moviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 1987, "s": 1972, "text": "Python-MoviePy" }, { "code": null, "e": 1994, "s": 1987, "text": "Python" } ]
Programmatically Specifying the Schema
The second method for creating DataFrame is through programmatic interface that allows you to construct a schema and then apply it to an existing RDD. We can create a DataFrame programmatically using the following three steps. Create an RDD of Rows from an Original RDD. Create an RDD of Rows from an Original RDD. Create the schema represented by a StructType matching the structure of Rows in the RDD created in Step 1. Create the schema represented by a StructType matching the structure of Rows in the RDD created in Step 1. Apply the schema to the RDD of Rows via createDataFrame method provided by SQLContext. Apply the schema to the RDD of Rows via createDataFrame method provided by SQLContext. Let us consider an example of employee records in a text file named employee.txt. Create a Schema using DataFrame directly by reading the data from text file. Given Data βˆ’ Look at the following data of a file named employee.txt placed in the current respective directory where the spark shell point is running. 1201, satish, 25 1202, krishna, 28 1203, amith, 39 1204, javed, 23 1205, prudvi, 23 Follow the steps given below to generate a schema programmatically. Start the Spark shell using following example. $ spark-shell Generate SQLContext using the following command. Here, sc means SparkContext object. scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc) Create an RDD DataFrame by reading a data from the text file named employee.txt using the following command. scala> val employee = sc.textFile("employee.txt") Use the following command for creating an encoded schema in a string format. That means, assume the field structure of a table and pass the field names using some delimiter. scala> val schemaString = "id name age" schemaString: String = id name age Use the following command to import Row capabilities and SQL DataTypes. scala> import org.apache.spark.sql.Row; scala> import org.apache.spark.sql.types.{StructType, StructField, StringType}; The following command is used to generate a schema by reading the schemaString variable. It means you need to read each field by splitting the whole string with space as a delimiter and take each field type is String type, by default. scala> val schema = StructType(schemaString.split(" ").map(fieldName β‡’ StructField(fieldName, StringType, true))) Use the following command to convert an RDD (employee) to Rows. It means, here we are specifying the logic for reading the RDD data and store it into rowRDD. Here we are using two map functions: one is a delimiter for splitting the record string (.map(_.split(","))) and the second map function for defining a Row with the field index value (.map(e β‡’ Row(e(0).trim.toInt, e(1), e(2).trim.toInt))). scala> val rowRDD = employee.map(_.split(",")).map(e β‡’ Row(e(0).trim.toInt, e(1), e(2).trim.toInt)) Use the following statement for creating a DataFrame using rowRDD data and schema (SCHEMA) variable. scala> val employeeDF = sqlContext.createDataFrame(rowRDD, schema) employeeDF: org.apache.spark.sql.DataFrame = [id: string, name: string, age: string] Use the following command to store the DataFrame into a table named employee. scala> employeeDF.registerTempTable("employee") The employee table is now ready. Let us pass some SQL queries into the table using the method SQLContext.sql(). Use the following statement for selecting all records from the employee table. Here we use the variable allrecords for capturing all records data. To display those records, call show() method on it. scala> val allrecords = sqlContext.sql("SELECT * FROM employee") To see the result data of allrecords DataFrame, use the following command. scala> allrecords.show() +------+--------+----+ | id | name |age | +------+--------+----+ | 1201 | satish | 25 | | 1202 | krishna| 28 | | 1203 | amith | 39 | | 1204 | javed | 23 | | 1205 | prudvi | 23 | +------+--------+----+ The method sqlContext.sql allows you to construct DataFrames when the columns and their types are not known until runtime. Now you can run different SQL queries into it. 46 Lectures 3.5 hours Arnab Chakraborty 31 Lectures 1 hours Frahaan Hussain 12 Lectures 1 hours Pranjal Srivastava 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1947, "s": 1720, "text": "The second method for creating DataFrame is through programmatic interface that allows you to construct a schema and then apply it to an existing RDD. We can create a DataFrame programmatically using the following three steps." }, { "code": null, "e": 1991, "s": 1947, "text": "Create an RDD of Rows from an Original RDD." }, { "code": null, "e": 2035, "s": 1991, "text": "Create an RDD of Rows from an Original RDD." }, { "code": null, "e": 2142, "s": 2035, "text": "Create the schema represented by a StructType matching the structure of Rows in the RDD created in Step 1." }, { "code": null, "e": 2249, "s": 2142, "text": "Create the schema represented by a StructType matching the structure of Rows in the RDD created in Step 1." }, { "code": null, "e": 2336, "s": 2249, "text": "Apply the schema to the RDD of Rows via createDataFrame method provided by SQLContext." }, { "code": null, "e": 2423, "s": 2336, "text": "Apply the schema to the RDD of Rows via createDataFrame method provided by SQLContext." }, { "code": null, "e": 2582, "s": 2423, "text": "Let us consider an example of employee records in a text file named employee.txt. Create a Schema using DataFrame directly by reading the data from text file." }, { "code": null, "e": 2734, "s": 2582, "text": "Given Data βˆ’ Look at the following data of a file named employee.txt placed in the current respective directory where the spark shell point is running." }, { "code": null, "e": 2819, "s": 2734, "text": "1201, satish, 25\n1202, krishna, 28\n1203, amith, 39\n1204, javed, 23\n1205, prudvi, 23\n" }, { "code": null, "e": 2887, "s": 2819, "text": "Follow the steps given below to generate a schema programmatically." }, { "code": null, "e": 2934, "s": 2887, "text": "Start the Spark shell using following example." }, { "code": null, "e": 2949, "s": 2934, "text": "$ spark-shell\n" }, { "code": null, "e": 3034, "s": 2949, "text": "Generate SQLContext using the following command. Here, sc means SparkContext object." }, { "code": null, "e": 3099, "s": 3034, "text": "scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)\n" }, { "code": null, "e": 3208, "s": 3099, "text": "Create an RDD DataFrame by reading a data from the text file named employee.txt using the following command." }, { "code": null, "e": 3259, "s": 3208, "text": "scala> val employee = sc.textFile(\"employee.txt\")\n" }, { "code": null, "e": 3433, "s": 3259, "text": "Use the following command for creating an encoded schema in a string format. That means, assume the field structure of a table and pass the field names using some delimiter." }, { "code": null, "e": 3474, "s": 3433, "text": "scala> val schemaString = \"id name age\"\n" }, { "code": null, "e": 3510, "s": 3474, "text": "schemaString: String = id name age\n" }, { "code": null, "e": 3582, "s": 3510, "text": "Use the following command to import Row capabilities and SQL DataTypes." }, { "code": null, "e": 3703, "s": 3582, "text": "scala> import org.apache.spark.sql.Row;\nscala> import org.apache.spark.sql.types.{StructType, StructField, StringType};\n" }, { "code": null, "e": 3938, "s": 3703, "text": "The following command is used to generate a schema by reading the schemaString variable. It means you need to read each field by splitting the whole string with space as a delimiter and take each field type is String type, by default." }, { "code": null, "e": 4053, "s": 3938, "text": "scala> val schema = StructType(schemaString.split(\" \").map(fieldName β‡’ StructField(fieldName, StringType, true)))\n" }, { "code": null, "e": 4451, "s": 4053, "text": "Use the following command to convert an RDD (employee) to Rows. It means, here we are specifying the logic for reading the RDD data and store it into rowRDD. Here we are using two map functions: one is a delimiter for splitting the record string (.map(_.split(\",\"))) and the second map function for defining a Row with the field index value (.map(e β‡’ Row(e(0).trim.toInt, e(1), e(2).trim.toInt)))." }, { "code": null, "e": 4552, "s": 4451, "text": "scala> val rowRDD = employee.map(_.split(\",\")).map(e β‡’ Row(e(0).trim.toInt, e(1), e(2).trim.toInt))\n" }, { "code": null, "e": 4653, "s": 4552, "text": "Use the following statement for creating a DataFrame using rowRDD data and schema (SCHEMA) variable." }, { "code": null, "e": 4721, "s": 4653, "text": "scala> val employeeDF = sqlContext.createDataFrame(rowRDD, schema)\n" }, { "code": null, "e": 4807, "s": 4721, "text": "employeeDF: org.apache.spark.sql.DataFrame = [id: string, name: string, age: string]\n" }, { "code": null, "e": 4885, "s": 4807, "text": "Use the following command to store the DataFrame into a table named employee." }, { "code": null, "e": 4934, "s": 4885, "text": "scala> employeeDF.registerTempTable(\"employee\")\n" }, { "code": null, "e": 5046, "s": 4934, "text": "The employee table is now ready. Let us pass some SQL queries into the table using the method SQLContext.sql()." }, { "code": null, "e": 5245, "s": 5046, "text": "Use the following statement for selecting all records from the employee table. Here we use the variable allrecords for capturing all records data. To display those records, call show() method on it." }, { "code": null, "e": 5311, "s": 5245, "text": "scala> val allrecords = sqlContext.sql(\"SELECT * FROM employee\")\n" }, { "code": null, "e": 5386, "s": 5311, "text": "To see the result data of allrecords DataFrame, use the following command." }, { "code": null, "e": 5412, "s": 5386, "text": "scala> allrecords.show()\n" }, { "code": null, "e": 5620, "s": 5412, "text": "+------+--------+----+\n| id | name |age |\n+------+--------+----+\n| 1201 | satish | 25 |\n| 1202 | krishna| 28 |\n| 1203 | amith | 39 |\n| 1204 | javed | 23 |\n| 1205 | prudvi | 23 |\n+------+--------+----+\n" }, { "code": null, "e": 5790, "s": 5620, "text": "The method sqlContext.sql allows you to construct DataFrames when the columns and their types are not known until runtime. Now you can run different SQL queries into it." }, { "code": null, "e": 5825, "s": 5790, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5844, "s": 5825, "text": " Arnab Chakraborty" }, { "code": null, "e": 5877, "s": 5844, "text": "\n 31 Lectures \n 1 hours \n" }, { "code": null, "e": 5894, "s": 5877, "text": " Frahaan Hussain" }, { "code": null, "e": 5927, "s": 5894, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 5947, "s": 5927, "text": " Pranjal Srivastava" }, { "code": null, "e": 5982, "s": 5947, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6003, "s": 5982, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 6038, "s": 6003, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6056, "s": 6038, "text": " Bigdata Engineer" }, { "code": null, "e": 6089, "s": 6056, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6107, "s": 6089, "text": " Bigdata Engineer" }, { "code": null, "e": 6114, "s": 6107, "text": " Print" }, { "code": null, "e": 6125, "s": 6114, "text": " Add Notes" } ]
Running Jupyter Notebook on WSL while Using Browser on Windows | by Ali Akbar Septiandri | Towards Data Science
If you are a data scientist like me who had just recently moved (back) into Windows, you might find it awkward to get things up and running, especially when you want to have the power of bash terminal at your disposal. You immediately realize that the price you pay for Macs might be really worth it. You get the best of both worlds: GUI-based apps that just work and CLI-based apps to speed up things. While using Windows subsystem for Linux (WSL) can help me get the good ol’ bash terminal working, it did not give the same ready-to-go experience on running Jupyter Notebook. I also missed the good terminals, like iTerm2 on Mac or Terminator on Ubuntu. You can find people use workarounds like Hyper, or even go back to the old tmux, but I found the former to be sluggish, while the latter is not as easy as iTerm2 or Terminator. In this post, I would like to introduce you to Windows Terminal. It’s simple, reasonably fast, and iTerm2-like. It’s good. You can install it from Microsoft Store. You might need to update your Windows first. Don’t worry, it’s worth the wait. Done? Disclaimer: I assume that you have already installed WSL with your favorite distro. If you haven’t, follow this guide. In this case, I am using Ubuntu 18.04. Next, open your Windows Terminal. By default, you should see Windows PowerShell. With Windows Terminal, you can open multiple tabs, switching from Windows PowerShell, Command Prompt, your WSL of choice, and even Azure Cloud Shell. If you want to make bash your default, then hit Ctrl+, or click the down chevron, then click β€œSettings”. Find β€œdefaultProfile” and change the value to the β€œguid” in β€œprofiles” > β€œdefaults” > β€œlist”. { "defaultProfile": "{c6eaf9f4-32a7-5fdc-b5cf-066e8a4b1e40}", ... "profiles": { "defaults": { ... }, "list": [ { "guid": "{c6eaf9f4-32a7-5fdc-b5cf-066e8a4b1e40}", "hidden": false, "name": "Ubuntu-18.04", "source": "Windows.Terminal.Wsl", "startingDirectory": "//wsl$/Ubuntu-18.04/home/<username>" }, ... ] }, ...} Notice that I also added the β€œstartingDirectory” to WSL. With the default settings, you can open a new pane by pressing Alt+Shift+D. Now you don’t need Hyper anymore, do you? I am assuming that you have installed Python and Jupyter Notebook as well here. If not, I recommend to install them using Anaconda. To remind you, this is to be installed in your WSL. Next, generate your notebook config by using the following command: jupyter notebook --generate-config You will then see a Python file in .jupyter folder. Edit them using your favorite text editor. code ~/.jupyter/jupyter_notebook_config.py Disable launching browser by redicect file by changing this line (default value is True): c.NotebookApp.use_redirect_file = False The good thing about WSL is that you can open Windows programs directly from bash. Thus, to get your Jupyter Notebook opens up a tab in your browser, you can add them as $BROWSER in bash. I am using Firefox here, but you can swap it with your own favorite browser. In other words, you can edit ~/.bashrc, and add the following line: export BROWSER='/mnt/c/Program Files/Mozilla Firefox/firefox.exe' Et voila! The /mnt/c means that you can access your files on Windows directly from bash! Pretty neat isn’t it? So, we are using Firefox on Windows in this case. There’s no need to install Firefox or even X11 on WSL. You can now start your notebook as you have it on Ubuntu or Mac. Hope you find this useful!
[ { "code": null, "e": 450, "s": 47, "text": "If you are a data scientist like me who had just recently moved (back) into Windows, you might find it awkward to get things up and running, especially when you want to have the power of bash terminal at your disposal. You immediately realize that the price you pay for Macs might be really worth it. You get the best of both worlds: GUI-based apps that just work and CLI-based apps to speed up things." }, { "code": null, "e": 945, "s": 450, "text": "While using Windows subsystem for Linux (WSL) can help me get the good ol’ bash terminal working, it did not give the same ready-to-go experience on running Jupyter Notebook. I also missed the good terminals, like iTerm2 on Mac or Terminator on Ubuntu. You can find people use workarounds like Hyper, or even go back to the old tmux, but I found the former to be sluggish, while the latter is not as easy as iTerm2 or Terminator. In this post, I would like to introduce you to Windows Terminal." }, { "code": null, "e": 1003, "s": 945, "text": "It’s simple, reasonably fast, and iTerm2-like. It’s good." }, { "code": null, "e": 1123, "s": 1003, "text": "You can install it from Microsoft Store. You might need to update your Windows first. Don’t worry, it’s worth the wait." }, { "code": null, "e": 1129, "s": 1123, "text": "Done?" }, { "code": null, "e": 1287, "s": 1129, "text": "Disclaimer: I assume that you have already installed WSL with your favorite distro. If you haven’t, follow this guide. In this case, I am using Ubuntu 18.04." }, { "code": null, "e": 1623, "s": 1287, "text": "Next, open your Windows Terminal. By default, you should see Windows PowerShell. With Windows Terminal, you can open multiple tabs, switching from Windows PowerShell, Command Prompt, your WSL of choice, and even Azure Cloud Shell. If you want to make bash your default, then hit Ctrl+, or click the down chevron, then click β€œSettings”." }, { "code": null, "e": 1717, "s": 1623, "text": "Find β€œdefaultProfile” and change the value to the β€œguid” in β€œprofiles” > β€œdefaults” > β€œlist”." }, { "code": null, "e": 2210, "s": 1717, "text": "{ \"defaultProfile\": \"{c6eaf9f4-32a7-5fdc-b5cf-066e8a4b1e40}\", ... \"profiles\": { \"defaults\": { ... }, \"list\": [ { \"guid\": \"{c6eaf9f4-32a7-5fdc-b5cf-066e8a4b1e40}\", \"hidden\": false, \"name\": \"Ubuntu-18.04\", \"source\": \"Windows.Terminal.Wsl\", \"startingDirectory\": \"//wsl$/Ubuntu-18.04/home/<username>\" }, ... ] }, ...}" }, { "code": null, "e": 2267, "s": 2210, "text": "Notice that I also added the β€œstartingDirectory” to WSL." }, { "code": null, "e": 2385, "s": 2267, "text": "With the default settings, you can open a new pane by pressing Alt+Shift+D. Now you don’t need Hyper anymore, do you?" }, { "code": null, "e": 2569, "s": 2385, "text": "I am assuming that you have installed Python and Jupyter Notebook as well here. If not, I recommend to install them using Anaconda. To remind you, this is to be installed in your WSL." }, { "code": null, "e": 2637, "s": 2569, "text": "Next, generate your notebook config by using the following command:" }, { "code": null, "e": 2672, "s": 2637, "text": "jupyter notebook --generate-config" }, { "code": null, "e": 2767, "s": 2672, "text": "You will then see a Python file in .jupyter folder. Edit them using your favorite text editor." }, { "code": null, "e": 2810, "s": 2767, "text": "code ~/.jupyter/jupyter_notebook_config.py" }, { "code": null, "e": 2900, "s": 2810, "text": "Disable launching browser by redicect file by changing this line (default value is True):" }, { "code": null, "e": 2940, "s": 2900, "text": "c.NotebookApp.use_redirect_file = False" }, { "code": null, "e": 3273, "s": 2940, "text": "The good thing about WSL is that you can open Windows programs directly from bash. Thus, to get your Jupyter Notebook opens up a tab in your browser, you can add them as $BROWSER in bash. I am using Firefox here, but you can swap it with your own favorite browser. In other words, you can edit ~/.bashrc, and add the following line:" }, { "code": null, "e": 3339, "s": 3273, "text": "export BROWSER='/mnt/c/Program Files/Mozilla Firefox/firefox.exe'" }, { "code": null, "e": 3349, "s": 3339, "text": "Et voila!" }, { "code": null, "e": 3620, "s": 3349, "text": "The /mnt/c means that you can access your files on Windows directly from bash! Pretty neat isn’t it? So, we are using Firefox on Windows in this case. There’s no need to install Firefox or even X11 on WSL. You can now start your notebook as you have it on Ubuntu or Mac." } ]
AngularJS | ng-maxlength Directive - GeeksforGeeks
26 Mar, 2019 The ng-maxlength Directive in AngularJS is used to set the maximum length for an input field i.e it adds the restriction for an input field. It is different from maxlength attribute in HTML because the former prevent users from exceeding the limit whereas the later doesn’t do that. It will make the form invalid if the input limit exceeds. Syntax: <element ng-maxlength="expression"> Contents... </element> Where expression is a number denoting the maximum limit upto which the input is valid. Example: This example uses ng-maxlength Directive to check the maximum length of string. <!DOCTYPE html><html> <head> <title>ng-maxlength Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body style="text-align: center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-maxlength Directive</h2> <div ng-app="app" ng-controller="geek"> <form name="maxlen" novalidate ng-submit= "maxlen.$valid &&maxlength()"> <pre>Atmax 5 characters required</pre> Input: <input type="text" name="code" ng-model="txt" ng-maxlength="5" required /> <br><br> <button type="submit">Click it</button> <br><br> <span>{{msg}}</span> </form> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.maxlength = function () { $scope.msg = "Input is valid"; }; }); </script></body> </html> Output:Before clicking the button:After clicking the button: AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? How to set focus on input field automatically on page load in AngularJS ? Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 24585, "s": 24557, "text": "\n26 Mar, 2019" }, { "code": null, "e": 24926, "s": 24585, "text": "The ng-maxlength Directive in AngularJS is used to set the maximum length for an input field i.e it adds the restriction for an input field. It is different from maxlength attribute in HTML because the former prevent users from exceeding the limit whereas the later doesn’t do that. It will make the form invalid if the input limit exceeds." }, { "code": null, "e": 24934, "s": 24926, "text": "Syntax:" }, { "code": null, "e": 24995, "s": 24934, "text": " <element ng-maxlength=\"expression\"> Contents... </element> " }, { "code": null, "e": 25082, "s": 24995, "text": "Where expression is a number denoting the maximum limit upto which the input is valid." }, { "code": null, "e": 25171, "s": 25082, "text": "Example: This example uses ng-maxlength Directive to check the maximum length of string." }, { "code": "<!DOCTYPE html><html> <head> <title>ng-maxlength Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body style=\"text-align: center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-maxlength Directive</h2> <div ng-app=\"app\" ng-controller=\"geek\"> <form name=\"maxlen\" novalidate ng-submit= \"maxlen.$valid &&maxlength()\"> <pre>Atmax 5 characters required</pre> Input: <input type=\"text\" name=\"code\" ng-model=\"txt\" ng-maxlength=\"5\" required /> <br><br> <button type=\"submit\">Click it</button> <br><br> <span>{{msg}}</span> </form> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.maxlength = function () { $scope.msg = \"Input is valid\"; }; }); </script></body> </html>", "e": 26277, "s": 25171, "text": null }, { "code": null, "e": 26338, "s": 26277, "text": "Output:Before clicking the button:After clicking the button:" }, { "code": null, "e": 26359, "s": 26338, "text": "AngularJS-Directives" }, { "code": null, "e": 26369, "s": 26359, "text": "AngularJS" }, { "code": null, "e": 26386, "s": 26369, "text": "Web Technologies" }, { "code": null, "e": 26484, "s": 26386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26528, "s": 26484, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26559, "s": 26528, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 26601, "s": 26559, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 26675, "s": 26601, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 26710, "s": 26675, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 26752, "s": 26710, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26785, "s": 26752, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26828, "s": 26785, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26890, "s": 26828, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
React Native - TouchableHighlight
We already mentioned touchable components in one of our previous chapters. This chapter will show you how to use TouchableHighlight component. We already done this in our previous chapters. We will create src/components/home/TouchableHighlight.js file. This is container component. We are passing buttonPressed function as a prop. src/components/home/HomeContainer.js import React, { Component } from 'react' import TouchableHighlightExample from './TouchableHighlightExample' export default class HomeContainer extends Component { constructor() { super(); } buttonPressed = () => { console.log('TouchableHighlight pressed...'); } render() { return ( <TouchableHighlightExample buttonPressed = {this.buttonPressed}/> ); } } This component is our button. underlayColor will be visible when button is pressed. src/components/home/TouchableHighlightExample.js import React, { Component } from 'react' import { View, TouchableHighlight, Text, StyleSheet } from 'react-native' export default TouchableHighlightExample = (props) => { return ( <View style = {styles.container}> <TouchableHighlight underlayColor = {'red'} onPress = {props.buttonPressed}> <Text style = {styles.button}> Button </Text> </TouchableHighlight> </View> ) } const styles = StyleSheet.create ({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, button: { borderWidth: 1, padding: 25, borderColor: 'black' } }) You can press the button to see red color. 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": 2487, "s": 2344, "text": "We already mentioned touchable components in one of our previous chapters. This chapter will show you how to use TouchableHighlight component." }, { "code": null, "e": 2597, "s": 2487, "text": "We already done this in our previous chapters. We will create src/components/home/TouchableHighlight.js file." }, { "code": null, "e": 2675, "s": 2597, "text": "This is container component. We are passing buttonPressed function as a prop." }, { "code": null, "e": 2712, "s": 2675, "text": "src/components/home/HomeContainer.js" }, { "code": null, "e": 3121, "s": 2712, "text": "import React, { Component } from 'react'\nimport TouchableHighlightExample from './TouchableHighlightExample'\n\nexport default class HomeContainer extends Component {\n\n constructor() {\n super();\n }\n buttonPressed = () => {\n console.log('TouchableHighlight pressed...');\n }\n render() {\n return (\n <TouchableHighlightExample buttonPressed = {this.buttonPressed}/>\n );\n }\n}" }, { "code": null, "e": 3205, "s": 3121, "text": "This component is our button. underlayColor will be visible when button is pressed." }, { "code": null, "e": 3254, "s": 3205, "text": "src/components/home/TouchableHighlightExample.js" }, { "code": null, "e": 3933, "s": 3254, "text": "import React, { Component } from 'react'\nimport {\n View,\n TouchableHighlight,\n Text,\n StyleSheet\n} from 'react-native'\n\nexport default TouchableHighlightExample = (props) => {\n return (\n <View style = {styles.container}>\n <TouchableHighlight underlayColor = {'red'} onPress = {props.buttonPressed}>\n <Text style = {styles.button}>\n Button\n </Text>\n </TouchableHighlight>\n </View>\n )\n}\n\nconst styles = StyleSheet.create ({\n container: {\n flex: 1,\n justifyContent: 'center',\n alignItems: 'center',\n },\n button: {\n borderWidth: 1,\n padding: 25,\n borderColor: 'black'\n }\n})" }, { "code": null, "e": 3976, "s": 3933, "text": "You can press the button to see red color." }, { "code": null, "e": 4011, "s": 3976, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4025, "s": 4011, "text": " Anadi Sharma" }, { "code": null, "e": 4060, "s": 4025, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4075, "s": 4060, "text": " A To Z Mentor" }, { "code": null, "e": 4110, "s": 4075, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4138, "s": 4110, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4174, "s": 4138, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4202, "s": 4174, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4237, "s": 4202, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4249, "s": 4237, "text": " Senol Atac" }, { "code": null, "e": 4284, "s": 4249, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4296, "s": 4284, "text": " Senol Atac" }, { "code": null, "e": 4303, "s": 4296, "text": " Print" }, { "code": null, "e": 4314, "s": 4303, "text": " Add Notes" } ]
Python String maketrans() Method - GeeksforGeeks
05 Oct, 2021 Python String maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted from the string. Syntax: maketrans(str1, str2, str3) Parameters: str1: Specifies the list of characters that need to be replaced. str2: Specifies the list of characters with which the characters need to be replaced. str3: Specifies the list of characters that need to be deleted. Returns: Returns the translation table which specifies the conversions that can be used by translate() To translate the characters in the string translate() is used to make the translations. This function uses the translation mapping specified using the maketrans(). Syntax: translate(table, delstr) Parameters: table: Translate mapping specified to perform translations. delstr: The delete string can be specified as optional argument is not mentioned in table. Returns: Returns the argument string after performing the translations using the translation table. Python3 # Python3 code to demonstrate# translations using# maketrans() and translate() # specify to translate charsstr1 = "wy" # specify to replace withstr2 = "gf" # delete charsstr3 = "u" # target stringtrg = "weeksyourweeks" # using maketrans() to# construct translate# tabletable = trg.maketrans(str1, str2, str3) # Printing original stringprint ("The string before translating is : ", end ="")print (trg) # using translate() to make translations.print ("The string after translating is : ", end ="")print (trg.translate(table)) Output: The string before translating is : weeksyourweeks The string after translating is : geeksforgeeks Python-Built-in-functions python-string Python-string-functions 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": "\n05 Oct, 2021" }, { "code": null, "e": 24508, "s": 24292, "text": "Python String maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted from the string." }, { "code": null, "e": 24516, "s": 24508, "text": "Syntax:" }, { "code": null, "e": 24544, "s": 24516, "text": "maketrans(str1, str2, str3)" }, { "code": null, "e": 24556, "s": 24544, "text": "Parameters:" }, { "code": null, "e": 24621, "s": 24556, "text": "str1: Specifies the list of characters that need to be replaced." }, { "code": null, "e": 24707, "s": 24621, "text": "str2: Specifies the list of characters with which the characters need to be replaced." }, { "code": null, "e": 24771, "s": 24707, "text": "str3: Specifies the list of characters that need to be deleted." }, { "code": null, "e": 24781, "s": 24771, "text": "Returns: " }, { "code": null, "e": 24875, "s": 24781, "text": "Returns the translation table which specifies the conversions that can be used by translate()" }, { "code": null, "e": 25039, "s": 24875, "text": "To translate the characters in the string translate() is used to make the translations. This function uses the translation mapping specified using the maketrans()." }, { "code": null, "e": 25047, "s": 25039, "text": "Syntax:" }, { "code": null, "e": 25072, "s": 25047, "text": "translate(table, delstr)" }, { "code": null, "e": 25084, "s": 25072, "text": "Parameters:" }, { "code": null, "e": 25144, "s": 25084, "text": "table: Translate mapping specified to perform translations." }, { "code": null, "e": 25235, "s": 25144, "text": "delstr: The delete string can be specified as optional argument is not mentioned in table." }, { "code": null, "e": 25335, "s": 25235, "text": "Returns: Returns the argument string after performing the translations using the translation table." }, { "code": null, "e": 25343, "s": 25335, "text": "Python3" }, { "code": "# Python3 code to demonstrate# translations using# maketrans() and translate() # specify to translate charsstr1 = \"wy\" # specify to replace withstr2 = \"gf\" # delete charsstr3 = \"u\" # target stringtrg = \"weeksyourweeks\" # using maketrans() to# construct translate# tabletable = trg.maketrans(str1, str2, str3) # Printing original stringprint (\"The string before translating is : \", end =\"\")print (trg) # using translate() to make translations.print (\"The string after translating is : \", end =\"\")print (trg.translate(table))", "e": 25874, "s": 25343, "text": null }, { "code": null, "e": 25882, "s": 25874, "text": "Output:" }, { "code": null, "e": 25980, "s": 25882, "text": "The string before translating is : weeksyourweeks\nThe string after translating is : geeksforgeeks" }, { "code": null, "e": 26006, "s": 25980, "text": "Python-Built-in-functions" }, { "code": null, "e": 26020, "s": 26006, "text": "python-string" }, { "code": null, "e": 26044, "s": 26020, "text": "Python-string-functions" }, { "code": null, "e": 26051, "s": 26044, "text": "Python" }, { "code": null, "e": 26149, "s": 26051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26158, "s": 26149, "text": "Comments" }, { "code": null, "e": 26171, "s": 26158, "text": "Old Comments" }, { "code": null, "e": 26203, "s": 26171, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26259, "s": 26203, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26314, "s": 26259, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26356, "s": 26314, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26398, "s": 26356, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26429, "s": 26398, "text": "Python | os.path.join() method" }, { "code": null, "e": 26468, "s": 26429, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26490, "s": 26468, "text": "Defaultdict in Python" }, { "code": null, "e": 26519, "s": 26490, "text": "Create a directory in Python" } ]
Python - Reading RSS feed
RSS (Rich Site Summary) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it. In python we take help of the below package to read and process these feeds. pip install feedparser In the below example we get the structure of the feed so that we can analyse further about which parts of the feed we want to process. import feedparser NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms") entry = NewsFeed.entries[1] print entry.keys() When we run the above program, we get the following output βˆ’ ['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id'] In the below example we read the title and head of the rss feed. import feedparser NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms") print 'Number of RSS posts :', len(NewsFeed.entries) entry = NewsFeed.entries[1] print 'Post Title :',entry.title When we run the above program we get the following output βˆ’ Number of RSS posts : 5 Post Title : Cong-JD(S) in SC over choice of pro tem speaker Based on above entry structure we can derive the necessary details from the feed using python program as shown below. As entry is a dictionary we utilise its keys to produce the values needed. import feedparser NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms") entry = NewsFeed.entries[1] print entry.published print "******" print entry.summary print "------News Link--------" print entry.link When we run the above program we get the following output βˆ’ Fri, 18 May 2018 20:13:13 GMT ****** Controversy erupted on Friday over the appointment of BJP MLA K G Bopaiah as pro tem speaker for the assembly, with Congress and JD(S) claiming the move went against convention that the post should go to the most senior member of the House. The combine approached the SC to challenge the appointment. Hearing is scheduled for 10:30 am today. ------News Link-------- https://timesofindia.indiatimes.com/india/congress-jds-in-sc-over-bjp-mla-made-pro-tem-speaker-hearing-at-1030-am/articleshow/64228740.cms 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2869, "s": 2587, "text": "RSS (Rich Site Summary) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it. In python we take help of the below package to read and process these feeds. " }, { "code": null, "e": 2892, "s": 2869, "text": "pip install feedparser" }, { "code": null, "e": 3027, "s": 2892, "text": "In the below example we get the structure of the feed so that we can analyse further about which parts of the feed we want to process." }, { "code": null, "e": 3183, "s": 3027, "text": "import feedparser\nNewsFeed = feedparser.parse(\"https://timesofindia.indiatimes.com/rssfeedstopstories.cms\")\nentry = NewsFeed.entries[1]\n\nprint entry.keys()" }, { "code": null, "e": 3244, "s": 3183, "text": "When we run the above program, we get the following output βˆ’" }, { "code": null, "e": 3370, "s": 3244, "text": "['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id']\n" }, { "code": null, "e": 3436, "s": 3370, "text": " In the below example we read the title and head of the rss feed." }, { "code": null, "e": 3661, "s": 3436, "text": "import feedparser\n\nNewsFeed = feedparser.parse(\"https://timesofindia.indiatimes.com/rssfeedstopstories.cms\")\n\nprint 'Number of RSS posts :', len(NewsFeed.entries)\n\nentry = NewsFeed.entries[1]\nprint 'Post Title :',entry.title" }, { "code": null, "e": 3721, "s": 3661, "text": "When we run the above program we get the following output βˆ’" }, { "code": null, "e": 3807, "s": 3721, "text": "Number of RSS posts : 5\nPost Title : Cong-JD(S) in SC over choice of pro tem speaker\n" }, { "code": null, "e": 4002, "s": 3807, "text": "Based on above entry structure we can derive the necessary details from the feed using python program as shown below. As entry is a dictionary we utilise its keys to produce the values needed. " }, { "code": null, "e": 4247, "s": 4002, "text": "import feedparser\n\nNewsFeed = feedparser.parse(\"https://timesofindia.indiatimes.com/rssfeedstopstories.cms\")\n\nentry = NewsFeed.entries[1]\n\nprint entry.published\nprint \"******\"\nprint entry.summary\nprint \"------News Link--------\"\nprint entry.link" }, { "code": null, "e": 4307, "s": 4247, "text": "When we run the above program we get the following output βˆ’" }, { "code": null, "e": 4850, "s": 4307, "text": "Fri, 18 May 2018 20:13:13 GMT\n******\nControversy erupted on Friday over the appointment of BJP MLA K G Bopaiah as pro tem speaker for the assembly, with Congress and JD(S) claiming the move went against convention that the post should go to the most senior member of the House. The combine approached the SC to challenge the appointment. Hearing is scheduled for 10:30 am today.\n------News Link--------\nhttps://timesofindia.indiatimes.com/india/congress-jds-in-sc-over-bjp-mla-made-pro-tem-speaker-hearing-at-1030-am/articleshow/64228740.cms\n" }, { "code": null, "e": 4887, "s": 4850, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4903, "s": 4887, "text": " Malhar Lathkar" }, { "code": null, "e": 4936, "s": 4903, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4955, "s": 4936, "text": " Arnab Chakraborty" }, { "code": null, "e": 4990, "s": 4955, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5012, "s": 4990, "text": " In28Minutes Official" }, { "code": null, "e": 5046, "s": 5012, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5074, "s": 5046, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5109, "s": 5074, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5123, "s": 5109, "text": " Lets Kode It" }, { "code": null, "e": 5156, "s": 5123, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5173, "s": 5156, "text": " Abhilash Nelson" }, { "code": null, "e": 5180, "s": 5173, "text": " Print" }, { "code": null, "e": 5191, "s": 5180, "text": " Add Notes" } ]
How can we take a backup of a particular table from a database by using mysqldump client program?
By using mysql dump client program we can take the backup of a particular table from the databases into a file having the extension β€˜.sql’. It can be understood with the help of the following example βˆ’ In this example, with the help of mysql dump client program, we are taking the backup of a table named β€˜student_info’ from β€˜query’ database in a file named β€˜student_info.sql’. The following command will do this: C:\mysql\bin>mysqldump -u root query student_info > student_info.sql The above command will create a file named student_info.sql which has the dump information of a file named β€˜student_info’ from database named β€˜query’.
[ { "code": null, "e": 1264, "s": 1062, "text": "By using mysql dump client program we can take the backup of a particular table from the databases into a file having the extension β€˜.sql’. It can be understood with the help of the following example βˆ’" }, { "code": null, "e": 1476, "s": 1264, "text": "In this example, with the help of mysql dump client program, we are taking the backup of a table named β€˜student_info’ from β€˜query’ database in a file named β€˜student_info.sql’. The following command will do this:" }, { "code": null, "e": 1545, "s": 1476, "text": "C:\\mysql\\bin>mysqldump -u root query student_info > student_info.sql" }, { "code": null, "e": 1696, "s": 1545, "text": "The above command will create a file named student_info.sql which has the dump information of a file named β€˜student_info’ from database named β€˜query’." } ]
Espresso Testing Framework - WebView
WebView is a special view provided by android to display web pages inside the application. WebView does not provide all the features of a full-fledged browser application like chrome and firefox. However, it provides complete control over the content to be shown and exposes all the android features to be invoked inside the web pages. It enables WebView and provides a special environment where the UI can be easily designed using HTML technology and native features like camera and dial a contact. This feature set enables a WebView to provide a new kind of application called Hybrid application, where the UI is done in HTML and business logic is done in either JavaScript or through an external API endpoint. Normally, testing a WebView needs to be a challenge because it uses HTML technology for its user interface elements rather than native user interface/views. Espresso excels in this area by providing a new set to web matchers and web assertions, which is intentionally similar to native view matchers and view assertions. At the same time, it provides a wellbalanced approach by including a web technology based testing environment as well. Espresso web is built upon WebDriver Atom framework, which is used to find and manipulate web elements. Atom is similar to view actions. Atom will do all the interaction inside a web page. WebDriver exposes a predefined set of methods, like findElement(), getElement() to find web elements and returns the corresponding atoms (to do action in the web page). A standard web testing statement looks like the below code, onWebView() .withElement(Atom) .perform(Atom) .check(WebAssertion) Here, onWebView() βˆ’ Similar to onView(), it exposes a set of API to test a WebView. onWebView() βˆ’ Similar to onView(), it exposes a set of API to test a WebView. withElement() βˆ’ One of the several methods used to locate web elements inside a web page using Atom and returns WebInteration object, which is similar to ViewInteraction. withElement() βˆ’ One of the several methods used to locate web elements inside a web page using Atom and returns WebInteration object, which is similar to ViewInteraction. perform() βˆ’ Executes the action inside a web page using Atom and returns WebInteraction. perform() βˆ’ Executes the action inside a web page using Atom and returns WebInteraction. check() βˆ’ This does the necessary assertion using WebAssertion. check() βˆ’ This does the necessary assertion using WebAssertion. A sample web testing code is as follows, onWebView() .withElement(findElement(Locator.ID, "apple")) .check(webMatches(getText(), containsString("Apple"))) Here, findElement() locate a element and returns an Atom findElement() locate a element and returns an Atom webMatches is similar to matches method webMatches is similar to matches method Let us write a simple application based on WebView and write a test case using the onWebView() method. Follow these steps to write a sample application βˆ’ Start Android studio. Start Android studio. Create new project as discussed earlier and name it, MyWebViewApp. Create new project as discussed earlier and name it, MyWebViewApp. Migrate the application to AndroidX framework using Refactor β†’ Migrate to AndroidX option menu. Migrate the application to AndroidX framework using Refactor β†’ Migrate to AndroidX option menu. Add the below configuration option in the AndroidManifest.xml file to give permission to access Internet. Add the below configuration option in the AndroidManifest.xml file to give permission to access Internet. <uses-permission android:name = "android.permission.INTERNET" /> Espresso web is provided as a separate plugin. So, add the dependency in the app/build.gradle and sync it. Espresso web is provided as a separate plugin. So, add the dependency in the app/build.gradle and sync it. dependencies { androidTestImplementation 'androidx.test:rules:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.1' } Remove default design in the main activity and add WebView. The content of the activity_main.xml is as follows, Remove default design in the main activity and add WebView. The content of the activity_main.xml is as follows, <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <WebView android:id = "@+id/web_view_test" android:layout_width = "fill_parent" android:layout_height = "fill_parent" /> </RelativeLayout> Create a new class, ExtendedWebViewClient extending WebViewClient and override shouldOverrideUrlLoading method to load link action in the same WebView; otherwise, it will open a new browser window outside the application. Place it in MainActivity.java. Create a new class, ExtendedWebViewClient extending WebViewClient and override shouldOverrideUrlLoading method to load link action in the same WebView; otherwise, it will open a new browser window outside the application. Place it in MainActivity.java. private class ExtendedWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } Now, add the below code in the onCreate method of MainActivity. The purpose of the code is to find the WebView, properly configure it and then finally load the target url. Now, add the below code in the onCreate method of MainActivity. The purpose of the code is to find the WebView, properly configure it and then finally load the target url. // Find web view WebView webView = (WebView) findViewById(R.id.web_view_test); // set web view client webView.setWebViewClient(new ExtendedWebViewClient()); // Clear cache webView.clearCache(true); // load Url webView.loadUrl("http://<your domain or IP>/index.html"); Here, The content of index.html is as follows βˆ’ The content of index.html is as follows βˆ’ <html> <head> <title>Android Web View Sample</title> </head> <body> <h1>Fruits</h1> <ol> <li><a href = "apple.html" id = "apple">Apple</a></li> <li><a href = "banana.html" id = "banana">Banana</a></li> </ol> </body> </html> The content of the apple.html file referred in index.html is as follows βˆ’ The content of the apple.html file referred in index.html is as follows βˆ’ <html> <head> <title>Android Web View Sample</title> </head> <body> <h1>Apple</h1> </body> </html> The content of the banana.html file referred in banana.html is as follows, The content of the banana.html file referred in banana.html is as follows, <html> <head> <title>Android Web View Sample</title> </head> <body> <h1>Banana</h1> </body> </html> Place index.html, apple.html and banana.html in a web server Place index.html, apple.html and banana.html in a web server Replace the url in loadUrl method with your configured url. Replace the url in loadUrl method with your configured url. Now, run the application and manually check if everything is fine. Below is the screenshot of the WebView sample application βˆ’ Now, run the application and manually check if everything is fine. Below is the screenshot of the WebView sample application βˆ’ Now, open the ExampleInstrumentedTest.java file and add the below rule βˆ’ Now, open the ExampleInstrumentedTest.java file and add the below rule βˆ’ @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<MainActivity>(MainActivity.class, false, true) { @Override protected void afterActivityLaunched() { onWebView(withId(R.id.web_view_test)).forceJavascriptEnabled(); } }; Here, we found the WebView and enabled JavaScript of the WebView because espresso web testing framework works exclusively through JavaScript engine to identify and manipulate web element. Now, add the test case to test our WebView and its behavior. Now, add the test case to test our WebView and its behavior. @Test public void webViewTest(){ onWebView() .withElement(findElement(Locator.ID, "apple")) .check(webMatches(getText(), containsString("Apple"))) .perform(webClick()) .withElement(findElement(Locator.TAG_NAME, "h1")) .check(webMatches(getText(), containsString("Apple"))); } Here, the testing was done in the following order, found the link, apple using its id attribute through findElement() method and Locator.ID enumeration. found the link, apple using its id attribute through findElement() method and Locator.ID enumeration. checks the text of the link using webMatches() method checks the text of the link using webMatches() method performs click action on the link. It opens the apple.html page. performs click action on the link. It opens the apple.html page. again found the h1 element using findElement() methods and Locator.TAG_NAME enumeration. again found the h1 element using findElement() methods and Locator.TAG_NAME enumeration. finally again checks the text of the h1 tag using webMatches() method. finally again checks the text of the h1 tag using webMatches() method. Finally, run the test case using android studio context menu. Finally, run the test case using android studio context menu. 17 Lectures 1.5 hours Anuja Jain Print Add Notes Bookmark this page
[ { "code": null, "e": 2689, "s": 1976, "text": "WebView is a special view provided by android to display web pages inside the application. WebView does not provide all the features of a full-fledged browser application like chrome and firefox. However, it provides complete control over the content to be shown and exposes all the android features to be invoked inside the web pages. It enables WebView and provides a special environment where the UI can be easily designed using HTML technology and native features like camera and dial a contact. This feature set enables a WebView to provide a new kind of application called Hybrid application, where the UI is done in HTML and business logic is done in either JavaScript or through an external API endpoint." }, { "code": null, "e": 3129, "s": 2689, "text": "Normally, testing a WebView needs to be a challenge because it uses HTML technology for its user interface elements rather than native user interface/views. Espresso excels in this area by providing a new set to web matchers and web assertions, which is intentionally similar to native view matchers and view assertions. At the same time, it provides a wellbalanced approach by including a web technology based testing environment as well." }, { "code": null, "e": 3487, "s": 3129, "text": "Espresso web is built upon WebDriver Atom framework, which is used to find and manipulate web elements. Atom is similar to view actions. Atom will do all the interaction inside a web page. WebDriver exposes a predefined set of methods, like findElement(), getElement() to find web elements and returns the corresponding atoms (to do action in the web page)." }, { "code": null, "e": 3547, "s": 3487, "text": "A standard web testing statement looks like the below code," }, { "code": null, "e": 3624, "s": 3547, "text": "onWebView()\n .withElement(Atom)\n .perform(Atom)\n .check(WebAssertion)\n" }, { "code": null, "e": 3630, "s": 3624, "text": "Here," }, { "code": null, "e": 3708, "s": 3630, "text": "onWebView() βˆ’ Similar to onView(), it exposes a set of API to test a WebView." }, { "code": null, "e": 3786, "s": 3708, "text": "onWebView() βˆ’ Similar to onView(), it exposes a set of API to test a WebView." }, { "code": null, "e": 3957, "s": 3786, "text": "withElement() βˆ’ One of the several methods used to locate web elements inside a web page using Atom and returns WebInteration object, which is similar to ViewInteraction." }, { "code": null, "e": 4128, "s": 3957, "text": "withElement() βˆ’ One of the several methods used to locate web elements inside a web page using Atom and returns WebInteration object, which is similar to ViewInteraction." }, { "code": null, "e": 4217, "s": 4128, "text": "perform() βˆ’ Executes the action inside a web page using Atom and returns WebInteraction." }, { "code": null, "e": 4306, "s": 4217, "text": "perform() βˆ’ Executes the action inside a web page using Atom and returns WebInteraction." }, { "code": null, "e": 4370, "s": 4306, "text": "check() βˆ’ This does the necessary assertion using WebAssertion." }, { "code": null, "e": 4434, "s": 4370, "text": "check() βˆ’ This does the necessary assertion using WebAssertion." }, { "code": null, "e": 4475, "s": 4434, "text": "A sample web testing code is as follows," }, { "code": null, "e": 4596, "s": 4475, "text": "onWebView()\n .withElement(findElement(Locator.ID, \"apple\"))\n .check(webMatches(getText(), containsString(\"Apple\")))\n" }, { "code": null, "e": 4602, "s": 4596, "text": "Here," }, { "code": null, "e": 4653, "s": 4602, "text": "findElement() locate a element and returns an Atom" }, { "code": null, "e": 4704, "s": 4653, "text": "findElement() locate a element and returns an Atom" }, { "code": null, "e": 4744, "s": 4704, "text": "webMatches is similar to matches method" }, { "code": null, "e": 4784, "s": 4744, "text": "webMatches is similar to matches method" }, { "code": null, "e": 4938, "s": 4784, "text": "Let us write a simple application based on WebView and write a test case using the onWebView() method. Follow these steps to write a sample application βˆ’" }, { "code": null, "e": 4960, "s": 4938, "text": "Start Android studio." }, { "code": null, "e": 4982, "s": 4960, "text": "Start Android studio." }, { "code": null, "e": 5049, "s": 4982, "text": "Create new project as discussed earlier and name it, MyWebViewApp." }, { "code": null, "e": 5116, "s": 5049, "text": "Create new project as discussed earlier and name it, MyWebViewApp." }, { "code": null, "e": 5212, "s": 5116, "text": "Migrate the application to AndroidX framework using Refactor β†’ Migrate to AndroidX option menu." }, { "code": null, "e": 5308, "s": 5212, "text": "Migrate the application to AndroidX framework using Refactor β†’ Migrate to AndroidX option menu." }, { "code": null, "e": 5414, "s": 5308, "text": "Add the below configuration option in the AndroidManifest.xml file to give permission to access Internet." }, { "code": null, "e": 5520, "s": 5414, "text": "Add the below configuration option in the AndroidManifest.xml file to give permission to access Internet." }, { "code": null, "e": 5586, "s": 5520, "text": "<uses-permission android:name = \"android.permission.INTERNET\" />\n" }, { "code": null, "e": 5693, "s": 5586, "text": "Espresso web is provided as a separate plugin. So, add the dependency in the app/build.gradle and sync it." }, { "code": null, "e": 5800, "s": 5693, "text": "Espresso web is provided as a separate plugin. So, add the dependency in the app/build.gradle and sync it." }, { "code": null, "e": 5948, "s": 5800, "text": "dependencies {\n androidTestImplementation 'androidx.test:rules:1.1.1'\n androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.1'\n}\n" }, { "code": null, "e": 6060, "s": 5948, "text": "Remove default design in the main activity and add WebView. The content of the activity_main.xml is as follows," }, { "code": null, "e": 6172, "s": 6060, "text": "Remove default design in the main activity and add WebView. The content of the activity_main.xml is as follows," }, { "code": null, "e": 6680, "s": 6172, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <WebView\n android:id = \"@+id/web_view_test\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\" />\n</RelativeLayout>" }, { "code": null, "e": 6933, "s": 6680, "text": "Create a new class, ExtendedWebViewClient extending WebViewClient and override shouldOverrideUrlLoading method to load link action in the same WebView; otherwise, it will open a new browser window outside the application. Place it in MainActivity.java." }, { "code": null, "e": 7186, "s": 6933, "text": "Create a new class, ExtendedWebViewClient extending WebViewClient and override shouldOverrideUrlLoading method to load link action in the same WebView; otherwise, it will open a new browser window outside the application. Place it in MainActivity.java." }, { "code": null, "e": 7381, "s": 7186, "text": "private class ExtendedWebViewClient extends WebViewClient {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n}" }, { "code": null, "e": 7553, "s": 7381, "text": "Now, add the below code in the onCreate method of MainActivity. The purpose of the code is to find the WebView, properly configure it and then finally load the target url." }, { "code": null, "e": 7725, "s": 7553, "text": "Now, add the below code in the onCreate method of MainActivity. The purpose of the code is to find the WebView, properly configure it and then finally load the target url." }, { "code": null, "e": 7997, "s": 7725, "text": "// Find web view\nWebView webView = (WebView) findViewById(R.id.web_view_test);\n\n// set web view client\nwebView.setWebViewClient(new ExtendedWebViewClient());\n\n// Clear cache\nwebView.clearCache(true);\n\n// load Url\nwebView.loadUrl(\"http://<your domain or IP>/index.html\");\n" }, { "code": null, "e": 8003, "s": 7997, "text": "Here," }, { "code": null, "e": 8045, "s": 8003, "text": "The content of index.html is as follows βˆ’" }, { "code": null, "e": 8087, "s": 8045, "text": "The content of index.html is as follows βˆ’" }, { "code": null, "e": 8368, "s": 8087, "text": "<html>\n <head>\n <title>Android Web View Sample</title>\n </head>\n <body>\n <h1>Fruits</h1>\n <ol>\n <li><a href = \"apple.html\" id = \"apple\">Apple</a></li>\n <li><a href = \"banana.html\" id = \"banana\">Banana</a></li>\n </ol>\n </body>\n</html>" }, { "code": null, "e": 8442, "s": 8368, "text": "The content of the apple.html file referred in index.html is as follows βˆ’" }, { "code": null, "e": 8516, "s": 8442, "text": "The content of the apple.html file referred in index.html is as follows βˆ’" }, { "code": null, "e": 8643, "s": 8516, "text": "<html>\n <head>\n <title>Android Web View Sample</title>\n </head>\n \n <body>\n <h1>Apple</h1>\n </body>\n</html>" }, { "code": null, "e": 8718, "s": 8643, "text": "The content of the banana.html file referred in banana.html is as follows," }, { "code": null, "e": 8793, "s": 8718, "text": "The content of the banana.html file referred in banana.html is as follows," }, { "code": null, "e": 8921, "s": 8793, "text": "<html>\n <head>\n <title>Android Web View Sample</title>\n </head>\n \n <body>\n <h1>Banana</h1>\n </body>\n</html>" }, { "code": null, "e": 8982, "s": 8921, "text": "Place index.html, apple.html and banana.html in a web server" }, { "code": null, "e": 9043, "s": 8982, "text": "Place index.html, apple.html and banana.html in a web server" }, { "code": null, "e": 9103, "s": 9043, "text": "Replace the url in loadUrl method with your configured url." }, { "code": null, "e": 9163, "s": 9103, "text": "Replace the url in loadUrl method with your configured url." }, { "code": null, "e": 9290, "s": 9163, "text": "Now, run the application and manually check if everything is fine. Below is the screenshot of the WebView sample application βˆ’" }, { "code": null, "e": 9417, "s": 9290, "text": "Now, run the application and manually check if everything is fine. Below is the screenshot of the WebView sample application βˆ’" }, { "code": null, "e": 9490, "s": 9417, "text": "Now, open the ExampleInstrumentedTest.java file and add the below rule βˆ’" }, { "code": null, "e": 9563, "s": 9490, "text": "Now, open the ExampleInstrumentedTest.java file and add the below rule βˆ’" }, { "code": null, "e": 9831, "s": 9563, "text": "@Rule\npublic ActivityTestRule<MainActivity> mActivityRule =\n new ActivityTestRule<MainActivity>(MainActivity.class, false, true) {\n @Override\n protected void afterActivityLaunched() {\n onWebView(withId(R.id.web_view_test)).forceJavascriptEnabled();\n }\n};" }, { "code": null, "e": 10019, "s": 9831, "text": "Here, we found the WebView and enabled JavaScript of the WebView because espresso web testing framework works exclusively through JavaScript engine to identify and manipulate web element." }, { "code": null, "e": 10080, "s": 10019, "text": "Now, add the test case to test our WebView and its behavior." }, { "code": null, "e": 10141, "s": 10080, "text": "Now, add the test case to test our WebView and its behavior." }, { "code": null, "e": 10450, "s": 10141, "text": "@Test\npublic void webViewTest(){\n onWebView()\n .withElement(findElement(Locator.ID, \"apple\"))\n .check(webMatches(getText(), containsString(\"Apple\")))\n .perform(webClick())\n .withElement(findElement(Locator.TAG_NAME, \"h1\"))\n .check(webMatches(getText(), containsString(\"Apple\")));\n}" }, { "code": null, "e": 10501, "s": 10450, "text": "Here, the testing was done in the following order," }, { "code": null, "e": 10603, "s": 10501, "text": "found the link, apple using its id attribute through findElement() method and Locator.ID enumeration." }, { "code": null, "e": 10705, "s": 10603, "text": "found the link, apple using its id attribute through findElement() method and Locator.ID enumeration." }, { "code": null, "e": 10759, "s": 10705, "text": "checks the text of the link using webMatches() method" }, { "code": null, "e": 10813, "s": 10759, "text": "checks the text of the link using webMatches() method" }, { "code": null, "e": 10878, "s": 10813, "text": "performs click action on the link. It opens the apple.html page." }, { "code": null, "e": 10943, "s": 10878, "text": "performs click action on the link. It opens the apple.html page." }, { "code": null, "e": 11032, "s": 10943, "text": "again found the h1 element using findElement() methods and Locator.TAG_NAME enumeration." }, { "code": null, "e": 11121, "s": 11032, "text": "again found the h1 element using findElement() methods and Locator.TAG_NAME enumeration." }, { "code": null, "e": 11192, "s": 11121, "text": "finally again checks the text of the h1 tag using webMatches() method." }, { "code": null, "e": 11263, "s": 11192, "text": "finally again checks the text of the h1 tag using webMatches() method." }, { "code": null, "e": 11325, "s": 11263, "text": "Finally, run the test case using android studio context menu." }, { "code": null, "e": 11387, "s": 11325, "text": "Finally, run the test case using android studio context menu." }, { "code": null, "e": 11422, "s": 11387, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11434, "s": 11422, "text": " Anuja Jain" }, { "code": null, "e": 11441, "s": 11434, "text": " Print" }, { "code": null, "e": 11452, "s": 11441, "text": " Add Notes" } ]
Extract word from a String at specified position in R Programming – word() Function
03 Jun, 2020 word() Function in R Language is used to extract words from a string from the position specified as argument. Syntax: word(string, position) Parameter:string: From which word needs to be extractedposition: Specified Index value Example 1: # R Program to illustrate # the use of word function # Loading Librarylibrary(stringr) # Creating a stringx <- "Geeks for Geeks" # Extracting wordword(x, 2) Output: [1] "for" Example 2: # R Program to illustrate # the use of word function # Loading Librarylibrary(stringr) # Creating a stringx <- "abc bcd 100 efg" # Extracting wordsword(x, 2, 4) Output: [1] "bcd 100 efg" R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 138, "s": 28, "text": "word() Function in R Language is used to extract words from a string from the position specified as argument." }, { "code": null, "e": 169, "s": 138, "text": "Syntax: word(string, position)" }, { "code": null, "e": 256, "s": 169, "text": "Parameter:string: From which word needs to be extractedposition: Specified Index value" }, { "code": null, "e": 267, "s": 256, "text": "Example 1:" }, { "code": "# R Program to illustrate # the use of word function # Loading Librarylibrary(stringr) # Creating a stringx <- \"Geeks for Geeks\" # Extracting wordword(x, 2)", "e": 427, "s": 267, "text": null }, { "code": null, "e": 435, "s": 427, "text": "Output:" }, { "code": null, "e": 446, "s": 435, "text": "[1] \"for\"\n" }, { "code": null, "e": 457, "s": 446, "text": "Example 2:" }, { "code": "# R Program to illustrate # the use of word function # Loading Librarylibrary(stringr) # Creating a stringx <- \"abc bcd 100 efg\" # Extracting wordsword(x, 2, 4)", "e": 621, "s": 457, "text": null }, { "code": null, "e": 629, "s": 621, "text": "Output:" }, { "code": null, "e": 648, "s": 629, "text": "[1] \"bcd 100 efg\"\n" }, { "code": null, "e": 667, "s": 648, "text": "R String-Functions" }, { "code": null, "e": 678, "s": 667, "text": "R Language" } ]
fsetpos() (Set File Position) in C
30 Jun, 2021 The fsetpos() function moves the file position indicator to the location specified by the object pointed to by position. When fsetpos() is executed ,the end-of-file indicator is reset.Declaration Parameters – stream – This is the pointer to a FILE object that identifies the stream. position – This is the pointer to a fpos_t object containing a position previously obtained with fgetpos. Return – If it successful, it return zero otherwise returns nonzero value. C // c code to demonstrate fsetpos() function.#include <stdio.h>int main () { FILE *fp; fpos_t position; /*write your own file name. My file name is "myfile.txt"*/ fp = fopen("myfile.txt","w+"); fgetpos(fp, &position); fputs("HelloWorld!", fp); fsetpos(fp, &position); // previous function is override fputs("geeksforgeeks", fp); fclose(fp); return(0);} Output – geeksforgeeks This article is contributed by Shivani Ghughtyal. 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. dpatwal8 C-File Handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 250, "s": 52, "text": "The fsetpos() function moves the file position indicator to the location specified by the object pointed to by position. When fsetpos() is executed ,the end-of-file indicator is reset.Declaration " }, { "code": null, "e": 267, "s": 252, "text": "Parameters – " }, { "code": null, "e": 341, "s": 267, "text": "stream – This is the pointer to a FILE object that identifies the stream." }, { "code": null, "e": 447, "s": 341, "text": "position – This is the pointer to a fpos_t object containing a position previously obtained with fgetpos." }, { "code": null, "e": 523, "s": 447, "text": "Return – If it successful, it return zero otherwise returns nonzero value. " }, { "code": null, "e": 525, "s": 523, "text": "C" }, { "code": "// c code to demonstrate fsetpos() function.#include <stdio.h>int main () { FILE *fp; fpos_t position; /*write your own file name. My file name is \"myfile.txt\"*/ fp = fopen(\"myfile.txt\",\"w+\"); fgetpos(fp, &position); fputs(\"HelloWorld!\", fp); fsetpos(fp, &position); // previous function is override fputs(\"geeksforgeeks\", fp); fclose(fp); return(0);}", "e": 911, "s": 525, "text": null }, { "code": null, "e": 922, "s": 911, "text": "Output – " }, { "code": null, "e": 936, "s": 922, "text": "geeksforgeeks" }, { "code": null, "e": 1362, "s": 936, "text": "This article is contributed by Shivani Ghughtyal. 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": 1371, "s": 1362, "text": "dpatwal8" }, { "code": null, "e": 1387, "s": 1371, "text": "C-File Handling" }, { "code": null, "e": 1398, "s": 1387, "text": "C Language" } ]
response.url – Python requests
01 Mar, 2020 response.url returns the URL of the response. It will show the main url which has returned the content, after all redirections, if done. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.url out of a response object. To illustrate use of response.url, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC. Download and Install Python 3 Latest Version How to install requests in Python – For windows, linux, mac # import requests moduleimport requests # Making a get requestresponse = requests.get('http://api.github.com') # print responseprint(response) # print urlprint(response.url) Save above file as request.py and run using Python request.py Check that https://api.github.com/, it shows the url that returned the response. There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. requests.status_code If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Different ways to create Pandas Dataframe How to Install PIP on Windows ? Python String | replace() Python OOPs Concepts Python Classes and Objects *args and **kwargs in Python Introduction To PYTHON Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Mar, 2020" }, { "code": null, "e": 528, "s": 28, "text": "response.url returns the URL of the response. It will show the main url which has returned the content, after all redirections, if done. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.url out of a response object." }, { "code": null, "e": 669, "s": 528, "text": "To illustrate use of response.url, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC." }, { "code": null, "e": 714, "s": 669, "text": "Download and Install Python 3 Latest Version" }, { "code": null, "e": 774, "s": 714, "text": "How to install requests in Python – For windows, linux, mac" }, { "code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('http://api.github.com') # print responseprint(response) # print urlprint(response.url)", "e": 951, "s": 774, "text": null }, { "code": null, "e": 995, "s": 951, "text": "Save above file as request.py and run using" }, { "code": null, "e": 1014, "s": 995, "text": "Python request.py\n" }, { "code": null, "e": 1095, "s": 1014, "text": "Check that https://api.github.com/, it shows the url that returned the response." }, { "code": null, "e": 1346, "s": 1095, "text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute." }, { "code": null, "e": 1367, "s": 1346, "text": "requests.status_code" }, { "code": null, "e": 1524, "s": 1367, "text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources." }, { "code": null, "e": 1540, "s": 1524, "text": "Python-requests" }, { "code": null, "e": 1547, "s": 1540, "text": "Python" }, { "code": null, "e": 1645, "s": 1547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1663, "s": 1645, "text": "Python Dictionary" }, { "code": null, "e": 1685, "s": 1663, "text": "Enumerate() in Python" }, { "code": null, "e": 1727, "s": 1685, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1759, "s": 1727, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1785, "s": 1759, "text": "Python String | replace()" }, { "code": null, "e": 1806, "s": 1785, "text": "Python OOPs Concepts" }, { "code": null, "e": 1833, "s": 1806, "text": "Python Classes and Objects" }, { "code": null, "e": 1862, "s": 1833, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1885, "s": 1862, "text": "Introduction To PYTHON" } ]
Special variables in Perl
21 Nov, 2019 Special Variables in Perl are those which are already defined to carry out a specific function when required. The differentiating factor between a special Variable in Perl and a random character is the use of Punctuation mark after the variable, these could be @, $ or %, etc, for example, $_. Perl Variables helps a developer in saving time since these are generally shortcuts to bigger commands in English. Note: The most common special variable is $_, which is used to store the default input. Look at the following codes to get an idea about this special variable: # Providing some input while ( <> ) { # Printing the default value # stored in $_ print lc($_); } This is the same as #!/usr/bin/perlwhile ( $abc = <> ) { print lc($abc);} Following is an example of the above mentioned special variable in working format: #!/usr/bin/perlforeach ('Mango', 'Orange', 'Apple'){ print($_); print("\n");} Mango Orange Apple Special Variables can be categorized on the basis of their usage and nature. These are: Regular Expression Special VariablesFile handle Special VariablesGlobal Scalar Special VariablesGlobal Array Special VariablesGlobal Hash Special VariablesGlobal Special ConstantsGlobal Special File handles Regular Expression Special Variables File handle Special Variables Global Scalar Special Variables Global Array Special Variables Global Hash Special Variables Global Special Constants Global Special File handles $digit: The main function of $digit is to hold the text matched in a similar set of parentheses in the last matched pattern. However, patterns already matched in a nested block are not counted. $&, $MATCH: Used to find the string matched in the last successful pattern search. Though Matched in a hidden block or enclosed in the current set are not counted. This is a read-only variable and is scoped dynamically. #!/usr/bin/perl # Declaring local stringlocal $_ = 'abcdefghi'; # Pattern matching/def/; # Printing the matched patternprint "$&\n"; def $`, $PREMATCH: The string preceding a quoted string was matched with the last successful pattern match. It doesn’t count any matches enclosed within a block or eval enclosed by the current block. #!/usr/bin/perl # Declaring local stringlocal $_ = 'abcdefghi'; # Pattern matching/def/; # Prematching the patternprint "$`:$&\n"; abc:def $’, $POSTMATCH: The string following whatever was matched by the last successful pattern match not counting any matches hidden within a block or eval enclosed by the current block. #!/usr/bin/perl # Declaring local stringlocal $_ = 'abcdefghi'; # Pattern matching/def/; # Postmatching the patternprint "$&:$'\n"; def:ghi $|, $OUTPUT_AUTOFLUSH: If set to nonzero, this variable forces a flush after every write or print statement on the output channel that is currently being selected. $%, $FORMAT_PAGE_NUMBER: This variable finds the currently selected output channel and the current page number. $=, $FORMAT_LINES_PER_PAGE: This variable returns the current page length i.e. the lines which are printable of the currently selected output channel. The default value for this variable is 60. $-, $FORMAT_LINES_LEFT: Returns the number of lines left on the page of the currently selected output channel. $~, $FORMAT_NAME: The name of the current report format for the currently selected output channel. The default value is the name of the filehandle. For example, for STDOUT, the default format name would be STDOUT itself. Below mentioned is the list of some of the scalar special variables. And listed corresponding English like names along with the symbolic names.$_, $ARG : Used as a default variable to accept input and to perform pattern-searching, when variable is omitted. $., $NR : Contains the line number of the filehandle last updated. The value is reset to zero if the filehandle is closed. This variable will never move the seek pointer in the file. $/, $RS : This is the input record separator. If $/ is undefined, the entire file is read as a single input for null value a blank is considered as a delimiter. It creates a new line by default. #!/usr/bin/perl local $/; # enable "slurp" modelocal $_ = <FH>; # whole file now heres/\n[ \t]+/ /g; β€˜$, β€˜, $ OFS: The Output Field Separator command is used when the user wants to print a default value between each print operator argument. The default value for this variable is undef. $\, $ORS: The Output Record Separator command is used when the user wants to print the value at the last of the print operator arguments. $!, $OS_ERROR or $ERRNO : Yields the current value of error no. variable if used in a numeric context.If utilized in a string context, it yields the corresponding system error string. if (open my $fh, "<", $filename) { # Here $! is meaningless. ...}else { # ONLY here is $! meaningful. ... # Already here $! might be meaningless.} # Since here we might have either success or failure,# $! is meaningless. Here, it is said that it’s meaningless because here this variable($!) is unrelated to the outcome of open() operator. @ARGV : In a command-line argument @ARGV is the array which is used for the intended script. It is generally one value less than the total number of arguments. $ perl -e 'print join( ", ", @ARGV), "\n"' a b c a, b, c $ perl -e 'print join( ", ", @ARGV), "\n"' a "b c" d a, b c, d Here, a, b, c, d represents any numeric values. @INC: This variable can be considered as the inbuilt help array which contains the list of places to find scripts to be evaluated by the do, require, or use constructs. BEGIN { unshift @INC, "local/lib" }; use lib "local/lib"; @F : When we use the -a command-line switch we use @F to split and input the lines into an array. This array needs a full package name because it is package-specific. %INC : This variable contains the entries for the file name of each file that has been included. These entries are done via do, require or use operators. %ENV : The hash containing your current environment. #!/usr/bin/perlmy $doo = 1;$ENV{'car'} = \$doo; if( ref $ENV{'car'} ) { print "Ver 5.18.0";} else{ print "Ver 5.18.0";} Ver 5.18.0 %SIG : To update the value of various signals this hash is used. It contains signal handlers for signals. ARGV: ARGV is a special filehandle the file name is iterated over a command line when @ARGV is used. Generally, it is the null filehandle. STDERR: It is the special file handle for standard error in any package. STDIN: The special file handle for standard input in any package. STDOUT: The special file handle for standard output in any package. DATA: The special filehandle that refers to anything following the __END__ token in the file containing the script. _ (underscore): The special filehandle used to cache the information from the last stat, lstat, or file test operator. __END__: Used to show the end of a program. __FILE__: Show the file name where it is referenced. __LINE__: Shows the current line number __PACKAGE__: This variable shows the package name. perl-basics Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2019" }, { "code": null, "e": 322, "s": 28, "text": "Special Variables in Perl are those which are already defined to carry out a specific function when required. The differentiating factor between a special Variable in Perl and a random character is the use of Punctuation mark after the variable, these could be @, $ or %, etc, for example, $_." }, { "code": null, "e": 437, "s": 322, "text": "Perl Variables helps a developer in saving time since these are generally shortcuts to bigger commands in English." }, { "code": null, "e": 525, "s": 437, "text": "Note: The most common special variable is $_, which is used to store the default input." }, { "code": null, "e": 597, "s": 525, "text": "Look at the following codes to get an idea about this special variable:" }, { "code": "# Providing some input while ( <> ) { # Printing the default value # stored in $_ print lc($_); }", "e": 706, "s": 597, "text": null }, { "code": null, "e": 726, "s": 706, "text": "This is the same as" }, { "code": "#!/usr/bin/perlwhile ( $abc = <> ) { print lc($abc);}", "e": 783, "s": 726, "text": null }, { "code": null, "e": 866, "s": 783, "text": "Following is an example of the above mentioned special variable in working format:" }, { "code": "#!/usr/bin/perlforeach ('Mango', 'Orange', 'Apple'){ print($_); print(\"\\n\");}", "e": 948, "s": 866, "text": null }, { "code": null, "e": 968, "s": 948, "text": "Mango\nOrange\nApple\n" }, { "code": null, "e": 1056, "s": 968, "text": "Special Variables can be categorized on the basis of their usage and nature. These are:" }, { "code": null, "e": 1263, "s": 1056, "text": "Regular Expression Special VariablesFile handle Special VariablesGlobal Scalar Special VariablesGlobal Array Special VariablesGlobal Hash Special VariablesGlobal Special ConstantsGlobal Special File handles" }, { "code": null, "e": 1300, "s": 1263, "text": "Regular Expression Special Variables" }, { "code": null, "e": 1330, "s": 1300, "text": "File handle Special Variables" }, { "code": null, "e": 1362, "s": 1330, "text": "Global Scalar Special Variables" }, { "code": null, "e": 1393, "s": 1362, "text": "Global Array Special Variables" }, { "code": null, "e": 1423, "s": 1393, "text": "Global Hash Special Variables" }, { "code": null, "e": 1448, "s": 1423, "text": "Global Special Constants" }, { "code": null, "e": 1476, "s": 1448, "text": "Global Special File handles" }, { "code": null, "e": 1670, "s": 1476, "text": "$digit: The main function of $digit is to hold the text matched in a similar set of parentheses in the last matched pattern. However, patterns already matched in a nested block are not counted." }, { "code": null, "e": 1890, "s": 1670, "text": "$&, $MATCH: Used to find the string matched in the last successful pattern search. Though Matched in a hidden block or enclosed in the current set are not counted. This is a read-only variable and is scoped dynamically." }, { "code": "#!/usr/bin/perl # Declaring local stringlocal $_ = 'abcdefghi'; # Pattern matching/def/; # Printing the matched patternprint \"$&\\n\"; ", "e": 2028, "s": 1890, "text": null }, { "code": null, "e": 2033, "s": 2028, "text": "def\n" }, { "code": null, "e": 2229, "s": 2033, "text": "$`, $PREMATCH: The string preceding a quoted string was matched with the last successful pattern match. It doesn’t count any matches enclosed within a block or eval enclosed by the current block." }, { "code": "#!/usr/bin/perl # Declaring local stringlocal $_ = 'abcdefghi'; # Pattern matching/def/; # Prematching the patternprint \"$`:$&\\n\"; ", "e": 2365, "s": 2229, "text": null }, { "code": null, "e": 2374, "s": 2365, "text": "abc:def\n" }, { "code": null, "e": 2555, "s": 2374, "text": "$’, $POSTMATCH: The string following whatever was matched by the last successful pattern match not counting any matches hidden within a block or eval enclosed by the current block." }, { "code": "#!/usr/bin/perl # Declaring local stringlocal $_ = 'abcdefghi'; # Pattern matching/def/; # Postmatching the patternprint \"$&:$'\\n\"; ", "e": 2692, "s": 2555, "text": null }, { "code": null, "e": 2701, "s": 2692, "text": "def:ghi\n" }, { "code": null, "e": 2865, "s": 2701, "text": "$|, $OUTPUT_AUTOFLUSH: If set to nonzero, this variable forces a flush after every write or print statement on the output channel that is currently being selected." }, { "code": null, "e": 2977, "s": 2865, "text": "$%, $FORMAT_PAGE_NUMBER: This variable finds the currently selected output channel and the current page number." }, { "code": null, "e": 3171, "s": 2977, "text": "$=, $FORMAT_LINES_PER_PAGE: This variable returns the current page length i.e. the lines which are printable of the currently selected output channel. The default value for this variable is 60." }, { "code": null, "e": 3282, "s": 3171, "text": "$-, $FORMAT_LINES_LEFT: Returns the number of lines left on the page of the currently selected output channel." }, { "code": null, "e": 3503, "s": 3282, "text": "$~, $FORMAT_NAME: The name of the current report format for the currently selected output channel. The default value is the name of the filehandle. For example, for STDOUT, the default format name would be STDOUT itself." }, { "code": null, "e": 3760, "s": 3503, "text": "Below mentioned is the list of some of the scalar special variables. And listed corresponding English like names along with the symbolic names.$_, $ARG : Used as a default variable to accept input and to perform pattern-searching, when variable is omitted." }, { "code": null, "e": 3943, "s": 3760, "text": "$., $NR : Contains the line number of the filehandle last updated. The value is reset to zero if the filehandle is closed. This variable will never move the seek pointer in the file." }, { "code": null, "e": 4138, "s": 3943, "text": "$/, $RS : This is the input record separator. If $/ is undefined, the entire file is read as a single input for null value a blank is considered as a delimiter. It creates a new line by default." }, { "code": "#!/usr/bin/perl local $/; # enable \"slurp\" modelocal $_ = <FH>; # whole file now heres/\\n[ \\t]+/ /g;", "e": 4253, "s": 4138, "text": null }, { "code": null, "e": 4439, "s": 4253, "text": "β€˜$, β€˜, $ OFS: The Output Field Separator command is used when the user wants to print a default value between each print operator argument. The default value for this variable is undef." }, { "code": null, "e": 4577, "s": 4439, "text": "$\\, $ORS: The Output Record Separator command is used when the user wants to print the value at the last of the print operator arguments." }, { "code": null, "e": 4761, "s": 4577, "text": "$!, $OS_ERROR or $ERRNO : Yields the current value of error no. variable if used in a numeric context.If utilized in a string context, it yields the corresponding system error string." }, { "code": "if (open my $fh, \"<\", $filename) { # Here $! is meaningless. ...}else { # ONLY here is $! meaningful. ... # Already here $! might be meaningless.} # Since here we might have either success or failure,# $! is meaningless.", "e": 4998, "s": 4761, "text": null }, { "code": null, "e": 5116, "s": 4998, "text": "Here, it is said that it’s meaningless because here this variable($!) is unrelated to the outcome of open() operator." }, { "code": null, "e": 5276, "s": 5116, "text": "@ARGV : In a command-line argument @ARGV is the array which is used for the intended script. It is generally one value less than the total number of arguments." }, { "code": null, "e": 5448, "s": 5276, "text": " \n$ perl -e 'print join( \", \", @ARGV), \"\\n\"' a b c\na, b, c\n$ perl -e 'print join( \", \", @ARGV), \"\\n\"' a \"b c\" d\na, b c, d\n\nHere, a, b, c, d represents any numeric values.\n" }, { "code": null, "e": 5617, "s": 5448, "text": "@INC: This variable can be considered as the inbuilt help array which contains the list of places to find scripts to be evaluated by the do, require, or use constructs." }, { "code": null, "e": 5684, "s": 5617, "text": " BEGIN { unshift @INC, \"local/lib\" };\n\n use lib \"local/lib\";" }, { "code": null, "e": 5851, "s": 5684, "text": "@F : When we use the -a command-line switch we use @F to split and input the lines into an array. This array needs a full package name because it is package-specific." }, { "code": null, "e": 6005, "s": 5851, "text": "%INC : This variable contains the entries for the file name of each file that has been included. These entries are done via do, require or use operators." }, { "code": null, "e": 6058, "s": 6005, "text": "%ENV : The hash containing your current environment." }, { "code": "#!/usr/bin/perlmy $doo = 1;$ENV{'car'} = \\$doo; if( ref $ENV{'car'} ) { print \"Ver 5.18.0\";} else{ print \"Ver 5.18.0\";}", "e": 6185, "s": 6058, "text": null }, { "code": null, "e": 6197, "s": 6185, "text": "Ver 5.18.0\n" }, { "code": null, "e": 6303, "s": 6197, "text": "%SIG : To update the value of various signals this hash is used. It contains signal handlers for signals." }, { "code": null, "e": 6442, "s": 6303, "text": "ARGV: ARGV is a special filehandle the file name is iterated over a command line when @ARGV is used. Generally, it is the null filehandle." }, { "code": null, "e": 6515, "s": 6442, "text": "STDERR: It is the special file handle for standard error in any package." }, { "code": null, "e": 6581, "s": 6515, "text": "STDIN: The special file handle for standard input in any package." }, { "code": null, "e": 6649, "s": 6581, "text": "STDOUT: The special file handle for standard output in any package." }, { "code": null, "e": 6765, "s": 6649, "text": "DATA: The special filehandle that refers to anything following the __END__ token in the file containing the script." }, { "code": null, "e": 6884, "s": 6765, "text": "_ (underscore): The special filehandle used to cache the information from the last stat, lstat, or file test operator." }, { "code": null, "e": 6928, "s": 6884, "text": "__END__: Used to show the end of a program." }, { "code": null, "e": 6981, "s": 6928, "text": "__FILE__: Show the file name where it is referenced." }, { "code": null, "e": 7021, "s": 6981, "text": "__LINE__: Shows the current line number" }, { "code": null, "e": 7072, "s": 7021, "text": "__PACKAGE__: This variable shows the package name." }, { "code": null, "e": 7084, "s": 7072, "text": "perl-basics" }, { "code": null, "e": 7091, "s": 7084, "text": "Picked" }, { "code": null, "e": 7096, "s": 7091, "text": "Perl" }, { "code": null, "e": 7101, "s": 7096, "text": "Perl" } ]
How to Drop Rows that Contain a Specific String in Pandas?
03 Dec, 2021 In this article, we are going to see how to drop rows that contain a specific string in pandas. Now, to drop the rows with a specific string we can use the contains() function from the pandas library. Syntax: series.str.contains(string, case=True, flags=0, na=None, regex=True) Returns – Series or index of Boolean Values Basically, this function will search for the string in the given column and returns the rows respective to that. For this, we need to create a new data frame by filtering the data frame using this function. Syntax: df[ df[ β€œcolumn” ].str.contains( β€œsomeString” )==False ] Example: Create DataFrame Python3 # Importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # displaydf Output: In this method, we are going to find the rows with str.contains() function which will basically take the string from the series and check for the match of the given string, and using a boolean we are selecting the rows and setting them to False will help us to neglect the selected rows and keep the remaining rows. syntax: df[df[β€œcolumn_name”].str.contains(β€œstring”)==False] Example: In the following example, we are going to select all the teams except β€œTeam 1”. Python3 # importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # Dropping the team 1df = df[df["team"].str.contains("Team 1") == False] df Output: Same as method 1, we follow the same steps here but with a bitwise or operator to add an extra string to search for. syntax: df = df[df[β€œcolumn_name”].str.contains(β€œstring1|string2”)==False] Example: In the following, program we are going to drop the rows that contain β€œTeam 1” or β€œTeam 2”. Python3 # importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # Dropping the rows of team 1 and team 2df = df[df["team"].str.contains("Team 1|Team 2") == False] # displaydf Output: Here we are using the same function with a join method that carries the part of the word we need to search. syntax: df[ ~df.column_name.str.contains(β€˜|’.join([β€œstring”])) ] Example: In this following program, the situation is different from the above two cases. Here we are going to select and drop the rows with the given partial string. For example, we are going to drop the rows with β€œSci” on the column subjects. Python3 # importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # Dropping the rows with "Sci"# identify partial stringdiscard = ["Sci"] # drop rows that contain the partial string "Sci"df[~df.Subject.str.contains('|'.join(discard))] #displaydf Output: singghakshay pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Dec, 2021" }, { "code": null, "e": 255, "s": 53, "text": "In this article, we are going to see how to drop rows that contain a specific string in pandas. Now, to drop the rows with a specific string we can use the contains() function from the pandas library. " }, { "code": null, "e": 332, "s": 255, "text": "Syntax: series.str.contains(string, case=True, flags=0, na=None, regex=True)" }, { "code": null, "e": 345, "s": 332, "text": "Returns – " }, { "code": null, "e": 379, "s": 345, "text": "Series or index of Boolean Values" }, { "code": null, "e": 587, "s": 379, "text": "Basically, this function will search for the string in the given column and returns the rows respective to that. For this, we need to create a new data frame by filtering the data frame using this function. " }, { "code": null, "e": 595, "s": 587, "text": "Syntax:" }, { "code": null, "e": 652, "s": 595, "text": "df[ df[ β€œcolumn” ].str.contains( β€œsomeString” )==False ]" }, { "code": null, "e": 678, "s": 652, "text": "Example: Create DataFrame" }, { "code": null, "e": 686, "s": 678, "text": "Python3" }, { "code": "# Importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # displaydf", "e": 1039, "s": 686, "text": null }, { "code": null, "e": 1047, "s": 1039, "text": "Output:" }, { "code": null, "e": 1363, "s": 1047, "text": "In this method, we are going to find the rows with str.contains() function which will basically take the string from the series and check for the match of the given string, and using a boolean we are selecting the rows and setting them to False will help us to neglect the selected rows and keep the remaining rows." }, { "code": null, "e": 1424, "s": 1363, "text": "syntax: df[df[β€œcolumn_name”].str.contains(β€œstring”)==False]" }, { "code": null, "e": 1433, "s": 1424, "text": "Example:" }, { "code": null, "e": 1514, "s": 1433, "text": "In the following example, we are going to select all the teams except β€œTeam 1”." }, { "code": null, "e": 1522, "s": 1514, "text": "Python3" }, { "code": "# importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # Dropping the team 1df = df[df[\"team\"].str.contains(\"Team 1\") == False] df", "e": 1941, "s": 1522, "text": null }, { "code": null, "e": 1950, "s": 1941, "text": "Output: " }, { "code": null, "e": 2067, "s": 1950, "text": "Same as method 1, we follow the same steps here but with a bitwise or operator to add an extra string to search for." }, { "code": null, "e": 2141, "s": 2067, "text": "syntax: df = df[df[β€œcolumn_name”].str.contains(β€œstring1|string2”)==False]" }, { "code": null, "e": 2150, "s": 2141, "text": "Example:" }, { "code": null, "e": 2241, "s": 2150, "text": "In the following, program we are going to drop the rows that contain β€œTeam 1” or β€œTeam 2”." }, { "code": null, "e": 2249, "s": 2241, "text": "Python3" }, { "code": "# importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # Dropping the rows of team 1 and team 2df = df[df[\"team\"].str.contains(\"Team 1|Team 2\") == False] # displaydf", "e": 2704, "s": 2249, "text": null }, { "code": null, "e": 2712, "s": 2704, "text": "Output:" }, { "code": null, "e": 2821, "s": 2712, "text": "Here we are using the same function with a join method that carries the part of the word we need to search. " }, { "code": null, "e": 2830, "s": 2821, "text": "syntax: " }, { "code": null, "e": 2888, "s": 2830, "text": " df[ ~df.column_name.str.contains(β€˜|’.join([β€œstring”])) ]" }, { "code": null, "e": 2897, "s": 2888, "text": "Example:" }, { "code": null, "e": 3132, "s": 2897, "text": "In this following program, the situation is different from the above two cases. Here we are going to select and drop the rows with the given partial string. For example, we are going to drop the rows with β€œSci” on the column subjects." }, { "code": null, "e": 3140, "s": 3132, "text": "Python3" }, { "code": "# importing the libraryimport pandas as pd # Dataframedf = pd.DataFrame({'team': ['Team 1', 'Team 1', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science', 'Math', 'Science', 'Math'], 'points': [10, 8, 10, 6, 6, 5]}) # Dropping the rows with \"Sci\"# identify partial stringdiscard = [\"Sci\"] # drop rows that contain the partial string \"Sci\"df[~df.Subject.str.contains('|'.join(discard))] #displaydf", "e": 3665, "s": 3140, "text": null }, { "code": null, "e": 3673, "s": 3665, "text": "Output:" }, { "code": null, "e": 3686, "s": 3673, "text": "singghakshay" }, { "code": null, "e": 3711, "s": 3686, "text": "pandas-dataframe-program" }, { "code": null, "e": 3718, "s": 3711, "text": "Picked" }, { "code": null, "e": 3742, "s": 3718, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3756, "s": 3742, "text": "Python-pandas" }, { "code": null, "e": 3763, "s": 3756, "text": "Python" } ]
How to Build a Dice Game in Android?
29 Dec, 2020 In this article, we will be building a Dice Game Project using Java and XML in Android. The Dice Game is based on a two-player game. Both players roll the dice and the player who gets the highest phase value will win the game. There will be a single activity in this application. This activity will show the two player’s name and their dice. The result will be displayed on the top and there will be a roll button at the bottom. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Before going to the coding section first you have to do some pre-task Dice Images: All the dice images are listed below. Save them in your drawable folder in resources. Go to the app > res > drawable and paste the following files:Dice 1Dice 2Dice 3Dice 4Dice 5Dice 6 Dice 1 Dice 2 Dice 3 Dice 4 Dice 5 Dice 6 Modify the colors.xml file: XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#6200EE</color> <color name="colorPrimaryDark">#3700B3</color> <color name="colorAccent">#03DAC5</color> <color name="gradStop">#0F9D58</color> <color name="white">#FFFFFF</color></resources> background.xml file: XML <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <gradient android:angle="90" android:startColor="#0E5131" android:endColor="#0F9D58" android:type="linear"/> </shape> </item></selector> btn_bg.xml file: XML <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:topLeftRadius="20dp" android:topRightRadius="20dp" android:bottomLeftRadius="20dp" android:bottomRightRadius="20dp"/> <stroke android:color="@color/white" android:width="2dp"/> <solid android:color="#022127"/> </shape> Step 3: Working with the activity_main.xml file The XML codes are used to build the structure of the activity as well as its styling part. It contains a TextView at the very top of the activity to show the game result. Then it contains two ImageView, each with a TextView for the Player name and the image of the rolled dice. At the bottom of the activity, there is a Button to roll the dice. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" android:padding="20dp"> <TextView android:id="@+id/tvVar2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginBottom="40dp" android:fontFamily="sans-serif-black" android:gravity="center" android:text="GFG | Android" android:textSize="40dp" android:textStyle="bold" /> <TextView android:id="@+id/tvVar1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_below="@+id/tvVar2" android:fontFamily="sans-serif-smallcaps" android:gravity="center" android:text="WINNER : Player 1" android:textAlignment="center" android:textColor="@color/white" android:textSize="35dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/tvVar1" android:layout_marginTop="40dp" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="50dp" android:layout_gravity="center" android:layout_marginBottom="40dp" android:orientation="horizontal"> <TextView android:layout_width="140dp" android:layout_height="50dp" android:layout_gravity="center" android:gravity="center" android:padding="10dp" android:text="Player 1" android:textAlignment="center" android:textColor="#000000" android:textSize="25dp" /> <TextView android:layout_width="140dp" android:layout_height="50dp" android:layout_gravity="center" android:gravity="center" android:padding="10dp" android:text="Player 2" android:textAlignment="center" android:textColor="#000000" android:textSize="25dp" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="horizontal"> <ImageView android:id="@+id/ivVar1" android:layout_width="140dp" android:layout_height="140dp" android:padding="10dp" android:src="@drawable/dice6" /> <ImageView android:id="@+id/ivVar2" android:layout_width="140dp" android:layout_height="140dp" android:padding="10dp" android:src="@drawable/dice6" /> </LinearLayout> <Button android:id="@+id/btVar1" android:layout_width="wrap_content" android:layout_height="65dp" android:layout_gravity="center" android:layout_marginTop="60dp" android:background="@drawable/btn_bg" android:gravity="center" android:padding="12dp" android:text="Roll the Dice" android:textAlignment="center" android:textColor="#ffffff" android:textSize="30dp" /> </LinearLayout> </RelativeLayout> Step 4: Working with the MainActivity.java file We will create an array inside the Java file that will contain all the images of the dice. Then we will call onClickListener() for the button and generate two random numbers using the Random function. Then we will check the two numbers and display the result respectively. Also, we will set the two images from the array. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.Random; public class MainActivity extends AppCompatActivity { public static Button button; public static TextView textView; public static ImageView img1, img2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // array to store dice images final int dice[] = {R.drawable.dice1, R.drawable.dice2, R.drawable.dice3, R.drawable.dice4, R.drawable.dice5, R.drawable.dice6}; // linking the roll button from its id.. button = findViewById(R.id.btVar1); // linking the result textview from its id.. textView = findViewById(R.id.tvVar1); // linking both the imageView of // the dice images from its id.. img1 = findViewById(R.id.ivVar1); img2 = findViewById(R.id.ivVar2); // call the on click function button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // generate two random numbers // using Random function Random random = new Random(); int num1 = random.nextInt(6); Random random1 = new Random(); int num2 = random.nextInt(6); // the bigger number will be displayed in the // textView as the winner otherwise draw.. if (num1 > num2) { textView.setText("WINNER : Player 1"); } else if (num2 > num1) { textView.setText("WINNER : Player 2"); } else { textView.setText("RESULT : Draw"); } // set the images from the array by the index // position of the numbers generated img1.setImageResource(dice[num1]); img2.setImageResource(dice[num2]); } }); }} android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 622, "s": 28, "text": "In this article, we will be building a Dice Game Project using Java and XML in Android. The Dice Game is based on a two-player game. Both players roll the dice and the player who gets the highest phase value will win the game. There will be a single activity in this application. This activity will show the two player’s name and their dice. The result will be displayed on the top and there will be a roll button at the bottom. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 651, "s": 622, "text": "Step 1: Create a New Project" }, { "code": null, "e": 813, "s": 651, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 891, "s": 813, "text": "Step 2: Before going to the coding section first you have to do some pre-task" }, { "code": null, "e": 1088, "s": 891, "text": "Dice Images: All the dice images are listed below. Save them in your drawable folder in resources. Go to the app > res > drawable and paste the following files:Dice 1Dice 2Dice 3Dice 4Dice 5Dice 6" }, { "code": null, "e": 1095, "s": 1088, "text": "Dice 1" }, { "code": null, "e": 1102, "s": 1095, "text": "Dice 2" }, { "code": null, "e": 1109, "s": 1102, "text": "Dice 3" }, { "code": null, "e": 1116, "s": 1109, "text": "Dice 4" }, { "code": null, "e": 1123, "s": 1116, "text": "Dice 5" }, { "code": null, "e": 1130, "s": 1123, "text": "Dice 6" }, { "code": null, "e": 1158, "s": 1130, "text": "Modify the colors.xml file:" }, { "code": null, "e": 1162, "s": 1158, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#6200EE</color> <color name=\"colorPrimaryDark\">#3700B3</color> <color name=\"colorAccent\">#03DAC5</color> <color name=\"gradStop\">#0F9D58</color> <color name=\"white\">#FFFFFF</color></resources>", "e": 1446, "s": 1162, "text": null }, { "code": null, "e": 1467, "s": 1446, "text": "background.xml file:" }, { "code": null, "e": 1471, "s": 1467, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item> <shape> <gradient android:angle=\"90\" android:startColor=\"#0E5131\" android:endColor=\"#0F9D58\" android:type=\"linear\"/> </shape> </item></selector>", "e": 1822, "s": 1471, "text": null }, { "code": null, "e": 1839, "s": 1822, "text": "btn_bg.xml file:" }, { "code": null, "e": 1843, "s": 1839, "text": "XML" }, { "code": "<shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <corners android:topLeftRadius=\"20dp\" android:topRightRadius=\"20dp\" android:bottomLeftRadius=\"20dp\" android:bottomRightRadius=\"20dp\"/> <stroke android:color=\"@color/white\" android:width=\"2dp\"/> <solid android:color=\"#022127\"/> </shape>", "e": 2222, "s": 1843, "text": null }, { "code": null, "e": 2270, "s": 2222, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 2665, "s": 2270, "text": "The XML codes are used to build the structure of the activity as well as its styling part. It contains a TextView at the very top of the activity to show the game result. Then it contains two ImageView, each with a TextView for the Player name and the image of the rolled dice. At the bottom of the activity, there is a Button to roll the dice. Below is the code for the activity_main.xml file." }, { "code": null, "e": 2669, "s": 2665, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@drawable/background\" android:padding=\"20dp\"> <TextView android:id=\"@+id/tvVar2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginBottom=\"40dp\" android:fontFamily=\"sans-serif-black\" android:gravity=\"center\" android:text=\"GFG | Android\" android:textSize=\"40dp\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/tvVar1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_below=\"@+id/tvVar2\" android:fontFamily=\"sans-serif-smallcaps\" android:gravity=\"center\" android:text=\"WINNER : Player 1\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"35dp\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/tvVar1\" android:layout_marginTop=\"40dp\" android:orientation=\"vertical\"> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"50dp\" android:layout_gravity=\"center\" android:layout_marginBottom=\"40dp\" android:orientation=\"horizontal\"> <TextView android:layout_width=\"140dp\" android:layout_height=\"50dp\" android:layout_gravity=\"center\" android:gravity=\"center\" android:padding=\"10dp\" android:text=\"Player 1\" android:textAlignment=\"center\" android:textColor=\"#000000\" android:textSize=\"25dp\" /> <TextView android:layout_width=\"140dp\" android:layout_height=\"50dp\" android:layout_gravity=\"center\" android:gravity=\"center\" android:padding=\"10dp\" android:text=\"Player 2\" android:textAlignment=\"center\" android:textColor=\"#000000\" android:textSize=\"25dp\" /> </LinearLayout> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:orientation=\"horizontal\"> <ImageView android:id=\"@+id/ivVar1\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:padding=\"10dp\" android:src=\"@drawable/dice6\" /> <ImageView android:id=\"@+id/ivVar2\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:padding=\"10dp\" android:src=\"@drawable/dice6\" /> </LinearLayout> <Button android:id=\"@+id/btVar1\" android:layout_width=\"wrap_content\" android:layout_height=\"65dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"60dp\" android:background=\"@drawable/btn_bg\" android:gravity=\"center\" android:padding=\"12dp\" android:text=\"Roll the Dice\" android:textAlignment=\"center\" android:textColor=\"#ffffff\" android:textSize=\"30dp\" /> </LinearLayout> </RelativeLayout>", "e": 6307, "s": 2669, "text": null }, { "code": null, "e": 6355, "s": 6307, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 6801, "s": 6355, "text": "We will create an array inside the Java file that will contain all the images of the dice. Then we will call onClickListener() for the button and generate two random numbers using the Random function. Then we will check the two numbers and display the result respectively. Also, we will set the two images from the array. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 6806, "s": 6801, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.Random; public class MainActivity extends AppCompatActivity { public static Button button; public static TextView textView; public static ImageView img1, img2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // array to store dice images final int dice[] = {R.drawable.dice1, R.drawable.dice2, R.drawable.dice3, R.drawable.dice4, R.drawable.dice5, R.drawable.dice6}; // linking the roll button from its id.. button = findViewById(R.id.btVar1); // linking the result textview from its id.. textView = findViewById(R.id.tvVar1); // linking both the imageView of // the dice images from its id.. img1 = findViewById(R.id.ivVar1); img2 = findViewById(R.id.ivVar2); // call the on click function button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // generate two random numbers // using Random function Random random = new Random(); int num1 = random.nextInt(6); Random random1 = new Random(); int num2 = random.nextInt(6); // the bigger number will be displayed in the // textView as the winner otherwise draw.. if (num1 > num2) { textView.setText(\"WINNER : Player 1\"); } else if (num2 > num1) { textView.setText(\"WINNER : Player 2\"); } else { textView.setText(\"RESULT : Draw\"); } // set the images from the array by the index // position of the numbers generated img1.setImageResource(dice[num1]); img2.setImageResource(dice[num2]); } }); }}", "e": 9069, "s": 6806, "text": null }, { "code": null, "e": 9077, "s": 9069, "text": "android" }, { "code": null, "e": 9085, "s": 9077, "text": "Android" }, { "code": null, "e": 9090, "s": 9085, "text": "Java" }, { "code": null, "e": 9095, "s": 9090, "text": "Java" }, { "code": null, "e": 9103, "s": 9095, "text": "Android" } ]
How to Iterate over months between two dates in Python?
18 Feb, 2022 In this article, we will discuss how to iterate over months between two dates using Python. We can iterate over months between two dates using timedelta and rrule methods. timedelta() is used for calculating differences in dates and also can be used for date manipulations in Python Example: But using timedelta we can’t iterate over months between dates perfectly because here we are adding 31 days for each month. But every month won’t have exact 31 days. Some months have 30 and even 28, 29. In order to solve the problem rrule comes into the act that helps to iterate between dates by a specific period of time. Python3 # import necessary packagesfrom datetime import datetime, timedelta # date initialisationstartDate = datetime(2020, 1, 10)endDate = datetime(2020, 4, 20) # stores 31 days that can be addedaddDays = timedelta(days=31) while startDate <= endDate: print(startDate) # add a month startDate += addDays 2020-01-10 00:00:00 2020-02-10 00:00:00 2020-03-12 00:00:00 2020-04-12 00:00:00 rrule is a package present in dateutil library and this package consists of a method also rrule which takes dtstart, until and specific time period as parameters which are start date, end date, and time period based on iteration respectively. Specific time periods are WEEKLY, MONTHLY, YEARLY, etc. Note: Use MONTHLY when you want to iterate over months between dates. Syntax: rrule(rrule.MONTHLY, dtstart=start_date, until=end_date) Example: Iterate over months between dates using rrule. Python3 # import necessary packagesfrom datetime import datetimefrom dateutil import rrule # datesstart_date = datetime(2021, 1, 1)end_date = datetime(2022, 1, 1) for dt in rrule.rrule(rrule.MONTHLY, dtstart=start_date, until=end_date): print(dt) 2021-01-01 00:00:00 2021-02-01 00:00:00 2021-03-01 00:00:00 2021-04-01 00:00:00 2021-05-01 00:00:00 2021-06-01 00:00:00 2021-07-01 00:00:00 2021-08-01 00:00:00 2021-09-01 00:00:00 2021-10-01 00:00:00 2021-11-01 00:00:00 2021-12-01 00:00:00 2022-01-01 00:00:00 Example: Iterate over years in between dates using rrule. Python3 # import necessary packagesfrom datetime import datetimefrom dateutil import rrule # datesstart_date = datetime(2021, 1, 1)end_date = datetime(2022, 1, 1) for dt in rrule.rrule(rrule.YEARLY, dtstart=start_date, until=end_date): print(dt) 2021-01-01 00:00:00 2022-01-01 00:00:00 kk773572498 Picked Python-datetime 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": 121, "s": 28, "text": "In this article, we will discuss how to iterate over months between two dates using Python. " }, { "code": null, "e": 201, "s": 121, "text": "We can iterate over months between two dates using timedelta and rrule methods." }, { "code": null, "e": 312, "s": 201, "text": "timedelta() is used for calculating differences in dates and also can be used for date manipulations in Python" }, { "code": null, "e": 321, "s": 312, "text": "Example:" }, { "code": null, "e": 645, "s": 321, "text": "But using timedelta we can’t iterate over months between dates perfectly because here we are adding 31 days for each month. But every month won’t have exact 31 days. Some months have 30 and even 28, 29. In order to solve the problem rrule comes into the act that helps to iterate between dates by a specific period of time." }, { "code": null, "e": 653, "s": 645, "text": "Python3" }, { "code": "# import necessary packagesfrom datetime import datetime, timedelta # date initialisationstartDate = datetime(2020, 1, 10)endDate = datetime(2020, 4, 20) # stores 31 days that can be addedaddDays = timedelta(days=31) while startDate <= endDate: print(startDate) # add a month startDate += addDays", "e": 959, "s": 653, "text": null }, { "code": null, "e": 1039, "s": 959, "text": "2020-01-10 00:00:00\n2020-02-10 00:00:00\n2020-03-12 00:00:00\n2020-04-12 00:00:00" }, { "code": null, "e": 1338, "s": 1039, "text": "rrule is a package present in dateutil library and this package consists of a method also rrule which takes dtstart, until and specific time period as parameters which are start date, end date, and time period based on iteration respectively. Specific time periods are WEEKLY, MONTHLY, YEARLY, etc." }, { "code": null, "e": 1408, "s": 1338, "text": "Note: Use MONTHLY when you want to iterate over months between dates." }, { "code": null, "e": 1416, "s": 1408, "text": "Syntax:" }, { "code": null, "e": 1473, "s": 1416, "text": "rrule(rrule.MONTHLY, dtstart=start_date, until=end_date)" }, { "code": null, "e": 1482, "s": 1473, "text": "Example:" }, { "code": null, "e": 1529, "s": 1482, "text": "Iterate over months between dates using rrule." }, { "code": null, "e": 1537, "s": 1529, "text": "Python3" }, { "code": "# import necessary packagesfrom datetime import datetimefrom dateutil import rrule # datesstart_date = datetime(2021, 1, 1)end_date = datetime(2022, 1, 1) for dt in rrule.rrule(rrule.MONTHLY, dtstart=start_date, until=end_date): print(dt)", "e": 1779, "s": 1537, "text": null }, { "code": null, "e": 2039, "s": 1779, "text": "2021-01-01 00:00:00\n2021-02-01 00:00:00\n2021-03-01 00:00:00\n2021-04-01 00:00:00\n2021-05-01 00:00:00\n2021-06-01 00:00:00\n2021-07-01 00:00:00\n2021-08-01 00:00:00\n2021-09-01 00:00:00\n2021-10-01 00:00:00\n2021-11-01 00:00:00\n2021-12-01 00:00:00\n2022-01-01 00:00:00" }, { "code": null, "e": 2048, "s": 2039, "text": "Example:" }, { "code": null, "e": 2097, "s": 2048, "text": "Iterate over years in between dates using rrule." }, { "code": null, "e": 2105, "s": 2097, "text": "Python3" }, { "code": "# import necessary packagesfrom datetime import datetimefrom dateutil import rrule # datesstart_date = datetime(2021, 1, 1)end_date = datetime(2022, 1, 1) for dt in rrule.rrule(rrule.YEARLY, dtstart=start_date, until=end_date): print(dt)", "e": 2346, "s": 2105, "text": null }, { "code": null, "e": 2386, "s": 2346, "text": "2021-01-01 00:00:00\n2022-01-01 00:00:00" }, { "code": null, "e": 2398, "s": 2386, "text": "kk773572498" }, { "code": null, "e": 2405, "s": 2398, "text": "Picked" }, { "code": null, "e": 2421, "s": 2405, "text": "Python-datetime" }, { "code": null, "e": 2428, "s": 2421, "text": "Python" } ]
How to hide the table header using JavaScript ?
30 Jun, 2020 There are two approaches that can help to hide a table header with the help of JavaScript. They are discussed below: Approach 1: Select the header using a CSS selector and modify the style property such that the value of the display property is set to none. This will hide the selected table header element from the page. Example: html <!DOCTYPE HTML><html><head> <title> How to hide the table header using JavaScript </title> <style> table { margin-left: 180px; } td { padding: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <table id="table"> <colgroup> <col id="myCol" span="2"> <col> </colgroup> <tr id="thead"> <th>S.No</th> <th>Title</th> </tr> <tr> <td>Geek_1</td> <td>GeekForGeeks</td> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> </tr> </table> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN"> </p> <script> var el_down = document.getElementById("GFG_DOWN"); function Geeks() { var tb = document.getElementById("thead"); tb.style.display = "none"; el_down.innerHTML = "Table header is hidden"; } </script></body> </html> Output: Approach 2: Use jQuery to select the header to be hidden and use the hide() method on it. This jQuery method helps to hide the element on which it is used. Example: html <!DOCTYPE HTML><html><head> <title> How to hide the table header using JavaScript </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> table { margin-left: 180px; } td { padding: 10px; } </style></head><body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <table id="table"> <colgroup> <col id="myCol" span="2"> <col> </colgroup> <tr id="thead"> <th>S.No</th> <th>Title</th> </tr> <tr> <td>Geek_1</td> <td>GeekForGeeks</td> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> </tr> </table> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN"> </p> <script> var el_down = document.getElementById("GFG_DOWN"); function Geeks() { $("#thead").hide(); el_down.innerHTML = "Table header is hidden"; } </script></body></html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 146, "s": 28, "text": "There are two approaches that can help to hide a table header with the help of JavaScript. They are discussed below: " }, { "code": null, "e": 351, "s": 146, "text": "Approach 1: Select the header using a CSS selector and modify the style property such that the value of the display property is set to none. This will hide the selected table header element from the page." }, { "code": null, "e": 360, "s": 351, "text": "Example:" }, { "code": null, "e": 365, "s": 360, "text": "html" }, { "code": "<!DOCTYPE HTML><html><head> <title> How to hide the table header using JavaScript </title> <style> table { margin-left: 180px; } td { padding: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <table id=\"table\"> <colgroup> <col id=\"myCol\" span=\"2\"> <col> </colgroup> <tr id=\"thead\"> <th>S.No</th> <th>Title</th> </tr> <tr> <td>Geek_1</td> <td>GeekForGeeks</td> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> </tr> </table> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function Geeks() { var tb = document.getElementById(\"thead\"); tb.style.display = \"none\"; el_down.innerHTML = \"Table header is hidden\"; } </script></body> </html>", "e": 1605, "s": 365, "text": null }, { "code": null, "e": 1614, "s": 1605, "text": "Output: " }, { "code": null, "e": 1770, "s": 1614, "text": "Approach 2: Use jQuery to select the header to be hidden and use the hide() method on it. This jQuery method helps to hide the element on which it is used." }, { "code": null, "e": 1779, "s": 1770, "text": "Example:" }, { "code": null, "e": 1784, "s": 1779, "text": "html" }, { "code": "<!DOCTYPE HTML><html><head> <title> How to hide the table header using JavaScript </title> <script src =\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> table { margin-left: 180px; } td { padding: 10px; } </style></head><body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <table id=\"table\"> <colgroup> <col id=\"myCol\" span=\"2\"> <col> </colgroup> <tr id=\"thead\"> <th>S.No</th> <th>Title</th> </tr> <tr> <td>Geek_1</td> <td>GeekForGeeks</td> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> </tr> </table> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function Geeks() { $(\"#thead\").hide(); el_down.innerHTML = \"Table header is hidden\"; } </script></body></html>", "e": 3047, "s": 1784, "text": null }, { "code": null, "e": 3055, "s": 3047, "text": "Output:" }, { "code": null, "e": 3064, "s": 3055, "text": "CSS-Misc" }, { "code": null, "e": 3074, "s": 3064, "text": "HTML-Misc" }, { "code": null, "e": 3090, "s": 3074, "text": "JavaScript-Misc" }, { "code": null, "e": 3094, "s": 3090, "text": "CSS" }, { "code": null, "e": 3099, "s": 3094, "text": "HTML" }, { "code": null, "e": 3110, "s": 3099, "text": "JavaScript" }, { "code": null, "e": 3127, "s": 3110, "text": "Web Technologies" }, { "code": null, "e": 3154, "s": 3127, "text": "Web technologies Questions" }, { "code": null, "e": 3159, "s": 3154, "text": "HTML" } ]
Operations on Sparse Matrices
06 Jan, 2020 Given two sparse matrices (Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)), perform operations such as add, multiply or transpose of the matrices in their sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input matrices, one by multiplying the two matrices and one obtained by transpose of the first matrix. Example: Note that other entries of matrices will be zero as matrices are sparse. Input : Matrix 1: (4x4) Row Column Value 1 2 10 1 4 12 3 3 5 4 1 15 4 2 12 Matrix 2: (4X4) Row Column Value 1 3 8 2 4 23 3 3 9 4 1 20 4 2 25 Output : Result of Addition: (4x4) Row Column Value 1 2 10 1 3 8 1 4 12 2 4 23 3 3 14 4 1 35 4 2 37 Result of Multiplication: (4x4) Row Column Value 1 1 240 1 2 300 1 4 230 3 3 45 4 3 120 4 4 276 Result of transpose on the first matrix: (4x4) Row Column Value 1 4 15 2 1 10 2 4 12 3 3 5 4 1 12 The sparse matrix used anywhere in the program is sorted according to its row values. Two elements with the same row values are further sorted according to their column values. Now to Add the matrices, we simply traverse through both matrices element by element and insert the smaller element (one with smaller row and col value) into the resultant matrix. If we come across an element with the same row and column value, we simply add their values and insert the added data into the resultant matrix. To Transpose a matrix, we can simply change every column value to the row value and vice-versa, however, in this case, the resultant matrix won’t be sorted as we require. Hence, we initially determine the number of elements less than the current element’s column being inserted in order to get the exact index of the resultant matrix where the current element should be placed. This is done by maintaining an array index[] whose ith value indicates the number of elements in the matrix less than the column i. To Multiply the matrices, we first calculate transpose of the second matrix to simplify our comparisons and maintain the sorted order. So, the resultant matrix is obtained by traversing through the entire length of both matrices and summing the appropriate multiplied values.Any row value equal to x in the first matrix and row value equal to y in the second matrix (transposed one) will contribute towards result[x][y]. This is obtained by multiplying all such elements having col value in both matrices and adding only those with the row as x in first matrix and row as y in the second transposed matrix to get the result[x][y]. For example: Consider 2 matrices: Row Col Val Row Col Val 1 2 10 1 1 2 1 3 12 1 2 5 2 1 1 2 2 1 2 3 2 3 1 8 The resulting matrix after multiplication will be obtained as follows: Transpose of second matrix: Row Col Val Row Col Val 1 2 10 1 1 2 1 3 12 1 3 8 2 1 1 2 1 5 2 3 2 2 2 1 Summation of multiplied values: result[1][1] = A[1][3]*B[1][3] = 12*8 = 96 result[1][2] = A[1][2]*B[2][2] = 10*1 = 10 result[2][1] = A[2][1]*B[1][1] + A[2][3]*B[1][3] = 2*1 + 2*8 = 18 result[2][2] = A[2][1]*B[2][1] = 1*5 = 5 Any other element cannot be obtained by any combination of row in Matrix A and Row in Matrix B. Hence the final resultant matrix will be: Row Col Val 1 1 96 1 2 10 2 1 18 2 2 5 Following is the implementation of above approach: C++ Java C# // C++ code to perform add, multiply // and transpose on sparse matrices#include <iostream>using namespace std; class sparse_matrix{ // Maximum number of elements in matrix const static int MAX = 100; // Double-pointer initialized by // the constructor to store // the triple-represented form int **data; // dimensions of matrix int row, col; // total number of elements in matrix int len; public: sparse_matrix(int r, int c) { // initialize row row = r; // initialize col col = c; // initialize length to 0 len = 0; //Array of Pointer to make a matrix data = new int *[MAX]; // Array representation // of sparse matrix //[,0] represents row //[,1] represents col //[,2] represents value for (int i = 0; i < MAX; i++) data[i] = new int[3]; } // insert elements into sparse matrix void insert(int r, int c, int val) { // invalid entry if (r > row || c > col) { cout << "Wrong entry"; } else { // insert row value data[len][0] = r; // insert col value data[len][1] = c; // insert element's value data[len][2] = val; // increment number of data in matrix len++; } } void add(sparse_matrix b) { // if matrices don't have same dimensions if (row != b.row || col != b.col) { cout << "Matrices can't be added"; } else { int apos = 0, bpos = 0; sparse_matrix result(row, col); while (apos < len && bpos < b.len) { // if b's row and col is smaller if (data[apos][0] > b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] > b.data[bpos][1])) { // insert smaller value into result result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos][2]); bpos++; } // if a's row and col is smaller else if (data[apos][0] < b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] < b.data[bpos][1])) { // insert smaller value into result result.insert(data[apos][0], data[apos][1], data[apos][2]); apos++; } else { // add the values as row and col is same int addedval = data[apos][2] + b.data[bpos][2]; if (addedval != 0) result.insert(data[apos][0], data[apos][1], addedval); // then insert apos++; bpos++; } } // insert remaining elements while (apos < len) result.insert(data[apos][0], data[apos][1], data[apos++][2]); while (bpos < b.len) result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos++][2]); // print result result.print(); } } sparse_matrix transpose() { // new matrix with inversed row X col sparse_matrix result(col, row); // same number of elements result.len = len; // to count number of elements in each column int *count = new int[col + 1]; // initialize all to 0 for (int i = 1; i <= col; i++) count[i] = 0; for (int i = 0; i < len; i++) count[data[i][1]]++; int *index = new int[col + 1]; // to count number of elements having // col smaller than particular i // as there is no col with value < 0 index[0] = 0; // initialize rest of the indices for (int i = 1; i <= col; i++) index[i] = index[i - 1] + count[i - 1]; for (int i = 0; i < len; i++) { // insert a data at rpos and // increment its value int rpos = index[data[i][1]]++; // transpose row=col result.data[rpos][0] = data[i][1]; // transpose col=row result.data[rpos][1] = data[i][0]; // same value result.data[rpos][2] = data[i][2]; } // the above method ensures // sorting of transpose matrix // according to row-col value return result; } void multiply(sparse_matrix b) { if (col != b.row) { // Invalid multiplication cout << "Can't multiply, Invalid dimensions"; return; } // transpose b to compare row // and col values and to add them at the end b = b.transpose(); int apos, bpos; // result matrix of dimension row X b.col // however b has been transposed, // hence row X b.row sparse_matrix result(row, b.row); // iterate over all elements of A for (apos = 0; apos < len;) { // current row of result matrix int r = data[apos][0]; // iterate over all elements of B for (bpos = 0; bpos < b.len;) { // current column of result matrix // data[,0] used as b is transposed int c = b.data[bpos][0]; // temporary pointers created to add all // multiplied values to obtain current // element of result matrix int tempa = apos; int tempb = bpos; int sum = 0; // iterate over all elements with // same row and col value // to calculate result[r] while (tempa < len && data[tempa][0] == r && tempb < b.len && b.data[tempb][0] == c) { if (data[tempa][1] < b.data[tempb][1]) // skip a tempa++; else if (data[tempa][1] > b.data[tempb][1]) // skip b tempb++; else // same col, so multiply and increment sum += data[tempa++][2] * b.data[tempb++][2]; } // insert sum obtained in result[r] // if its not equal to 0 if (sum != 0) result.insert(r, c, sum); while (bpos < b.len && b.data[bpos][0] == c) // jump to next column bpos++; } while (apos < len && data[apos][0] == r) // jump to next row apos++; } result.print(); } // printing matrix void print() { cout << "\nDimension: " << row << "x" << col; cout << "\nSparse Matrix: \nRow\tColumn\tValue\n"; for (int i = 0; i < len; i++) { cout << data[i][0] << "\t " << data[i][1] << "\t " << data[i][2] << endl; } }}; // Driver Codeint main(){ // create two sparse matrices and insert values sparse_matrix a(4, 4); sparse_matrix b(4, 4); a.insert(1, 2, 10); a.insert(1, 4, 12); a.insert(3, 3, 5); a.insert(4, 1, 15); a.insert(4, 2, 12); b.insert(1, 3, 8); b.insert(2, 4, 23); b.insert(3, 3, 9); b.insert(4, 1, 20); b.insert(4, 2, 25); // Output result cout << "Addition: "; a.add(b); cout << "\nMultiplication: "; a.multiply(b); cout << "\nTranspose: "; sparse_matrix atranspose = a.transpose(); atranspose.print();} // This code is contributed// by Bharath Vignesh J K // Java code to perform add,// multiply and transpose on sparse matrices public class sparse_matrix { // Maximum number of elements in matrix int MAX = 100; // Array representation // of sparse matrix //[][0] represents row //[][1] represents col //[][2] represents value int data[][] = new int[MAX][3]; // dimensions of matrix int row, col; // total number of elements in matrix int len; public sparse_matrix(int r, int c) { // initialize row row = r; // initialize col col = c; // initialize length to 0 len = 0; } // insert elements into sparse matrix public void insert(int r, int c, int val) { // invalid entry if (r > row || c > col) { System.out.println("Wrong entry"); } else { // insert row value data[len][0] = r; // insert col value data[len][1] = c; // insert element's value data[len][2] = val; // increment number of data in matrix len++; } } public void add(sparse_matrix b) { // if matrices don't have same dimensions if (row != b.row || col != b.col) { System.out.println("Matrices can't be added"); } else { int apos = 0, bpos = 0; sparse_matrix result = new sparse_matrix(row, col); while (apos < len && bpos < b.len) { // if b's row and col is smaller if (data[apos][0] > b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] > b.data[bpos][1])) { // insert smaller value into result result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos][2]); bpos++; } // if a's row and col is smaller else if (data[apos][0] < b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] < b.data[bpos][1])) { // insert smaller value into result result.insert(data[apos][0], data[apos][1], data[apos][2]); apos++; } else { // add the values as row and col is same int addedval = data[apos][2] + b.data[bpos][2]; if (addedval != 0) result.insert(data[apos][0], data[apos][1], addedval); // then insert apos++; bpos++; } } // insert remaining elements while (apos < len) result.insert(data[apos][0], data[apos][1], data[apos++][2]); while (bpos < b.len) result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos++][2]); // print result result.print(); } } public sparse_matrix transpose() { // new matrix with inversed row X col sparse_matrix result = new sparse_matrix(col, row); // same number of elements result.len = len; // to count number of elements in each column int count[] = new int[col + 1]; // initialize all to 0 for (int i = 1; i <= col; i++) count[i] = 0; for (int i = 0; i < len; i++) count[data[i][1]]++; int[] index = new int[col + 1]; // to count number of elements having col smaller // than particular i // as there is no col with value < 1 index[1] = 0; // initialize rest of the indices for (int i = 2; i <= col; i++) index[i] = index[i - 1] + count[i - 1]; for (int i = 0; i < len; i++) { // insert a data at rpos and increment its value int rpos = index[data[i][1]]++; // transpose row=col result.data[rpos][0] = data[i][1]; // transpose col=row result.data[rpos][1] = data[i][0]; // same value result.data[rpos][2] = data[i][2]; } // the above method ensures // sorting of transpose matrix // according to row-col value return result; } public void multiply(sparse_matrix b) { if (col != b.row) { // Invalid multiplication System.out.println("Can't multiply, " + "Invalid dimensions"); return; } // transpose b to compare row // and col values and to add them at the end b = b.transpose(); int apos, bpos; // result matrix of dimension row X b.col // however b has been transposed, hence row X b.row sparse_matrix result = new sparse_matrix(row, b.row); // iterate over all elements of A for (apos = 0; apos < len;) { // current row of result matrix int r = data[apos][0]; // iterate over all elements of B for (bpos = 0; bpos < b.len;) { // current column of result matrix // data[][0] used as b is transposed int c = b.data[bpos][0]; // temporary pointers created to add all // multiplied values to obtain current // element of result matrix int tempa = apos; int tempb = bpos; int sum = 0; // iterate over all elements with // same row and col value // to calculate result[r] while (tempa < len && data[tempa][0] == r && tempb < b.len && b.data[tempb][0] == c) { if (data[tempa][1] < b.data[tempb][1]) // skip a tempa++; else if (data[tempa][1] > b.data[tempb][1]) // skip b tempb++; else // same col, so multiply and increment sum += data[tempa++][2] * b.data[tempb++][2]; } // insert sum obtained in result[r] // if its not equal to 0 if (sum != 0) result.insert(r, c, sum); while (bpos < b.len && b.data[bpos][0] == c) // jump to next column bpos++; } while (apos < len && data[apos][0] == r) // jump to next row apos++; } result.print(); } // printing matrix public void print() { System.out.println("Dimension: " + row + "x" + col); System.out.println("Sparse Matrix: \nRow Column Value"); for (int i = 0; i < len; i++) { System.out.println(data[i][0] + " " + data[i][1] + " " + data[i][2]); } } public static void main(String args[]) { // create two sparse matrices and insert values sparse_matrix a = new sparse_matrix(4, 4); sparse_matrix b = new sparse_matrix(4, 4); a.insert(1, 2, 10); a.insert(1, 4, 12); a.insert(3, 3, 5); a.insert(4, 1, 15); a.insert(4, 2, 12); b.insert(1, 3, 8); b.insert(2, 4, 23); b.insert(3, 3, 9); b.insert(4, 1, 20); b.insert(4, 2, 25); // Output result System.out.println("Addition: "); a.add(b); System.out.println("\nMultiplication: "); a.multiply(b); System.out.println("\nTranspose: "); sparse_matrix atranspose = a.transpose(); atranspose.print(); }} // This code is contributed by Sudarshan Khasnis // C# code to perform add, // multiply and transpose on sparse matrices public class sparse_matrix { // Maximum number of elements in matrix static int MAX = 100; // Array representation // of sparse matrix //[,0] represents row //[,1] represents col //[,2] represents value int[,] data = new int[MAX,3]; // dimensions of matrix int row, col; // total number of elements in matrix int len; public sparse_matrix(int r, int c) { // initialize row row = r; // initialize col col = c; // initialize length to 0 len = 0; } // insert elements into sparse matrix public void insert(int r, int c, int val) { // invalid entry if (r > row || c > col) { System.Console.WriteLine("Wrong entry"); } else { // insert row value data[len,0] = r; // insert col value data[len,1] = c; // insert element's value data[len,2] = val; // increment number of data in matrix len++; } } public void add(sparse_matrix b) { // if matrices don't have same dimensions if (row != b.row || col != b.col) { System.Console.WriteLine("Matrices can't be added"); } else { int apos = 0, bpos = 0; sparse_matrix result = new sparse_matrix(row, col); while (apos < len && bpos < b.len) { // if b's row and col is smaller if (data[apos,0] > b.data[bpos,0] || (data[apos,0] == b.data[bpos,0] && data[apos,1] > b.data[bpos,1])) { // insert smaller value into result result.insert(b.data[bpos,0], b.data[bpos,1], b.data[bpos,2]); bpos++; } // if a's row and col is smaller else if (data[apos,0] < b.data[bpos,0] || (data[apos,0] == b.data[bpos,0] && data[apos,1] < b.data[bpos,1])) { // insert smaller value into result result.insert(data[apos,0], data[apos,1], data[apos,2]); apos++; } else { // add the values as row and col is same int addedval = data[apos,2] + b.data[bpos,2]; if (addedval != 0) result.insert(data[apos,0], data[apos,1], addedval); // then insert apos++; bpos++; } } // insert remaining elements while (apos < len) result.insert(data[apos,0], data[apos,1], data[apos++,2]); while (bpos < b.len) result.insert(b.data[bpos,0], b.data[bpos,1], b.data[bpos++,2]); // print result result.print(); } } public sparse_matrix transpose() { // new matrix with inversed row X col sparse_matrix result = new sparse_matrix(col, row); // same number of elements result.len = len; // to count number of elements in each column int[] count = new int[col + 1]; // initialize all to 0 for (int i = 1; i <= col; i++) count[i] = 0; for (int i = 0; i < len; i++) count[data[i,1]]++; int[] index = new int[col + 1]; // to count number of elements having col smaller // than particular i // as there is no col with value < 1 index[1] = 0; // initialize rest of the indices for (int i = 2; i <= col; i++) index[i] = index[i - 1] + count[i - 1]; for (int i = 0; i < len; i++) { // insert a data at rpos and increment its value int rpos = index[data[i,1]]++; // transpose row=col result.data[rpos,0] = data[i,1]; // transpose col=row result.data[rpos,1] = data[i,0]; // same value result.data[rpos,2] = data[i,2]; } // the above method ensures // sorting of transpose matrix // according to row-col value return result; } public void multiply(sparse_matrix b) { if (col != b.row) { // Invalid multiplication System.Console.WriteLine("Can't multiply, " + "Invalid dimensions"); return; } // transpose b to compare row // and col values and to add them at the end b = b.transpose(); int apos, bpos; // result matrix of dimension row X b.col // however b has been transposed, hence row X b.row sparse_matrix result = new sparse_matrix(row, b.row); // iterate over all elements of A for (apos = 0; apos < len;) { // current row of result matrix int r = data[apos,0]; // iterate over all elements of B for (bpos = 0; bpos < b.len;) { // current column of result matrix // data[,0] used as b is transposed int c = b.data[bpos,0]; // temporary pointers created to add all // multiplied values to obtain current // element of result matrix int tempa = apos; int tempb = bpos; int sum = 0; // iterate over all elements with // same row and col value // to calculate result[r] while (tempa < len && data[tempa,0] == r && tempb < b.len && b.data[tempb,0] == c) { if (data[tempa,1] < b.data[tempb,1]) // skip a tempa++; else if (data[tempa,1] > b.data[tempb,1]) // skip b tempb++; else // same col, so multiply and increment sum += data[tempa++,2] * b.data[tempb++,2]; } // insert sum obtained in result[r] // if its not equal to 0 if (sum != 0) result.insert(r, c, sum); while (bpos < b.len && b.data[bpos,0] == c) // jump to next column bpos++; } while (apos < len && data[apos,0] == r) // jump to next row apos++; } result.print(); } // printing matrix public void print() { System.Console.WriteLine("Dimension: " + row + "x" + col); System.Console.WriteLine("Sparse Matrix: \nRow Column Value"); for (int i = 0; i < len; i++) { System.Console.WriteLine(data[i,0] + " " + data[i,1] + " " + data[i,2]); } } public static void Main() { // create two sparse matrices and insert values sparse_matrix a = new sparse_matrix(4, 4); sparse_matrix b = new sparse_matrix(4, 4); a.insert(1, 2, 10); a.insert(1, 4, 12); a.insert(3, 3, 5); a.insert(4, 1, 15); a.insert(4, 2, 12); b.insert(1, 3, 8); b.insert(2, 4, 23); b.insert(3, 3, 9); b.insert(4, 1, 20); b.insert(4, 2, 25); // Output result System.Console.WriteLine("Addition: "); a.add(b); System.Console.WriteLine("\nMultiplication: "); a.multiply(b); System.Console.WriteLine("\nTranspose: "); sparse_matrix atranspose = a.transpose(); atranspose.print(); } } // This code is contributed by mits Addition: Dimension: 4x4 Sparse Matrix: Row Column Value 1 2 10 1 3 8 1 4 12 2 4 23 3 3 14 4 1 35 4 2 37 Multiplication: Dimension: 4x4 Sparse Matrix: Row Column Value 1 1 240 1 2 300 1 4 230 3 3 45 4 3 120 4 4 276 Transpose: Dimension: 4x4 Sparse Matrix: Row Column Value 1 4 15 2 1 10 2 4 12 3 3 5 4 1 12 Worst case time complexity: Addition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements in the larger matrix amongst the two. Transpose has a time complexity of O(n+m), where n is the number of columns and m is the number of non-zero elements in the matrix. Multiplication, however, has a time complexity of O(x*n + y*m), where (x, m) is number of columns and terms in the second matrix; and (y, n) is number of rows and terms in the first matrix. aayushk61466 Mithun Kumar nidhi_biet shubham_singh BharathVigneshJK Arrays Mathematical Randomized Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jan, 2020" }, { "code": null, "e": 446, "s": 54, "text": "Given two sparse matrices (Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)), perform operations such as add, multiply or transpose of the matrices in their sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input matrices, one by multiplying the two matrices and one obtained by transpose of the first matrix." }, { "code": null, "e": 528, "s": 446, "text": "Example: Note that other entries of matrices will be zero as matrices are sparse." }, { "code": null, "e": 1178, "s": 528, "text": "Input : \n\nMatrix 1: (4x4)\nRow Column Value\n1 2 10\n1 4 12\n3 3 5\n4 1 15\n4 2 12\n\nMatrix 2: (4X4)\nRow Column Value\n1 3 8\n2 4 23\n3 3 9\n4 1 20\n4 2 25\n\nOutput :\n\nResult of Addition: (4x4)\nRow Column Value\n1 2 10\n1 3 8\n1 4 12\n2 4 23\n3 3 14\n4 1 35\n4 2 37\n\nResult of Multiplication: (4x4)\nRow Column Value\n1 1 240\n1 2 300\n1 4 230\n3 3 45\n4 3 120\n4 4 276\n\nResult of transpose on the first matrix: (4x4)\nRow Column Value\n1 4 15\n2 1 10\n2 4 12\n3 3 5\n4 1 12\n\n" }, { "code": null, "e": 1355, "s": 1178, "text": "The sparse matrix used anywhere in the program is sorted according to its row values. Two elements with the same row values are further sorted according to their column values." }, { "code": null, "e": 1680, "s": 1355, "text": "Now to Add the matrices, we simply traverse through both matrices element by element and insert the smaller element (one with smaller row and col value) into the resultant matrix. If we come across an element with the same row and column value, we simply add their values and insert the added data into the resultant matrix." }, { "code": null, "e": 2190, "s": 1680, "text": "To Transpose a matrix, we can simply change every column value to the row value and vice-versa, however, in this case, the resultant matrix won’t be sorted as we require. Hence, we initially determine the number of elements less than the current element’s column being inserted in order to get the exact index of the resultant matrix where the current element should be placed. This is done by maintaining an array index[] whose ith value indicates the number of elements in the matrix less than the column i." }, { "code": null, "e": 2821, "s": 2190, "text": "To Multiply the matrices, we first calculate transpose of the second matrix to simplify our comparisons and maintain the sorted order. So, the resultant matrix is obtained by traversing through the entire length of both matrices and summing the appropriate multiplied values.Any row value equal to x in the first matrix and row value equal to y in the second matrix (transposed one) will contribute towards result[x][y]. This is obtained by multiplying all such elements having col value in both matrices and adding only those with the row as x in first matrix and row as y in the second transposed matrix to get the result[x][y]." }, { "code": null, "e": 2855, "s": 2821, "text": "For example: Consider 2 matrices:" }, { "code": null, "e": 2993, "s": 2855, "text": "Row Col Val Row Col Val\n1 2 10 1 1 2\n1 3 12 1 2 5\n2 1 1 2 2 1\n2 3 2 3 1 8\n" }, { "code": null, "e": 3064, "s": 2993, "text": "The resulting matrix after multiplication will be obtained as follows:" }, { "code": null, "e": 3664, "s": 3064, "text": "Transpose of second matrix:\n\nRow Col Val Row Col Val\n1 2 10 1 1 2\n1 3 12 1 3 8\n2 1 1 2 1 5\n2 3 2 2 2 1\n\nSummation of multiplied values:\n\nresult[1][1] = A[1][3]*B[1][3] = 12*8 = 96\nresult[1][2] = A[1][2]*B[2][2] = 10*1 = 10\nresult[2][1] = A[2][1]*B[1][1] + A[2][3]*B[1][3] = 2*1 + 2*8 = 18\nresult[2][2] = A[2][1]*B[2][1] = 1*5 = 5\n\nAny other element cannot be obtained \nby any combination of row in \nMatrix A and Row in Matrix B.\n\nHence the final resultant matrix will be:\n \nRow Col Val \n1 1 96 \n1 2 10 \n2 1 18 \n2 2 5 \n" }, { "code": null, "e": 3715, "s": 3664, "text": "Following is the implementation of above approach:" }, { "code": null, "e": 3719, "s": 3715, "text": "C++" }, { "code": null, "e": 3724, "s": 3719, "text": "Java" }, { "code": null, "e": 3727, "s": 3724, "text": "C#" }, { "code": "// C++ code to perform add, multiply // and transpose on sparse matrices#include <iostream>using namespace std; class sparse_matrix{ // Maximum number of elements in matrix const static int MAX = 100; // Double-pointer initialized by // the constructor to store // the triple-represented form int **data; // dimensions of matrix int row, col; // total number of elements in matrix int len; public: sparse_matrix(int r, int c) { // initialize row row = r; // initialize col col = c; // initialize length to 0 len = 0; //Array of Pointer to make a matrix data = new int *[MAX]; // Array representation // of sparse matrix //[,0] represents row //[,1] represents col //[,2] represents value for (int i = 0; i < MAX; i++) data[i] = new int[3]; } // insert elements into sparse matrix void insert(int r, int c, int val) { // invalid entry if (r > row || c > col) { cout << \"Wrong entry\"; } else { // insert row value data[len][0] = r; // insert col value data[len][1] = c; // insert element's value data[len][2] = val; // increment number of data in matrix len++; } } void add(sparse_matrix b) { // if matrices don't have same dimensions if (row != b.row || col != b.col) { cout << \"Matrices can't be added\"; } else { int apos = 0, bpos = 0; sparse_matrix result(row, col); while (apos < len && bpos < b.len) { // if b's row and col is smaller if (data[apos][0] > b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] > b.data[bpos][1])) { // insert smaller value into result result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos][2]); bpos++; } // if a's row and col is smaller else if (data[apos][0] < b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] < b.data[bpos][1])) { // insert smaller value into result result.insert(data[apos][0], data[apos][1], data[apos][2]); apos++; } else { // add the values as row and col is same int addedval = data[apos][2] + b.data[bpos][2]; if (addedval != 0) result.insert(data[apos][0], data[apos][1], addedval); // then insert apos++; bpos++; } } // insert remaining elements while (apos < len) result.insert(data[apos][0], data[apos][1], data[apos++][2]); while (bpos < b.len) result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos++][2]); // print result result.print(); } } sparse_matrix transpose() { // new matrix with inversed row X col sparse_matrix result(col, row); // same number of elements result.len = len; // to count number of elements in each column int *count = new int[col + 1]; // initialize all to 0 for (int i = 1; i <= col; i++) count[i] = 0; for (int i = 0; i < len; i++) count[data[i][1]]++; int *index = new int[col + 1]; // to count number of elements having // col smaller than particular i // as there is no col with value < 0 index[0] = 0; // initialize rest of the indices for (int i = 1; i <= col; i++) index[i] = index[i - 1] + count[i - 1]; for (int i = 0; i < len; i++) { // insert a data at rpos and // increment its value int rpos = index[data[i][1]]++; // transpose row=col result.data[rpos][0] = data[i][1]; // transpose col=row result.data[rpos][1] = data[i][0]; // same value result.data[rpos][2] = data[i][2]; } // the above method ensures // sorting of transpose matrix // according to row-col value return result; } void multiply(sparse_matrix b) { if (col != b.row) { // Invalid multiplication cout << \"Can't multiply, Invalid dimensions\"; return; } // transpose b to compare row // and col values and to add them at the end b = b.transpose(); int apos, bpos; // result matrix of dimension row X b.col // however b has been transposed, // hence row X b.row sparse_matrix result(row, b.row); // iterate over all elements of A for (apos = 0; apos < len;) { // current row of result matrix int r = data[apos][0]; // iterate over all elements of B for (bpos = 0; bpos < b.len;) { // current column of result matrix // data[,0] used as b is transposed int c = b.data[bpos][0]; // temporary pointers created to add all // multiplied values to obtain current // element of result matrix int tempa = apos; int tempb = bpos; int sum = 0; // iterate over all elements with // same row and col value // to calculate result[r] while (tempa < len && data[tempa][0] == r && tempb < b.len && b.data[tempb][0] == c) { if (data[tempa][1] < b.data[tempb][1]) // skip a tempa++; else if (data[tempa][1] > b.data[tempb][1]) // skip b tempb++; else // same col, so multiply and increment sum += data[tempa++][2] * b.data[tempb++][2]; } // insert sum obtained in result[r] // if its not equal to 0 if (sum != 0) result.insert(r, c, sum); while (bpos < b.len && b.data[bpos][0] == c) // jump to next column bpos++; } while (apos < len && data[apos][0] == r) // jump to next row apos++; } result.print(); } // printing matrix void print() { cout << \"\\nDimension: \" << row << \"x\" << col; cout << \"\\nSparse Matrix: \\nRow\\tColumn\\tValue\\n\"; for (int i = 0; i < len; i++) { cout << data[i][0] << \"\\t \" << data[i][1] << \"\\t \" << data[i][2] << endl; } }}; // Driver Codeint main(){ // create two sparse matrices and insert values sparse_matrix a(4, 4); sparse_matrix b(4, 4); a.insert(1, 2, 10); a.insert(1, 4, 12); a.insert(3, 3, 5); a.insert(4, 1, 15); a.insert(4, 2, 12); b.insert(1, 3, 8); b.insert(2, 4, 23); b.insert(3, 3, 9); b.insert(4, 1, 20); b.insert(4, 2, 25); // Output result cout << \"Addition: \"; a.add(b); cout << \"\\nMultiplication: \"; a.multiply(b); cout << \"\\nTranspose: \"; sparse_matrix atranspose = a.transpose(); atranspose.print();} // This code is contributed// by Bharath Vignesh J K", "e": 12071, "s": 3727, "text": null }, { "code": "// Java code to perform add,// multiply and transpose on sparse matrices public class sparse_matrix { // Maximum number of elements in matrix int MAX = 100; // Array representation // of sparse matrix //[][0] represents row //[][1] represents col //[][2] represents value int data[][] = new int[MAX][3]; // dimensions of matrix int row, col; // total number of elements in matrix int len; public sparse_matrix(int r, int c) { // initialize row row = r; // initialize col col = c; // initialize length to 0 len = 0; } // insert elements into sparse matrix public void insert(int r, int c, int val) { // invalid entry if (r > row || c > col) { System.out.println(\"Wrong entry\"); } else { // insert row value data[len][0] = r; // insert col value data[len][1] = c; // insert element's value data[len][2] = val; // increment number of data in matrix len++; } } public void add(sparse_matrix b) { // if matrices don't have same dimensions if (row != b.row || col != b.col) { System.out.println(\"Matrices can't be added\"); } else { int apos = 0, bpos = 0; sparse_matrix result = new sparse_matrix(row, col); while (apos < len && bpos < b.len) { // if b's row and col is smaller if (data[apos][0] > b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] > b.data[bpos][1])) { // insert smaller value into result result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos][2]); bpos++; } // if a's row and col is smaller else if (data[apos][0] < b.data[bpos][0] || (data[apos][0] == b.data[bpos][0] && data[apos][1] < b.data[bpos][1])) { // insert smaller value into result result.insert(data[apos][0], data[apos][1], data[apos][2]); apos++; } else { // add the values as row and col is same int addedval = data[apos][2] + b.data[bpos][2]; if (addedval != 0) result.insert(data[apos][0], data[apos][1], addedval); // then insert apos++; bpos++; } } // insert remaining elements while (apos < len) result.insert(data[apos][0], data[apos][1], data[apos++][2]); while (bpos < b.len) result.insert(b.data[bpos][0], b.data[bpos][1], b.data[bpos++][2]); // print result result.print(); } } public sparse_matrix transpose() { // new matrix with inversed row X col sparse_matrix result = new sparse_matrix(col, row); // same number of elements result.len = len; // to count number of elements in each column int count[] = new int[col + 1]; // initialize all to 0 for (int i = 1; i <= col; i++) count[i] = 0; for (int i = 0; i < len; i++) count[data[i][1]]++; int[] index = new int[col + 1]; // to count number of elements having col smaller // than particular i // as there is no col with value < 1 index[1] = 0; // initialize rest of the indices for (int i = 2; i <= col; i++) index[i] = index[i - 1] + count[i - 1]; for (int i = 0; i < len; i++) { // insert a data at rpos and increment its value int rpos = index[data[i][1]]++; // transpose row=col result.data[rpos][0] = data[i][1]; // transpose col=row result.data[rpos][1] = data[i][0]; // same value result.data[rpos][2] = data[i][2]; } // the above method ensures // sorting of transpose matrix // according to row-col value return result; } public void multiply(sparse_matrix b) { if (col != b.row) { // Invalid multiplication System.out.println(\"Can't multiply, \" + \"Invalid dimensions\"); return; } // transpose b to compare row // and col values and to add them at the end b = b.transpose(); int apos, bpos; // result matrix of dimension row X b.col // however b has been transposed, hence row X b.row sparse_matrix result = new sparse_matrix(row, b.row); // iterate over all elements of A for (apos = 0; apos < len;) { // current row of result matrix int r = data[apos][0]; // iterate over all elements of B for (bpos = 0; bpos < b.len;) { // current column of result matrix // data[][0] used as b is transposed int c = b.data[bpos][0]; // temporary pointers created to add all // multiplied values to obtain current // element of result matrix int tempa = apos; int tempb = bpos; int sum = 0; // iterate over all elements with // same row and col value // to calculate result[r] while (tempa < len && data[tempa][0] == r && tempb < b.len && b.data[tempb][0] == c) { if (data[tempa][1] < b.data[tempb][1]) // skip a tempa++; else if (data[tempa][1] > b.data[tempb][1]) // skip b tempb++; else // same col, so multiply and increment sum += data[tempa++][2] * b.data[tempb++][2]; } // insert sum obtained in result[r] // if its not equal to 0 if (sum != 0) result.insert(r, c, sum); while (bpos < b.len && b.data[bpos][0] == c) // jump to next column bpos++; } while (apos < len && data[apos][0] == r) // jump to next row apos++; } result.print(); } // printing matrix public void print() { System.out.println(\"Dimension: \" + row + \"x\" + col); System.out.println(\"Sparse Matrix: \\nRow Column Value\"); for (int i = 0; i < len; i++) { System.out.println(data[i][0] + \" \" + data[i][1] + \" \" + data[i][2]); } } public static void main(String args[]) { // create two sparse matrices and insert values sparse_matrix a = new sparse_matrix(4, 4); sparse_matrix b = new sparse_matrix(4, 4); a.insert(1, 2, 10); a.insert(1, 4, 12); a.insert(3, 3, 5); a.insert(4, 1, 15); a.insert(4, 2, 12); b.insert(1, 3, 8); b.insert(2, 4, 23); b.insert(3, 3, 9); b.insert(4, 1, 20); b.insert(4, 2, 25); // Output result System.out.println(\"Addition: \"); a.add(b); System.out.println(\"\\nMultiplication: \"); a.multiply(b); System.out.println(\"\\nTranspose: \"); sparse_matrix atranspose = a.transpose(); atranspose.print(); }} // This code is contributed by Sudarshan Khasnis", "e": 20279, "s": 12071, "text": null }, { "code": "// C# code to perform add, // multiply and transpose on sparse matrices public class sparse_matrix { // Maximum number of elements in matrix static int MAX = 100; // Array representation // of sparse matrix //[,0] represents row //[,1] represents col //[,2] represents value int[,] data = new int[MAX,3]; // dimensions of matrix int row, col; // total number of elements in matrix int len; public sparse_matrix(int r, int c) { // initialize row row = r; // initialize col col = c; // initialize length to 0 len = 0; } // insert elements into sparse matrix public void insert(int r, int c, int val) { // invalid entry if (r > row || c > col) { System.Console.WriteLine(\"Wrong entry\"); } else { // insert row value data[len,0] = r; // insert col value data[len,1] = c; // insert element's value data[len,2] = val; // increment number of data in matrix len++; } } public void add(sparse_matrix b) { // if matrices don't have same dimensions if (row != b.row || col != b.col) { System.Console.WriteLine(\"Matrices can't be added\"); } else { int apos = 0, bpos = 0; sparse_matrix result = new sparse_matrix(row, col); while (apos < len && bpos < b.len) { // if b's row and col is smaller if (data[apos,0] > b.data[bpos,0] || (data[apos,0] == b.data[bpos,0] && data[apos,1] > b.data[bpos,1])) { // insert smaller value into result result.insert(b.data[bpos,0], b.data[bpos,1], b.data[bpos,2]); bpos++; } // if a's row and col is smaller else if (data[apos,0] < b.data[bpos,0] || (data[apos,0] == b.data[bpos,0] && data[apos,1] < b.data[bpos,1])) { // insert smaller value into result result.insert(data[apos,0], data[apos,1], data[apos,2]); apos++; } else { // add the values as row and col is same int addedval = data[apos,2] + b.data[bpos,2]; if (addedval != 0) result.insert(data[apos,0], data[apos,1], addedval); // then insert apos++; bpos++; } } // insert remaining elements while (apos < len) result.insert(data[apos,0], data[apos,1], data[apos++,2]); while (bpos < b.len) result.insert(b.data[bpos,0], b.data[bpos,1], b.data[bpos++,2]); // print result result.print(); } } public sparse_matrix transpose() { // new matrix with inversed row X col sparse_matrix result = new sparse_matrix(col, row); // same number of elements result.len = len; // to count number of elements in each column int[] count = new int[col + 1]; // initialize all to 0 for (int i = 1; i <= col; i++) count[i] = 0; for (int i = 0; i < len; i++) count[data[i,1]]++; int[] index = new int[col + 1]; // to count number of elements having col smaller // than particular i // as there is no col with value < 1 index[1] = 0; // initialize rest of the indices for (int i = 2; i <= col; i++) index[i] = index[i - 1] + count[i - 1]; for (int i = 0; i < len; i++) { // insert a data at rpos and increment its value int rpos = index[data[i,1]]++; // transpose row=col result.data[rpos,0] = data[i,1]; // transpose col=row result.data[rpos,1] = data[i,0]; // same value result.data[rpos,2] = data[i,2]; } // the above method ensures // sorting of transpose matrix // according to row-col value return result; } public void multiply(sparse_matrix b) { if (col != b.row) { // Invalid multiplication System.Console.WriteLine(\"Can't multiply, \" + \"Invalid dimensions\"); return; } // transpose b to compare row // and col values and to add them at the end b = b.transpose(); int apos, bpos; // result matrix of dimension row X b.col // however b has been transposed, hence row X b.row sparse_matrix result = new sparse_matrix(row, b.row); // iterate over all elements of A for (apos = 0; apos < len;) { // current row of result matrix int r = data[apos,0]; // iterate over all elements of B for (bpos = 0; bpos < b.len;) { // current column of result matrix // data[,0] used as b is transposed int c = b.data[bpos,0]; // temporary pointers created to add all // multiplied values to obtain current // element of result matrix int tempa = apos; int tempb = bpos; int sum = 0; // iterate over all elements with // same row and col value // to calculate result[r] while (tempa < len && data[tempa,0] == r && tempb < b.len && b.data[tempb,0] == c) { if (data[tempa,1] < b.data[tempb,1]) // skip a tempa++; else if (data[tempa,1] > b.data[tempb,1]) // skip b tempb++; else // same col, so multiply and increment sum += data[tempa++,2] * b.data[tempb++,2]; } // insert sum obtained in result[r] // if its not equal to 0 if (sum != 0) result.insert(r, c, sum); while (bpos < b.len && b.data[bpos,0] == c) // jump to next column bpos++; } while (apos < len && data[apos,0] == r) // jump to next row apos++; } result.print(); } // printing matrix public void print() { System.Console.WriteLine(\"Dimension: \" + row + \"x\" + col); System.Console.WriteLine(\"Sparse Matrix: \\nRow Column Value\"); for (int i = 0; i < len; i++) { System.Console.WriteLine(data[i,0] + \" \" + data[i,1] + \" \" + data[i,2]); } } public static void Main() { // create two sparse matrices and insert values sparse_matrix a = new sparse_matrix(4, 4); sparse_matrix b = new sparse_matrix(4, 4); a.insert(1, 2, 10); a.insert(1, 4, 12); a.insert(3, 3, 5); a.insert(4, 1, 15); a.insert(4, 2, 12); b.insert(1, 3, 8); b.insert(2, 4, 23); b.insert(3, 3, 9); b.insert(4, 1, 20); b.insert(4, 2, 25); // Output result System.Console.WriteLine(\"Addition: \"); a.add(b); System.Console.WriteLine(\"\\nMultiplication: \"); a.multiply(b); System.Console.WriteLine(\"\\nTranspose: \"); sparse_matrix atranspose = a.transpose(); atranspose.print(); } } // This code is contributed by mits", "e": 28647, "s": 20279, "text": null }, { "code": null, "e": 28963, "s": 28647, "text": "Addition: \nDimension: 4x4\nSparse Matrix: \nRow Column Value\n1 2 10\n1 3 8\n1 4 12\n2 4 23\n3 3 14\n4 1 35\n4 2 37\n\nMultiplication: \nDimension: 4x4\nSparse Matrix: \nRow Column Value\n1 1 240\n1 2 300\n1 4 230\n3 3 45\n4 3 120\n4 4 276\n\nTranspose: \nDimension: 4x4\nSparse Matrix: \nRow Column Value\n1 4 15\n2 1 10\n2 4 12\n3 3 5\n4 1 12\n" }, { "code": null, "e": 29484, "s": 28963, "text": "Worst case time complexity: Addition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements in the larger matrix amongst the two. Transpose has a time complexity of O(n+m), where n is the number of columns and m is the number of non-zero elements in the matrix. Multiplication, however, has a time complexity of O(x*n + y*m), where (x, m) is number of columns and terms in the second matrix; and (y, n) is number of rows and terms in the first matrix." }, { "code": null, "e": 29497, "s": 29484, "text": "aayushk61466" }, { "code": null, "e": 29510, "s": 29497, "text": "Mithun Kumar" }, { "code": null, "e": 29521, "s": 29510, "text": "nidhi_biet" }, { "code": null, "e": 29535, "s": 29521, "text": "shubham_singh" }, { "code": null, "e": 29552, "s": 29535, "text": "BharathVigneshJK" }, { "code": null, "e": 29559, "s": 29552, "text": "Arrays" }, { "code": null, "e": 29572, "s": 29559, "text": "Mathematical" }, { "code": null, "e": 29583, "s": 29572, "text": "Randomized" }, { "code": null, "e": 29590, "s": 29583, "text": "Arrays" }, { "code": null, "e": 29603, "s": 29590, "text": "Mathematical" } ]
Python program to check if number is palindrome (one-liner)
23 Apr, 2020 Sometimes, we have an application of checking a number is palindrome or not and it’s quite common while day-day programming or competitive programming, it’s easy to reverse a number and check it but sometimes for readability and reducing lines of code, we require to perform this in one-liner logic. Let’s discuss certain ways in which this can be achieved. Input : test_number = 12321Output : True Input : test_number = 1234Output : False Method #1 : Using math.log() + recursion + list comprehensionThe combination of above three functions can perform this particular task easily, the logs function extracts the number of digits which is powered by 10 to get the number for that iteration for comparison. The process is recurred to test for palindrome. # Python3 code to demonstrate# checking a number is palindrome# using math.log() + recursion + list comprehensionimport math # the recursive function to reversedef rev(num): return int(num != 0) and ((num % 10) * \ (10**int(math.log(num, 10))) + \ rev(num // 10)) # initializing number test_number = 9669669 # printing the original number print ("The original number is : " + str(test_number)) # using math.log() + recursion + list comprehension# for checking a number is palindromeres = test_number == rev(test_number) # printing resultprint ("Is the number palindrome ? : " + str(res)) The original number is : 9669669 Is the number palindrome ? : True Method #2 : Using str() + string slicingThis can also be done by converting the number into a string and then reversing it using the string slicing method and comparing it, truth of which returns the answer to it. # Python3 code to demonstrate# checking a number is palindrome# using str() + string slicing # initializing number test_number = 9669669 # printing the original number print ("The original number is : " + str(test_number)) # using str() + string slicing# for checking a number is palindromeres = str(test_number) == str(test_number)[::-1] # printing resultprint ("Is the number palindrome ? : " + str(res)) The original number is : 9669669 Is the number palindrome ? : True We can also read input as string and then simply check for palindrome. num = input("Enter a number")if num == num[::-1]: print("Yes its a palindrome")else: print("No, its not a palindrome") jackyuvaraj551 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Apr, 2020" }, { "code": null, "e": 412, "s": 54, "text": "Sometimes, we have an application of checking a number is palindrome or not and it’s quite common while day-day programming or competitive programming, it’s easy to reverse a number and check it but sometimes for readability and reducing lines of code, we require to perform this in one-liner logic. Let’s discuss certain ways in which this can be achieved." }, { "code": null, "e": 453, "s": 412, "text": "Input : test_number = 12321Output : True" }, { "code": null, "e": 494, "s": 453, "text": "Input : test_number = 1234Output : False" }, { "code": null, "e": 809, "s": 494, "text": "Method #1 : Using math.log() + recursion + list comprehensionThe combination of above three functions can perform this particular task easily, the logs function extracts the number of digits which is powered by 10 to get the number for that iteration for comparison. The process is recurred to test for palindrome." }, { "code": "# Python3 code to demonstrate# checking a number is palindrome# using math.log() + recursion + list comprehensionimport math # the recursive function to reversedef rev(num): return int(num != 0) and ((num % 10) * \\ (10**int(math.log(num, 10))) + \\ rev(num // 10)) # initializing number test_number = 9669669 # printing the original number print (\"The original number is : \" + str(test_number)) # using math.log() + recursion + list comprehension# for checking a number is palindromeres = test_number == rev(test_number) # printing resultprint (\"Is the number palindrome ? : \" + str(res))", "e": 1443, "s": 809, "text": null }, { "code": null, "e": 1511, "s": 1443, "text": "The original number is : 9669669\nIs the number palindrome ? : True\n" }, { "code": null, "e": 1726, "s": 1511, "text": " Method #2 : Using str() + string slicingThis can also be done by converting the number into a string and then reversing it using the string slicing method and comparing it, truth of which returns the answer to it." }, { "code": "# Python3 code to demonstrate# checking a number is palindrome# using str() + string slicing # initializing number test_number = 9669669 # printing the original number print (\"The original number is : \" + str(test_number)) # using str() + string slicing# for checking a number is palindromeres = str(test_number) == str(test_number)[::-1] # printing resultprint (\"Is the number palindrome ? : \" + str(res))", "e": 2137, "s": 1726, "text": null }, { "code": null, "e": 2205, "s": 2137, "text": "The original number is : 9669669\nIs the number palindrome ? : True\n" }, { "code": null, "e": 2276, "s": 2205, "text": "We can also read input as string and then simply check for palindrome." }, { "code": "num = input(\"Enter a number\")if num == num[::-1]: print(\"Yes its a palindrome\")else: print(\"No, its not a palindrome\")", "e": 2401, "s": 2276, "text": null }, { "code": null, "e": 2416, "s": 2401, "text": "jackyuvaraj551" }, { "code": null, "e": 2437, "s": 2416, "text": "Python list-programs" }, { "code": null, "e": 2444, "s": 2437, "text": "Python" }, { "code": null, "e": 2460, "s": 2444, "text": "Python Programs" }, { "code": null, "e": 2558, "s": 2460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2576, "s": 2558, "text": "Python Dictionary" }, { "code": null, "e": 2618, "s": 2576, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2640, "s": 2618, "text": "Enumerate() in Python" }, { "code": null, "e": 2675, "s": 2640, "text": "Read a file line by line in Python" }, { "code": null, "e": 2701, "s": 2675, "text": "Python String | replace()" }, { "code": null, "e": 2744, "s": 2701, "text": "Python program to convert a list to string" }, { "code": null, "e": 2766, "s": 2744, "text": "Defaultdict in Python" }, { "code": null, "e": 2805, "s": 2766, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2843, "s": 2805, "text": "Python | Convert a list to dictionary" } ]
Python | focus_set() and focus_get() method
25 Jun, 2019 Tkinter has a number of widgets to provide functionality in any GUI. It also supports a variety of universal widget methods which can be applied on any of the widget.focus_get() and focus_set() methods are also universal widget methods. They can also be applied on Tk() method. This method is used to set the focus on the desired widget if and only if the master window is focused. Syntax: widget.focus_set() Below is the Python program- # Importing tkinter module# and all functionsfrom tkinter import * from tkinter.ttk import * # creating master windowmaster = Tk() # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH) # Button widget which currently has the focuse2 = Button(master, text ="Button") # here focus_set() method is used to set the focuse2.focus_set()e2.pack(pady = 5) # Radiobuton widgete3 = Radiobutton(master, text ="Hello")e3.pack(pady = 5) # Infinite loopmainloop() Output: You may observe in above image that Button widget has the focus. For better understanding copy and run above program. This method returns the name of the widget which currently has the focus. Syntax: master.focus_get() Note: You can use it with any of the widget, master in not necessary. Below is the Python program – # Importing tkinter module# and all functionsfrom tkinter import * from tkinter.ttk import * # creating master windowmaster = Tk() # This method is used to get# the name of the widget# which currently has the focus# by clicking Mouse Button-1def focus(event): widget = master.focus_get() print(widget, "has focus") # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH) # Button Widgete2 = Button(master, text ="Button")e2.pack(pady = 5) # Radiobutton widgete3 = Radiobutton(master, text ="Hello")e3.pack(pady = 5) # Here function focus() is binded with Mouse Button-1# so every time you click mouse, it will call the# focus method, defined abovemaster.bind_all("<Button-1>", lambda e: focus(e)) # infinite loopmainloop() Output: Every time you click on any widget OR if you click the mouse button-1 above program will print the name of the widget which has the focus. For better understanding copy and run above program. .!radiobutton has focus .!entry has focus .!button has focus Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 306, "s": 28, "text": "Tkinter has a number of widgets to provide functionality in any GUI. It also supports a variety of universal widget methods which can be applied on any of the widget.focus_get() and focus_set() methods are also universal widget methods. They can also be applied on Tk() method." }, { "code": null, "e": 410, "s": 306, "text": "This method is used to set the focus on the desired widget if and only if the master window is focused." }, { "code": null, "e": 418, "s": 410, "text": "Syntax:" }, { "code": null, "e": 438, "s": 418, "text": "widget.focus_set()\n" }, { "code": null, "e": 467, "s": 438, "text": "Below is the Python program-" }, { "code": "# Importing tkinter module# and all functionsfrom tkinter import * from tkinter.ttk import * # creating master windowmaster = Tk() # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH) # Button widget which currently has the focuse2 = Button(master, text =\"Button\") # here focus_set() method is used to set the focuse2.focus_set()e2.pack(pady = 5) # Radiobuton widgete3 = Radiobutton(master, text =\"Hello\")e3.pack(pady = 5) # Infinite loopmainloop()", "e": 934, "s": 467, "text": null }, { "code": null, "e": 942, "s": 934, "text": "Output:" }, { "code": null, "e": 1060, "s": 942, "text": "You may observe in above image that Button widget has the focus. For better understanding copy and run above program." }, { "code": null, "e": 1134, "s": 1060, "text": "This method returns the name of the widget which currently has the focus." }, { "code": null, "e": 1142, "s": 1134, "text": "Syntax:" }, { "code": null, "e": 1162, "s": 1142, "text": "master.focus_get()\n" }, { "code": null, "e": 1232, "s": 1162, "text": "Note: You can use it with any of the widget, master in not necessary." }, { "code": null, "e": 1262, "s": 1232, "text": "Below is the Python program –" }, { "code": "# Importing tkinter module# and all functionsfrom tkinter import * from tkinter.ttk import * # creating master windowmaster = Tk() # This method is used to get# the name of the widget# which currently has the focus# by clicking Mouse Button-1def focus(event): widget = master.focus_get() print(widget, \"has focus\") # Entry widgete1 = Entry(master)e1.pack(expand = 1, fill = BOTH) # Button Widgete2 = Button(master, text =\"Button\")e2.pack(pady = 5) # Radiobutton widgete3 = Radiobutton(master, text =\"Hello\")e3.pack(pady = 5) # Here function focus() is binded with Mouse Button-1# so every time you click mouse, it will call the# focus method, defined abovemaster.bind_all(\"<Button-1>\", lambda e: focus(e)) # infinite loopmainloop()", "e": 2007, "s": 1262, "text": null }, { "code": null, "e": 2207, "s": 2007, "text": "Output: Every time you click on any widget OR if you click the mouse button-1 above program will print the name of the widget which has the focus. For better understanding copy and run above program." }, { "code": null, "e": 2269, "s": 2207, "text": ".!radiobutton has focus\n.!entry has focus\n.!button has focus\n" }, { "code": null, "e": 2280, "s": 2269, "text": "Python-gui" }, { "code": null, "e": 2295, "s": 2280, "text": "Python-tkinter" }, { "code": null, "e": 2302, "s": 2295, "text": "Python" } ]
fmax() and fmin() in C++
13 Apr, 2018 fmax() and fmin() functions are defined in cmath header file. fmax() function: The syntax of this function is:double fmax (double x, double y); float fmax (float x, float y); long double fmax (long double x, long double y); The input to this function are two values of type float, double or long double. The function returns maximum of the two input values.Below is sample C++ program to show working of fmax() function:// CPP program to show working// of fmax() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find maximum value when both the inputs // are positive. val = fmax(10.0, 1.0); cout << fixed << setprecision(4) << "fmax(10.0, 1.0) = " << val << "\n"; // Find maximum value when inputs have // opposite sign. val = fmax(-10.0, 1.0); cout << fixed << setprecision(4) << "fmax(-10.0, 1.0) = " << val << "\n"; // Find maximum value when both the inputs // are negative. val = fmax(-10.0, -1.0); cout << fixed << setprecision(4) << "fmax(-10.0, -1.0) = " << val << "\n"; return 0;}Output:fmax(10.0, 1.0) = 10.0000 fmax(-10.0, 1.0) = 1.0000 fmax(-10.0, -1.0) = -1.0000 fmin() function: The syntax of this function is:double fmin (double x, double y); float fmin (float x, float y); long double fmin (long double x, long double y); The input to this function are two values of type float, double or long double. The function returns minimum of the two input values.Below is sample C++ program to show working of fmin() function:// CPP program to show working// of fmin() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when both the inputs // are positive. val = fmin(10.0, 1.0); cout << fixed << setprecision(4) << "fmin(10.0, 1.0) = " << val << "\n"; // Find minimum value when inputs have // opposite sign. val = fmin(-10.0, 1.0); cout << fixed << setprecision(4) << "fmin(-10.0, 1.0) = " << val << "\n"; // Find minimum value when both the inputs // are negative. val = fmin(-10.0, -1.0); cout << fixed << setprecision(4) << "fmin(-10.0, -1.0) = " << val << "\n"; return 0;}Output:fmin(10.0, 1.0) = 1.0000 fmin(-10.0, 1.0) = -10.0000 fmin(-10.0, -1.0) = -10.0000 Note : Consider a case when the arguments of the function are of different types. In that case, the arguments are first implicity typecast by the function and then the required maximum/minimum value is returned.Below is sample C++ program that illustrates this case:// CPP program to show working// of fmin() and fmax()function// when input values are of// different data types. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when one of the inputs // is of type float and other is of type // double. val = fmin(10.0f, 1.0); cout << fixed << setprecision(4) << "fmin(10.0f, 1.0) = " << val << "\n"; // Find maximum value when one of the inputs // is of type float and other is of type // double. val = fmax(10.0, -1.0f); cout << fixed << setprecision(4) << "fmax(10.0, -1.0f) = " << val << "\n"; return 0;}Output:fmin(10.0f, 1.0) = 1.0000 fmax(10.0, -1.0f) = 10.0000 My Personal Notes arrow_drop_upSave fmax() function: The syntax of this function is:double fmax (double x, double y); float fmax (float x, float y); long double fmax (long double x, long double y); The input to this function are two values of type float, double or long double. The function returns maximum of the two input values.Below is sample C++ program to show working of fmax() function:// CPP program to show working// of fmax() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find maximum value when both the inputs // are positive. val = fmax(10.0, 1.0); cout << fixed << setprecision(4) << "fmax(10.0, 1.0) = " << val << "\n"; // Find maximum value when inputs have // opposite sign. val = fmax(-10.0, 1.0); cout << fixed << setprecision(4) << "fmax(-10.0, 1.0) = " << val << "\n"; // Find maximum value when both the inputs // are negative. val = fmax(-10.0, -1.0); cout << fixed << setprecision(4) << "fmax(-10.0, -1.0) = " << val << "\n"; return 0;}Output:fmax(10.0, 1.0) = 10.0000 fmax(-10.0, 1.0) = 1.0000 fmax(-10.0, -1.0) = -1.0000 double fmax (double x, double y); float fmax (float x, float y); long double fmax (long double x, long double y); The input to this function are two values of type float, double or long double. The function returns maximum of the two input values. Below is sample C++ program to show working of fmax() function: // CPP program to show working// of fmax() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find maximum value when both the inputs // are positive. val = fmax(10.0, 1.0); cout << fixed << setprecision(4) << "fmax(10.0, 1.0) = " << val << "\n"; // Find maximum value when inputs have // opposite sign. val = fmax(-10.0, 1.0); cout << fixed << setprecision(4) << "fmax(-10.0, 1.0) = " << val << "\n"; // Find maximum value when both the inputs // are negative. val = fmax(-10.0, -1.0); cout << fixed << setprecision(4) << "fmax(-10.0, -1.0) = " << val << "\n"; return 0;} fmax(10.0, 1.0) = 10.0000 fmax(-10.0, 1.0) = 1.0000 fmax(-10.0, -1.0) = -1.0000 fmin() function: The syntax of this function is:double fmin (double x, double y); float fmin (float x, float y); long double fmin (long double x, long double y); The input to this function are two values of type float, double or long double. The function returns minimum of the two input values.Below is sample C++ program to show working of fmin() function:// CPP program to show working// of fmin() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when both the inputs // are positive. val = fmin(10.0, 1.0); cout << fixed << setprecision(4) << "fmin(10.0, 1.0) = " << val << "\n"; // Find minimum value when inputs have // opposite sign. val = fmin(-10.0, 1.0); cout << fixed << setprecision(4) << "fmin(-10.0, 1.0) = " << val << "\n"; // Find minimum value when both the inputs // are negative. val = fmin(-10.0, -1.0); cout << fixed << setprecision(4) << "fmin(-10.0, -1.0) = " << val << "\n"; return 0;}Output:fmin(10.0, 1.0) = 1.0000 fmin(-10.0, 1.0) = -10.0000 fmin(-10.0, -1.0) = -10.0000 double fmin (double x, double y); float fmin (float x, float y); long double fmin (long double x, long double y); The input to this function are two values of type float, double or long double. The function returns minimum of the two input values. Below is sample C++ program to show working of fmin() function: // CPP program to show working// of fmin() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when both the inputs // are positive. val = fmin(10.0, 1.0); cout << fixed << setprecision(4) << "fmin(10.0, 1.0) = " << val << "\n"; // Find minimum value when inputs have // opposite sign. val = fmin(-10.0, 1.0); cout << fixed << setprecision(4) << "fmin(-10.0, 1.0) = " << val << "\n"; // Find minimum value when both the inputs // are negative. val = fmin(-10.0, -1.0); cout << fixed << setprecision(4) << "fmin(-10.0, -1.0) = " << val << "\n"; return 0;} fmin(10.0, 1.0) = 1.0000 fmin(-10.0, 1.0) = -10.0000 fmin(-10.0, -1.0) = -10.0000 Note : Consider a case when the arguments of the function are of different types. In that case, the arguments are first implicity typecast by the function and then the required maximum/minimum value is returned.Below is sample C++ program that illustrates this case: // CPP program to show working// of fmin() and fmax()function// when input values are of// different data types. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when one of the inputs // is of type float and other is of type // double. val = fmin(10.0f, 1.0); cout << fixed << setprecision(4) << "fmin(10.0f, 1.0) = " << val << "\n"; // Find maximum value when one of the inputs // is of type float and other is of type // double. val = fmax(10.0, -1.0f); cout << fixed << setprecision(4) << "fmax(10.0, -1.0f) = " << val << "\n"; return 0;} fmin(10.0f, 1.0) = 1.0000 fmax(10.0, -1.0f) = 10.0000 CPP-Library cpp-math C++ Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2018" }, { "code": null, "e": 90, "s": 28, "text": "fmax() and fmin() functions are defined in cmath header file." }, { "code": null, "e": 3440, "s": 90, "text": "fmax() function: The syntax of this function is:double fmax (double x, double y);\nfloat fmax (float x, float y);\nlong double fmax (long double x, long double y);\nThe input to this function are two values of type float, double or long double. The function returns maximum of the two input values.Below is sample C++ program to show working of fmax() function:// CPP program to show working// of fmax() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find maximum value when both the inputs // are positive. val = fmax(10.0, 1.0); cout << fixed << setprecision(4) << \"fmax(10.0, 1.0) = \" << val << \"\\n\"; // Find maximum value when inputs have // opposite sign. val = fmax(-10.0, 1.0); cout << fixed << setprecision(4) << \"fmax(-10.0, 1.0) = \" << val << \"\\n\"; // Find maximum value when both the inputs // are negative. val = fmax(-10.0, -1.0); cout << fixed << setprecision(4) << \"fmax(-10.0, -1.0) = \" << val << \"\\n\"; return 0;}Output:fmax(10.0, 1.0) = 10.0000\nfmax(-10.0, 1.0) = 1.0000\nfmax(-10.0, -1.0) = -1.0000\nfmin() function: The syntax of this function is:double fmin (double x, double y);\nfloat fmin (float x, float y);\nlong double fmin (long double x, long double y);\nThe input to this function are two values of type float, double or long double. The function returns minimum of the two input values.Below is sample C++ program to show working of fmin() function:// CPP program to show working// of fmin() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when both the inputs // are positive. val = fmin(10.0, 1.0); cout << fixed << setprecision(4) << \"fmin(10.0, 1.0) = \" << val << \"\\n\"; // Find minimum value when inputs have // opposite sign. val = fmin(-10.0, 1.0); cout << fixed << setprecision(4) << \"fmin(-10.0, 1.0) = \" << val << \"\\n\"; // Find minimum value when both the inputs // are negative. val = fmin(-10.0, -1.0); cout << fixed << setprecision(4) << \"fmin(-10.0, -1.0) = \" << val << \"\\n\"; return 0;}Output:fmin(10.0, 1.0) = 1.0000\nfmin(-10.0, 1.0) = -10.0000\nfmin(-10.0, -1.0) = -10.0000\nNote : Consider a case when the arguments of the function are of different types. In that case, the arguments are first implicity typecast by the function and then the required maximum/minimum value is returned.Below is sample C++ program that illustrates this case:// CPP program to show working// of fmin() and fmax()function// when input values are of// different data types. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when one of the inputs // is of type float and other is of type // double. val = fmin(10.0f, 1.0); cout << fixed << setprecision(4) << \"fmin(10.0f, 1.0) = \" << val << \"\\n\"; // Find maximum value when one of the inputs // is of type float and other is of type // double. val = fmax(10.0, -1.0f); cout << fixed << setprecision(4) << \"fmax(10.0, -1.0f) = \" << val << \"\\n\"; return 0;}Output:fmin(10.0f, 1.0) = 1.0000\nfmax(10.0, -1.0f) = 10.0000\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 4596, "s": 3440, "text": "fmax() function: The syntax of this function is:double fmax (double x, double y);\nfloat fmax (float x, float y);\nlong double fmax (long double x, long double y);\nThe input to this function are two values of type float, double or long double. The function returns maximum of the two input values.Below is sample C++ program to show working of fmax() function:// CPP program to show working// of fmax() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find maximum value when both the inputs // are positive. val = fmax(10.0, 1.0); cout << fixed << setprecision(4) << \"fmax(10.0, 1.0) = \" << val << \"\\n\"; // Find maximum value when inputs have // opposite sign. val = fmax(-10.0, 1.0); cout << fixed << setprecision(4) << \"fmax(-10.0, 1.0) = \" << val << \"\\n\"; // Find maximum value when both the inputs // are negative. val = fmax(-10.0, -1.0); cout << fixed << setprecision(4) << \"fmax(-10.0, -1.0) = \" << val << \"\\n\"; return 0;}Output:fmax(10.0, 1.0) = 10.0000\nfmax(-10.0, 1.0) = 1.0000\nfmax(-10.0, -1.0) = -1.0000\n" }, { "code": null, "e": 4711, "s": 4596, "text": "double fmax (double x, double y);\nfloat fmax (float x, float y);\nlong double fmax (long double x, long double y);\n" }, { "code": null, "e": 4845, "s": 4711, "text": "The input to this function are two values of type float, double or long double. The function returns maximum of the two input values." }, { "code": null, "e": 4909, "s": 4845, "text": "Below is sample C++ program to show working of fmax() function:" }, { "code": "// CPP program to show working// of fmax() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find maximum value when both the inputs // are positive. val = fmax(10.0, 1.0); cout << fixed << setprecision(4) << \"fmax(10.0, 1.0) = \" << val << \"\\n\"; // Find maximum value when inputs have // opposite sign. val = fmax(-10.0, 1.0); cout << fixed << setprecision(4) << \"fmax(-10.0, 1.0) = \" << val << \"\\n\"; // Find maximum value when both the inputs // are negative. val = fmax(-10.0, -1.0); cout << fixed << setprecision(4) << \"fmax(-10.0, -1.0) = \" << val << \"\\n\"; return 0;}", "e": 5620, "s": 4909, "text": null }, { "code": null, "e": 5701, "s": 5620, "text": "fmax(10.0, 1.0) = 10.0000\nfmax(-10.0, 1.0) = 1.0000\nfmax(-10.0, -1.0) = -1.0000\n" }, { "code": null, "e": 6859, "s": 5701, "text": "fmin() function: The syntax of this function is:double fmin (double x, double y);\nfloat fmin (float x, float y);\nlong double fmin (long double x, long double y);\nThe input to this function are two values of type float, double or long double. The function returns minimum of the two input values.Below is sample C++ program to show working of fmin() function:// CPP program to show working// of fmin() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when both the inputs // are positive. val = fmin(10.0, 1.0); cout << fixed << setprecision(4) << \"fmin(10.0, 1.0) = \" << val << \"\\n\"; // Find minimum value when inputs have // opposite sign. val = fmin(-10.0, 1.0); cout << fixed << setprecision(4) << \"fmin(-10.0, 1.0) = \" << val << \"\\n\"; // Find minimum value when both the inputs // are negative. val = fmin(-10.0, -1.0); cout << fixed << setprecision(4) << \"fmin(-10.0, -1.0) = \" << val << \"\\n\"; return 0;}Output:fmin(10.0, 1.0) = 1.0000\nfmin(-10.0, 1.0) = -10.0000\nfmin(-10.0, -1.0) = -10.0000\n" }, { "code": null, "e": 6974, "s": 6859, "text": "double fmin (double x, double y);\nfloat fmin (float x, float y);\nlong double fmin (long double x, long double y);\n" }, { "code": null, "e": 7108, "s": 6974, "text": "The input to this function are two values of type float, double or long double. The function returns minimum of the two input values." }, { "code": null, "e": 7172, "s": 7108, "text": "Below is sample C++ program to show working of fmin() function:" }, { "code": "// CPP program to show working// of fmin() function. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when both the inputs // are positive. val = fmin(10.0, 1.0); cout << fixed << setprecision(4) << \"fmin(10.0, 1.0) = \" << val << \"\\n\"; // Find minimum value when inputs have // opposite sign. val = fmin(-10.0, 1.0); cout << fixed << setprecision(4) << \"fmin(-10.0, 1.0) = \" << val << \"\\n\"; // Find minimum value when both the inputs // are negative. val = fmin(-10.0, -1.0); cout << fixed << setprecision(4) << \"fmin(-10.0, -1.0) = \" << val << \"\\n\"; return 0;}", "e": 7883, "s": 7172, "text": null }, { "code": null, "e": 7966, "s": 7883, "text": "fmin(10.0, 1.0) = 1.0000\nfmin(-10.0, 1.0) = -10.0000\nfmin(-10.0, -1.0) = -10.0000\n" }, { "code": null, "e": 8233, "s": 7966, "text": "Note : Consider a case when the arguments of the function are of different types. In that case, the arguments are first implicity typecast by the function and then the required maximum/minimum value is returned.Below is sample C++ program that illustrates this case:" }, { "code": "// CPP program to show working// of fmin() and fmax()function// when input values are of// different data types. #include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ double val; // Find minimum value when one of the inputs // is of type float and other is of type // double. val = fmin(10.0f, 1.0); cout << fixed << setprecision(4) << \"fmin(10.0f, 1.0) = \" << val << \"\\n\"; // Find maximum value when one of the inputs // is of type float and other is of type // double. val = fmax(10.0, -1.0f); cout << fixed << setprecision(4) << \"fmax(10.0, -1.0f) = \" << val << \"\\n\"; return 0;}", "e": 8909, "s": 8233, "text": null }, { "code": null, "e": 8964, "s": 8909, "text": "fmin(10.0f, 1.0) = 1.0000\nfmax(10.0, -1.0f) = 10.0000\n" }, { "code": null, "e": 8976, "s": 8964, "text": "CPP-Library" }, { "code": null, "e": 8985, "s": 8976, "text": "cpp-math" }, { "code": null, "e": 8989, "s": 8985, "text": "C++" }, { "code": null, "e": 9010, "s": 8989, "text": "Programming Language" }, { "code": null, "e": 9014, "s": 9010, "text": "CPP" } ]
ReactJS findDOMNode() Method
26 May, 2021 React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the FindDOMNode() method is used to return DOM of the given element. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import ReactDOM from 'react-dom'; // Defining our App Componentconst App = () => { // Function to get element from findDOMNode() function find() { var node = document.getElementById("node"); var a = ReactDOM.findDOMNode(node); console.log(a); a.style.color = 'green'; a.style.fontSize = "x-large"; } // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> <div id='node'>DOM Node</div> <button onClick={find}>Click to find</button> </div> </>;} // Exporting your Default App Componentexport default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference:https://reactjs.org/docs/react-dom.html#finddomnode ReactJS-Basics ReactJS-Methods ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2021" }, { "code": null, "e": 353, "s": 28, "text": "React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the FindDOMNode() method is used to return DOM of the given element." }, { "code": null, "e": 403, "s": 353, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 498, "s": 403, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 562, "s": 498, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 594, "s": 562, "text": "npx create-react-app foldername" }, { "code": null, "e": 707, "s": 594, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 807, "s": 707, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 821, "s": 807, "text": "cd foldername" }, { "code": null, "e": 873, "s": 821, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1003, "s": 873, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1010, "s": 1003, "text": "App.js" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; // Defining our App Componentconst App = () => { // Function to get element from findDOMNode() function find() { var node = document.getElementById(\"node\"); var a = ReactDOM.findDOMNode(node); console.log(a); a.style.color = 'green'; a.style.fontSize = \"x-large\"; } // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> <div id='node'>DOM Node</div> <button onClick={find}>Click to find</button> </div> </>;} // Exporting your Default App Componentexport default App", "e": 1596, "s": 1010, "text": null }, { "code": null, "e": 1709, "s": 1596, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1719, "s": 1709, "text": "npm start" }, { "code": null, "e": 1818, "s": 1719, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 1880, "s": 1818, "text": "Reference:https://reactjs.org/docs/react-dom.html#finddomnode" }, { "code": null, "e": 1895, "s": 1880, "text": "ReactJS-Basics" }, { "code": null, "e": 1911, "s": 1895, "text": "ReactJS-Methods" }, { "code": null, "e": 1919, "s": 1911, "text": "ReactJS" }, { "code": null, "e": 1936, "s": 1919, "text": "Web Technologies" } ]
How to display notnull rows and columns in a Python dataframe?
03 Mar, 2021 In Python, not null rows and columns mean the rows and columns which have Nan values, especially in the Pandas library. To display not null rows and columns in a python data frame we are going to use different methods as dropna(), notnull(), loc[]. dropna() : This function is used to remove rows and column which has missing values that are NaN values. dropna() function has axis parameter. If it set to 0 then it will remove all the rows which have NaN value and if it is set to 1 then it will remove all the columns which have NaN value. By default, the value of axis parameter is 0. notnull(): This function detects non-missing values and returns a mask of boolean values for each element in DataFrame that indicates whether an element is not an NA value. loc[]: This method filter rows and columns by labels or boolean array. In our example, this method filters rows by a boolean array which is returned by notnull() method. Steps: Import pandas library Read the CSV file, or you can create your own data frame. Use one of the method like dropna(), notnull(), loc[] as described below. Display result Below StudentData.csv file used in the program: Method 1: Using dropna() method In this method, we are using the dropna() method which drops the null rows and displays the modified data frame. Python3 # Import libraryimport pandas as pd # Reading csv filedf = pd.read_csv('StudentData.csv') # using dropna() methoddf = df.dropna() # Printing resultprint(df) Output: Method 2: Using notnull() and dropna() method In this method, we will first use notnull() method which is return a boolean object having True and False values. If there is NaN value it will return false otherwise true. And then give these boolean objects as input parameters to where function along with this function use drpna() to drop NaN rows. Python3 # Import libraryimport pandas as pd # Reading csv filedf = pd.read_csv('StudentData.csv') # using notnull() method ,it will return # boolean valuesmask = df.notnull() # using dropna() method to drop NaN # value rowsdf = df.where(mask).dropna() # Displaying resultprint(df) Output: Method 3: Using loc[] and notnull() method In this method, we are using two concepts one is a method and the other is property. So first, we find a data frame with not null instances per specific column and then locate the instances over whole data to get the data frame. Python3 # Import libraryimport pandas as pd # Reading csv filedf = pd.read_csv('StudentData.csv') # Here filtering the rows according to # Grade column which has notnull value.df = df.loc[df['Grade'].notnull()] # Displaying resultprint(df) Output: As shown in the output image, only the rows having Grade != NaN is displayed. Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts Introduction To PYTHON 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": "\n03 Mar, 2021" }, { "code": null, "e": 277, "s": 28, "text": "In Python, not null rows and columns mean the rows and columns which have Nan values, especially in the Pandas library. To display not null rows and columns in a python data frame we are going to use different methods as dropna(), notnull(), loc[]." }, { "code": null, "e": 615, "s": 277, "text": "dropna() : This function is used to remove rows and column which has missing values that are NaN values. dropna() function has axis parameter. If it set to 0 then it will remove all the rows which have NaN value and if it is set to 1 then it will remove all the columns which have NaN value. By default, the value of axis parameter is 0." }, { "code": null, "e": 788, "s": 615, "text": "notnull(): This function detects non-missing values and returns a mask of boolean values for each element in DataFrame that indicates whether an element is not an NA value." }, { "code": null, "e": 958, "s": 788, "text": "loc[]: This method filter rows and columns by labels or boolean array. In our example, this method filters rows by a boolean array which is returned by notnull() method." }, { "code": null, "e": 965, "s": 958, "text": "Steps:" }, { "code": null, "e": 987, "s": 965, "text": "Import pandas library" }, { "code": null, "e": 1045, "s": 987, "text": "Read the CSV file, or you can create your own data frame." }, { "code": null, "e": 1119, "s": 1045, "text": "Use one of the method like dropna(), notnull(), loc[] as described below." }, { "code": null, "e": 1134, "s": 1119, "text": "Display result" }, { "code": null, "e": 1182, "s": 1134, "text": "Below StudentData.csv file used in the program:" }, { "code": null, "e": 1215, "s": 1182, "text": "Method 1: Using dropna() method " }, { "code": null, "e": 1328, "s": 1215, "text": "In this method, we are using the dropna() method which drops the null rows and displays the modified data frame." }, { "code": null, "e": 1336, "s": 1328, "text": "Python3" }, { "code": "# Import libraryimport pandas as pd # Reading csv filedf = pd.read_csv('StudentData.csv') # using dropna() methoddf = df.dropna() # Printing resultprint(df)", "e": 1496, "s": 1336, "text": null }, { "code": null, "e": 1504, "s": 1496, "text": "Output:" }, { "code": null, "e": 1550, "s": 1504, "text": "Method 2: Using notnull() and dropna() method" }, { "code": null, "e": 1852, "s": 1550, "text": "In this method, we will first use notnull() method which is return a boolean object having True and False values. If there is NaN value it will return false otherwise true. And then give these boolean objects as input parameters to where function along with this function use drpna() to drop NaN rows." }, { "code": null, "e": 1860, "s": 1852, "text": "Python3" }, { "code": "# Import libraryimport pandas as pd # Reading csv filedf = pd.read_csv('StudentData.csv') # using notnull() method ,it will return # boolean valuesmask = df.notnull() # using dropna() method to drop NaN # value rowsdf = df.where(mask).dropna() # Displaying resultprint(df)", "e": 2137, "s": 1860, "text": null }, { "code": null, "e": 2145, "s": 2137, "text": "Output:" }, { "code": null, "e": 2188, "s": 2145, "text": "Method 3: Using loc[] and notnull() method" }, { "code": null, "e": 2417, "s": 2188, "text": "In this method, we are using two concepts one is a method and the other is property. So first, we find a data frame with not null instances per specific column and then locate the instances over whole data to get the data frame." }, { "code": null, "e": 2425, "s": 2417, "text": "Python3" }, { "code": "# Import libraryimport pandas as pd # Reading csv filedf = pd.read_csv('StudentData.csv') # Here filtering the rows according to # Grade column which has notnull value.df = df.loc[df['Grade'].notnull()] # Displaying resultprint(df)", "e": 2660, "s": 2425, "text": null }, { "code": null, "e": 2668, "s": 2660, "text": "Output:" }, { "code": null, "e": 2746, "s": 2668, "text": "As shown in the output image, only the rows having Grade != NaN is displayed." }, { "code": null, "e": 2753, "s": 2746, "text": "Picked" }, { "code": null, "e": 2777, "s": 2753, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2791, "s": 2777, "text": "Python-pandas" }, { "code": null, "e": 2798, "s": 2791, "text": "Python" }, { "code": null, "e": 2896, "s": 2798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2928, "s": 2896, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2955, "s": 2928, "text": "Python Classes and Objects" }, { "code": null, "e": 2986, "s": 2955, "text": "Python | os.path.join() method" }, { "code": null, "e": 3007, "s": 2986, "text": "Python OOPs Concepts" }, { "code": null, "e": 3030, "s": 3007, "text": "Introduction To PYTHON" }, { "code": null, "e": 3086, "s": 3030, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3128, "s": 3086, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3170, "s": 3128, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3209, "s": 3170, "text": "Python | Get unique values from a list" } ]
EAFP Principle in Python - GeeksforGeeks
10 May, 2020 EAFP is a piece of gem advice in the Python community which may not be familiar to programmers of other communities. Quickly, EAFP or β€˜Easier to Ask for Forgiveness than Permission’ means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with it later. β€œAlways remember that it’s much easier to apologize than to get permission. In this world of computers, the best thing to do is to do it.” β€” Grace Hopper It is unlike the traditional method of LBYL or β€˜Look Before You Leap’, where you check whether your code will succeed and proceed if and only if there is no error. Example: Suppose you want to open a file and read its contents. β€˜Permission’ code: import os # Race conditionFile_name ="test.txt" if os.access(File_name, os.R_ok): with open(File_name) as f: print(f.read())else: print("No such file accessed") When you ask for permission to read the file, the answer is β€˜Yes’, but by the time you actually go for reading the answer is changed. This is where you open yourself to the Race condition. β€˜Forgiveness’ code: What you should do instead is go ahead with the flow and ask for forgiveness i.e catch the error using Exception handling. # No Race conditionFile_name ="test.txt" try: f = open(File_name)except IOError: print("No such file accessed") else: with f: print(f.read()) The Advantages of the EAFP method: Explicit is better than implicit Fail, but Fail fast and Succeed faster Fail, but Fail cheap Don’t repeat yourself Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25579, "s": 25551, "text": "\n10 May, 2020" }, { "code": null, "e": 25890, "s": 25579, "text": "EAFP is a piece of gem advice in the Python community which may not be familiar to programmers of other communities. Quickly, EAFP or β€˜Easier to Ask for Forgiveness than Permission’ means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with it later." }, { "code": null, "e": 26044, "s": 25890, "text": "β€œAlways remember that it’s much easier to apologize than to get permission. In this world of computers, the best thing to do is to do it.” β€” Grace Hopper" }, { "code": null, "e": 26208, "s": 26044, "text": "It is unlike the traditional method of LBYL or β€˜Look Before You Leap’, where you check whether your code will succeed and proceed if and only if there is no error." }, { "code": null, "e": 26272, "s": 26208, "text": "Example: Suppose you want to open a file and read its contents." }, { "code": null, "e": 26291, "s": 26272, "text": "β€˜Permission’ code:" }, { "code": "import os # Race conditionFile_name =\"test.txt\" if os.access(File_name, os.R_ok): with open(File_name) as f: print(f.read())else: print(\"No such file accessed\") ", "e": 26470, "s": 26291, "text": null }, { "code": null, "e": 26659, "s": 26470, "text": "When you ask for permission to read the file, the answer is β€˜Yes’, but by the time you actually go for reading the answer is changed. This is where you open yourself to the Race condition." }, { "code": null, "e": 26802, "s": 26659, "text": "β€˜Forgiveness’ code: What you should do instead is go ahead with the flow and ask for forgiveness i.e catch the error using Exception handling." }, { "code": "# No Race conditionFile_name =\"test.txt\" try: f = open(File_name)except IOError: print(\"No such file accessed\") else: with f: print(f.read())", "e": 26961, "s": 26802, "text": null }, { "code": null, "e": 26996, "s": 26961, "text": "The Advantages of the EAFP method:" }, { "code": null, "e": 27029, "s": 26996, "text": "Explicit is better than implicit" }, { "code": null, "e": 27068, "s": 27029, "text": "Fail, but Fail fast and Succeed faster" }, { "code": null, "e": 27089, "s": 27068, "text": "Fail, but Fail cheap" }, { "code": null, "e": 27111, "s": 27089, "text": "Don’t repeat yourself" }, { "code": null, "e": 27132, "s": 27111, "text": "Python-Miscellaneous" }, { "code": null, "e": 27139, "s": 27132, "text": "Python" }, { "code": null, "e": 27237, "s": 27139, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27269, "s": 27237, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27311, "s": 27269, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27353, "s": 27311, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27409, "s": 27353, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27436, "s": 27409, "text": "Python Classes and Objects" }, { "code": null, "e": 27467, "s": 27436, "text": "Python | os.path.join() method" }, { "code": null, "e": 27496, "s": 27467, "text": "Create a directory in Python" }, { "code": null, "e": 27518, "s": 27496, "text": "Defaultdict in Python" }, { "code": null, "e": 27557, "s": 27518, "text": "Python | Get unique values from a list" } ]
Arranging clustering column in descending order in Cassandra - GeeksforGeeks
15 Jan, 2020 Perquisite – CassandraIn this article, we are going to discuss how we can arrange table data and how we can arrange clustering column in descending order in a table. To arrange clustering column in descending order first, we are going to create a table with clustering column. First, we will see the results without using order by clause.Let’s have a look. CREATE TABLE Emp_track ( emp_no int, dept text, name text, PRIMARY KEY (dept, emp_no) ); Now, we are going to insert some data into the table.Let’s have a look. insert into Emp_track(emp_no, dept, name) values (101, 'database', 'Ashish'); insert into Emp_track(emp_no, dept, name) values (102, 'database', 'rana'); insert into Emp_track(emp_no, dept, name) values (103, 'database', 'zishan'); insert into Emp_track(emp_no, dept, name) values (104, 'database', 'abi'); insert into Emp_track(emp_no, dept, name) values (105, 'database', 'kartikey'); Now, to see the results used the following CQL query given below. select * from Emp_track; Output: Now, here we are going to using order by clause.Let’s have a look. CREATE TABLE Emp_track ( emp_no int, dept text, name text, PRIMARY KEY (dept, emp_no) ) WITH CLUSTERING ORDER BY (emp_no desc); Here, we will see emp_no is a clustering column and to arrange it in descending order we will use order by clause at the time of table creation. Now, we are going to insert some data into the table.Let’s have a look. insert into Emp_track(emp_no, dept, name) values (101, 'database', 'Ashish'); insert into Emp_track(emp_no, dept, name) values (102, 'database', 'rana'); insert into Emp_track(emp_no, dept, name) values (103, 'database', 'zishan'); insert into Emp_track(emp_no, dept, name) values (104, 'database', 'abi'); insert into Emp_track(emp_no, dept, name) values (105, 'database', 'kartikey'); Now, to see the results used the following CQL query given below. select * from Emp_track; Output: Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions SQL Trigger | Student Database CTE in SQL Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of ER Model Data Preprocessing in Data Mining Introduction of DBMS (Database Management System) | Set 1 SQL | GROUP BY SQL | Views
[ { "code": null, "e": 25393, "s": 25365, "text": "\n15 Jan, 2020" }, { "code": null, "e": 25559, "s": 25393, "text": "Perquisite – CassandraIn this article, we are going to discuss how we can arrange table data and how we can arrange clustering column in descending order in a table." }, { "code": null, "e": 25670, "s": 25559, "text": "To arrange clustering column in descending order first, we are going to create a table with clustering column." }, { "code": null, "e": 25750, "s": 25670, "text": "First, we will see the results without using order by clause.Let’s have a look." }, { "code": null, "e": 25848, "s": 25750, "text": "CREATE TABLE Emp_track (\n emp_no int,\n dept text,\n name text,\n PRIMARY KEY (dept, emp_no)\n); " }, { "code": null, "e": 25920, "s": 25848, "text": "Now, we are going to insert some data into the table.Let’s have a look." }, { "code": null, "e": 26313, "s": 25920, "text": "insert into Emp_track(emp_no, dept, name) values (101, 'database', 'Ashish'); \ninsert into Emp_track(emp_no, dept, name) values (102, 'database', 'rana'); \ninsert into Emp_track(emp_no, dept, name) values (103, 'database', 'zishan'); \ninsert into Emp_track(emp_no, dept, name) values (104, 'database', 'abi'); \ninsert into Emp_track(emp_no, dept, name) values (105, 'database', 'kartikey'); " }, { "code": null, "e": 26379, "s": 26313, "text": "Now, to see the results used the following CQL query given below." }, { "code": null, "e": 26406, "s": 26379, "text": "select * \nfrom Emp_track; " }, { "code": null, "e": 26414, "s": 26406, "text": "Output:" }, { "code": null, "e": 26481, "s": 26414, "text": "Now, here we are going to using order by clause.Let’s have a look." }, { "code": null, "e": 26618, "s": 26481, "text": "CREATE TABLE Emp_track (\n emp_no int,\n dept text,\n name text,\n PRIMARY KEY (dept, emp_no)\n)\nWITH CLUSTERING ORDER BY (emp_no desc); " }, { "code": null, "e": 26763, "s": 26618, "text": "Here, we will see emp_no is a clustering column and to arrange it in descending order we will use order by clause at the time of table creation." }, { "code": null, "e": 26835, "s": 26763, "text": "Now, we are going to insert some data into the table.Let’s have a look." }, { "code": null, "e": 27228, "s": 26835, "text": "insert into Emp_track(emp_no, dept, name) values (101, 'database', 'Ashish'); \ninsert into Emp_track(emp_no, dept, name) values (102, 'database', 'rana'); \ninsert into Emp_track(emp_no, dept, name) values (103, 'database', 'zishan'); \ninsert into Emp_track(emp_no, dept, name) values (104, 'database', 'abi'); \ninsert into Emp_track(emp_no, dept, name) values (105, 'database', 'kartikey'); \n" }, { "code": null, "e": 27294, "s": 27228, "text": "Now, to see the results used the following CQL query given below." }, { "code": null, "e": 27321, "s": 27294, "text": "select * \nfrom Emp_track; " }, { "code": null, "e": 27329, "s": 27321, "text": "Output:" }, { "code": null, "e": 27336, "s": 27329, "text": "Apache" }, { "code": null, "e": 27341, "s": 27336, "text": "DBMS" }, { "code": null, "e": 27346, "s": 27341, "text": "DBMS" }, { "code": null, "e": 27444, "s": 27346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27468, "s": 27444, "text": "SQL Interview Questions" }, { "code": null, "e": 27499, "s": 27468, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 27510, "s": 27499, "text": "CTE in SQL" }, { "code": null, "e": 27533, "s": 27510, "text": "Introduction of B-Tree" }, { "code": null, "e": 27586, "s": 27533, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27611, "s": 27586, "text": "Introduction of ER Model" }, { "code": null, "e": 27645, "s": 27611, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 27703, "s": 27645, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 27718, "s": 27703, "text": "SQL | GROUP BY" } ]
How to Use Word() Function in Arduino?
The word() function converts a variable of any data type to the word data type. It is essentially a cast function. The syntax is βˆ’ word(var) Where var is a variable of any datatype. Alternatively, you can also construct a word by specifying two bytes, the higher byte and the lower byte. The syntax is βˆ’ word(highByte, lowByte) For instance, word(2,5) will return 517 (2 is 0b00000010 and 5 is 0b00000101; word(2,5) will return 0b0000001000000101, which equals 517). You can try out other combinations of characters and data types. You can read more about the word function from Arduino’s official documentation here.
[ { "code": null, "e": 1177, "s": 1062, "text": "The word() function converts a variable of any data type to the word data type. It is essentially a cast function." }, { "code": null, "e": 1193, "s": 1177, "text": "The syntax is βˆ’" }, { "code": null, "e": 1203, "s": 1193, "text": "word(var)" }, { "code": null, "e": 1244, "s": 1203, "text": "Where var is a variable of any datatype." }, { "code": null, "e": 1350, "s": 1244, "text": "Alternatively, you can also construct a word by specifying two bytes, the higher byte and the lower byte." }, { "code": null, "e": 1366, "s": 1350, "text": "The syntax is βˆ’" }, { "code": null, "e": 1390, "s": 1366, "text": "word(highByte, lowByte)" }, { "code": null, "e": 1529, "s": 1390, "text": "For instance, word(2,5) will return 517 (2 is 0b00000010 and 5 is 0b00000101; word(2,5) will return 0b0000001000000101, which equals 517)." }, { "code": null, "e": 1680, "s": 1529, "text": "You can try out other combinations of characters and data types. You can read more about the word function from Arduino’s official documentation here." } ]
C program to represent the numbers in spiral pattern
The spiral pattern to represent the numbers is shown below βˆ’ The logic applied to print the numbers in spiral pattern is as follows βˆ’ for(i=1;i<=rows*2;i+=2){ if(k%2==1){ printf("%3d %3d",i,i+1); k++; }else{ printf("%3d %3d",i+1,i); k++; } printf("\n"); } Following is the C program for representing the numbers in spiral pattern βˆ’ #include<stdio.h> main(){ int i,rows,k=1; printf("Enter number of Rows for Spiral Pattern\n"); scanf("%d",&rows); for(i=1;i<=rows*2;i+=2){ if(k%2==1){ printf("%3d %3d",i,i+1); k++; }else{ printf("%3d %3d",i+1,i); k++; } printf("\n"); } } When the above program is executed, it produces the following result βˆ’ Enter number of Rows for Spiral Pattern 10 1 2 4 3 5 6 8 7 9 10 12 11 13 14 16 15 17 18 20 19
[ { "code": null, "e": 1123, "s": 1062, "text": "The spiral pattern to represent the numbers is shown below βˆ’" }, { "code": null, "e": 1196, "s": 1123, "text": "The logic applied to print the numbers in spiral pattern is as follows βˆ’" }, { "code": null, "e": 1354, "s": 1196, "text": "for(i=1;i<=rows*2;i+=2){\n if(k%2==1){\n printf(\"%3d %3d\",i,i+1);\n k++;\n }else{\n printf(\"%3d %3d\",i+1,i);\n k++;\n }\n printf(\"\\n\");\n}" }, { "code": null, "e": 1430, "s": 1354, "text": "Following is the C program for representing the numbers in spiral pattern βˆ’" }, { "code": null, "e": 1743, "s": 1430, "text": "#include<stdio.h>\nmain(){\n int i,rows,k=1;\n printf(\"Enter number of Rows for Spiral Pattern\\n\");\n scanf(\"%d\",&rows);\n for(i=1;i<=rows*2;i+=2){\n if(k%2==1){\n printf(\"%3d %3d\",i,i+1);\n k++;\n }else{\n printf(\"%3d %3d\",i+1,i);\n k++;\n }\n printf(\"\\n\");\n }\n}" }, { "code": null, "e": 1814, "s": 1743, "text": "When the above program is executed, it produces the following result βˆ’" }, { "code": null, "e": 1908, "s": 1814, "text": "Enter number of Rows for Spiral Pattern\n10\n1 2\n4 3\n5 6\n8 7\n9 10\n12 11\n13 14\n16 15\n17 18\n20 19" } ]
Python Program to find the cube of each list element - GeeksforGeeks
17 Feb, 2021 Given a list, the task is to write a python program to cube all the list elements. Input: [1, 2, 3, 4] Output: [1, 8, 27, 64] Explanation: Cubing all the list elements Input: [2, 4, 6] Output: [8, 64, 216] Method 1 : Using loop This is the brute force way. In this, we just multiply the same element two times to itself. Example: Python3 # Initializing listl = [1, 2, 3, 4] # Cube List using loopres = []for i in l: res.append(i*i*i) # printing resultprint(res) Output: [1, 8, 27, 64] Method 2 : Using pow() function This is also the brute force way. In this, we use in-built pow() function Example: Python3 # Initializing listl = [1, 2, 3, 4] # Cube List using loopres = []for i in l: res.append(pow(i, 3)) # printing resultprint(res) Output: [1, 8, 27, 64] Method 3 : Using list comprehension This task can also be performed using list comprehension. This is similar to above function. Just the difference is that its compact and one liner. Example: Python3 # Initializing listl = [1, 2, 3, 4] # Cube List using list comprehensionres = [pow(i, 3) for i in l] # printing resultprint(res) Output: [1, 8, 27, 64] Method 4: Using lambda This can also be achieved using lambda function Example: Python3 # Initializing listl = [1, 2, 3, 4] res = list(map(lambda x: x ** 3, l))print(res) Output: [1, 8, 27, 64] Python list-programs Technical Scripter 2020 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Defaultdict in Python Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24237, "s": 24209, "text": "\n17 Feb, 2021" }, { "code": null, "e": 24320, "s": 24237, "text": "Given a list, the task is to write a python program to cube all the list elements." }, { "code": null, "e": 24340, "s": 24320, "text": "Input: [1, 2, 3, 4]" }, { "code": null, "e": 24363, "s": 24340, "text": "Output: [1, 8, 27, 64]" }, { "code": null, "e": 24405, "s": 24363, "text": "Explanation: Cubing all the list elements" }, { "code": null, "e": 24422, "s": 24405, "text": "Input: [2, 4, 6]" }, { "code": null, "e": 24443, "s": 24422, "text": "Output: [8, 64, 216]" }, { "code": null, "e": 24465, "s": 24443, "text": "Method 1 : Using loop" }, { "code": null, "e": 24558, "s": 24465, "text": "This is the brute force way. In this, we just multiply the same element two times to itself." }, { "code": null, "e": 24567, "s": 24558, "text": "Example:" }, { "code": null, "e": 24575, "s": 24567, "text": "Python3" }, { "code": "# Initializing listl = [1, 2, 3, 4] # Cube List using loopres = []for i in l: res.append(i*i*i) # printing resultprint(res)", "e": 24704, "s": 24575, "text": null }, { "code": null, "e": 24712, "s": 24704, "text": "Output:" }, { "code": null, "e": 24727, "s": 24712, "text": "[1, 8, 27, 64]" }, { "code": null, "e": 24759, "s": 24727, "text": "Method 2 : Using pow() function" }, { "code": null, "e": 24833, "s": 24759, "text": "This is also the brute force way. In this, we use in-built pow() function" }, { "code": null, "e": 24842, "s": 24833, "text": "Example:" }, { "code": null, "e": 24850, "s": 24842, "text": "Python3" }, { "code": "# Initializing listl = [1, 2, 3, 4] # Cube List using loopres = []for i in l: res.append(pow(i, 3)) # printing resultprint(res)", "e": 24983, "s": 24850, "text": null }, { "code": null, "e": 24991, "s": 24983, "text": "Output:" }, { "code": null, "e": 25006, "s": 24991, "text": "[1, 8, 27, 64]" }, { "code": null, "e": 25042, "s": 25006, "text": "Method 3 : Using list comprehension" }, { "code": null, "e": 25190, "s": 25042, "text": "This task can also be performed using list comprehension. This is similar to above function. Just the difference is that its compact and one liner." }, { "code": null, "e": 25199, "s": 25190, "text": "Example:" }, { "code": null, "e": 25207, "s": 25199, "text": "Python3" }, { "code": "# Initializing listl = [1, 2, 3, 4] # Cube List using list comprehensionres = [pow(i, 3) for i in l] # printing resultprint(res)", "e": 25338, "s": 25207, "text": null }, { "code": null, "e": 25346, "s": 25338, "text": "Output:" }, { "code": null, "e": 25361, "s": 25346, "text": "[1, 8, 27, 64]" }, { "code": null, "e": 25384, "s": 25361, "text": "Method 4: Using lambda" }, { "code": null, "e": 25432, "s": 25384, "text": "This can also be achieved using lambda function" }, { "code": null, "e": 25441, "s": 25432, "text": "Example:" }, { "code": null, "e": 25449, "s": 25441, "text": "Python3" }, { "code": "# Initializing listl = [1, 2, 3, 4] res = list(map(lambda x: x ** 3, l))print(res)", "e": 25533, "s": 25449, "text": null }, { "code": null, "e": 25541, "s": 25533, "text": "Output:" }, { "code": null, "e": 25556, "s": 25541, "text": "[1, 8, 27, 64]" }, { "code": null, "e": 25577, "s": 25556, "text": "Python list-programs" }, { "code": null, "e": 25601, "s": 25577, "text": "Technical Scripter 2020" }, { "code": null, "e": 25608, "s": 25601, "text": "Python" }, { "code": null, "e": 25624, "s": 25608, "text": "Python Programs" }, { "code": null, "e": 25643, "s": 25624, "text": "Technical Scripter" }, { "code": null, "e": 25741, "s": 25643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25750, "s": 25741, "text": "Comments" }, { "code": null, "e": 25763, "s": 25750, "text": "Old Comments" }, { "code": null, "e": 25784, "s": 25763, "text": "Python OOPs Concepts" }, { "code": null, "e": 25816, "s": 25784, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25839, "s": 25816, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25861, "s": 25839, "text": "Defaultdict in Python" }, { "code": null, "e": 25888, "s": 25861, "text": "Python Classes and Objects" }, { "code": null, "e": 25910, "s": 25888, "text": "Defaultdict in Python" }, { "code": null, "e": 25956, "s": 25910, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26013, "s": 25956, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 26052, "s": 26013, "text": "Python | Get dictionary keys as a list" } ]
Count common characters in two strings in C++
We are given with the two strings let’s say str1 and str2 and the task is to find the count of common characters in two strings i.e. if str1[i] = str[j], then they will be considered as a pair and count will increased to 1 and if str1[i]!=str2[j] then they willn’t be considered as a pair and count willn’t increase to 1. Input βˆ’ str1 = β€œhello” str2 = β€œheoo” Output βˆ’ count is: 3 Explanation βˆ’ str1[0] = str2[0] i.e. h ; str1[1] = str2[1] i.e. e ; str1[2]!=str2[2] i.e. l and o; str1[3]=str2[3] i.e. o. So, the pairs with similar letters are 3 and 1 pair containing different letters. Input βˆ’ str1 = β€œpoint” str2 = β€œprint” Output βˆ’ count is: 4 Explanation βˆ’ str1[0] = str2[0] i.e. p ; str1[1] != str2[1] i.e. o and r ; str1[2] =str2[2] i.e. i; str1[3]=str2[3] i.e. n; str1[4]=str2[4] i.e. t. So, the pairs with similar letters are 4 and 1 pair containing different letters. Input the two strings str1 and str2 Input the two strings str1 and str2 Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces. Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces. Initially, Initialize the frequency of characters in both the string with 0. Initially, Initialize the frequency of characters in both the string with 0. Now, for updating the frequency of str1 apply β€œf1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2 Now, for updating the frequency of str1 apply β€œf1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2 For calculating the count of pairs apply min() function for f1 and f2. For calculating the count of pairs apply min() function for f1 and f2. Display the result Display the result Live Demo #include <iostream> using namespace std; // Function to count the valid indices pairs int pairs(string str1, int size1, string str2, int size2){ // f1 and f2 for frequencies of characters // of string str1 and str2 int f1[26] = { 0 }; int f2[26] = { 0 }; // 'c' To count the valid pairs int i, c = 0; //updating the frequencies of str1 and st2 for (i = 0; i < size1; i++){ f1[str1[i] - 'a']++; } for (i = 0; i < size2; i++){ f2[str2[i] - 'a']++; } // Find the count of valid pairs for (i = 0; i < 26; i++){ c += (min(f1[i], f2[i])); } return c; } // main function int main(){ string str1 = "tutorialspoint", str2 = "codingground"; int size1 = str1.length(), size2 = str2.length(); cout<<”Total pairs with str1[i]=str2[j] are: ”; cout << pairs(str1, size1, str2, size2); return 0; } If we run the above code it will generate the following output βˆ’ Total pairs with str1[i]=str2[j] are βˆ’ 6
[ { "code": null, "e": 1384, "s": 1062, "text": "We are given with the two strings let’s say str1 and str2 and the task is to find the count of common characters in two strings i.e. if str1[i] = str[j], then they will be considered as a pair and count will increased to 1 and if str1[i]!=str2[j] then they willn’t be considered as a pair and count willn’t increase to 1." }, { "code": null, "e": 1448, "s": 1384, "text": "Input βˆ’ str1 = β€œhello”\n str2 = β€œheoo”\nOutput βˆ’ count is: 3" }, { "code": null, "e": 1653, "s": 1448, "text": "Explanation βˆ’ str1[0] = str2[0] i.e. h ; str1[1] = str2[1] i.e. e ; str1[2]!=str2[2] i.e. l and o; str1[3]=str2[3] i.e. o. So, the pairs with similar letters are 3 and 1 pair containing different letters." }, { "code": null, "e": 1718, "s": 1653, "text": "Input βˆ’ str1 = β€œpoint”\n str2 = β€œprint”\nOutput βˆ’ count is: 4" }, { "code": null, "e": 1948, "s": 1718, "text": "Explanation βˆ’ str1[0] = str2[0] i.e. p ; str1[1] != str2[1] i.e. o and r ; str1[2] =str2[2] i.e. i; str1[3]=str2[3] i.e. n; str1[4]=str2[4] i.e. t. So, the pairs with similar letters are 4 and 1 pair containing different letters." }, { "code": null, "e": 1984, "s": 1948, "text": "Input the two strings str1 and str2" }, { "code": null, "e": 2020, "s": 1984, "text": "Input the two strings str1 and str2" }, { "code": null, "e": 2182, "s": 2020, "text": "Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces." }, { "code": null, "e": 2344, "s": 2182, "text": "Calculate the size of both the strings using length() function that will return an integer value as per the number of letters in the string including the spaces." }, { "code": null, "e": 2421, "s": 2344, "text": "Initially, Initialize the frequency of characters in both the string with 0." }, { "code": null, "e": 2498, "s": 2421, "text": "Initially, Initialize the frequency of characters in both the string with 0." }, { "code": null, "e": 2657, "s": 2498, "text": "Now, for updating the frequency of str1 apply β€œf1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2" }, { "code": null, "e": 2816, "s": 2657, "text": "Now, for updating the frequency of str1 apply β€œf1[str1[i] - 'a']++” that will increase the frequency with every iteration and apply the same process with str2" }, { "code": null, "e": 2887, "s": 2816, "text": "For calculating the count of pairs apply min() function for f1 and f2." }, { "code": null, "e": 2958, "s": 2887, "text": "For calculating the count of pairs apply min() function for f1 and f2." }, { "code": null, "e": 2977, "s": 2958, "text": "Display the result" }, { "code": null, "e": 2996, "s": 2977, "text": "Display the result" }, { "code": null, "e": 3007, "s": 2996, "text": " Live Demo" }, { "code": null, "e": 3867, "s": 3007, "text": "#include <iostream>\nusing namespace std;\n// Function to count the valid indices pairs\nint pairs(string str1, int size1, string str2, int size2){\n // f1 and f2 for frequencies of characters\n // of string str1 and str2\n int f1[26] = { 0 };\n int f2[26] = { 0 };\n // 'c' To count the valid pairs\n int i, c = 0;\n //updating the frequencies of str1 and st2\n for (i = 0; i < size1; i++){\n f1[str1[i] - 'a']++;\n }\n for (i = 0; i < size2; i++){\n f2[str2[i] - 'a']++;\n }\n // Find the count of valid pairs\n for (i = 0; i < 26; i++){\n c += (min(f1[i], f2[i]));\n }\n return c;\n}\n// main function\nint main(){\n string str1 = \"tutorialspoint\", str2 = \"codingground\";\n int size1 = str1.length(), size2 = str2.length();\n cout<<”Total pairs with str1[i]=str2[j] are: ”;\n cout << pairs(str1, size1, str2, size2);\n return 0;\n}" }, { "code": null, "e": 3932, "s": 3867, "text": "If we run the above code it will generate the following output βˆ’" }, { "code": null, "e": 3973, "s": 3932, "text": "Total pairs with str1[i]=str2[j] are βˆ’ 6" } ]
WifiManager in Android - GeeksforGeeks
23 Dec, 2021 WifiManager is the class related to the operations done with wifi. This class provides the primary API for managing all aspects of Wi-Fi connectivity. It deals with several categories of items: The list of available configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.Results of access point scans, containing enough information to make decisions about what access point to connect to.It defines the names of various Intent actions that are broadcast upon any sort of the change in the Wi-Fi state. The list of available configured networks. The list can be viewed and updated, and attributes of individual entries can be modified. The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried. Results of access point scans, containing enough information to make decisions about what access point to connect to. It defines the names of various Intent actions that are broadcast upon any sort of the change in the Wi-Fi state. Wifi of the android can be switched on manually or via the app. This article is all about making the app turn on the wifi without the user’s intervention. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file There is no need to change anything inside the activity_main.xml file. Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java public class MainActivity extends AppCompatActivity { private WifiManager wifiManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.empty); // wifiManager gets the Application // context and wifi services wifiManager=(WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); // wifi services are switched on wifiManager.setWifiEnabled(true); try { // we check if wifi is connected to any of the connections String ip=Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress()); // the IP address of the connection is shown in the toast message Toast.makeText(getApplicationContext(),"SUCCESSFULLY CONNECTED TO "+ip,Toast.LENGTH_SHORT).show(); } catch (Exception e) { // print error if unsuccessful to connect e.printStackTrace(); } }} Output: Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android How to Add Image to Drawable Folder in Android Studio? How to Change the Background Color After Clicking the Button in Android? How to Retrieve Data from the Firebase Realtime Database in Android? GridView in Android with Example ImageView in Android with Example
[ { "code": null, "e": 24725, "s": 24697, "text": "\n23 Dec, 2021" }, { "code": null, "e": 24919, "s": 24725, "text": "WifiManager is the class related to the operations done with wifi. This class provides the primary API for managing all aspects of Wi-Fi connectivity. It deals with several categories of items:" }, { "code": null, "e": 25442, "s": 24919, "text": "The list of available configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.Results of access point scans, containing enough information to make decisions about what access point to connect to.It defines the names of various Intent actions that are broadcast upon any sort of the change in the Wi-Fi state." }, { "code": null, "e": 25575, "s": 25442, "text": "The list of available configured networks. The list can be viewed and updated, and attributes of individual entries can be modified." }, { "code": null, "e": 25736, "s": 25575, "text": "The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried." }, { "code": null, "e": 25854, "s": 25736, "text": "Results of access point scans, containing enough information to make decisions about what access point to connect to." }, { "code": null, "e": 25968, "s": 25854, "text": "It defines the names of various Intent actions that are broadcast upon any sort of the change in the Wi-Fi state." }, { "code": null, "e": 26124, "s": 25968, "text": "Wifi of the android can be switched on manually or via the app. This article is all about making the app turn on the wifi without the user’s intervention. " }, { "code": null, "e": 26153, "s": 26124, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26315, "s": 26153, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 26363, "s": 26315, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26434, "s": 26363, "text": "There is no need to change anything inside the activity_main.xml file." }, { "code": null, "e": 26482, "s": 26434, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 26672, "s": 26482, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 26677, "s": 26672, "text": "Java" }, { "code": "public class MainActivity extends AppCompatActivity { private WifiManager wifiManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.empty); // wifiManager gets the Application // context and wifi services wifiManager=(WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); // wifi services are switched on wifiManager.setWifiEnabled(true); try { // we check if wifi is connected to any of the connections String ip=Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress()); // the IP address of the connection is shown in the toast message Toast.makeText(getApplicationContext(),\"SUCCESSFULLY CONNECTED TO \"+ip,Toast.LENGTH_SHORT).show(); } catch (Exception e) { // print error if unsuccessful to connect e.printStackTrace(); } }}", "e": 27752, "s": 26677, "text": null }, { "code": null, "e": 27760, "s": 27752, "text": "Output:" }, { "code": null, "e": 27768, "s": 27760, "text": "Android" }, { "code": null, "e": 27776, "s": 27768, "text": "Android" }, { "code": null, "e": 27874, "s": 27776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27883, "s": 27874, "text": "Comments" }, { "code": null, "e": 27896, "s": 27883, "text": "Old Comments" }, { "code": null, "e": 27935, "s": 27896, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27985, "s": 27935, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 28036, "s": 27985, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 28074, "s": 28036, "text": "Android Listview in Java with Example" }, { "code": null, "e": 28116, "s": 28074, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28171, "s": 28116, "text": "How to Add Image to Drawable Folder in Android Studio?" }, { "code": null, "e": 28244, "s": 28171, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 28313, "s": 28244, "text": "How to Retrieve Data from the Firebase Realtime Database in Android?" }, { "code": null, "e": 28346, "s": 28313, "text": "GridView in Android with Example" } ]
Getting Started with TabPy. An introduction to integrating Tableau... | by Kayla Hartman | Towards Data Science
In any field, it is essential to be resilient and adaptive, approaching new tools and ideas with diligence. In a field as young as data science, it is ever more important to be a self-learner and to take on new challenges. As I entered the final month of my data science bootcamp, I thought back to the below chart I had seen at the beginning of my course. Jeff Hale scraped several job listing sites and outlined the technology skills most commonly listed in data science job postings. While my bootcamp has covered a large number of these skills, it would be impossible for the program to exhaustively introduce skills pertinent to data science. For the skills that I did not learn, just because they were not introduced in the program doesn’t mean they won’t be useful during my career. If they do come up, I want to ensure that I am ready to best utilize available resources and my existing knowledge to develop a well-rounded understanding of these skills. For this blog, I decided to dive into one of these relevant concepts that we did not cover in my bootcamp. I had heard about Tableau several times before, but I had never used it. I understood its capabilities as a data visualization tool that easily connects to several data sources and allows users to build dashboards, but I didn’t know much beyond that, so I decided to investigate. Once I downloaded the free trial (https://www.tableau.com/products/trial), I imported a CSV file I had used for a recent project using data from James LeDoux. This file included a large amount of data surrounding coffee beans and their quality. Once I imported the file, I was able to view the data in a table on Tableau, as shown below. After importing this dataset, I was pleasantly surprised by the simplicity in creating data visualizations with the user-centered interface. The dataset features were listed on the left side of the workbook and the geographic coordinates associated with the country of origin for each bean were automatically generated. I was able to simply drag the measures listed below to an area labeled β€œcolumns” and β€œrows” to generate visualizations. In order to create the below heat map, I dragged the β€œlatitude” and β€œlongitude” tags to the β€œcolumn” and β€œrow” entries, as shown below. To create the below scatterplot, I simply dragged the β€œAroma” and β€œAftertaste” fields to the β€œcolumn” and β€œrows” entries. Next, I clicked on the arrow to on the right side of the β€œAroma” and β€œAftertaste” tags in order to select standard deviation as the unit of measure to display. After creating the heat map, scatterplot, and a few other basic visualizations, I was curious about how to integrate Python with Tableau. I discovered that this can easily be accomplished using the API Tableau Python Server (TabPy), which enables remote execution of Python code. In order to integrate TabPy with Tableau, I cloned the following Github repository. github.com Next, using instructions on the repository and instructions here, I followed the below steps: 1. Install tabpy-server by typing the following in the command line. pip install tabpy-server 2. In the cloned repository, go to the path tabpy-server/tabpy_server . 3. Run the file tabpy.py. In order to run this file, I needed to change the file common/config.py.template to common/config.py. 4. Open a Tableau workbook. Follow the path Help > Settings and Performance > Manage External Service Connection to select an external service connection on Tableau. At this point, the connection was set up to run Python code in the Tableau workbook. This can be done by filling in calculated fields. Calculated fields follow the general format seen in the examples below. The function can begin with SCRIPT_REAL, SCRIPT_INT, SCRIPT_STR, and SCRIPT_BOOL, which represents the function return type. Within quotation marks, the inputs are referred to as _arg1, _arg2, ... , _argN. The closed quotation mark is followed by a comma and the argument definitions. According to a community post on Tableau’s website, these are table calculations, so they must be aggregated, such as SUM(), MAX(), MIN(), ATTR(). This blog post only provides a general overview of what can be done with Tableau and TabPy. There are a plethora of other capabilities. Tableau can be connected to additional data sources and can create real-time dashboards that are constantly updated. I simply wanted to gain an understanding of the way Python can be incorporated into Tableau and there are certainly additional ways in which Python can be incorporated. The links below include additional resources describing how to use Tableau and more advanced ways of incorporating Python, such as machine learning models. I plan to use these resources continue my exploration into Tableau and hope to further my abilities to integrate my knowledge of Python and Tableau.
[ { "code": null, "e": 529, "s": 172, "text": "In any field, it is essential to be resilient and adaptive, approaching new tools and ideas with diligence. In a field as young as data science, it is ever more important to be a self-learner and to take on new challenges. As I entered the final month of my data science bootcamp, I thought back to the below chart I had seen at the beginning of my course." }, { "code": null, "e": 1134, "s": 529, "text": "Jeff Hale scraped several job listing sites and outlined the technology skills most commonly listed in data science job postings. While my bootcamp has covered a large number of these skills, it would be impossible for the program to exhaustively introduce skills pertinent to data science. For the skills that I did not learn, just because they were not introduced in the program doesn’t mean they won’t be useful during my career. If they do come up, I want to ensure that I am ready to best utilize available resources and my existing knowledge to develop a well-rounded understanding of these skills." }, { "code": null, "e": 1859, "s": 1134, "text": "For this blog, I decided to dive into one of these relevant concepts that we did not cover in my bootcamp. I had heard about Tableau several times before, but I had never used it. I understood its capabilities as a data visualization tool that easily connects to several data sources and allows users to build dashboards, but I didn’t know much beyond that, so I decided to investigate. Once I downloaded the free trial (https://www.tableau.com/products/trial), I imported a CSV file I had used for a recent project using data from James LeDoux. This file included a large amount of data surrounding coffee beans and their quality. Once I imported the file, I was able to view the data in a table on Tableau, as shown below." }, { "code": null, "e": 2299, "s": 1859, "text": "After importing this dataset, I was pleasantly surprised by the simplicity in creating data visualizations with the user-centered interface. The dataset features were listed on the left side of the workbook and the geographic coordinates associated with the country of origin for each bean were automatically generated. I was able to simply drag the measures listed below to an area labeled β€œcolumns” and β€œrows” to generate visualizations." }, { "code": null, "e": 2435, "s": 2299, "text": "In order to create the below heat map, I dragged the β€œlatitude” and β€œlongitude” tags to the β€œcolumn” and β€œrow” entries, as shown below." }, { "code": null, "e": 2717, "s": 2435, "text": "To create the below scatterplot, I simply dragged the β€œAroma” and β€œAftertaste” fields to the β€œcolumn” and β€œrows” entries. Next, I clicked on the arrow to on the right side of the β€œAroma” and β€œAftertaste” tags in order to select standard deviation as the unit of measure to display." }, { "code": null, "e": 2997, "s": 2717, "text": "After creating the heat map, scatterplot, and a few other basic visualizations, I was curious about how to integrate Python with Tableau. I discovered that this can easily be accomplished using the API Tableau Python Server (TabPy), which enables remote execution of Python code." }, { "code": null, "e": 3081, "s": 2997, "text": "In order to integrate TabPy with Tableau, I cloned the following Github repository." }, { "code": null, "e": 3092, "s": 3081, "text": "github.com" }, { "code": null, "e": 3186, "s": 3092, "text": "Next, using instructions on the repository and instructions here, I followed the below steps:" }, { "code": null, "e": 3255, "s": 3186, "text": "1. Install tabpy-server by typing the following in the command line." }, { "code": null, "e": 3280, "s": 3255, "text": "pip install tabpy-server" }, { "code": null, "e": 3352, "s": 3280, "text": "2. In the cloned repository, go to the path tabpy-server/tabpy_server ." }, { "code": null, "e": 3480, "s": 3352, "text": "3. Run the file tabpy.py. In order to run this file, I needed to change the file common/config.py.template to common/config.py." }, { "code": null, "e": 3646, "s": 3480, "text": "4. Open a Tableau workbook. Follow the path Help > Settings and Performance > Manage External Service Connection to select an external service connection on Tableau." }, { "code": null, "e": 3781, "s": 3646, "text": "At this point, the connection was set up to run Python code in the Tableau workbook. This can be done by filling in calculated fields." }, { "code": null, "e": 3853, "s": 3781, "text": "Calculated fields follow the general format seen in the examples below." }, { "code": null, "e": 4285, "s": 3853, "text": "The function can begin with SCRIPT_REAL, SCRIPT_INT, SCRIPT_STR, and SCRIPT_BOOL, which represents the function return type. Within quotation marks, the inputs are referred to as _arg1, _arg2, ... , _argN. The closed quotation mark is followed by a comma and the argument definitions. According to a community post on Tableau’s website, these are table calculations, so they must be aggregated, such as SUM(), MAX(), MIN(), ATTR()." } ]
What is the difference between IEnumerable and IQueryable in C#?
IEnumerable exists in System.Collections Namespace. IQueryable exists in System. Linq Namespace. Both IEnumerable and IQueryable are forward collection. IEnumerable doesn’t support lazy loading IQueryable support lazy loading Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data. Querying data from a database, IQueryable execute the select query on the server side with all filters. IEnumerable Extension methods take functional objects. IQueryable Extension methods take expression objects means expression tree. dbContext dc = new dbContext (); IEnumerable <SocialMedia> list = dc.SocialMedias.Where(p => p.Name.StartsWith("T")); list = list.Take<SocialMedia>(1); </SocialMedia> SELECT [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0] WHERE [t0].[Name] LIKE @p0 dbContext dc = new dbContext (); IQueryable<SocialMedia> list = dc.SocialMedias.Where(p => p.Name.StartsWith("T")); list = list.Take<SocialMedia>(1); SELECT top 1 [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0] WHERE [t0].[Name] LIKE @p0
[ { "code": null, "e": 1114, "s": 1062, "text": "IEnumerable exists in System.Collections Namespace." }, { "code": null, "e": 1159, "s": 1114, "text": "IQueryable exists in System. Linq Namespace." }, { "code": null, "e": 1215, "s": 1159, "text": "Both IEnumerable and IQueryable are forward collection." }, { "code": null, "e": 1256, "s": 1215, "text": "IEnumerable doesn’t support lazy loading" }, { "code": null, "e": 1288, "s": 1256, "text": "IQueryable support lazy loading" }, { "code": null, "e": 1433, "s": 1288, "text": "Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data." }, { "code": null, "e": 1537, "s": 1433, "text": "Querying data from a database, IQueryable execute the select query on the server side with all filters." }, { "code": null, "e": 1592, "s": 1537, "text": "IEnumerable Extension methods take functional objects." }, { "code": null, "e": 1668, "s": 1592, "text": "IQueryable Extension methods take expression objects means expression tree." }, { "code": null, "e": 1835, "s": 1668, "text": "dbContext dc = new dbContext ();\nIEnumerable\n<SocialMedia>\nlist = dc.SocialMedias.Where(p => p.Name.StartsWith(\"T\"));\nlist = list.Take<SocialMedia>(1);\n</SocialMedia>" }, { "code": null, "e": 1919, "s": 1835, "text": "SELECT [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0]\nWHERE [t0].[Name] LIKE @p0" }, { "code": null, "e": 2069, "s": 1919, "text": "dbContext dc = new dbContext ();\nIQueryable<SocialMedia> list = dc.SocialMedias.Where(p => p.Name.StartsWith(\"T\"));\nlist = list.Take<SocialMedia>(1);" }, { "code": null, "e": 2159, "s": 2069, "text": "SELECT top 1 [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0]\nWHERE [t0].[Name] LIKE @p0" } ]
Calculate the Interquartile Range in R Programming - IQR() Function - GeeksforGeeks
17 Jun, 2020 IQR() function in R Language is used to calculate the interquartile range of a data set. Mathematically,IQR = Q3 – Q1 where,Q3 specifies the median of n largest valuesQ1 specifies the median of n smallest values But, R provides in-built IQR() function to perform the upgiven calculations Syntax: IQR(x) Parameters:x: Data set Example 1: # R program to calculate IQR value # Defining vector x <- c(5, 5, 8, 12, 15, 16) # Print Interquartile range print(IQR(x)) Output: [1] 8.5 Example 2: # R program to calculate IQR value # Defining a matrix x <- matrix(c(1:9), 3, 3) # Print Interquartile range print(IQR(x)) Output: [1] 4 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to 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? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n17 Jun, 2020" }, { "code": null, "e": 25331, "s": 25242, "text": "IQR() function in R Language is used to calculate the interquartile range of a data set." }, { "code": null, "e": 25360, "s": 25331, "text": "Mathematically,IQR = Q3 – Q1" }, { "code": null, "e": 25454, "s": 25360, "text": "where,Q3 specifies the median of n largest valuesQ1 specifies the median of n smallest values" }, { "code": null, "e": 25530, "s": 25454, "text": "But, R provides in-built IQR() function to perform the upgiven calculations" }, { "code": null, "e": 25545, "s": 25530, "text": "Syntax: IQR(x)" }, { "code": null, "e": 25568, "s": 25545, "text": "Parameters:x: Data set" }, { "code": null, "e": 25579, "s": 25568, "text": "Example 1:" }, { "code": "# R program to calculate IQR value # Defining vector x <- c(5, 5, 8, 12, 15, 16) # Print Interquartile range print(IQR(x)) ", "e": 25708, "s": 25579, "text": null }, { "code": null, "e": 25716, "s": 25708, "text": "Output:" }, { "code": null, "e": 25725, "s": 25716, "text": "[1] 8.5\n" }, { "code": null, "e": 25736, "s": 25725, "text": "Example 2:" }, { "code": "# R program to calculate IQR value # Defining a matrix x <- matrix(c(1:9), 3, 3) # Print Interquartile range print(IQR(x)) ", "e": 25864, "s": 25736, "text": null }, { "code": null, "e": 25872, "s": 25864, "text": "Output:" }, { "code": null, "e": 25879, "s": 25872, "text": "[1] 4\n" }, { "code": null, "e": 25895, "s": 25879, "text": "R Math-Function" }, { "code": null, "e": 25906, "s": 25895, "text": "R Language" }, { "code": null, "e": 26004, "s": 25906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26056, "s": 26004, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26094, "s": 26056, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26129, "s": 26094, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26187, "s": 26129, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26236, "s": 26187, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26273, "s": 26236, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 26323, "s": 26273, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26366, "s": 26323, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26392, "s": 26366, "text": "Time Series Analysis in R" } ]
Maximum sum of pairwise product in an array with negative allowed in C++ program
In this problem, we are given an array arr[] that contains n integers values (negative values allowed). Our task is to create a program to find the maximum sum of pairwise products in an array with negative allowed. Problem Description βˆ’ We need to create pairs using the elements of the array such that the sum of the product of elements of pairs is maximum. Let’s take an example to understand the problem, arr[] = {βˆ’5, 2, 3, 7, βˆ’1, 1, βˆ’3, 12} 104 The pairs to be considered: (βˆ’5, βˆ’3), (2, 3), (βˆ’1, 1), (7, 12) Sum of product = (βˆ’5 * βˆ’3) + (2 * 3) + (βˆ’1 * 1) + (7 * 12) = 15 + 6 βˆ’ 1 + 84 = 104. To solve the problem, we will be finding pairs in such a way that the sum of their products is maximum. To maximize the sum, we need to pair the same pair values together. And making this pairing easy, we need to sort the array and then pair up negatives and positives. Then find if one positive or negative or both values are present in the pair. If a positive/negative value is remaining add it to the pair and if one negative and one positive are present then add their product. Initialize βˆ’ maxSum = 0. Step 1 βˆ’ Sort the array arr[]. Step 2 βˆ’ Loop for all negative values of the array. Make pairs, and add their product to maxSum. Step 3 βˆ’ Loop for all positive values of the array. Make pairs, and add their product to maxSum. Step 4 βˆ’ At last check the remaining values. Step 4.1 βˆ’ If one positive value remains, add it to maxSum. Step 4.1 βˆ’ If one negative value remains, add it to maxSum. Step 4.1 βˆ’ If one positive value and one negative value remains, add their product to maxSum. Step 5 βˆ’ Return maxSum. Program to illustrate the working of our solution, Live Demo #include <bits/stdc++.h> using namespace std; long calcSumPairProd(int arr[], int n) { long maxSum = 0; sort(arr, arr + n); int i = 0, j = (n βˆ’ 1); while (i < n && arr[i] < 0) { if (i != n βˆ’ 1 && arr[i + 1] <= 0) { maxSum = (maxSum + (arr[i] * arr[i + 1]) ); i += 2; } else break; } while (j >= 0 && arr[j] > 0) { if (j != 0 && arr[j βˆ’ 1] > 0) { maxSum = (maxSum + (arr[j] * arr[j βˆ’ 1]) ); j βˆ’= 2; } else break; } if (j > i) maxSum = (maxSum + (arr[i] * arr[j]) ); else if (i == j) maxSum = (maxSum + arr[i]); return maxSum; } int main() { int arr[] = { βˆ’5, 2, 3, 7, βˆ’1, 1, βˆ’3, 12 }; int n = sizeof(arr) / sizeof(arr[0]); cout<<"The maximum sum of pairwise product in an array is "<<calcSumPairProd(arr, n); return 0; } The maximum sum of pairwise product in an array is 104
[ { "code": null, "e": 1278, "s": 1062, "text": "In this problem, we are given an array arr[] that contains n integers values\n(negative values allowed). Our task is to create a program to find the\nmaximum sum of pairwise products in an array with negative allowed." }, { "code": null, "e": 1422, "s": 1278, "text": "Problem Description βˆ’ We need to create pairs using the elements of the array such that the sum of the product of elements of pairs is maximum." }, { "code": null, "e": 1471, "s": 1422, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1508, "s": 1471, "text": "arr[] = {βˆ’5, 2, 3, 7, βˆ’1, 1, βˆ’3, 12}" }, { "code": null, "e": 1512, "s": 1508, "text": "104" }, { "code": null, "e": 1659, "s": 1512, "text": "The pairs to be considered: (βˆ’5, βˆ’3), (2, 3), (βˆ’1, 1), (7, 12)\nSum of product = (βˆ’5 * βˆ’3) + (2 * 3) + (βˆ’1 * 1) + (7 * 12) = 15 + 6 βˆ’ 1 + 84 =\n104." }, { "code": null, "e": 2141, "s": 1659, "text": "To solve the problem, we will be finding pairs in such a way that the sum of\ntheir products is maximum. To maximize the sum, we need to pair the same\npair values together. And making this pairing easy, we need to sort the array\nand then pair up negatives and positives. Then find if one positive or\nnegative or both values are present in the pair. If a positive/negative value is\nremaining add it to the pair and if one negative and one positive are present\nthen add their product." }, { "code": null, "e": 2154, "s": 2141, "text": "Initialize βˆ’" }, { "code": null, "e": 2166, "s": 2154, "text": "maxSum = 0." }, { "code": null, "e": 2175, "s": 2166, "text": "Step 1 βˆ’" }, { "code": null, "e": 2197, "s": 2175, "text": "Sort the array arr[]." }, { "code": null, "e": 2206, "s": 2197, "text": "Step 2 βˆ’" }, { "code": null, "e": 2294, "s": 2206, "text": "Loop for all negative values of the array. Make pairs, and add their\nproduct to maxSum." }, { "code": null, "e": 2303, "s": 2294, "text": "Step 3 βˆ’" }, { "code": null, "e": 2391, "s": 2303, "text": "Loop for all positive values of the array. Make pairs, and add their\nproduct to maxSum." }, { "code": null, "e": 2400, "s": 2391, "text": "Step 4 βˆ’" }, { "code": null, "e": 2436, "s": 2400, "text": "At last check the remaining values." }, { "code": null, "e": 2447, "s": 2436, "text": "Step 4.1 βˆ’" }, { "code": null, "e": 2496, "s": 2447, "text": "If one positive value remains, add it to maxSum." }, { "code": null, "e": 2507, "s": 2496, "text": "Step 4.1 βˆ’" }, { "code": null, "e": 2556, "s": 2507, "text": "If one negative value remains, add it to maxSum." }, { "code": null, "e": 2567, "s": 2556, "text": "Step 4.1 βˆ’" }, { "code": null, "e": 2650, "s": 2567, "text": "If one positive value and one negative value remains, add\ntheir product to maxSum." }, { "code": null, "e": 2659, "s": 2650, "text": "Step 5 βˆ’" }, { "code": null, "e": 2674, "s": 2659, "text": "Return maxSum." }, { "code": null, "e": 2725, "s": 2674, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 2736, "s": 2725, "text": " Live Demo" }, { "code": null, "e": 3588, "s": 2736, "text": "#include <bits/stdc++.h>\nusing namespace std;\nlong calcSumPairProd(int arr[], int n) {\n long maxSum = 0;\n sort(arr, arr + n);\n int i = 0, j = (n βˆ’ 1);\n while (i < n && arr[i] < 0) {\n if (i != n βˆ’ 1 && arr[i + 1] <= 0) {\n maxSum = (maxSum + (arr[i] * arr[i + 1]) );\n i += 2;\n }\n else\n break;\n }\n while (j >= 0 && arr[j] > 0) {\n if (j != 0 && arr[j βˆ’ 1] > 0) {\n maxSum = (maxSum + (arr[j] * arr[j βˆ’ 1]) );\n j βˆ’= 2;\n }\n else\n break;\n }\n if (j > i)\n maxSum = (maxSum + (arr[i] * arr[j]) );\n else if (i == j)\n maxSum = (maxSum + arr[i]);\n return maxSum;\n}\nint main() {\n int arr[] = { βˆ’5, 2, 3, 7, βˆ’1, 1, βˆ’3, 12 };\n int n = sizeof(arr) / sizeof(arr[0]);\n cout<<\"The maximum sum of pairwise product in an array is \"<<calcSumPairProd(arr, n);\n return 0;\n}" }, { "code": null, "e": 3643, "s": 3588, "text": "The maximum sum of pairwise product in an array is 104" } ]
MYBATIS - Dynamic SQL
Dynamic SQL is a very powerful feature of MyBatis. It enables programmers to build queries based on the scenario dynamically. For example, if you want to search the Student data base, based on the name of the student in MyBatis, you have to write the query using the dynamic SQL. MyBatis uses a powerful Dynamic SQL language that can be used within any mapped SQL statement. Following are the OGNL based Dynamic SQL expressions provided by MyBatis. if choose (when, otherwise) trim (where, set) foreach The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example βˆ’ <select id = "getRecByName" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <if test = "name != null"> WHERE name LIKE #{name} </if> </select> This statement provides an optional text search type of functionality. If you pass in no name, then all active records will be returned. But if you do pass in a name, it will look for a name with the given like condition. You can include multiple if conditions as βˆ’ <select id = "getRecByName_Id" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <if test = "name != null"> WHERE name LIKE #{name} </if> <if test = "id != null"> AND id LIKE #{id} </if> </select> MyBatis offers a choose element, which is similar to Java's switch statement. It helps to choose only one case among many options. The following example will search only by name if it is provided, and if the name is not given, then only by id βˆ’ <select id = "getRecByName_Id_phone" parameterType = "Student" resultType = "Student"> SELECT * FROM Student WHERE id != 0 <choose> <when test = "name != null"> AND name LIKE #{name} </when> <when test = "phone != null"> AND phone LIKE #{phone} </when> </choose> </select> Take a look at our previous examples to see what happens if none of the conditions are met. You would end up with an SQL that looks like this βˆ’ SELECT * FROM Student WHERE This would fail, but MyBatis has a simple solution with one simple change, everything works fine βˆ’ <select id = "getName_Id_phone" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <where> <if test = "id != null"> id = #{id} </if> <if test = "name != null"> AND name LIKE #{name} </if> </where> </select> The where element inserts a WHERE only when the containing tags return any content. Furthermore, if that content begins with AND or OR, it knows to strip it off. The foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element. It also allows you to specify opening and closing strings, and add a separator to place in between iterations. You can build an IN condition as follows βˆ’ <select id = "selectPostIn" resultType = "domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item = "item" index = "index" collection = "list" open = "(" separator = "," close = ")"> #{item} </foreach> </select> This is an example if using dynamic SQL. Consider, we have the following Student table in MySQL βˆ’ CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Query OK, 0 rows affected (0.37 sec) Let’s assume this table has two records as βˆ’ mysql> select * from student; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 900000000 | [email protected] | | 2 | Shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec) To perform read operation, let us have a Student class in Student.java as βˆ’ public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.branch = branch; this.percentage = percentage; this.phone = phone; this.email = email; } public Student() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } } This file contains the result map named Student, to map the results of the SELECT Query. We will define an "id" which will be used in mybatisRead.java for executing Dynamic SQL SELECT query on database. <?xml version = "1.0" encoding = "UTF-8"?> &l;t!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "getRecByName" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <if test = "name != null"> WHERE name LIKE #{name} </if> </select> </mapper> This file has application level logic to read conditional records from the Student table βˆ’ import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class GetRecordByName { public static void main(String args[]) throws IOException{ String req_name = "Mohammad"; Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); Student stud = new Student(); stud.setName(req_name); //select contact all contacts //List<Student> student = session.selectList("getRecByName",stud); stud.setId(1); List<Student> student = session.selectList("getRecByName_Id",stud); for(Student st : student ){ System.out.println("++++++++++++++details of the student named Mohammad are "+"+++++++++++++++++++" ); System.out.println("Id : "+st.getId()); System.out.println("Name : "+st.getName()); System.out.println("Branch : "+st.getBranch()); System.out.println("Percentage : "+st.getPercentage()); System.out.println("Email : "+st.getEmail()); System.out.println("Phone : "+st.getPhone()); } System.out.println("Records Read Successfully "); session.commit(); session.close(); } } Here are the steps to compile and run the above mentioned software. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.java as shown above and compile it. Create GetRecordByName.java as shown above and compile it. Execute GetRecordByName binary to run the program. You would get the following result, and a record would be read from the Student table. ++++++++++++++details of the student named Mohammad are +++++++++++++++++++ Id : 1 Name : Mohammad Branch : It Percentage : 80 Email : [email protected] Phone : 90000000 Records Read Successfully Print Add Notes Bookmark this page
[ { "code": null, "e": 2151, "s": 1871, "text": "Dynamic SQL is a very powerful feature of MyBatis. It enables programmers to build queries based on the scenario dynamically. For example, if you want to search the Student data base, based on the name of the student in MyBatis, you have to write the query using the dynamic SQL." }, { "code": null, "e": 2320, "s": 2151, "text": "MyBatis uses a powerful Dynamic SQL language that can be used within any mapped SQL statement. Following are the OGNL based Dynamic SQL expressions provided by MyBatis." }, { "code": null, "e": 2323, "s": 2320, "text": "if" }, { "code": null, "e": 2348, "s": 2323, "text": "choose (when, otherwise)" }, { "code": null, "e": 2366, "s": 2348, "text": "trim (where, set)" }, { "code": null, "e": 2374, "s": 2366, "text": "foreach" }, { "code": null, "e": 2482, "s": 2374, "text": "The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example βˆ’" }, { "code": null, "e": 2669, "s": 2482, "text": "<select id = \"getRecByName\" parameterType = \"Student\" resultType = \"Student\">\n\n SELECT * FROM STUDENT\t\t \n <if test = \"name != null\">\n WHERE name LIKE #{name}\n </if> \n</select>" }, { "code": null, "e": 2891, "s": 2669, "text": "This statement provides an optional text search type of functionality. If you pass in no name, then all active records will be returned. But if you do pass in a name, it will look for a name with the given like condition." }, { "code": null, "e": 2935, "s": 2891, "text": "You can include multiple if conditions as βˆ’" }, { "code": null, "e": 3187, "s": 2935, "text": "<select id = \"getRecByName_Id\" parameterType = \"Student\" resultType = \"Student\">\n\n SELECT * FROM STUDENT\t\t \n <if test = \"name != null\">\n WHERE name LIKE #{name}\n </if>\n\n <if test = \"id != null\">\n AND id LIKE #{id}\n </if> \n</select>" }, { "code": null, "e": 3318, "s": 3187, "text": "MyBatis offers a choose element, which is similar to Java's switch statement. It helps to choose only one case among many options." }, { "code": null, "e": 3432, "s": 3318, "text": "The following example will search only by name if it is provided, and if the name is not given, then only by id βˆ’" }, { "code": null, "e": 3762, "s": 3432, "text": "<select id = \"getRecByName_Id_phone\" parameterType = \"Student\" resultType = \"Student\">\n SELECT * FROM Student WHERE id != 0\n\t\n <choose>\n <when test = \"name != null\">\n AND name LIKE #{name}\n </when> \n\n <when test = \"phone != null\">\n AND phone LIKE #{phone}\n </when>\n </choose>\n\t\n</select>" }, { "code": null, "e": 3906, "s": 3762, "text": "Take a look at our previous examples to see what happens if none of the conditions are met. You would end up with an SQL that looks like this βˆ’" }, { "code": null, "e": 3935, "s": 3906, "text": "SELECT * FROM Student\nWHERE\n" }, { "code": null, "e": 4034, "s": 3935, "text": "This would fail, but MyBatis has a simple solution with one simple change, everything works fine βˆ’" }, { "code": null, "e": 4319, "s": 4034, "text": "<select id = \"getName_Id_phone\" parameterType = \"Student\" resultType = \"Student\">\n SELECT * FROM STUDENT\n\t\n <where>\n <if test = \"id != null\">\n id = #{id}\n </if>\n\n <if test = \"name != null\">\n AND name LIKE #{name}\n </if>\n </where>\n\t\t\n</select>" }, { "code": null, "e": 4481, "s": 4319, "text": "The where element inserts a WHERE only when the containing tags return any content. Furthermore, if that content begins with AND or OR, it knows to strip it off." }, { "code": null, "e": 4622, "s": 4481, "text": "The foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element." }, { "code": null, "e": 4777, "s": 4622, "text": "It also allows you to specify opening and closing strings, and add a separator to place in between iterations. You can build an IN condition as follows βˆ’" }, { "code": null, "e": 5030, "s": 4777, "text": "<select id = \"selectPostIn\" resultType = \"domain.blog.Post\">\n SELECT *\n FROM POST P\n WHERE ID in\n\t\n <foreach item = \"item\" index = \"index\" collection = \"list\"\n open = \"(\" separator = \",\" close = \")\">\n #{item}\n </foreach>\n\t\n</select>" }, { "code": null, "e": 5128, "s": 5030, "text": "This is an example if using dynamic SQL. Consider, we have the following Student table in MySQL βˆ’" }, { "code": null, "e": 5414, "s": 5128, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\nQuery OK, 0 rows affected (0.37 sec)\n" }, { "code": null, "e": 5459, "s": 5414, "text": "Let’s assume this table has two records as βˆ’" }, { "code": null, "e": 5965, "s": 5459, "text": "mysql> select * from student;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 900000000 | [email protected] |\n| 2 | Shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+----------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 6041, "s": 5965, "text": "To perform read operation, let us have a Student class in Student.java as βˆ’" }, { "code": null, "e": 7286, "s": 6041, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\t\n \n}" }, { "code": null, "e": 7489, "s": 7286, "text": "This file contains the result map named Student, to map the results of the SELECT Query. We will define an \"id\" which will be used in mybatisRead.java for executing Dynamic SQL SELECT query on database." }, { "code": null, "e": 8285, "s": 7489, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n&l;t!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n </resultMap>\t \n\n <select id = \"getRecByName\" parameterType = \"Student\" resultType = \"Student\">\n SELECT * FROM STUDENT\t\t \n\t\t\n <if test = \"name != null\">\n WHERE name LIKE #{name}\n </if>\n\t\t\n </select>\n\t\n</mapper>" }, { "code": null, "e": 8376, "s": 8285, "text": "This file has application level logic to read conditional records from the Student table βˆ’" }, { "code": null, "e": 9995, "s": 8376, "text": "import java.io.IOException;\nimport java.io.Reader;\nimport java.util.List;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class GetRecordByName { \n\n public static void main(String args[]) throws IOException{\n\t \n String req_name = \"Mohammad\";\n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n Student stud = new Student();\n stud.setName(req_name);\n \n //select contact all contacts\t\t\n //List<Student> student = session.selectList(\"getRecByName\",stud);\n \n stud.setId(1);\n List<Student> student = session.selectList(\"getRecByName_Id\",stud);\n \n for(Student st : student ){ \t \n \t \t \n System.out.println(\"++++++++++++++details of the student named Mohammad are \"+\"+++++++++++++++++++\" );\n \t \n System.out.println(\"Id : \"+st.getId());\n System.out.println(\"Name : \"+st.getName());\n System.out.println(\"Branch : \"+st.getBranch());\n System.out.println(\"Percentage : \"+st.getPercentage()); \n System.out.println(\"Email : \"+st.getEmail()); \n System.out.println(\"Phone : \"+st.getPhone()); \t \n \t \n } \n \n System.out.println(\"Records Read Successfully \"); \n session.commit(); \n session.close();\t\t\t\n }\n}" }, { "code": null, "e": 10169, "s": 9995, "text": "Here are the steps to compile and run the above mentioned software. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 10204, "s": 10169, "text": "Create Student.xml as shown above." }, { "code": null, "e": 10255, "s": 10204, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 10314, "s": 10255, "text": "Create GetRecordByName.java as shown above and compile it." }, { "code": null, "e": 10365, "s": 10314, "text": "Execute GetRecordByName binary to run the program." }, { "code": null, "e": 10452, "s": 10365, "text": "You would get the following result, and a record would be read from the Student table." }, { "code": null, "e": 10659, "s": 10452, "text": "++++++++++++++details of the student named Mohammad are +++++++++++++++++++\nId : 1\nName : Mohammad\nBranch : It\nPercentage : 80\nEmail : [email protected]\nPhone : 90000000\nRecords Read Successfully \n" }, { "code": null, "e": 10666, "s": 10659, "text": " Print" }, { "code": null, "e": 10677, "s": 10666, "text": " Add Notes" } ]
JDBC - Streaming ASCII and Binary Data
A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types. There are following methods, which can be used to stream data βˆ’ setAsciiStream() βˆ’ This method is used to supply large ASCII values. setAsciiStream() βˆ’ This method is used to supply large ASCII values. setCharacterStream() βˆ’ This method is used to supply large UNICODE values. setCharacterStream() βˆ’ This method is used to supply large UNICODE values. setBinaryStream() βˆ’ This method is used to supply large binary values. setBinaryStream() βˆ’ This method is used to supply large binary values. The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream. This example would create a database table XML_Data and then XML content would be written into this table. Copy and paste the following example in FirstApplication.java, compile and run as follows βˆ’ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT Data FROM XML_Data WHERE id=100"; static final String INSERT_QUERY="INSERT INTO XML_Data VALUES (?,?)"; static final String CREATE_TABLE_QUERY = "CREATE TABLE XML_Data (id INTEGER, Data LONG)"; static final String DROP_TABLE_QUERY = "DROP TABLE XML_Data"; static final String XML_DATA = "<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>"; public static void createXMLTable(Statement stmt) throws SQLException{ System.out.println("Creating XML_Data table..." ); //Drop table first if it exists. try{ stmt.executeUpdate(DROP_TABLE_QUERY); }catch(SQLException se){ } stmt.executeUpdate(CREATE_TABLE_QUERY); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY); ) { createXMLTable(stmt); ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes()); pstmt.setInt(1,100); pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length); pstmt.execute(); //Close input stream bis.close(); ResultSet rs = stmt.executeQuery(QUERY); // Get the first row if (rs.next ()){ //Retrieve data from input stream InputStream xmlInputStream = rs.getAsciiStream (1); int c; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (( c = xmlInputStream.read ()) != -1) bos.write(c); //Print results System.out.println(bos.toString()); } // Clean-up environment rs.close(); } catch (SQLException | IOException e) { e.printStackTrace(); } } } Now let us compile the above example as follows βˆ’ C:\>javac FirstApplication.java C:\> When you run FirstApplication, it produces the following result βˆ’ C:\>java FirstApplication Creating XML_Data table... <Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee> C:\> 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": 2386, "s": 2162, "text": "A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can\nhold large values, such as CLOB and BLOB data types." }, { "code": null, "e": 2452, "s": 2386, "text": "There are following methods, which can be used to stream data βˆ’" }, { "code": null, "e": 2521, "s": 2452, "text": "setAsciiStream() βˆ’ This method is used to supply large ASCII values." }, { "code": null, "e": 2590, "s": 2521, "text": "setAsciiStream() βˆ’ This method is used to supply large ASCII values." }, { "code": null, "e": 2665, "s": 2590, "text": "setCharacterStream() βˆ’ This method is used to supply large UNICODE values." }, { "code": null, "e": 2740, "s": 2665, "text": "setCharacterStream() βˆ’ This method is used to supply large UNICODE values." }, { "code": null, "e": 2811, "s": 2740, "text": "setBinaryStream() βˆ’ This method is used to supply large binary values." }, { "code": null, "e": 2882, "s": 2811, "text": "setBinaryStream() βˆ’ This method is used to supply large binary values." }, { "code": null, "e": 3084, "s": 2882, "text": "The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream." }, { "code": null, "e": 3191, "s": 3084, "text": "This example would create a database table XML_Data and then XML content would be written into this table." }, { "code": null, "e": 3283, "s": 3191, "text": "Copy and paste the following example in FirstApplication.java, compile and run as follows βˆ’" }, { "code": null, "e": 5855, "s": 3283, "text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT Data FROM XML_Data WHERE id=100\";\n static final String INSERT_QUERY=\"INSERT INTO XML_Data VALUES (?,?)\";\n static final String CREATE_TABLE_QUERY = \"CREATE TABLE XML_Data (id INTEGER, Data LONG)\";\n static final String DROP_TABLE_QUERY = \"DROP TABLE XML_Data\";\n static final String XML_DATA = \"<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>\";\n \n public static void createXMLTable(Statement stmt) \n throws SQLException{\n System.out.println(\"Creating XML_Data table...\" );\n //Drop table first if it exists.\n try{\n stmt.executeUpdate(DROP_TABLE_QUERY);\n }catch(SQLException se){\n }\n stmt.executeUpdate(CREATE_TABLE_QUERY);\n }\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY);\n ) {\t\t \n createXMLTable(stmt);\n\n ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes());\n\n pstmt.setInt(1,100);\n pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length);\n pstmt.execute();\n\n //Close input stream\n bis.close();\n\n ResultSet rs = stmt.executeQuery(QUERY);\n // Get the first row\n if (rs.next ()){\n //Retrieve data from input stream\n InputStream xmlInputStream = rs.getAsciiStream (1);\n int c;\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n while (( c = xmlInputStream.read ()) != -1)\n bos.write(c);\n //Print results\n System.out.println(bos.toString());\n }\n // Clean-up environment\n rs.close();\n\n } catch (SQLException | IOException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 5905, "s": 5855, "text": "Now let us compile the above example as follows βˆ’" }, { "code": null, "e": 5942, "s": 5905, "text": "C:\\>javac FirstApplication.java\nC:\\>" }, { "code": null, "e": 6008, "s": 5942, "text": "When you run FirstApplication, it produces the following result βˆ’" }, { "code": null, "e": 6179, "s": 6008, "text": "C:\\>java FirstApplication\nCreating XML_Data table...\n<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>\nC:\\>\n" }, { "code": null, "e": 6212, "s": 6179, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6228, "s": 6212, "text": " Malhar Lathkar" }, { "code": null, "e": 6261, "s": 6228, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6277, "s": 6261, "text": " Malhar Lathkar" }, { "code": null, "e": 6312, "s": 6277, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6326, "s": 6312, "text": " Anadi Sharma" }, { "code": null, "e": 6360, "s": 6326, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6374, "s": 6360, "text": " Tushar Kale" }, { "code": null, "e": 6411, "s": 6374, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6426, "s": 6411, "text": " Monica Mittal" }, { "code": null, "e": 6459, "s": 6426, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6478, "s": 6459, "text": " Arnab Chakraborty" }, { "code": null, "e": 6485, "s": 6478, "text": " Print" }, { "code": null, "e": 6496, "s": 6485, "text": " Add Notes" } ]
C++ IOS Library - rdbuf
It is used to get/set stream buffer. If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit). Some derived stream classes (such as stringstream and fstream) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on that internal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer (although input/output operations on streams always use the associated stream buffer, as returned by this member function). Following is the declaration for ios::rdbuf function. get (1) streambuf* rdbuf() const; set (2) streambuf* rdbuf (streambuf* sb); The first form (1) returns a pointer to the stream buffer object currently associated with the stream. The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears the error state flags. sb βˆ’ Pointer to a streambuf object. A pointer to the stream buffer object associated with the stream before the call. Basic guarantee βˆ’ if an exception is thrown, the stream is in a valid state. It throws an exception of member type failure if sb is a null pointer and member exceptions was set to throw for badbit. Accesses (1) or modifies (2) the stream object. Concurrent access to the same stream object may cause data races. In below example explains about ios::rdbuf function. #include <iostream> #include <fstream> int main () { std::streambuf *psbuf, *backup; std::ofstream filestr; filestr.open ("test.txt"); backup = std::cout.rdbuf(); psbuf = filestr.rdbuf(); std::cout.rdbuf(psbuf); std::cout << "This is written to the file"; std::cout.rdbuf(backup); filestr.close(); return 0; } Print Add Notes Bookmark this page
[ { "code": null, "e": 2802, "s": 2603, "text": "It is used to get/set stream buffer. If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit)." }, { "code": null, "e": 3292, "s": 2802, "text": "Some derived stream classes (such as stringstream and fstream) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on that internal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer (although input/output operations on streams always use the associated stream buffer, as returned by this member function)." }, { "code": null, "e": 3346, "s": 3292, "text": "Following is the declaration for ios::rdbuf function." }, { "code": null, "e": 3422, "s": 3346, "text": "get (1)\tstreambuf* rdbuf() const;\nset (2)\tstreambuf* rdbuf (streambuf* sb);" }, { "code": null, "e": 3525, "s": 3422, "text": "The first form (1) returns a pointer to the stream buffer object currently associated with the stream." }, { "code": null, "e": 3662, "s": 3525, "text": "The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears the error state flags." }, { "code": null, "e": 3698, "s": 3662, "text": "sb βˆ’ Pointer to a streambuf object." }, { "code": null, "e": 3780, "s": 3698, "text": "A pointer to the stream buffer object associated with the stream before the call." }, { "code": null, "e": 3978, "s": 3780, "text": "Basic guarantee βˆ’ if an exception is thrown, the stream is in a valid state. It throws an exception of member type failure if sb is a null pointer and member exceptions was set to throw for badbit." }, { "code": null, "e": 4026, "s": 3978, "text": "Accesses (1) or modifies (2) the stream object." }, { "code": null, "e": 4092, "s": 4026, "text": "Concurrent access to the same stream object may cause data races." }, { "code": null, "e": 4145, "s": 4092, "text": "In below example explains about ios::rdbuf function." }, { "code": null, "e": 4533, "s": 4145, "text": "#include <iostream> \n#include <fstream> \n\nint main () {\n std::streambuf *psbuf, *backup;\n std::ofstream filestr;\n filestr.open (\"test.txt\");\n\n backup = std::cout.rdbuf(); \n\n psbuf = filestr.rdbuf(); \n std::cout.rdbuf(psbuf); \n\n std::cout << \"This is written to the file\";\n\n std::cout.rdbuf(backup); \n\n filestr.close();\n\n return 0;\n}" }, { "code": null, "e": 4540, "s": 4533, "text": " Print" }, { "code": null, "e": 4551, "s": 4540, "text": " Add Notes" } ]
AWT MouseAdapter Class
The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects. Following is the declaration for java.awt.event.MouseAdapter class: public abstract class MouseAdapter extends Object implements MouseListener, MouseWheelListener, MouseMotionListener MouseAdapter() void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and released) on a component. void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. void mouseEntered(MouseEvent e) Invoked when the mouse enters a component. void mouseExited(MouseEvent e) Invoked when the mouse exits a component. void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. void mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component. void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. void mouseWheelMoved(MouseWheelEvent e) Invoked when the mouse wheel is rotated. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtAdapterDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtAdapterDemo(){ prepareGUI(); } public static void main(String[] args){ AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo(); awtAdapterDemo.showMouseAdapterDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMouseAdapterDemo(){ headerLabel.setText("Listener in action: MouseAdapter"); Panel panel = new Panel(); panel.setBackground(Color.magenta); panel.setLayout(new FlowLayout()); panel.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { statusLabel.setText("Mouse Clicked: (" +e.getX()+", "+e.getY() +")"); } }); Label msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); msglabel.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { statusLabel.setText("Mouse Clicked: (" +e.getX()+", "+e.getY() +")"); } }); panel.add(msglabel); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1929, "s": 1747, "text": "The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects." }, { "code": null, "e": 1997, "s": 1929, "text": "Following is the declaration for java.awt.event.MouseAdapter class:" }, { "code": null, "e": 2122, "s": 1997, "text": "public abstract class MouseAdapter\n extends Object\n implements MouseListener, MouseWheelListener, MouseMotionListener" }, { "code": null, "e": 2137, "s": 2122, "text": "MouseAdapter()" }, { "code": null, "e": 2170, "s": 2137, "text": "void mouseClicked(MouseEvent e) " }, { "code": null, "e": 2256, "s": 2170, "text": "Invoked when the mouse button has been clicked (pressed and released) on a component." }, { "code": null, "e": 2289, "s": 2256, "text": "void mouseDragged(MouseEvent e) " }, { "code": null, "e": 2361, "s": 2289, "text": "Invoked when a mouse button is pressed on a component and then dragged." }, { "code": null, "e": 2394, "s": 2361, "text": "void mouseEntered(MouseEvent e) " }, { "code": null, "e": 2437, "s": 2394, "text": "Invoked when the mouse enters a component." }, { "code": null, "e": 2469, "s": 2437, "text": "void mouseExited(MouseEvent e) " }, { "code": null, "e": 2511, "s": 2469, "text": "Invoked when the mouse exits a component." }, { "code": null, "e": 2542, "s": 2511, "text": "void mouseMoved(MouseEvent e) " }, { "code": null, "e": 2637, "s": 2542, "text": "Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed." }, { "code": null, "e": 2670, "s": 2637, "text": "void mousePressed(MouseEvent e) " }, { "code": null, "e": 2731, "s": 2670, "text": "Invoked when a mouse button has been pressed on a component." }, { "code": null, "e": 2765, "s": 2731, "text": "void mouseReleased(MouseEvent e) " }, { "code": null, "e": 2827, "s": 2765, "text": "Invoked when a mouse button has been released on a component." }, { "code": null, "e": 2868, "s": 2827, "text": "void mouseWheelMoved(MouseWheelEvent e) " }, { "code": null, "e": 2909, "s": 2868, "text": "Invoked when the mouse wheel is rotated." }, { "code": null, "e": 2965, "s": 2909, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 2982, "s": 2965, "text": "java.lang.Object" }, { "code": null, "e": 2999, "s": 2982, "text": "java.lang.Object" }, { "code": null, "e": 3113, "s": 2999, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 5276, "s": 3113, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtAdapterDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtAdapterDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo(); \n awtAdapterDemo.showMouseAdapterDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showMouseAdapterDemo(){\n headerLabel.setText(\"Listener in action: MouseAdapter\"); \n\n Panel panel = new Panel(); \n panel.setBackground(Color.magenta);\n panel.setLayout(new FlowLayout()); \n panel.addMouseListener(new MouseAdapter(){\n public void mouseClicked(MouseEvent e) {\n statusLabel.setText(\"Mouse Clicked: (\"\n +e.getX()+\", \"+e.getY() +\")\");\n } \n });\n\n Label msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n msglabel.addMouseListener(new MouseAdapter(){\n public void mouseClicked(MouseEvent e) {\n statusLabel.setText(\"Mouse Clicked: (\"\n +e.getX()+\", \"+e.getY() +\")\");\n } \n });\n panel.add(msglabel);\n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 5367, "s": 5276, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 5423, "s": 5367, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtAdapterDemo.java" }, { "code": null, "e": 5520, "s": 5423, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 5570, "s": 5520, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtAdapterDemo" }, { "code": null, "e": 5598, "s": 5570, "text": "Verify the following output" }, { "code": null, "e": 5631, "s": 5598, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 5639, "s": 5631, "text": " EduOLC" }, { "code": null, "e": 5646, "s": 5639, "text": " Print" }, { "code": null, "e": 5657, "s": 5646, "text": " Add Notes" } ]